<?php
# $Id: webVersion.php,v 1.3 2009/07/01 08:13:18 Jian Exp $
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# *                                                                           *
# *   File....: webVersion.php                                                *
# *   Name....: web application Page                                          *
# *   Author..: Jian Li                                                       *
# *   Copyright by Author, All rights reserved                                *
# *                                                                           *
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
session_start();
include("nav.php");
error_reporting(E_ALL);

########################### global variables ##########################################

$wwwPath="modelmage";
$modelPath = "/var/www/modelmage/modelMaGePHP";
$sbmlPath = "/var/www/modelmage/SBMLs";
$LD_LIBRARY_PATH = "/usr/lib";
$PYTHONPATH = "PYTHONPATH=/var/www/modelmage/python/lib/python2.5/site-packages:/var/www/modelmage/python/lib/python2.6/site-packages:/usr/lib/python2.6/dist-packages".":".$sbmlPath;
$outputPathName = "";
$ndatafiles = 0;
$discriminate = 0;
$specfile = 0;

htmlHead("web");

########################### main function #######################################

echo " <div id='content'>";
if(!isset($_POST['Upload']) and !isset($_POST['generate']) and !isset($_POST['generateFit']) and !isset($_POST['UploadData']) and !isset($_POST['UploadSpec'])){
    echo "<h3><i>modelMaGe</i> web interface (preliminary)</h3>";
    echo "This web interface is designed only for testing <i>modelMaGe</i>.<br />
	    Please download and install <i>modelMaGe</i> on your local machine,<br />
	    in case you plan to generate large number of files.<br />
	    Especially, the 'Generate+Fit'-option should be used only<br />
	    for a small number of models.<p>
	    This service only runs smoothly with Firefox, <br />
	    whereas with Internet Explorer we experienced some problems.<p>
    ";

    echo "<h4><i>modelMaGe</i> specifications:  </h4>";  
    uploadFormular();
    echo "<br /><b>Note</b>: In case you upload a <i>Copasi</i>-file, with a defined parameter estimation task,<br />
         the corresponding data file should be defined to be loacted in the same directory as the model file.";

}
elseif (isset($_POST['Upload']) and !isset($_POST['UploadSpec'])){
    $offerDataUpload = uploading();
    if ($offerDataUpload == 1){
        uploadFormularData();	
    }
    generateFormular();
}
elseif (isset($_POST['UploadData']) and !isset($_POST['UploadSpec'])){
    $outputPathName = showResult2();
    transferData();
    generateFormular();
}
elseif (isset($_POST['UploadSpec']) and !isset($_POST['generate']) and !isset($_POST['generateFit'])) {
	$outputPathName = showResult2();
	transferSpec();
	generateFormular();
}
elseif (isset($_POST['generateFit'])){
	generateFit();
}
elseif (isset($_POST['generate'])){
	generate();
}
echo " </div>";    
footer('webVersion.php');


################################### function definitions #########################################


function getTime(){
    $timestamp = time();
    $datum = date("Y.m.d",$timestamp);
    $uhrzeit = date("H:i",$timestamp);
    #echo $datum," - ",$uhrzeit," Uhr";
    return $datum."-".$uhrzeit."-";

}

function uploadFormular(){
    echo "
	  <form id='uploadMaster' enctype='multipart/form-data' action='webVersion.php' method='POST'>  
            <a>Upload SBML or Copasi master model </a><br>
	    <INPUT NAME='mastermodel' TYPE='file'>
            <input type='submit' name='Upload' value='upload'>
         </form>
          ";
}

function uploading(){
    global $modelPath, $sbmlPath, $LD_LIBRARY_PATH, $PYTHONPATH, $ndatafiles;
    putenv('HOME='.$sbmlPath);
    putenv('LD_LIBRARY_PATH='.$LD_LIBRARY_PATH);
    putenv('PYTHONPATH='.$PYTHONPATH);
    $outputResult = 0;
    $b = 0;
    #$server = $_SERVER['DOCUMENT_ROOT'];     
    #$currentDir = getcwd();
    #echo "the dir: $currentDir <p>";
    $filename = $_FILES['mastermodel']['name'];
    #$type = $_FILES['mastermodel']['type'];
    #$tmpName = $_FILES['mastermodel']['tmp_name']; 
    $jobTime = getTime();
    $_SESSION['jobTime'] = $jobTime;
    $offerDataUpload = 0;
    if (preg_match('/\.cps$/',$filename)){
	$outputPathName = $sbmlPath."/".$jobTime."job.cps";
	$offerDataUpload = 1;
    }else{
    	$outputPathName = $sbmlPath."/".$jobTime."job.xml"; 
    }
    #copy ( $sbmlfile, "$modelPath/xxx.xml") or die ("Couldn't copy");
    $result = move_uploaded_file($_FILES['mastermodel']['tmp_name'], $outputPathName);
    if ($result == 1) 
               echo "<p>Uploaded file: <font size=+1>$filename</font><p>";
    else 
               echo "<p>There was a problem by uploading $filename.</p>";
    if ($offerDataUpload == 1){
		## for check data file
		$modelCommand = "python $modelPath/modelmage.py -e $outputPathName";  
		#echo $modelCommand;
		exec($modelCommand, $outputResult, $b);
		if ($b == 0) { # if everything ok
			# echo "b : $b <p>";
			$length = count($outputResult);
			#echo "length: $length <p>";
			$ndatafiles = $length-2;
			#echo "ndatafiles: $ndatafiles <p>";
			#$tt = $outputResult[$length-1];
			#echo "$tt <p>";
			if ( $outputResult[0] == " with no defined experimental data </p>"){
				$offerDataUpload = 0;
			}
		    ## producing the master model and the graph
		    $modelCommand = "python $modelPath/modelmage.py -w $outputPathName"; 
		    #unset($outputResult);
		    exec($modelCommand, $outputResult, $b);
		    showResult($outputPathName, $outputResult);		
		    return $offerDataUpload;	
		}
	    else {
	        echo "<p>Output: $outputResult</p>";
		    echo "
			    There was a problem executing $modelCommand<p>.
			    Please refer to the documentation
			    or send an email to admin<img src='images/atsign.gif' width=15 align='top' alt='at'>modelmage.org</p>.";
		}
    }
}

function showResult($outputPathName, $outputResult){
    global $sbmlPath;	
    ### open file for save result ### 
    $tmpFile = $sbmlPath."/".$_SESSION['jobTime']."a.text";
    if(file_exists($tmpFile)){
	unlink($tmpFile);
    }
    $fp = fopen($tmpFile,'w') or die("can't open file");		
    fwrite($fp, $outputPathName."<jian>");     
    foreach ( $outputResult as $ele){
    	echo "$ele";
		fwrite($fp, $ele);
    }
    fclose($fp);
}

function showResult2(){
    global $sbmlPath;
    $tmpFile = $sbmlPath."/".$_SESSION['jobTime']."a.text";
    $fp = fopen($tmpFile, 'r') or die("can't open file");
    $content = fread($fp, filesize($tmpFile));
    fclose($fp);
    $parts = split('<jian>', $content);
    echo $parts[1];
    return $parts[0];	
}

function getOutPutPathName(){
    global $sbmlPath;
    $tmpFile = $sbmlPath."/".$_SESSION['jobTime']."a.text"; 
    $fp = fopen($tmpFile, 'r') or die("can't open file");
    $content = fread($fp, filesize($tmpFile));
    fclose($fp);
    $parts = split('<jian>', $content);
    #echo $parts[1];
    return $parts[0];	
}

function generate(){
    global $modelPath, $sbmlPath, $LD_LIBRARY_PATH, $PYTHONPATH, $outputPathName, $specfile;
    putenv('HOME='.$sbmlPath);
    putenv('LD_LIBRARY_PATH='.$LD_LIBRARY_PATH);
    putenv('PYTHONPATH='.$PYTHONPATH);
    $outputResult = 0;
    $b = 0;
    $outputPathName = $_POST['outputPathName'];
    if ($outputPathName == ''){
        $outputPathName = getOutPutPathName();
    }
    if (isset($_POST['specfile'])){
    	$specfile = $_POST['specfile'];
    	#echo "spec: $specfile";
		$filename = $sbmlPath."/".$specfile;
		$modelCommand = "python $modelPath/modelmage.py  -w -i $filename $outputPathName";
    }
    else {
		$species_Id = $_POST['species_Id'];	
		$kinetics_Id = $_POST['kinetics_Id'];
		#echo "<p> outputPathName: $outputPathName</p>";
		#echo "species_id: ".$species_Id."<p>";
		#echo "kinetics_id: ".$kinetics_Id."<p>";
		if($species_Id != ''){
			$modelCommand = "python $modelPath/modelmage.py -r '$species_Id' $outputPathName -w";		
			#echo "enter species<p>";
		}
		if($kinetics_Id != ''){
			#echo "enter kinetics<p>";
			$modelCommand = "python $modelPath/modelmage.py -k '$kinetics_Id' $outputPathName -w";
		}
		if($kinetics_Id != '' & $species_Id != ''){
			#echo "enter both<p>";
			$modelCommand = "python $modelPath/modelmage.py -r '$species_Id' -k '$kinetics_Id' $outputPathName -w";
		}
		if($kinetics_Id == '' & $species_Id == '')
			$modelCommand = "python $modelPath/modelmage.py $outputPathName -w";
	}
	exec($modelCommand, $outputResult, $b);
	if ($b > 0) {
		errorMessage($modelCommand,$outputResult);
	}
	else {
		foreach ($outputResult as $ele)
			echo "$ele";
	}
	unset($_SESSION['jobTime']);
}

function generateFit(){
    global $modelPath, $sbmlPath, $LD_LIBRARY_PATH, $PYTHONPATH, $outputPathName, $discriminate, $specfile;
    putenv('HOME='.$sbmlPath);
    putenv('LD_LIBRARY_PATH='.$LD_LIBRARY_PATH);
    putenv('PYTHONPATH='.$PYTHONPATH);
    $outputResult = 0;
    $b = 0;
    $outputPathName = $_POST['outputPathName'];
    if ($outputPathName == ''){
        $outputPathName = getOutPutPathName();
    }
    $discriminate = $_POST['discriminate'];
    #echo "dis: $discriminate";
    if ($discriminate == 1){
	    if (isset($_POST['specfile'])){
	    	$specfile = $_POST['specfile'];
	    	#echo "spec: $specfile";
			$filename = $sbmlPath."/".$specfile;
	    	$modelCommand = "python $modelPath/modelmage.py -p -w -i $filename $outputPathName";
	    }
	    else {
			$species_Id = $_POST['species_Id'];	
			$kinetics_Id = $_POST['kinetics_Id'];
			if($species_Id != ''){
				$modelCommand = "python $modelPath/modelmage.py -p -w -r '$species_Id' $outputPathName";		
				#echo "enter species<p>";
			}
			if($kinetics_Id != ''){
				#echo "enter kinetics<p>";
				$modelCommand = "python $modelPath/modelmage.py -p -w -k '$kinetics_Id' $outputPathName";
			}
			if($kinetics_Id != '' & $species_Id != ''){
				#echo "enter both<p>";
				$modelCommand = "python $modelPath/modelmage.py -p -w -r '$species_Id' -k '$kinetics_Id' $outputPathName";
			}
			if($kinetics_Id == '' & $species_Id == ''){
				$modelCommand = "python $modelPath/modelmage.py -p -w $outputPathName";
			}
		}
		exec($modelCommand, $outputResult, $b);
		if ($b > 0) {
				errorMessage($modelCommand,$outputResult);
		}
		else {
			foreach ($outputResult as $ele){
				echo "$ele";
			}	
		}
    }
    else{
		print "<h3>Sorry, you haven't uploaded corresponding exprimental data for the parameter estimation task</h3>";
	}
    unset($_SESSION['jobTime']);
}

function errorMessage($modelCommand,$outputResult){

    echo "There was a problem executing $modelCommand.<br>";
	$length = count($outputResult);
	#echo "length: $length <p>";
	if ($length > 0) {
		foreach ($outputResult as $ele)	
			echo "$ele";
		echo "<p>If you have problems interpreting this error message,<br>
	    please refer to the documentation
	    or send an email to admin<img src='images/atsign.gif' width=15 align='top' alt='at'>modelmage.org</p>.";
    }
    else 
	echo "<p>No output was generated. <br>
	    Please refer to the documentation
	    or send an email to admin<img src='images/atsign.gif' width=15 align='top' alt='at'>modelmage.org.<p>";
}

function transferSpec(){
    global $sbmlPath, $specfile, $discriminate;
    $discriminate = $_POST['discriminate'];
    #echo "dis: $discriminate";
	$specfile = $_FILES['SpecData']['name'];
	$result = move_uploaded_file($_FILES['SpecData']['tmp_name'], $sbmlPath."/".$specfile);
	if ($result == 1)
		echo "<p>Uploaded file:  <font size=+1>$specfile</font></p>";
	else 
		echo "<p>There was a problem uploading the spec-file '$specfile'.</p>";
}

function transferData(){
    global $sbmlPath, $discriminate;
    while(list($key,$value) = each($_FILES['expData']['name'])){
    	if(!empty($value)){   // this will check if any blank field is entered
	        $filename = $value;    // filename stores the value
		    $result = move_uploaded_file($_FILES['expData']['tmp_name'][$key], $sbmlPath."/".$filename);
		    if ($result == 1) {
				$discriminate = 1; 
				echo "<p>Uploaded file:  <font size=+1>$filename</font></p>";
			}
			else {
				$discriminate = 0;
				echo "<p>There was a problem uploading $filename.</p>";
			}
        }
    }
}

function uploadFormularData(){	
    global $outputPathName, $ndatafiles;
    echo "<form id='uploadData' enctype='multipart/form-data' action='webVersion.php' method='POST'>"; 
    for ($i=1; $i<=$ndatafiles; $i++) {
        echo "
            <a>Upload experimental data file no. $i</a><br/>
	    <input name='expData[]' type='file'><br/>
          ";
    }
    echo "<input type='submit' name='UploadData' value='upload'><br />
         </form><br />";
}

function generateFormular(){
	global $outputPathName, $discriminate, $specfile;
#   echo "<table width='100%' height='100%' border='0' cellspacing='7' cellpadding='0'> ";
	#echo "dis: $discriminate";
	echo "<table  border='0' cellspacing='7' cellpadding='0'> ";
	echo "<tr valign=top><td>";
	if (!isset($_POST['UploadSpec'])){
	echo "
		<form id='uploadSpec' enctype='multipart/form-data' action='webVersion.php' method='POST'>
			<a>Upload generate-specifications as a file</a><br />
			<input name='SpecData' type='file'><br />
			<input type='submit' name='UploadSpec' value='upload'>
			<input type='hidden' name='discriminate' value=$discriminate>
			<input type='hidden' name='outputPathName' value=$outputPathName>
		</form>
		<form id='rmSpeciesKinetics' action='webVersion.php' method='POST'>
			<a><b> OR </b></a><br />
			<a> specify them here:</a><br />
			<a>Remove </a><br />
			<input type='text' name='species_Id' value=''><br>	
			<a>Kinetics </a><br />	
			<input type='text' name='kinetics_Id' value=''><br>
			</td<td></td></tr>
			<tr><td><input type='submit' name='generate' value='Generate'>
			<a><b> OR </b></a><br /></td>
			<td><input type='submit' name='generateFit' value='Generate + Fit'></td></tr>
			<tr><td></td><td><a> After pressing this button the interface <br />
			might take while to return.<br />
			Therefore, if you are using a proxy with a 'timeout-option',<br />
			you might not get any results at all.<br/>
			In this case, please use the stand-alone version. <a/></td>
			<input type='hidden' name='outputPathName' value=$outputPathName>
			<input type='hidden' name='discriminate' value=$discriminate>
		</form></tr></table>";
	}
	if (isset($_POST['UploadSpec'])){
	echo "
		<form id='rmSpeciesKinetics' action='webVersion.php' method='POST'>
			<tr><td><input type='submit' name='generate' value='Generate'>
			<a><b> OR </b></a><br /></td>
			<td><input type='submit' name='generateFit' value='Generate + Fit'></td></tr>
			<tr><td></td><td><a> After pressing this button the interface <br />
			might take while to return.<br />
			Therefore, if you are using a proxy with a 'timeout-option',<br />
			you might not get any results at all.<br/>
			In this case, please use the stand-alone version. <a/></td>
			<input type='hidden' name='UploadSpec' value='upload'>
			<input type='hidden' name='outputPathName' value=$outputPathName>
			<input type='hidden' name='discriminate' value=$discriminate>
			<input type='hidden' name='specfile' value=$specfile>
		</form></tr></table>";
	}
}

?>
