<?php
	include("connection.php");
    include("frames_header.php");
?>

<?php


/******************************************************************************\
*           This script allows to download automatically a swissprot           *
*           database and launch a blast analisys and record the new            *
*           best blast hits                                                    *

NB: the swprot db is donloaded from : ftp://us.expasy.org
    it's a tar.gz file and it is uncompressed when it's downloaded
*******************************************************************************/


//   To uncompress the swp database
function uncompress($fromFile, $toFile) 
{
   $zp = @gzopen($fromFile, "r");
   $fp = @fopen($toFile, "w");
   while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
   @gzclose($zp);
   @fclose($fp);
}

// if you want to know the client OS
$os=getenv("OS");


$update="";
if (isset($_POST["update"]))
	$update=$_POST["update"];
else $update='n';

$backup="";
if (isset($_POST["backup"]))
	$backup=$_POST["backup"];
else $backup='n';

$pathprotspecies="";
if (isset($_POST["protspecies"]))
{
	$pathprotspecies=$_POST["protspecies"];
	$pathprotspecies="\"".$pathprotspecies."\"";
}


$path="";
if (isset($_POST["filepath"]))
	$path=$_POST["filepath"];
else $path="";


if( (strlen($pathprotspecies)<=2)and(strlen($path)<=0) )
{
	echo "<br><center>ERROR: Please enter the protein models file path</center><br>";
	include("frames_footer.php");
	return;
	
}

$launch="";
if (isset($_POST["launch"]))
	$launch=$_POST["launch"];
else $launch='n';



$test="";
if (isset($_POST["test"]))
	$test=$_POST["test"];
	else $test='n';
if($test=='y'){
	print "test mode<br>";
}

$del="";
if (isset($_POST["del"]))
	$del=$_POST["del"];
else $del='n';

$maxhits="";
if (isset($_POST["hits"]))
	$maxhits=$_POST["hits"];
else $maxhits=5;

$record="";
if (isset($_POST["record"]))
	$record=$_POST["record"];
else $record='n';



$maxentry=$maxhits;



// connection to the ftp expasy server


//print"maxhits === $maxhits<br>";	
if ($update=='y')
{
	$ftp_server="us.expasy.org";
	$conn_id = ftp_connect($ftp_server); 
	$ftp_user_name = "anonymous";
	$ftp_user_pass = "guest@all.com";
	$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

	if ((!$conn_id) || (!$login_result)) { 

   		echo " The ftp connection has failed!<br>";
   		echo "Trying to connect $ftp_server <br>";
       	die;
   	} 
	else {
       	echo "<br> Connection OK <br>";
	}
	
	if ((!file_exists("./blast/uniprot_sprot.fasta")) or (ftp_mdtm ($conn_id,"./databases/uniprot/knowledgebase/complete/uniprot_sprot.fasta.gz") > filemtime("./blast/uniprot_sprot.fasta")))
	{
	
		echo "<br>File found.<br>";
		$destination_file="./blast/uniprot_sprot.fasta.gz";
		$source_file="./databases/uniprot/knowledgebase/complete/uniprot_sprot.fasta.gz";
		$cmpt=0;
		$echec=0;
		while(($cmpt<3)||($echec!=0))
		{
			$upload = ftp_get($conn_id, $destination_file , $source_file , FTP_BINARY); 
			if (!$upload) 
			{ 
				echo "<br>Download faillure: $source_file from $ftp_server <br>";
				$echec=0;
				$cmpt++;
			} 
			else 
			{
				echo "<br>Download complete: $source_file from $ftp_server <br>";
				$echec=1;
				break;		
			}
		}
		uncompress("./blast/uniprot_sprot.fasta.gz", "./blast/uniprot_sprot.fasta");
		if(filesize("./blast/uniprot_sprot.fasta")<=0)
		{
			echo "Error while uncompressing the downloaded file";
			include("frames_footer.php");
			return;
		}
		else
		{
			unlink("./blast/uniprot_sprot.fasta.gz");
		}
		
// if the user check update , the old database is saved in ./blast/backup		
		if($backup=='y')
		{
            print("Previous files copy and backup....<BR>\n");
		
			$nbfic=0;
			$sizetocopy=0;
			$strg1="swissprot.";
			if( !file_exists("./blast/backup"))
			{
				mkdir("./blast/backup");
				chmod("./blast/backup", 0777);
			}			
			if ($handle = opendir("./blast")) 
			{
   				while (false !== ($strg2 = readdir($handle))) 
				{
					if ($strg2 != "." && $strg2 != "..") 
					{
						if (strpos($strg2,$strg1)!==false) 
						{
							$nbfic++;
							$taillefic= filesize("./blast/".$strg2);
							$sizetocopy=$sizetocopy + $taillefic;
							if (!copy( "./blast/".$strg2, "./blast/backup/".$strg2)) 
							{
								print("Error: Backup failed...<BR>");
								include("frames_footer.php");
								return;
							}
						}
					}
   				}
   				closedir($handle);
			}
			if ($handle = opendir("./blast/backup")) 
			{
				$nbficcpy=0;
				$sizetocopy2=0;
   				while (false !== ($fcpy = readdir($handle))) 
				{
					if ($fcpy != "." && $fcpy != "..") 
					{
       					if (strpos($fcpy,$strg1)!==false) 
						{
           					$nbficcpy++;
							$taillefcpy= filesize("./blast/backup/".$fcpy);
							$sizetocopy2=$sizetocopy2+$taillefcpy;
       					}
  				 	}
				}
   				closedir($handle);
			}

			
		}
 	
	
		
		if (strpos($os,"Win")!==false)
		{
		    echo "Formating the database...<br>";
			if(`blast\formatdb -i blast\uniprot_sprot.fasta -p T -o T -n blast\swissprot`)
				;
			else echo "ERROR formatDB<br>";
		}
		else
		{
		    echo "Formating the database...<br>";
			if(`./blast/formatdb -i ./blast/uniprot_sprot.fasta -p T -o T -n ./blast/swissprot`)
				;
			else echo "ERROR formatDB<br>";
		}
		
		
			
		
	}
	else 
	{
		echo "The Swissprot database is already up to date<br>";
		print "Nothing will be done unless you uncheck the 'Update the Swissprot database' checkbox";
		include("frames_footer.php");
		return;
	}
	
	ftp_close($conn_id); 
}



if($launch=='y')
{
  // For BlastP win $exec ="blast\blastall -m 9 -b 10 -p blastp -d blast\swissprot -i $pathprotspecies -o blast\BlastP-swissprot.txt -F F";
	//print "$exec";
	// For BlastP linux $exec2 ="./blast/blastall -m 9 -b 10 -p blastp -d ./blast/swissprot -i $pathprotspecies -o ./blast/BlastP-swissprot.txt -F F";
	
	if (strpos($os,"Win")!==false)
	{
	    echo "blasting the file ciona.prot.fasta against the new swissprot database...<br>";
		if(exec("blast\blastpgp -m 9 -b 10 -i $pathprotspecies -o blast\BlastPGP-swissprot.txt -d blast\swissprot -F F"))
			;
		else echo "ERROR<br>";
	}
	else
	{
	    echo"blasting the file ciona.prot.fasta against the new swissprot database...<br>";
		if(exec("./blast/blastpgp -m 9 -b 10 -i $pathprotspecies -o ./blast/BlastPGP-swissprot.txt -d ./blast/swissprot -F F"))
			;
		else echo "ERROR<br>";
	}
}
	
	
	
if((strlen($path)<=0)&&($record=='y'))
{ 
	$path="./blast/BlastPGP-swissprot.txt";
	//echo "mon path est :::: $path<br>";
}
//else echo"mon path reste inchang�et est ::: $path <br>";

//Olivier	

////////////////////////////////////////////////////////////////////
	
$file = fopen ("$path", "r");
$testsize=0;
$testcount=0;

while ($line = fgets($file)){
	$line=rtrim($line);
	if (ereg ("^# Query: (.+)$",$line, $tabnom))
	{
		$requete= "SELECT \"GENE_ID\" from \"GENE\" where \"NAME\"='$tabnom[1]'";
		
			$stmta = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
			if( $rowa=pg_fetch_array($stmta)){
		
				$idci=$rowa["GENE_ID"];
				if ($del=='y')
				{
				 	 
					 $requete="DELETE from \"BLAST\" where \"DB\"='swissprot' and \"MOL_ID\"='$idci'";
					 if ($test=='n')
					 {		pg_query($c,"begin");
					 		$stmtb = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					 		pg_query($c,"commit");
							//ocifreestatement($stmtb);
							//OCICommit($connection);
						}
	 					//OCICommit($connection);
		 				//print "Old results deleted<br>";
				}
			
			
		}
		//ocifreestatement($stmta);
	}
	
	if( (ereg("^# Fields",$line))and(strlen($gene)>0) )
	{
		echo "<br>GENE= $gene<br>";
		
		
		
		if(($test=='n') and (count($clust[$gene])!=0))
		{
			    
			foreach($clust[$gene] as $key=>$value)
			{//enregistrement du nombre de fragments pour chaque hit
				$idprot.="$key";
			
				$requete="update \"BLAST\" set \"BLOCKS\"=".$clust[$gene][$key]." where \"MOL_ID\"=$geneid and \"PROTEIN\"='$key'";
				pg_query($c,"begin");
				$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
				//pg_query($c,"commit");
			}
				
		}
		print "--".count($clust[$gene])."<br>";
		
		$clust=(array)null;
	}
	
	if( ereg("^#",$line) ){continue;}
	$data=split("\t",$line);
	$gene = $data[0];
	$id = $data[2];		
	$evalue = $data[10];
	$score = $data[11];
	$hit = $data[1];//marche pour Swissprot
	++$clust[$gene][$hit];
	
	
	if($clust[$gene][$hit]==1){
		//recherche de la description de la prot sbjt
		$tmp=tempnam ("/tmp", "BLAST");
		$cmd='blast\fastacmd -d blast\swissprot -o '.$tmp.' -s '.$hit;
		$out=`$cmd`;
		$file2=fopen($tmp, "r");
		$descr = fgets($file2);
		$descr=rtrim($descr);
		$descr=ereg_replace("^\>lcl\|","",$descr);
		$descr=ereg_replace("'","\"",$descr);
		fclose ($file2);
		unlink( $tmp );
		
	}else{
	    $descr="";
	}
	if(strlen($descr)>$testsize)$testsize=strlen($descr);//calcul de la taille maxi des descriptions
	
	
//      print "$gene\t$hit\t$id\t$evalue\t$score\t".$clust[$gene][$hit]."<br>";
//      print "$descr<br><br>";
		
//////////////////////////////////////////requetes/////////////////////////////////////////
	if( ($test=='n')and(count($clust[$gene])<=$maxentry) )
	{
		$requete= "SELECT \"GENE_ID\" from \"GENE\" where \"NAME\"='$gene'";
		
		$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		if( $row=pg_fetch_array($stmt)){
		
				$geneid=$row["GENE_ID"];
				
		}else{
			print "Error: gene_id not found";
			return;
		}
		
				
		$requete="insert into \"BLAST\"(\"MOL_ID\",\"DB\",\"ID\",\"DESCRIPTION\",\"PROTEIN\",\"SCORE\",\"EVALUE\",\"BLOCKS\")values($geneid,'swissprot',$id,'$descr','$hit',$score,'$evalue',1)";
		//echo "REQUETE === $requete<br>";
		//pg_query($c,"begin");
		$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		//pg_query($c,"commit");

	}
////////////////////////////////////////////////////////////////////////////////////////////
//if(++$testcount==100){return;}
}
	
	
if($test=='n'){
	foreach($clust[$gene] as $key=>$value){//enregistrement du nombre de fragments pour la derniere serie
		$idprot.="$key";
		$requete="update \"BLAST\" set \"BLOCKS\"=".$clust[$gene][$key]." where \"MOL_ID\"=$geneid and \"PROTEIN\"='$key'";
		//pg_query($c,"begin");
		$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		//pg_query($c,"commit");
	}
}
	
	
	
if($test=='n'){
	// Validation de la transaction
	//$committed = OCICommit($connection);
	pg_query($c,"commit");
	// Verification de la validation : si une erreur est survenue, afficher le message d'erreur
	
		print "<br><center><H1>Update done</H1></center>";
	
}
	
fclose ($file);
print "<br><br>ok, no problem. max comment size=$testsize<br><br>";


?>
<?php
    include("frames_footer.php");
	//http://us.expasy.org/cgi-bin/niceprot.pl?3BP1_HUMAN
?>