<?php

/* $Id: upload_function.php 51 2012-02-01 09:28:42Z velez $ */

// 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_acert_function.php: DB server: $db_server" );
}

// Get user's login name
$login = $_SERVER['REMOTE_USER'];
if ( $debug ) {
  portal_debug ( "INFO: upload_upsig_function.php: login: $login" );
  portal_debug ( "INFO: upload_upsig_function.php: db_server: $db_server" );
  portal_debug ( "INFO: upload_upsig_function.php: db_name: $db_dbname" );
  portal_debug ( "INFO: upload_upsig_function.php.php: db_username: $db_username" );
}


//$_POST

//uploading the checkbox status
// Test if checkbox is ticked

/*

	if ( $_POST['reflow'] == 'yes' ) {
 		$enable_reflow = true;
		if ( $debug ) {
  
 		portal_debug ( "INFO: enable_reflow is true :: Checkbox= $enable_reflow" );
}
		}
		else {
 		$enable_reflow = false;
		if ( $debug ) {
  
 		portal_debug ( "INFO: enable_reflow is false :: Checkbox= $enable_reflow" );
		}
		}



if ( $_POST['highcontrast'] == 'yes' ) {
 		$enable_highcontrast= true;
		if ( $debug ) {
  
 		portal_debug ( "INFO: enable_reflow is true :: Checkbox= $enable_highcontrast" );
}
		}
		else {
 		$enable_highcontrast = false;
		if ( $debug ) {
  
 		portal_debug ( "INFO: enable_reflow is false :: Checkbox= $enable_highcontrast" );
		}
		}
*/

// 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'];

//PB the 4 following debug messages do not appear in the debug logs !!!
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" );
}



//LVZ 2014-01-30  created this clean_dir_function to remove the pdf, sha2 , html and the conf report from the company folder. 
// all files are seen a new as soon as the upload is perfomed. it prevents from displaying an old result of signature with the same file.
// it also allows to save spaces. only the TSL.xml are remaining in the folder
//clean_dir_content ( $root_dir.$testcases_dir."/".$company, false, $debug );



$filename = $root_dir.$upload_dir."/".$company."/".$filename_original;
$path_parts = pathinfo($filename);
$file_ext = $path_parts['extension'];


if ( strtolower ( $file_ext != "xml" ) || ( $file_ext != "pdf" ) || ( $file_ext != "p7m" ) || ( $file_ext != "asics" ) || ( $file_ext != "asice" )) {
if ( $debug ) {
  portal_debug ( "INFO: upload_upsigconf function.php: wrong extension: $file_ext" );
}

  header ( "Location: /protected/upload.php?error=zip" );
}



if ( $debug ) {
  portal_debug ( "INFO: upload_upsigconf function.php: $filename" );
}

/*
if (file_exists($filename)) {
    $sigexist = true;
} else {
    $sigexist = false;
}
*/
$sigexist = file_exists($filename);



if ( $debug ) {
  portal_debug ( "INFO: sigexist: $sigexist" );
  portal_debug ( "INFO: symlinkfile: $symlinkfile" );
  portal_debug ( "INFO: old_index: $old_index" );
}



/*
// Test if it's a xml file
if ( strtolower ( $filename_original_ext != "cer" ) ) {
  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" );
}
if ( $debug ) {
  portal_debug ( "INFO: Extension is : $file_ext" );
}
// 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 );

$filename = $root_dir.$upload_dir."/".$company."/".$filename_original;

if ( $debug ) {
  portal_debug ( "INFO: upload_upsig_function.php: Filename in upload dir: $filename_original" );
}


//$file = basename ($path,".php")
//$acerfile = basename ( $filename, ".cer" );




$upsigfile = basename( $filename, '.'.$file_ext.'' );
$upsigfolder = $root_dir.$testcases_dir."/".$company;
$TestcaseBaseFolder = "/var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-";



if ( $debug ) {
        portal_debug ( "INFO: upsigfile ".$upsigfile); 
		 portal_debug ( "INFO: upsigfolder ".$upsigfolder); 
		  portal_debug ( "INFO: filename ".$filename); 
		  	  portal_debug ( "INFO: file ext ".$file_ext); 
      }


	
	if ($file_ext == "xml") {
		$sigformat = 'X';
		}
		else if ($file_ext == "pdf") {
		$sigformat = 'P';
				}
		else if ($file_ext == "p7m") {
		$sigformat = 'C';
				}
		else if ($file_ext == "asics") {
		$sigformat = 'A';
				}
		else if ($file_ext == "asice") {
		$sigformat = 'A';
	}

	
	//content of the Test definition file
	$TestDefcontent = '<SignatureRequest><Documentation>'.$filename.'</Documentation></SignatureRequest>';
	$TestDefFolder = $TestcaseBaseFolder.$sigformat.'/TestDefinitions';
	

	if ($sigexist) {
				//$cmd_findsymlink = " find -L /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/ETSI/ -samefile ESIG-X-1.xml";

				$cmd_findsymlink = " find -L /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-".$sigformat."/".$company."/ -samefile ".$filename;
				//symlinkfile is the filename of the existing symlink into ESIG/TestCases
				// ex :symlinkfile = /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/ETSI/Signature-X-ETSI-1.xml

				$symlinkfile = shell_exec($cmd_findsymlink);

				$symlinkfilebase = basename( $symlinkfile, '.'.$file_ext.'' );

			
				// recover the index of the sym link of the existing signature
				$prefix = 'Signature-'.$sigformat.'-'.$company.'-';
				$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $symlinkfilebase);
				$info = pathinfo($str);
				$sigindex =  basename($str,'.'.$info['extension']);


					if ( $debug ) {
						
							
							portal_debug ( "INFO:  cmd_findsymlink ".$cmd_findsymlink); 
							portal_debug ( "INFO:  symlinkfile ".$symlinkfile); 
								portal_debug ( "INFO:  symlinkfilebase ".$symlinkfilebase); 
									portal_debug ( "INFO:  prefix ".$prefix); 
								portal_debug ( "INFO:  str ".$str); 
								
							portal_debug ( "INFO:  name of info ".$info);  
							portal_debug ( "INFO:  found the existing index ".$sigindex); 
					  }
					
	
	
	}
	

		else {

		$cmd_readindex = 'cd '.$TestDefFolder.'; ls -1 '.$sigformat.'-'.$company.'-*| wc -l';
	//for ex: 	cd /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/TestDefinitions; ls -1 X-ETSI-*| wc -l
	
	
		$sigindex = shell_exec($cmd_readindex);
		$sigindex = $sigindex + 1 ;
		
		}
		
			
		$TesdDefBaseFile = $sigformat.'-'.$company.'-'.$sigindex.'.xml';  // ex: X-ETSI-1.xml
	
		$SignatureBaseFile = 'Signature-'.$sigformat.'-'.$company.'-'.$sigindex.'.'.$file_ext;  // ex: Signature-X-ETSI-1.xml
		
		
		
		// LVZ 2014-10-21 : if the signature existe remove the testdef file and the corresponding symplink
		// example: if sigexist and sigindex = 1 for XAdES file
		// rem /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/ETSI/Signature-X-ETSI-1.xml
		// rem /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/TestDefinitions/X-ETSI-1.xml
		
		if ($sigexist) {
		$cmd_rem_sig =  'rem '.$TestcaseBaseFolder.$sigformat.'/'.$company.'/'.$SignatureBaseFile; 
		$cmd_rem_testdef = 'rem '.$TestDefFolder.'/'.$TesdDefBaseFile;
	//	$dstdir = '/var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/';
	//	$sigfile = $SignatureBaseFile;
		
		// delete all the verification reports of the corresponding signature
		// for ex : for i in `ls -d /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-X/*` ; do rm $i/Verification_of_ETSI_Signature-X-ETSI-1.xml; done

		$cmd_rem_all_verif = "for i in `ls -d ".$TestcaseBaseFolder.$sigformat.'/*` ; do rm $i/Verification_of_'.$company.'_'.$SignatureBaseFile.' ;done';
		
		
		
		shell_exec($cmd_rem_sig);
		shell_exec($cmd_rem_testdef);
		shell_exec($cmd_rem_all_verif);
		
		
			
					if ( $debug ) {
						portal_debug ( "INFO: removing existing sig  link ".$cmd_rem_sig); 
						 portal_debug ( "INFO: removing existing test def ".$cmd_rem_testdef); 
						 portal_debug ( "INFO: removing all the verification reports: ".$cmd_rem_all_verif); 
					}
		}
		
		
		// LVZ 2014-10 : Create the sym link between the uploaded signature and the Testcases folder
		$cmd_symlink = 'ln -s "'.$filename.'" '.$TestcaseBaseFolder.$sigformat.'/'.$company.'/'.$SignatureBaseFile;
//		ln -s "/var/www/html/xadesweb/protected/UPSIG/Upload/ETSI/EC_DSS-P-BpP-V-8.pdf" /var/www/html/xadesweb/protected/ESIG/TestCases/ESIG-P/ETSI/Signature-P-ETSI-9.pdf
		
		
		//LVZ 2014-10  : create the testdef file in the TestDefinition folder and upadte the content with the path of the uploaded signature
		$cmd_createTestdef = 'cd '.$TestDefFolder.'; cat > '.$TesdDefBaseFile.' &'; 
		$cmd_updateTestdef = 'cd '.$TestDefFolder.';echo " '.$TestDefcontent.'"  > '.$TesdDefBaseFile;
		
		
		if ( $debug ) {
        
		    portal_debug ( "INFO: executing create cmd_readindex ".$cmd_readindex); 
		      portal_debug ( "INFO: executing create testdef ".$cmd_createTestdef); 
			  portal_debug ( "INFO: executing update testdef ".$cmd_updateTestdef); 
      }
		shell_exec($cmd_createTestdef);
		shell_exec($cmd_updateTestdef);

	
$cmd_build = "cd /var/www/html/xadesweb/protected/ESIG/Documentation/ ; ./build.sh &";



if ( $debug ) {
        portal_debug ( "INFO: executing symlink ".$cmd_symlink); 
		   portal_debug ( "INFO: executing build.sh ".$cmd_build); 
		    
      }
	  
 

shell_exec($cmd_symlink);

exec ( $cmd_build, $output, $retval );


/*



    if (file_exists($cmd_newFiles)){
	
      //Complete the command for running the conformance checker
      $attrcertfiles_array = explode("\n",$newfile_list);
      $attrcertfiles = implode ( " ",$attrcertfiles_array);
      if ( $debug ) {
        portal_debug ( "INFO: TSL files to be tested ".$attrcertfiles);
      }
    
      $cmd_newFiles .= ' '.$attrcertfiles;
      if ( $debug ) {
        portal_debug ( "INFO: executing ".$cmd_newFiles); 
      }
   
      $ccreport = shell_exec($cmd_newFiles);
	  portal_debug("Output: $ccreport");

*/

$code='&error=ok';



//LVZ : 2014-10-13  added this part to generate a zip file ( ESIG folders) when uploading a signature, like it 
// is done for uploading a verification file.
 //////////////////////////////////////////////////////////////////////////////////////

				/* @var string path of Download directory, relative to root_dir */
				$download_dir = "/protected/ESIG/Download";
				/* @var string path of TestCases directory including TestClasses, relative to root_dir */
				$testcases_dir = "/protected/ESIG/TestCases";
				/* @var string prefix of testclass directories */
				$testcase_dir_prefix = "ESIG-";

				/* @var string zip file prefix for ESIG part */
				$zipfile_prefix = "ESIG_plugtest_";
				/* @var string file include mask for zip file */
				$zipfile_include_mask = "ESIG*";
				/* @var string file exclude mask for zipfile */
				$zipfile_exclude_mask = "index.php";



				// Create new download file
				$dt = datetime();
				$zipfile_name = $zipfile_prefix.$dt;

				if ( $debug ) {
						portal_debug ( "INFO: upload_function.php:$dt " );
						   portal_debug ( "INFO: upload_function.php:$zipfile_prefix " );
							  portal_debug ( "INFO: upload_function.php: $zipfile_name" );
				}










				if ( ! create_zipfile ( $zipfile_name, $root_dir.$testcases_dir , $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'" );
				}

				//LVZ 2011-11-30 in response of Frank Cornelis ' request to get always the latest zip file
				 
				 //$copiedzip_cmd = "cp /var/www/html/xadesweb/protected/UPSIG/Download/".$zipfile_name.".zip /var/www/html/xadesweb/protected/ESIG/Download/";
				 //exec ( $copiedzip_cmd, $output, $retval );
				 
				 $cmd = "cp $root_dir$download_dir/$zipfile_name.zip $root_dir$download_dir/plugtest_latest.zip";
				 exec ( $cmd, $output, $retval );
				
			//	$cmd_rem_zipfile = "rem -f ".$root_dir$download_dir/$zipfile_name.".zip";
			//	 exec ( $cmd_rem_zipfile, $output, $retval );





// end of part :LVZ : 2014-10-13  added this part to generate a zip file ( ESIG folders) when uploading a signature, like it 
// is done for uploading a verification file.
 //////////////////////////////////////////////////////////////////////////////////////










// 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";

$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 = "The content of the uploaded file is:
".$filename.' -> ' .$TestcaseBaseFolder.$sigformat.'/'.$company.'/'.$SignatureBaseFile."

Best Regards,
ETSI 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" );
}


portal_debug ( "INFO: upload_upsig_function.php: mail recipient: $recipient" );
$subject = "New Signature has been uploaded  by ".$login;

$headers = "From: Plugtests Portal <xades3_admin@list.etsi.org>";

$recipient = "ESIG2014_PARTICIPANTS@LIST.ETSI.ORG,laurent.velez@etsi.org";

//if ( $login == 'velez' ){ $recipient = "laurent.velez@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" );
}

# LVZ 05/06/2013 :  mail put in comment to improve performance of the server.
mail ( $recipient, $subject, $body, $headers );
  
  
//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.$xadesstats_dir."/".$company."/".$filename_stat;
$fp = fopen($filepath,"a+");
fputs($fp, $filename_stat);
fclose($fp);  
  
//header ("Location: /protected/upload.php?sigtype=".$sigtype.$code."&upsigreport=$upsigreport");
header ( "Location: /protected/upload.php?sigtype=".$sigtype."&error=ok" );
?>
