<?php
    //connection
    include("connection.php");
/*$c=  pg_connect ("host=localhost port=5432 dbname=cionaManager user=CIONA_DESIGN password=ciona4121");
set_time_limit(0); //Temps d'execution infini (plutot que limite a 30secondes (qui fait planté certaines pages))
*/
    include("frames_header.php");
?>

<?php
/*Function that counts the number of space at the begining of the string*/

function countBlank($mystring)
{
$tmpstring=$mystring;
if (ereg("(^ +)",$tmpstring,$tab)) return strlen($tab[1]);
else return 0;
}

function Type($mystring)
{
$tmpstring=$mystring;
$tmpstring=trim($tmpstring);

$type=substr($tmpstring,0,1);

if ($type=="%") return "is_a";
if ($type=="<") return "part_of";
if ($type=="^") return "inverse_of";
if ($type=="|") return "disjoint_from";
if ($type=="$") return "none";
if ($type=="!") return "comment";


}


function getGoID($mystring)
{
$tmpstring=$mystring;
if (ereg("(GO:[0-9]+)",$tmpstring,$tab)) return $tab[1];

}

?>


<?php

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

if (isset($_POST["test"]))
    $test=$_POST["test"];
else $test='n';
if($test=='y'){
    print "Test mode selected. No data will be recorded.<br>";
}//else print "No test mode selected. Data will be recorded.<br>";


//DUMMY VARIABLES


if ($download=='n') print "NO DOWNLOAD<br>"; else print "DOWNLOAD<br>";

//Set a dummy variable in order not to make the insert into GO ! <to trash>
$insertGO=1;
if ($insertGO==0) print "NO INSERT INTO TABLE GO<br>"; else print "INSERT INTO TABLE GO<br>";

//Set a dummy variable in order not to make the insert of component into GO_CHILD_OF ! <to trash>
$componentGO=1;
if ($componentGO==0) print "NO INSERT OF COMPONENT INTO TABLE GO_CHILD_OF<br>"; else print "INSERT OF COMPONENT INTO TABLE GO_CHILD_OF";

//Set a dummy variable in order not to make the insert of function inti GO_CHILD_OF ! <to trash>
$functionGO=1;
if ($functionGO==0) print "NO INSERT OF FUNCTION INTO TABLE GO_CHILD_OF<br>"; else print "INSERT OF FUNCTION INTO TABLE GO_CHILD_OF";

//Set a dummy variable in order not to make the insert of process into GO_CHILD_OF ! <to trash>
$processGO=1;
if ($processGO==0) print "NO INSERT OF PROCESS INTO TABLE GO_CHILD_OF<br>"; else print "INSERT OF PROCESS INTO TABLE GO_CHILD_OF";








if ($download=='y')	//To trash in the final version
{

//Downloading files from FTP: ftp://ftp.geneontology.org/pub/go/ontology/


//Connecting to the FTP server
    $ftp_server="ftp.geneontology.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 "ftp connection  failed!<br>";
        //echo "Trying to connect $ftp_server <br>";
        die;
    } 
    else {
        echo "Connected to $ftp_server <br>";
    }

//Retrieving data

$destination_file1="./updates/GO/gene_ontology.obo";
$source_file1="./pub/go/ontology/gene_ontology.obo";

$destination_file2="./updates/GO/component.ontology";
$source_file2="./pub/go/ontology/component.ontology";

$destination_file3="./updates/GO/function.ontology";
$source_file3="./pub/go/ontology/function.ontology";

$destination_file4="./updates/GO/process.ontology";
$source_file4="./pub/go/ontology/process.ontology";

// Upload 
$upload = ftp_get($conn_id, $destination_file1 , $source_file1 , FTP_BINARY); 

//
if (!$upload = ftp_get($conn_id, $destination_file1 , $source_file1 , FTP_BINARY))
	{
	echo "<br>ERROR: Can't download the file $source_file1 from $ftp_server<br>";
	include ("frames_footer.php");
	return;
	}
else	echo "<br>Download of $source_file1 from $ftp_server complete <br>";
//
if (!$upload = ftp_get($conn_id, $destination_file2 , $source_file2 , FTP_BINARY))
	{
	echo "<br>ERROR: Can't download the file $source_file2 from $ftp_server<br>";
	include ("frames_footer.php");
	return;
	}
else	echo "<br>Download of $source_file2 from $ftp_server complete <br>";
//
if (!$upload = ftp_get($conn_id, $destination_file3 , $source_file3 , FTP_BINARY))
	{
	echo "<br>ERROR: Can't download the file $source_file3 from $ftp_server<br>";
	include ("frames_footer.php");
	return;
	}
else	echo "<br>Download of $source_file3 from $ftp_server complete <br>";
//
if (!$upload = ftp_get($conn_id, $destination_file4 , $source_file4 , FTP_BINARY))
	{
	echo "<br>ERROR: Can't download the file $source_file4 from $ftp_server<br>";
	include ("frames_footer.php");
	return;
	}
else	echo "<br>Download of $source_file4 from $ftp_server complete <br>";
//

}


//Begin of database operations

if ($test=='n')
{
pg_query($c,"begin");


//drop referentials constraints
$requete="ALTER TABLE \"GO_DESCRIPTION\" drop constraint \"GO_DESCRIPTIO_FK\"";
$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));



//deleting tables
$requete= "delete from \"GO\"";
$stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
$requete= "delete from \"GO_CHILD_OF\"";
$stmt2 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));

pg_query($c,"commit");

}



if ($insertGO!=0)
{

//Parsing of geneontology.obo

$path="./updates/GO/gene_ontology.obo";

$count=0;
if (!($fd=fopen ($path, "r")))
{
    echo "ERROR: The file $path cannot be opened<br>";
    include("frames_footer.php");
    return;
}
else echo "The file $path is open <br>";

$term=false;

while (!feof($fd))
{
$buffer = fgets($fd, 4096);

$buffer=str_replace("\\\"","",$buffer);


if ($buffer=="[Term]\n") 
	{
	$count++;
	$term=true;
	}

if ($buffer=="[Typedef]\n")
	{
	$term=false;
	}
if ($buffer=="\n")
	{
	if ($term)
	{
		if ($test == 'n')
        	{
		pg_query($c,"begin");
            	$requete= "INSERT INTO \"GO\" (\"GO_ID\", \"GO_TERM\", \"GO_TYPE\", \"DEFINITION\") values ( '$go_id', '$name', '$type', '$def' )";
            	$stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");
        	}
		else
		{
		print "GOFIND: $go_id<br>";
		}
	}
	$term=false;
	}



if ($term)
{
if (ereg("id: (GO:[0-9]+)",$buffer, $tab)) {
//Pour eviter le alt_id !!!
	if (! ereg("alt_id: (GO:[0-9]+)",$buffer,$tab))
		{
		$go_id=$tab[1];$go_id=str_replace("'", "\"",$go_id);
		}
}
if (ereg("name: ([^\"]+)",$buffer, $tab)) {$name=$tab[1];$name=str_replace("'", "\"",$name);}
if (ereg("namespace: ([^\"]+)",$buffer, $tab)) {$type=$tab[1]; $type=str_replace("'", "\"",$type);}
if (ereg("def: \"([^\"]+)\"", $buffer, $tab)) {$def=$tab[1]; $def=str_replace("\\", "",$def);$def=str_replace("\"", "",$def); $def=str_replace("'", "\"",$def);}
}

}

fclose($fd);
print "done: $count GO Annotations.<br>";

echo "<BR><b> Table GO: OK </b><BR>";
}


//Parsing of component.ontology


if ($componentGO!=0)
{

$path="./updates/GO/component.ontology";
$curnivo=0;
$curpere="";


if (!($fd=fopen ($path, "r")))
{
    echo "ERROR: The file $path cannot be opened<br>";
    include("frames_footer.php");
    return;
}
else echo "The file $path is open <br>";

while (!feof($fd))
{
$buffer = fgets($fd, 4096);
if ($buffer=="") break;
$nivo=countBlank($buffer);	//Profondeur du noeud dans l'arbre
$type=Type($buffer);		//Type de noeud (is_a ou part_of);
$go_id=getGoId($buffer);	//GOID du noeud courant


if ($type=="none")	//Detection de la racine de l'arbre
	{

	$curnivo=$nivo;
	$pere[$nivo+1]=$go_id;

	}
else if ($type!="comment")
{
if ($test=='n')
{
	//$pere=$pere[$nivo];
	pg_query($c,"begin");
	$requete="insert into \"GO_CHILD_OF\" (\"GO_ID\",\"CHILD_OF\",\"LINK_TYPE\") values ('$go_id','".$pere[$nivo]."','$type')";
	$stmt3=pg_query($c,$requete) or die("ECRRERUIRIUR".pg_last_error($c));
	pg_query($c,"commit");
	$pere[$nivo+1]=$go_id;
}
else
{
print "COURANT:".$go_id;
print " A POUR PERE: ".$pere[$nivo]."<br>";
$pere[$nivo+1]=$go_id;
}

}

}
fclose($fd);
print "done: GO component.<br>";
}


// Parsing of function.ontology


if ($functionGO!=0)
{
$path="./updates/GO/function.ontology";
$curnivo=0;
$curpere="";


if (!($fd=fopen ($path, "r")))
{
    echo "ERROR: The file $path cannot be opened<br>";
    include("frames_footer.php");
    return;
}
else echo "The file $path is open <br>";

while (!feof($fd))
{
$buffer = fgets($fd, 4096);
if ($buffer=="") break;
$nivo=countBlank($buffer);	//Profondeur du noeud dans l'arbre
$type=Type($buffer);		//Type de noeud (is_a ou part_of);
$go_id=getGoId($buffer);	//GOID du noeud courant


if ($type=="none")	//Detection de la racine de l'arbre
	{

	$curnivo=$nivo;
	$pere[$nivo+1]=$go_id;

	}
else if ($type!="comment")
{
if ($test=='n')
{
	//$pere=$pere[$nivo];
	pg_query($c,"begin");
	$requete="insert into \"GO_CHILD_OF\" (\"GO_ID\",\"CHILD_OF\",\"LINK_TYPE\") values ('$go_id','".$pere[$nivo]."','$type')";
	$stmt3=pg_query($c,$requete) or die("ECRRERUIRIUR".pg_last_error($c));
	pg_query($c,"commit");
	$pere[$nivo+1]=$go_id;
}
else
{
print "COURANT:".$go_id;
print " A POUR PERE: ".$pere[$nivo]."<br>";
$pere[$nivo+1]=$go_id;
}

}

}
fclose($fd);
print "done: GO function.<br>";
}

// Parsing of process.ontology

if ($processGO!=0)
{
$path="./updates/GO/process.ontology";
$curnivo=0;
$curpere="";


if (!($fd=fopen ($path, "r")))
{
    echo "ERROR: The file $path cannot be opened<br>";
    include("frames_footer.php");
    return;
}
else echo "The file $path is open <br>";

while (!feof($fd))
{
$buffer = fgets($fd, 4096);
if ($buffer=="") break;
$nivo=countBlank($buffer);	//Profondeur du noeud dans l'arbre
$type=Type($buffer);		//Type de noeud (is_a ou part_of);
$go_id=getGoId($buffer);	//GOID du noeud courant


if ($type=="none")	//Detection de la racine de l'arbre
	{

	$curnivo=$nivo;
	$pere[$nivo+1]=$go_id;

	}
else if ($type!="comment")
{
if ($test=='n')
{
	//$pere=$pere[$nivo];
	pg_query($c,"begin");
	$requete="insert into \"GO_CHILD_OF\" (\"GO_ID\",\"CHILD_OF\",\"LINK_TYPE\") values ('$go_id','".$pere[$nivo]."','$type')";
	$stmt3=pg_query($c,$requete) or die("ERREUR".pg_last_error($c));
	pg_query($c,"commit");
	$pere[$nivo+1]=$go_id;
}
else
{
print "COURANT:".$go_id;
print " A POUR PERE: ".$pere[$nivo]."<br>";
$pere[$nivo+1]=$go_id;
}

}

}
fclose($fd);
print "done: GO process.<br>";
}


//Look for orphan

//$requete="SELECT \"GO_ID\" from \"GO_DESCRIPTION\" where \"GO_ID\" not in (select \"GO_ID\" from \"GO\")";
$requete="(SELECT \"GO_ID\" from \"GO_DESCRIPTION\") EXCEPT (select \"GO_ID\" from \"GO\")";

if ($test=='n')
{

	$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));

	/*Rajouter le test d'intégrité*/
	/**/
	
	$cmpt=0;
	echo "<br>--------------------Orphan Go-------------------<br>";
	while ($row=pg_fetch_array($stmt))
	{
		$GO_id=$row["GO_ID"];
		print "$GO_id<br>";
		$cmpt++;
		$requete="DELETE from \"GO_DESCRIPTION\" where \"GO_ID\"='$GO_id'";
		pg_query($c,"begin");
		$stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
        	pg_query($c,"commit");

		//ocifreestatement($stmt1);
	}
	if ($cmpt<=0)
	{
		echo "No orphan GO<br>";
	}
	print "Orphan(s): ".$cmpt."<br>";

}


//reactivate constraints

$requete="ALTER TABLE \"GO_DESCRIPTION\" ADD CONSTRAINT \"GO_DESCRIPTIO_FK\" FOREIGN KEY (\"GO_ID\") REFERENCES \"GO\" (\"GO_ID\")";

if ($test=='n')
{
pg_query($c,"begin");
	$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
pg_query($c,"commit");

	//ocifreestatement($stmt);
}






print "<br><strong>Update Done</strong>";






?>


<?php
include("frames_footer.php");
?>