<?
//------------- Setup ------------------
$mysql_user = "root";
$mysql_pwd = "xxxyyyzzz";
$mysql_db = "PURE";
$mysql_host = "localhost";
//$proxy_host = "proxserv.xxx.co.jp";  
$proxy_host = ""; // Empty in case of direct internet connection 
$proxy_port = "8080"; 
$table_color ="#ffddaa";
$PubMedLink = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pubmed&term=";
//--------------Cookie -----------------------
if(isset($_POST["user"])){
	setcookie("user",$_POST["user"],0);
	$user = $_POST["user"];
}
elseif(isset($_GET["user"])){
	setcookie("user",$_GET["user"],0);
	$user = $_GET["user"];
}
else{
	$user = $_COOKIE["user"];
}
if(isset($_POST["password"])){
	setcookie("password",$_POST["password"],0);
	$password = $_POST["password"];
}
elseif(isset($_GET["password"])){
	setcookie("password",$_GET["password"],0);
	$password = $_GET["password"];
}
else{
	$password = $_COOKIE["password"];
}
//-------------- Connect DB -----------------
mysql_connect($mysql_host,$mysql_user, $mysql_pwd);
mysql_select_db($mysql_db);
//-------------- Link from Mail Alert ----------
if($daylink){
	$result = mysql_query("select * from daylink where d_id = '$daylink'");
	if(!mysql_num_rows($result)){
		print "ERROR!! No. DataID<br>\n";
		exit;
	}
	$row = mysql_fetch_array($result);
	$user = $row['d_uid'];
	setcookie("user",$user,0);
	$date = $row['d_date'];
	$result = mysql_query("select * from user where u_id = '$user'");
	$row = mysql_fetch_array($result);
	$password = $row['u_pwd'];
	setcookie("password",$password,0);
	$branch = "DispResult"; // Go to Display Results
}
//-------------------------------------------
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PURE (PubMed Recommender System)</title>
</head>
<body>
<form action = "<? print "$PHP_SELF" ?>" method = "POST" ENCTYPE="multipart/form-data">
<?
//------------- User Information Maintenance --------------
if($branch == 'New_User'){
	UserForm("","",'new');
}
elseif(!$user){ //- Login Page --
	LoginPage();
}
elseif($branch == 'EditUserInfo'){
	CheckEmptyUser($user,$password);
	UserForm($user,$password,'update');
}
elseif($branch == 'DeleteUserInfo'){
	CheckEmptyUser($user,$password);
	CheckUser($user,$password);
	$result = mysql_query("select * from user where u_id = '$user'");
	$row = mysql_fetch_array($result);
	$mail = $row['u_mail'];
	$name = $row['u_name'];
	ConfirmUserInfo($user,$name,$mail,$password,$mail_type,$pick_num,'delete');
}
elseif($branch == 'userinfo'){
	CheckEmptyUser($user,$password);
	if($type == 'new'){
		CheckNewUserID($user);
	}
	CheckEmptyMailAndName($uname,$mail);
	$uname = addslashes($uname);
	$mail = addslashes($mail);
	if($type == 'new'){
		if(mysql_query("insert into user set u_id = '$user', u_name = '$uname', u_pwd='$password',u_mail = '$mail',u_pick_num='$pick_num', u_mail_type='$mail_type'")){
			print "$user is registered\n";
		}
		else{
			print "Error!! User '$user' could not be registered\n";
		}
	}
	elseif($type == 'update' and !$confirm){
		CheckUser($user,$password);
		if($new_password1 or $new_password2){
			$password = UpdatePwd($new_password1,$new_password2);
		}
		ConfirmUserInfo($user,$uname,$mail,$password,$mail_type,$pick_num, $type);
	}
	elseif($type == 'update' and $confirm){
		if(mysql_query("update user set u_name = '$uname', u_pwd='$password',u_mail = '$mail',u_pick_num='$pick_num', u_mail_type='$mail_type' where u_id = '$user'")){
			print "$user's record is updated\n";
		}
		else{
			print "Error!! $user's record could not be updated\n";
		}
	}
	elseif($type == 'delete'){
		if(mysql_query("delete from user where u_id = '$user'")){
			print "$user's record is deleted\n";
			mysql_query("delete from interest where i_uid = '$user'");
			mysql_query("delete from hit where h_id = '$user'");
		}
		else{
			print "Error!! $user's record could not be deleted\n";
		}
	}
}
//------------------ Model Records Maintenance ---------------------
elseif($branch == 'EditModelForm'){
	EditModelForm($user);
}
elseif($branch == 'UpdateModelData'){
	if(!$confirm){
		$tmpfile = time();
		ConfirmEditData($new_pmid,$pmid,$delete,$tmpfile);
	}
	else{
		if(!$tmpfile){ // Add from daily result
			$tmpfile = time();
			CollectMedline($pmid,$tmpfile);
		}
		UpdateModelData($new,$delete,$tmpfile);
	}
}	
elseif($branch == 'AddFromDailyResult'){
	$pmid = "";
	if($AddModel){
		for($i=0;$i<count($AddModel);$i++){
			$pmid .= "$AddModel[$i] ";
		}
		$pmid = ereg_replace(" $","",$pmid);
		$tmpfile = time();
		CollectMedline($pmid,$tmpfile);
		UpdateModelData($AddModel,"",$tmpfile);
	}
	else{
		print "Error!! No records selected!!<br>";
	}
}
//------------ After Login  ---------------------------------
elseif($branch == 'Login'){
	CheckUser($user,$password);
	DispResult($user,'Latest'); # Show latest Results
}
//------------ Display Results  -----------------------------
elseif($branch == 'DispResult'){
	if($pmid){
		DispFull($pmid);
	}
	elseif($date){
		DispResult($user,$date);
	}
	else{
		DateListDisp($user);
	}
}	
//------------------- Top Page -------------------------------------
else{
	DispResult($user,'Latest');
}
//------------- End of Main routin -------------------------------
//------------- Functions ----------------------------------------
function LoginPage(){
?>
<Table Border = 0>
<TR><TD>Userid:</TD><TD><input type = 'text' name ='user'></TD></TR>
<TR><TD>Password:</TD><TD><input type = 'password' name = 'password'></TD></TR>
</table>
<input type = 'submit' name = 'branch' value = 'Login'>
<input type = 'submit' name = 'reset' value = 'Reset'><br>
<?
}
function CheckEmptyUser($user, $password){
	if(!$user){
		print "Please input user ID!<br>\n";
		exit;
	}
	elseif(!$password){
		print "Please input password!<br>\n";
		exit;
	}
}
function CheckEmptyMailAndName($uname, $mail){
	if(!$uname){
		print "Please input your name!<br>\n";
		exit;
	}
	elseif(!$mail){
		print "Please input your e-mail address!<br>\n";
		exit;
	}
}
function CheckNewUserID($user){
	$result = mysql_query("select * from user where u_id = '$user'");
	if(mysql_num_rows($result)){
		print "UserID '$user' already exists. Please use another ID\n";
		exit;
	}
}
function UserForm($user,$password,$type){
	$mail_type_list = array('Title','Title+Abstract');
	print "<Table Border = 0>\n";
	if($type == 'update'){
		$result = mysql_query("select * from user where u_id = '$user'");
		$row = mysql_fetch_array($result);
		$mail = $row['u_mail'];
		$name = $row['u_name'];
		$pick_num = $row['u_pick_num'];
		$mail_type = $row['u_mail_type'];
		print "<TR><TD>UserID:</TD><TD>$user</TD></TR>\n";
		print "<input type = 'hidden' name = 'user' value = '$user'>\n";
	}
	else{ // In case of new user
		print "<TR><TD>UserID:</TD><TD><input type = 'text' name ='user'></TD></TR>\n";
		$pick_num = 10;
	}
	print "<TR><TD>Name:</TD><TD><input type = 'text' name ='uname' value = '$name'></TD></TR>\n";
	print "<TR><TD>E-mail:</TD><TD><input type = 'text' name ='mail' value = '$mail'></TD></TR>\n";
	print "<TR><TD>Password:</TD><TD><input type = 'password' name = 'password' value = '$password'></TD></TR>\n";
	print "<TR><TD>Mail Report:</TD><TD><select name = 'mail_type'>\n";
	for($i=0;$i<count($mail_type_list);$i++){
		print "	<option value = '$mail_type_list[$i]'";
		if($mail_type_list[$i] == $mail_type){
			print " selected";
		}
		print ">$mail_type_list[$i]\n";
	}
	print "<TR><TD>Report Count:</TD><TD><input type = 'text' name ='pick_num' value = '$pick_num'></TD></TR>\n";
	print "</select></TD></TR>\n";
	if($type == 'update'){
		print "<TR><TD>New Password:</TD><TD><input type = 'password' name = 'new_password1'></TD></TR>\n";
		print "<TR><TD>New Password <br>(re-enter):</TD><TD><input type = 'password' name = 'new_password2'></TD></TR>\n";
	}
	print "</table>\n";
	print "<input type = 'submit' name = 'userinfo' value = 'Submit'><br>\n";
	print "<input type = 'hidden' name = 'type' value = '$type'>\n";
	print "<input type = 'hidden' name = 'branch' value = 'userinfo'>\n";
}
function CheckUser($user,$pwd){
	$result = mysql_query("select * from user where u_id = '$user'");
	if(!mysql_num_rows($result)){
		print "UserID '$user' is not correct.\n";
		exit;
	}
	$row = mysql_fetch_array($result);
	if($row['u_pwd'] != $pwd){
		print "Password is not correct.\n";
		exit;
	}
}
function UpdatePwd($pwd1,$pwd2){
	if($pwd1 == $pwd2){
		return $pwd1;
	}
	else{
		print "Please re-enter new password!<br>\n";
		exit;
	}
}
function ConfirmUserInfo($user,$name, $mail,$password,$mail_type, $pick_num,$type){
	if($type == 'update'){
		print "Are you sure to update this record<br>\n";
	}
	elseif($type == 'delete'){
		print "Are you sure to delete this record<br>\n";
	}
	print "<Table Border = 0>\n";
	print "<TR><TD>Userid:</TD><TD>$user</TD></TR>\n";
	print "<TR><TD>Name:</TD><TD>$name</TD></TR>\n";
	print "<TR><TD>E-mail:</TD><TD>$mail</TD></TR>\n";
	print "<TR><TD>Mail Report:</TD><TD>$mail_type</TD></TR>\n";
	print "<TR><TD>Report Count:</TD><TD>$pick_num</TD></TR>\n";
	print "</table>\n";
	print "<input type = 'submit' name = 'submit' value = 'Submit'><br>\n";
	print "<input type = 'hidden' name = 'type' value = '$type'>\n";
	print "<input type = 'hidden' name = 'user' value = '$user'>\n";
	print "<input type = 'hidden' name = 'mail' value = '$mail'>\n";
	print "<input type = 'hidden' name = 'uname' value = '$name'>\n";
	print "<input type = 'hidden' name = 'password' value = '$password'>\n";
	print "<input type = 'hidden' name = 'mail_type' value = '$mail_type'>\n";
	print "<input type = 'hidden' name = 'pick_num' value = '$pick_num'>\n";
	print "<input type = 'hidden' name = 'branch' value = 'userinfo'>\n";
	print "<input type = 'hidden' name = 'confirm' value = '1'>\n";
}
function EditModelForm($user){
	global $table_color;
	print "New PubMed IDs<br>\n";
	print "<textarea name = 'new_pmid' cols=10 rows = 5></textarea><br>\n";
	$result = mysql_query("select * from interest where i_uid = '$user' order by i_date desc");
	if(mysql_num_rows($result)){
		print "Delete Registered IDs<br>\n";
		print "<TABLE BORDER = '1'>\n";
		print "<TR BGCOLOR = '$table_color'><TD>Delete</TD><TD>Reg. Date</TD><TD>PMID</TD><TD>Title</TD></TR>\n";
		$c=0;
		while ($row = mysql_fetch_array($result)){
			print "<TR><TD><input type = 'checkbox' name = 'delete[$c]'></TD>\n";
			print "<TD>$row[i_date]</TD>\n";
			print "<TD>$row[i_pmid]</TD><TD>$row[i_title]</TD></TR>\n";
			print "<input type = 'hidden' name = 'pmid[$c]' value = '$row[i_pmid]'>\n";
			$c++;
		}
		print "</TABLE><br>\n";
	}
	print "<input type = 'submit' value = 'submit'><br>\n";
	print "<input type = 'hidden' name = 'branch' value = 'UpdateModelData'>\n";
}
function ConfirmEditData($new_pmid,$pmid,$delete,$tmpfile){
	global $table_color;
	print "Are you sure to update these records?<br><br>\n";
	$new_pmid = trim($new_pmid);
	if($new_pmid){
		CollectMedline($new_pmid,$tmpfile);
		$title = GetTitleFromMedline($tmpfile);
		$ary = split("[^0-9]{1,}",$new_pmid);
		print "Add as Preferred Articles<br>\n";
		print "<table border = '1'>\n";
		print "<TR BGCOLOR = '$table_color'><TD>PMID</TD><TD>TITLE</TD></TR>";
		for($i=0;$i<count($ary);$i++){
			if(!$title[$ary[$i]]){
				print "<TR><TD>$ary[$i]</TD><TD>No Record??</TD></TR>\n";
			}
			else{
				print "<TR><TD>$ary[$i]</TD><TD><PRE>".$title[$ary[$i]]."</PRE></TD><TR>\n";
				print "<input type = 'hidden' name = 'new[]' value = '$ary[$i]'>\n";
			}
		}
		print "</table><br>\n";
	}
	$del_flag = 0;
	for($i=0;$i<count($pmid);$i++){
		if($delete[$i]){
			if(!$del_flag){
				print "Delete from Preferred Articles<br>\n";
				print "<table border = '1'>\n";
				print "<TR BGCOLOR='$table_color'><TD>PMID</TD><TD>TITLE</TD></TR>";
				$del_flag = 1;
			}
			$result = mysql_query("select i_title from interest where i_pmid = '$pmid[$i]'");
			$row = mysql_fetch_array($result);
			print "<TR><TD>$pmid[$i]</TD><TD><PRE>$row[i_title]</PRE></TD><br>\n";
			print "<input type = 'hidden' name = 'delete[]' value = '$pmid[$i]'>\n";
		}
	}
	print "</table><br>\n";
	print "<input type = 'submit' name = 'confirm' value = 'Update'>\n";
	print "<input type = 'hidden' name = 'branch' value = 'UpdateModelData'>\n";
	print "<input type = 'hidden' name = 'tmpfile' value = '$tmpfile'>\n";
}
function GetTitleFromMedline($file){
	$fp = fopen("temp/$file","r");
	$title = array();
	while ($buf = fgets($fp,4096)){
		if(ereg("^PMID- {1,}([0-9]{1,})",$buf,$ary)){
			$pmid = $ary[1];
		}
		elseif(ereg("^TI {1,}- {1,}(.{1,})",$buf,$ary)){
			$text = $ary[1];
			$flag = 1;
		}
		elseif(ereg("^[A-Z]{1,}",$buf,$ary)){
			$flag = 0;
			if($pmid and $text){
				$title[$pmid] = $text;
				$pmid = "";
				$text = "";
			}
		}
		elseif($flag){
			$buf = ereg_replace("^ {1,}","",$buf);
			$text .= $buf;
		}
	}
	return $title;
}
function GetMedlineByID($pmids,$tmpfile){
	global $proxy_host, $proxy_port;
	$utils = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";
	$db  = "Pubmed";
	$report = "MEDLINE";
	$query  = $pmids."[UID]";
	$esearch = "$utils/esearch.fcgi?db=$db&retmax=1&usehistory=y&term=$query";
	if($proxy_host){
		$abs_url = "http://$proxy_host:$proxy_port$esearch";

		# now we build our query
		$query = "GET $esearch HTTP/1.0\r\n".
			"Host: $proxy_host:$proxy_port\r\n".
			"User-agent: PHP/class http 0.1\r\n".
			"\r\n";

		# open a connection to the server
		$fp = fsockopen($proxy_host, $proxy_port);
	}
	else{
		$fp = fopen($esearch,"r");
	}

	# if the connection failed, return false
	if(!$fp) {
		print "URL Open Error";
	}
	else {
		// send our query
		fputs($fp, $query);
		// discard the HTTP header
		$buffer = "";
		while(!feof($fp)){
			$buffer .= trim(fgets($fp, 4096));
		}
	}
	ereg("<Count>([0-9]{1,})</Count>.{0,}<QueryKey>([0-9]{1,})</QueryKey>.{0,}<WebEnv>([^ ]{1,})</WebEnv>",$buffer,$ary);
	$Count    = $ary[1];
	$QueryKey = $ary[2];
	$WebEnv   = $ary[3];
	if(!$Count){
		print "No Records !!??<br>\n";
		exit;
	}
	$retstart;
	$retmax = $Count;
	#---------- Download and Save Records -------------
	$efetch = "$utils/efetch.fcgi?rettype=$report&retmode=text&retstart=$retstart&retmax=$retmax&db=$db&query_key=$QueryKey&WebEnv=$WebEnv";
	if($proxy_host){
		$abs_url = "http://$proxy_host:$proxy_port$efetch";
		$query = "GET $efetch HTTP/1.0\r\n".
			"Host: $proxy_host:$proxy_port\r\n".
			"User-agent: PHP/class http 0.1\r\n".
			"\r\n";
		$fp = fsockopen($proxy_host, $proxy_port);
	}
	else{
		$fp = fopen($efetch,"r");
	}
	if(!$fp) {
		print "URL Open Error";
	}
	else {
		fputs($fp, $query);
		$flag = 0;
		$fpw = fopen("temp/$tmpfile","w");
		while(!feof($fp)){
			$buffer = fgets($fp, 4096);
			if(ereg("^PMID",$buffer)){
				$flag = 1;
			}
			if($flag){
				fwrite($fpw,$buffer);
			}
		}
		fclose($fpw);
	}
}
function UpdateModelData($new,$delete,$tmpfile){
	global $user;
	if($new){
		$title = GetTitleFromMedline($tmpfile);
		$text = GetFullTextFromMedline($tmpfile);
		for($i=0;$i<count($new);$i++){
			$title[$new[$i]] = addslashes($title[$new[$i]]);
			$text[$new[$i]] = addslashes($text[$new[$i]]);
			$sql = "insert into interest set i_pmid = '$new[$i]',i_title = '".$title[$new[$i]]."',i_uid = '$user', i_full='".$text[$new[$i]]."', i_date=curdate()";
			if(mysql_query("$sql")){
				print "$new[$i] was registered<br>\n";
			}
			else{
				print "ERROR!! $new[$i] could not be registered<br>\n";
				//print "<PRE>$sql</PRE>\n";
			}
			$sql = "update user set u_para_update=curdate() where u_id = '$user'";
			mysql_query("$sql");
		}
		unlink("temp/$tmpfile");
	}
	if($delete){
		for($i=0;$i<count($delete);$i++){
			if(mysql_query("delete from interest where i_pmid = '$delete[$i]'AND i_uid = '$user'")){
				print "$delete[$i] is deleted.<br>\n";
			}
			else{
				print "ERROR!! $delete[$i] could not be deleted.<br>\n";
			}
			$sql = "update user set u_para_update=curdate() where u_id = '$user'";
			mysql_query("$sql");
		}
	}
}
function GetFullTextFromMedline($file){
	$fp = fopen("temp/$file","r");
	$full_text = array();
	$text = ""; 
	while ($buf = fgets($fp,4096)){
		$text .= $buf;
		if(ereg("^PMID- {1,}([0-9]{1,})",$buf,$ary)){
			$pmid = $ary[1];
		}
		elseif(ereg("^\n",$buf) and $pmid){
			$full_text[$pmid] = $text;
			$pmid = "";
			$text = "";
		}
	}
	return $full_text;
}
function DispResult($user,$date){
	global $table_color,$PHP_SELF;
	if($date == 'Latest'){
		$result = mysql_query("select h_date from hit where h_uid='$user' order by h_date desc");
		$row = mysql_fetch_array($result);
		$date = $row['h_date'];
	}
	if(!$date){
		print "NO previously recommended articles<br>\n";
	}
	else{
		print "<H2>Recommended articles in $date</H2>\n";
		$result = mysql_query("select * from hit where h_uid='$user' and h_date='$date' order by h_score desc");
		print "<TABLE BORDER = '1'>\n";
		print "<TR BGCOLOR='$table_color'><TD>&nbsp;</TD><TD>PMID</TD><TD>Score</TD><TD>Title</TD></TR>\n";
		$c = 0;
		while ($row = mysql_fetch_array($result)){
			print "<TR><TD><input type = 'checkbox' name = 'AddModel[]' value = '$row[h_pmid]'></TD>\n";
			print "<TD><a href= '$PHP_SELF?branch=DispResult&pmid=$row[h_pmid]' target='abstract'>$row[h_pmid]</TD>\n";
			print "<TD>$row[h_score]</TD>\n";
			$tmpfile = time();
			CollectMedline($row['h_pmid'],$tmpfile);
			$title = GetTitleFromMedline($tmpfile);
			print "<TD>".$title[$row['h_pmid']]."</TD></TR>\n";
			unlink("temp/$tmpfile");
		}
		print "</TABLE>\n";
		print "<input type = 'submit' name = 'submit' value = 'Add_to_preferred_articles'>\n";
		print "<input type = 'hidden' name = 'branch' value = 'AddFromDailyResult'>\n";

	}
}	
function CollectMedline($pmid,$tmpfile){
	$ary = split("[^0-9]{1,}",$pmid);
	$get_from_ncbi = "";
	$text = "";
	for($i=0;$i<count($ary);$i++){
		$result = mysql_query("select p_full from pubmed where p_pmid = '$ary[$i]'");
		$row = mysql_fetch_array($result);
		if($row['p_full']){
			$text .= "$row[p_full]\n";
		}
		else{
			$get_from_ncbi .= "$ary[$i]%20";
		}
	}
	$get_from_ncbi = ereg_replace("\%20$","",$get_from_ncbi);
	if($get_from_ncbi){
		GetMedlineByID($get_from_ncbi,$tmpfile);
	}
	$fp = fopen("temp/$tmpfile","a");
	fwrite($fp,$text);
	fclose($fp);
}
function DateListDisp($user){
	$result = mysql_query("select h_date from hit where h_uid = '$user' group by h_date order by h_date desc");
	print "<Select name='date'>\n";
	while ($row = mysql_fetch_array($result)){
		print "	<option value = '$row[h_date]'>$row[h_date]\n";
	}
	print "</Select><br>\n";
	print "<input type = 'submit' name = 'submit' value = 'Submit'><br>\n";
	print "<input type = 'hidden' name = 'branch' value = 'DispResult'>\n";
}
function DispFull($pmid){
	global $PubMedLink;
	$lineLength = 60;
	$tmpfile = time();
	CollectMedline($pmid,$tmpfile);
	$fp = fopen("temp/$tmpfile","r");
	while ($buf = fgets($fp,4096)){
		//trim($buf);
		if(ereg("^PMID- {1,}([0-9]{1,})",$buf,$ary)){
			$pmid = $ary[1];
		}
		elseif(ereg("^(TI|AB|SO|AD) {1,}- {1,}(.{1,})",$buf,$ary)){
			$flag = $ary[1];
			$text[$flag] = $ary[2];
		}
		elseif(ereg("^AU {1,}- {1,}(.{1,})\n",$buf,$ary)){
			$flag = "AU";
			if(strlen($text[$flag]) > $lineLength){
				$ary2 = split("\n",$text[$flag]);
				$c = count($ary2)-1;
				if(strlen($ary2[$c]) > $lineLength){
					$text[$flag] = ereg_replace("\, $","\n",$text[$flag]);
				}
			}
			$text[$flag] .= "$ary[1], ";
		}
		elseif(ereg("^[A-Z]{1,}",$buf,$ary)){
			$flag = "";
		}
		elseif($flag){
			$buf = ereg_replace("^ {1,}","",$buf);
			$text[$flag] .= $buf;
		}
	}
	fclose($fp);
	$text['AU'] = ereg_replace(", $","\n",$text['AU']);
	print "<HTML><BODY><PRE>\n";
	print "<B>$text[TI]</B>\n";
	print "$text[AU]\n";
	print "$text[AD]\n";
	print "$text[AB]\n";
	$text['SO'] = trim($text['SO']);
	print "$text[SO] [PMID:<a href='$PubMedLink$pmid'>$pmid</a>]\n";
	print "</PRE></BODY></HTML>\n";
	unlink("temp/$tmpfile");
}		
?>	
