<?php

/* $Id: upload_function.php 51 2009-12-17 09:28:42Z reinaortega $ */

// Test if user is connected
if ( !isset ( $_SERVER['REMOTE_USER'] ) ) {
  header ( 'Location: /pub' );
}

// Global settings
include_once "portal_settings.php";
include_once "portal_functions.php";


// Test if upload is allowed
if ( ! $enable_upload ) {
  header ( "Location: /protected/upload.php?sigtype=".$sigtype."&error=noup" );
}

if ( $debug ) {
  portal_debug ( "INFO: upload_confchecker_function.php: DB server: $db_server" );
}

// Get user's login name
$login = $_SERVER['REMOTE_USER'];
if ( $debug ) {
  portal_debug ( "INFO: upload_confchecker_function.php: login: $login" );
  portal_debug ( "INFO: upload_confchecker_function.php: db_server: $db_server" );
  portal_debug ( "INFO: upload_confchecker_function.php: db_name: $db_dbname" );
  portal_debug ( "INFO: upload_confchecker_function.php: db_username: $db_username" );
}

// Get user's company name
$company = get_company_name ( $login, $db_server, $db_username, $db_password, $db_dbname, $debug );

// Uploading file's name
$filename_original = $_FILES['thefile']['name'];
$filename_original_base = basename ( $filename_original, ".xml" );
$filename_original_ext = pathinfo ( $filename_original, PATHINFO_EXTENSION );
$filename_temp_server = $_FILES['thefile']['tmp_name'];
if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: Uploading file's full name: $filename_original" );
  portal_debug ( "INFO: upload_function.php: Uploading file's name: $filename_original_base" );
  portal_debug ( "INFO: upload_function.php: Uploading file's extension: $filename_original_ext" );
  portal_debug ( "INFO: upload_function.php: File's temp name on the server: $filename_temp_server" );
}

// Test if it's a xml file
if ( strtolower ( $filename_original_ext != "xml" ) ) {
  header ( "Location: /protected/upload.php?sigtype=".$sigtype."&error=zip" );
}

// Get actual date and time
$dt = datetime();
if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: Actual date and time: $dt" );
}

// Move the file to the upload dir
$filename_store = $dt."_".$login."_".$filename_original;
if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: Filename in upload dir: $filename_store" );
}

if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: Moving '$filename_temp_server' to '$root_dir$upload_dir/$company/$filename_store'" );
}

if ( ! move_uploaded_file ( $filename_temp_server, $root_dir.$upload_dir."/".$company."/".$filename_original ) ) {
  portal_error ( "upload_function.php: Unable to move '$filename_temp_server' to '$root_dir$upload_dir/$company/$filename_store'" );
}



// $newfile_list = "ConfChecker/".$company."/".$filename_original;

chmod ( $root_dir.$upload_dir."/".$company."/".$filename_original, 0666 );

// Create extract dir
//$extract_dir = $temp_dir."/".$filename_original_base."_".$login."_".$dt;
//if ( $debug ) {
 // portal_debug ( "INFO: upload_confchecker_function.php: Extract dir: $extract_dir" );
//}

//if ( ! mkdir ( $root_dir.$extract_dir, 0777 ) ) {
  //portal_error ( "upload_confchecker_function.php: Unable to create dir: $root_dir$extract_dir" );
//}

// Copy and rename files into test cases folder
 //if ( ! copy ( $root_dir$upload_dir."/".$company."/".$filename_store, $root_dir$extract_dir."/".$filename_original ) ) {
   //         portal_debug ( "ERROR: upload_confchecker_function(): Unable to copy $root_dir$upload_dir/$company/$filename_store, $root_dir$extract_dir/$filename_original" );
    //        closedir ( $dir );
      //      return false;
        //  }
 // $cmd = "cp $root_dir$upload_dir/$company/$filename_store $root_dir$extract_dir";
 // if ( $debug ) {
   // portal_debug ( "INFO: upload_confchecker_function.php: Copying $root_dir$upload_dir/$company/$filename_store into $root_dir$extract_dir " );
   // portal_debug ( "INFO: upload_confchecker_function.php: Command: $cmd" );
// }
 // exec ( $cmd, $output, $retval );
 // if ( $retval > 2 ) {
   // delete_dir_content ( $root_dir.$extract_dir, true, $debug );
   // portal_error ( "upload_function.php: Couldn't extract '$root_dir$upload_dir/$filename_store' to '$root_dir$extract_dir'" );
 // }

 // $cmd = "rename $root_dir$extract_dir/$filename_store  $filename_original $root_dir$extract_dir/$filename_store";
// if ( $debug ) {
  // portal_debug ( "INFO: upload_function.php: Unzipping $root_dir$upload_dir/$company/$filename_store into $root_dir$extract_dir " );
  // portal_debug ( "INFO: upload_function.php: Unzip command: $cmd" );
// }
 // exec ( $cmd, $output, $retval );
 // if ( $retval > 2 ) {
   // delete_dir_content ( $root_dir.$extract_dir, true, $debug );
   // portal_error ( "upload_function.php: Couldn't extract '$root_dir$upload_dir/$filename_store' to '$root_dir$extract_dir'" );
 // }

// Unzip uploaded file
// $cmd = "/usr/bin/unzip -o $root_dir$upload_dir/$filename_store -d $root_dir$extract_dir";
// if ( $debug ) {
  // portal_debug ( "INFO: upload_function.php: Unzipping $root_dir$upload_dir/$filename_store into $root_dir$extract_dir " );
  // portal_debug ( "INFO: upload_function.php: Unzip command: $cmd" );
// }
// exec ( $cmd, $output, $retval );
// if ( $retval > 2 ) {
  // delete_dir_content ( $root_dir.$extract_dir, true, $debug );
  // portal_error ( "upload_function.php: Couldn't extract '$root_dir$upload_dir/$filename_store' to '$root_dir$extract_dir'" );
// }

// list temp dir
// if ( $debug ) {
  // $cmd = "ls -laR $root_dir$temp_dir";
  // $output = shell_exec ( $cmd );
  // portal_debug ( "INFO: upload_function.php: shell command: $cmd" );
  // portal_debug ( "INFO: upload_function.php: \n$output" );
//}

// Select testcase dirs in uploaded file
// $list_newdir = select_dir ( $root_dir.$extract_dir, $testcase_dir_prefix, $debug );
// $list_newdir_size = count ( $list_newdir );
// if ( $debug ) {
  // portal_debug ( "INFO: upload_function.php: Number of testcase dirs in uploaded file: $list_newdir_size" );
// }

// Copy files to testcases dirs
$newfile_list = "";
$oldfile_list = "";

//if ( $list_newdir_size > 0 ) {
  // foreach ( $list_newdir as $newdir ) {
    // if ( check_dir ( $root_dir.$testcases_dir, $root_dir.$extract_dir."/".$newdir, $testcase_dir_prefix, $company, $debug ) ) {
      // if ( $debug ) {
        // portal_debug ( "INFO: upload_function.php: Directory $newdir/$company can be found in $root_dir$testcases_dir" );
      // }
	  
      if ( ! copy_tslConfChecker ( $root_dir.$upload_dir."/".$company, $root_dir.$testcases_dir."/".$company, $newfile_list, $oldfile_list, $testcase_dir_prefix, $debug ) ) {
        delete_dir ( $root_dir.$extract_dir, $debug );
        portal_error ( "upload_function.php: Unable to copy files from $root_dir$extract_dir/$newdir/$company to $root_dir$testcases_dir/$newdir/$company" );
      }
	  
    // } else {
      // if ( $debug ) {
        // portal_debug ( "INFO: upload_function.php: Directory $newdir doesn't exist in $root_dir$testcases_dir" );
      // }
    // }
//  }
//}

// Delete extract dir
//delete_dir_content ( $root_dir.$extract_dir, true, $debug );

// Create new download file
$dt = datetime();
$zipfile_name = $zipfile_prefix.$dt;

if ( ! create_zipfile ( $zipfile_name, $root_dir.$testcases_dir."/".$company , $root_dir.$download_dir, $zipfile_include_mask, $zipfile_exclude_mask, $debug ) ){
  portal_error ( "upload_function.php: Couldn't create zip file '$zipfile_name' in '$root_dir$download_dir'" );
}

// Compile notification mail body
$body1 = "Dear Participants,

A new file has been uploaded to the portal by the user '".$login."'. You can download the updated files from:
$portal_address$download_dir/$zipfile_name.zip\n\n";

if ( strlen ( $newfile_list ) > 0 ) {
  $body2 = "The following files are handled as new:\n".$newfile_list."\n";
  
  //Conformance Checker
  if( substr_count($testcases_dir,'ConfChecker') == 1)
  {
    if ( ! chdir ( $root_dir.$doc_dir) ) {
     portal_error ( "upload_function.php: Unable to change to $root_dir$doc_dir" );
    } else {
     portal_debug ( "INFO: upload_function.php: Changed to directory $root_dir$doc_dir");
    }

    $cmd_newFiles = './confChecker.sh';

    if ( $debug ) {
      portal_debug ( "INFO: trying to execute ".$cmd_newFiles);
    }

    if (file_exists($cmd_newFiles)){
	
      //Complete the command for running the conformance checker
      $tslfiles_array = explode("\n",$newfile_list);
      $tslfiles = implode ( " ",$tslfiles_array);
      if ( $debug ) {
        portal_debug ( "INFO: TSL files to be tested ".$tslfiles);
      }
    
      $cmd_newFiles .= ' '.$tslfiles;
      if ( $debug ) {
        portal_debug ( "INFO: executing ".$cmd_newFiles); 
      }
   
      $ccreport = shell_exec($cmd_newFiles);
	  portal_debug("Output: $ccreport");
	  
	  $cmd_prettyPrint = './confchecker_prettyPrint.sh';
	  if (file_exists($cmd_prettyPrint)){
		$cmd_prettyPrint .= ' '.$tslfiles;
		if ( $debug ) {
			portal_debug ( "INFO: executing ".$cmd_prettyPrint); 
	      }
   
		$ccpretty = exec($cmd_prettyPrint);
		portal_debug("Output: $ccpretty");
	  }

	  
	  
	  
	  delete_dir_content ( $root_dir.$upload_dir."/".$company, false, $debug );

      if ( $debug ) {	
        portal_debug ( "INFO: name  ".$ccreport);   
      }

    } else {
      portal_error ( "ERROR: could not find ".$cmd_newFiles);
    }
  }//End TSL Conformance Checker if
  
} else {
  $body2 = "";
}

if ( strlen ( $oldfile_list ) > 0 ) {
  $body3 = "The following files have been deleted:\n".$oldfile_list."\n";
} else {
  $body3 = "";
}

// $output = shell_exec ( "/usr/bin/unzip -lq $root_dir$upload_dir/$filename_store 2>&1" );
$body4 = "
Best Regards,
ETSI TSL Checker Team";

//$body4 = "The content of the uploaded file is:
// ".$output."
//BR,
//XAdES/TSL Remote Plugtest Team";

$body = $body1.$body2.$body3.$body4;

if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: \n$body" );
}

// Send notification mail

if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: Sigtype: $sigtype" );
}
//if($sigtype=="confchecker") {
 //   $recipient = "TSL_INTEROP@list.etsi.org";
//} 
portal_debug ( "INFO: upload_function.php: mail recipient: $recipient" );
$subject = "New TSL file was uploaded by ".$login;
//$headers = "From: XAdES/TSL Remote Plugtest Portal <xades3_admin@list.etsi.org>";
$headers = "From: TSL Conformance Checker Portal <laurent.velez@etsi.org>";

if ( $login == 'velez' ){ $recipient = "laurent.velez@etsi.org";}
//if ( $login == 'lanz' ) {$recipient = "Konrad.Lanz@iaik.tugraz.at";}
if ($login == 'reinaortega' ) {$recipient = "miguelangel.reinaortega@etsi.org";}

$recipient = "laurent.velez@etsi.org,miguelangel.reinaortega@etsi.org";

if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: mail recipient: $recipient" );
  portal_debug ( "INFO: upload_function.php: mail subject: $subject" );
  portal_debug ( "INFO: upload_function.php: mail headers: $headers" );
}


mail ( $recipient, $subject, $body, $headers );

//LVZ 21-11-2010
// Add a line (statreport_20101121_190246_ETSI_velez) in the file  /protected/TSLPlugtest/TestCases/statreport.txt
// it Allows a post analysis of the upload statistics

$filename_stat = "statreport_".$dt."_".$company."_".$login."\n";
$fp = fopen($root_dir.$testcases_dir."/reportstat.txt","a+");
$filepath = $root_dir.$testcases_dir."/".$company."/".$filename_stat;
fputs($fp, $filename_stat);
fclose($fp);

//LVZ 21-11-2010  
// Create a file for each upload in the company folder. used later for /protected/TSLPlugtest/stat_number_of_signatures.php
$filename_stat = "statreport_".$dt."_".$company."_".$login.".txt";
$filepath = $root_dir.$testcases_dir."/".$company."/".$filename_stat;
$fp = fopen($filepath,"a+");
fputs($fp, $filename_stat);
fclose($fp);


if ( ! chdir ( $root_dir.$doc_dir) ) {
  portal_error ( "upload_function.php: Unable to change to $root_dir$doc_dir" );
}

//$cmd = "./build.sh &";
//exec ( $cmd, $output, $retval );

if ( $debug ) {
  portal_debug ( "INFO: upload_function.php: End of normal operation" );
}

//TODO MIGUEL PLEASE fix this quick and dirty schema check to maybe use the location where the files ar copied to

$this_dir = dirname(__FILE__)."/TSLPlugtest/Upload/TslConfChecker";
portal_debug ( "INFO this_dir: $this_dir" );
//$tslfile = "/TSLPlugtest/TestCases/ConfChecker".substr($tslfiles_array[0], strlen($this_dir));
$tslfile = substr($tslfiles_array[0], strlen($this_dir));

portal_debug ( "INFO tslfile: $tslfile" );

portal_debug ( "INFO ccpretty: $ccpretty" );
 
//Conformance checker
//header ( "Location: /protected/upload.php?sigtype=".$sigtype."&error=ok&tslfile=".$tslfile."&confcheckerreport=".$ccreport."&confcheckerpretty=".$ccpretty); 
header ( "Location: /protected/upload.php?sigtype=".$sigtype."&error=ok&confcheckerpretty=$ccpretty&confcheckerreport=$ccreport"); 

?>
