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

<?php

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>";


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

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


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);
}

//Download of the file XML
if ($download=='y')
{
    $ftp_server="ftp.ebi.ac.uk";
    $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>";
    }
    if ((!file_exists("./updates/interpro/interpro.xml"))
            or (ftp_mdtm ($conn_id,"./pub/databases/interpro/interpro.xml.gz") > filemtime("./updates/interpro/interpro.xml")))
    {
        //echo "The file does not exist so I download it <br>";
        $destination_file="./updates/interpro/interpro.xml.gz";
        $source_file="./pub/databases/interpro/interpro.xml.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>ERROR: Can't download the file $source_file from $ftp_server<br>";
                $echec=0;
                $cmpt++;
            } 
            else 
            {
                echo "<br>Download of $source_file from $ftp_server complete <br>";
                $echec=1;
                break;      
            }
        }
        uncompress("./updates/interpro/interpro.xml.gz", "./updates/interpro/interpro.xml");
        if(filesize("./updates/interpro/interpro.xml")<=0)
        {
            echo "Bad uncompressed GZ file";
            include("frames_footer.php");
            return;
        }
        else
        {
            unlink("./updates/interpro/interpro.xml.gz");
        }
       
	}
    if ((!file_exists("./updates/interpro/interpro.dtd"))
            or (ftp_mdtm ($conn_id,"./pub/databases/interpro/interpro.dtd") > filemtime("./updates/interpro/interpro.dtd")))
    {
        //echo "The file does not exist so I download it <br>";
       	$destination_file="./updates/interpro/interpro.dtd";
        $source_file="./pub/databases/interpro/interpro.dtd";
        $cmpt=0;
        $echec=0;
       	while(($cmpt<3)||($echec!=0))
        {
            $upload = ftp_get($conn_id, $destination_file , $source_file , FTP_BINARY); 
            if (!$upload) 
            { 
                echo "<br>ERROR: Can't download the file $source_file from $ftp_server<br>";
                $echec=0;
                $cmpt++;
            } 
           	else 
            {
              	echo "<br>Download of $source_file from $ftp_server complete <br>";
             	$echec=1;
            	break;      
            }
        }
        
    }
    $path="./updates/interpro/interpro.xml";
}
 
if ($test =='n')
{

    $requete="ALTER TABLE \"IP_DESCRIPTION\" drop constraint \"IP_ID_FK\"";
    
pg_query($c,"begin");
$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
pg_query($c,"commit");

    //echo "$requete : Done <br>"; 
    
pg_query($c,"begin");
$requete= "delete from \"IP_CONTAINS\"";
    $stmt3 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
pg_query($c,"commit");

pg_query($c,"begin");
$requete= "delete from \"IP_CHILD_OF\"";
    $stmt2 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
pg_query($c,"commit");

pg_query($c,"begin");
$requete= "delete from \"INTERPRO\"";
    $stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
pg_query($c,"commit");

}

$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>";
}
while(!feof($fd))
{
    $buffer = fgets($fd, 4096);
    if (ereg("interpro id=\"(IPR[0-9]+)\" type=\"([^\"]+)\" short_name=\"([^\"]+)\"",$buffer, $tab))
    {
        ++$count;
        $ipr=$tab[1];
        $type=$tab[2];
        $short=$tab[3];
        
        $buffer = fgets($fd, 4096);
        if (ereg("<name>([^<]+)<\/name>",$buffer,$res))
        {
            $name = $res[1];
        }
        
        $ipr=str_replace("'", "\"",$ipr);
        $type=str_replace("'", "\"",$type);
        $short=str_replace("'", "\"",$short);
        $name=str_replace("'", "\"",$name);
        //echo"ipr : $ipr , type : $type , short : $short , name : $name<br>";
        
        if ((strlen($ipr)==0)or(strlen($type)==0) or (strlen($short)==0) or (strlen($name)==0)) 
        {
            echo"<br>ERROR: Missing parameter <br>";
            include("frames_footer.php");
            return;
        }
        
        if ($test == 'n')
        {
		pg_query($c,"begin");
            $requete= "INSERT INTO \"INTERPRO\" (\"IP_ID\", \"NAME\", \"TYPE\", \"SHORT_NAME\") values ( '$ipr', '$name', '$type', '$short' )";
            $stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
            
		pg_query($c,"commit");
              
            
            //ocifreestatement($stmt1);           
        }
    }
    if (ereg("<contains>", $buffer))
    {
        //echo"contains: ";
        while (($buffer = fgets($fd, 4096))&&!ereg("<\/contains>", $buffer))
        {
            if(ereg("<rel_ref ipr_ref=\"(IPR[^\"]+)\"", $buffer, $tmp))
            {
                $contains=$tmp[1];
                //echo" $contains ";
                
                if ($test =='n')
                {
                   pg_query($c,"begin");   
		   $requete= "INSERT INTO \"IP_CONTAINS\" (\"IP_ID\", \"CONTAINS\") values ( '$ipr', '$contains' )";
                   pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		   pg_query($c,"commit");   
		 //   ocifreestatement($stmt1);           
                    
                }
            }
        }
        //echo"<br>";
    }
    
    if (ereg("<parent_list>",$buffer))
    {
        $a=0;
        //echo"parent : ";
        while (($buffer = fgets($fd, 4096))&&(!ereg("<\/parent_list>", $buffer)))
        {
            if(ereg("<rel_ref ipr_ref=\"(IPR[^\"]+)\"",$buffer, $temp))
            {
                $parent=$temp[1];
                //echo"$parent ";
                ++$a;
                
                if ($a>1)
                {
                    print "ERROR: multiple parents <br>";
                    include("frames_footer.php");
                    return;
                }
                if ($test=='n')
                {
                    pg_query($c,"begin");
		    $requete="INSERT INTO \"IP_CHILD_OF\" (\"IP_ID\", \"CHILD_OF\") values ( '$ipr', '$parent' )";
                    $stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		    pg_query($c,"commit");

                   // ocifreestatement($stmt1);
                }
            }
        }
        //echo"<br>";
    }
}
$requete="SELECT \"IP_ID\" from \"IP_DESCRIPTION\" where \"IP_ID\" not in (select \"IP_ID\" from \"INTERPRO\")";
if ($test=='n')
{
	$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
	$cmpt=0;
	echo "<br>--------------------Orphan Interpro-------------------<br>";
	while ($row=pg_fetch_array($stmt))
	{
		$interpro_id=$row["IP_ID"];
		print "$interpro_id<br>";
		$cmpt++;
		$requete="DELETE from \"IP_DESCRIPTION\" where \"IP_ID\"='$interpro_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 INTERPRO<br>";
	}
	//ocifreestatement($stmt);
}





//$requete="ALTER TABLE \"IP_DESCRIPTION\" add constraint \"IP_ID_FK\" foreign key (\"IP_ID\")";
$requete="ALTER TABLE \"IP_DESCRIPTION\" ADD CONSTRAINT \"IP_ID_FK\" FOREIGN KEY (\"IP_ID\") REFERENCES \"INTERPRO\" (\"IP_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);
}
//else "<br>(FAKE)REQUETE= $requete";

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

echo "<BR><b> OK </b><BR>";
?>

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