<?php

if(!isset($_SESSION)) session_start();
include_once("config.php");
include("loginCheckPoint.php");
include_once("authorizations.php");
require_once("demosettings.php");
//include_once("C:/xampp/htdocs/iventitymatcherhtm/bsw/utils.php");
include_once 'write_log.php';

//$pageNumber = $_REQUEST["pageNumber"];
$idEnd = $_REQUEST["idEnd"];
$numberOfLines = 100;
$saveToFile = false;

$userdetails = fetchUserDetails($_SESSION['username']);
global $AUTH;
$userAuth = $AUTH["'" . $userdetails['Group_ID']. "'"];
$username = $userdetails['Username'];
	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IntuScan Station</title>
<meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"  /> 
<link rel="stylesheet" href="js/jquery-ui/development-bundle/themes/base/jquery.ui.all.css">
<link rel="stylesheet" href="css/jquery.ui.autocomplete.css">
<script src="js/jquery/jquery.js" type="text/javascript"></script>
<script src="js/jquery/jquery-ui.custom.js" type="text/javascript"></script>
<script src="js/jquery/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-ui/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.tabs.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.effects.core.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.effects.blind.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.core.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.position.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.autocomplete.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.sortable.js"></script>
<script src="js/ivutils.js"></script>
<script type="text/javascript">

setTimeout(function(){
	window.location.href = "listFilesPage.php";   	
}, 
<?php
	$time = "5000";
	try{
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	if (!($mysqli->connect_error)) {    
		$sql = "SELECT isRunning FROM user_status WHERE username=\"$username\""; 												
		$res = $mysqli->query($sql);		
		if(is_object($res)){
			$row = $res->fetch_object();
			if ($row->isRunning == 0)
				$time = "1000000000";
			else{							
				$time = "5000";
				$sql = "SELECT filename,date FROM files ORDER BY id DESC LIMIT 1,1";
				$res = $mysqli->query($sql);
				if(is_object($res)){
					
					$row = $res->fetch_object();
					$fileName = $row->filename;
					$db_time = strtotime($row->date);					
					$t = time();					
					if (($db_time - $t) > 300)
					{
						$sql = "UPDATE user_status SET isRunning=0 WHERE username=\"$username\""; 												
						$res = $mysqli->query($sql);
						write_to_log("ERROR", "UPDATE user_status SET isRunning=0 t=$t time=".$db_time);	
						$time = "1000000000";
					}				
				}else{
					$fileName = "";
				}
			}
		}
	}
	}catch (Exception $e){	
		$time = "5000";
	}
	sqlClose($mysqli, 'listFilesPage');
	
	echo $time;?>
);

function goTo(path)
{	
	//clearTimout();
	window.location.href = path;
};

function clearTimout()
{
	//clearTimeout(1);
};
function gotopage(id)
{
	window.location.href = "listFilesPage.php?idEnd=" + id;
};
</script>
<link href="style.css" rel="stylesheet" type="text/css" />

</head>

<body>
<div class="main">
 <div class="top-banner">
	 <a href="home.php"><img src="images/intuscan-img.png" style="border:0;"/></a>
	 <p style="padding:0 10px 10px 10px; float:right;"><b>version 1</b></p>
	 <p style="padding:0 10px 10px 10px; float:right;">Hi, <?php echo $_SERVER['PHP_AUTH_USER'] ?></p>
	 <p style="padding:0 10px 10px 10px; float:right;"><a style="color:red;" href="logoff.php">logoff</a></p>
 </div>
  <div class="header">
    
    <div class="header_block">
     
      <div class="clr"></div>
      <?php
      	include('general-toolbar.php'); 
      ?>
      <div class="clr"></div>
    </div>
    <div class="clr"></div>
  </div>
  <div class="content">             
        <div>   
        	 	<?php
        	 		if ($time != "1000000000")      
      					echo "<center><b><span style=\"color:red;\">In Progress    </span>$fileName</b></center>";  
      			?>
        	     	
        	<table>
	 			<tr>
	 				<td class="filestdhd" style="background:#D8D8D8; width:35px; highet:10px;"><b>ID</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:150px; highet:10px;"><b>File Name</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:80px; highet:10px;"><b>Languages</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:150px; highet:10px;"><b>Topic</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:150px; highet:10px;"><b>Theatre</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:150px; highet:10px;"><b>Positive Sentiment</b></td>
	 				<td class="filestdhd" style="background:#D8D8D8; width:150px; highet:10px;"><b>Negative Sentiment</b></td>
	 				<td class="filestdhd" style="background:red; color:white; width:50px; highet:10px;"><b>Analyze</b></td>	 				
	 				<td class="filestdhd" style="background:red; color:white; width:50px; highet:10px;"><b>Download</b></td>
	 			</tr>
	 		
			<?php
			if ($time != "1000000000"){
				$sort = "DESC";
			}else {
				$sort ="";
			}
			if (empty($idEnd)){
				if ($userdetails['Group_ID'] == 0) 
					$sql = "SELECT * FROM files ORDER BY id $sort limit $numberOfLines";
				else{
					$username = $userdetails['Username'];				
					$sql = "SELECT * FROM files WHERE username='$username' ORDER BY userId $sort limit $numberOfLines";
				}				
			}
			else{
				//TODO handle users page display
				$begin = $idEnd;
				$username = $userdetails['Username'];	
				if ($userdetails['Group_ID'] == 0) 			 
					$sql = "SELECT * FROM files where id>$begin ORDER BY id $sort limit $numberOfLines";
				else 
					$sql = "SELECT * FROM files where username='$username' AND userId>$begin ORDER BY userId $sort limit $numberOfLines";				
			}					
			$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
			if ($mysqli->connect_error) {    
				sleep(10);
			}		
			$mysqli->close();		  
			$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
			$res = $mysqli->query($sql);							
			$line = 0;	
			$file_list = file_put_contents("c:\\tmp\\list_data.txt", "File Name;Languages;Topic;Theatre;Positive Sentiment;Negative Sentiment" . PHP_EOL);				
			$file_listwith_entity = file_put_contents("c:\\tmp\\list_data_with_entity.txt", "File Name;Languages;Topic;Theatre;Positive Sentiment;Negative Sentiment;Person;Organization;places" . PHP_EOL);
			if (!empty($res)){			
				while ($row = $res->fetch_object()) {
					$data_list = "";
					if (!empty($row->filename)){
						$tooltip = "";
						if (!empty($row->file_size)){
							$size = intval($row->file_size/1000);
							$tooltip = "File size = " . $size . "KB";
						}
						if (!empty($row->file_creation_date))
							$tooltip .= "
	File creation date = " . $row->file_creation_date;
						if (!empty($row->file_format))
							$tooltip .= "
	File format = " . $row->file_format;
						if (!empty($row->file_last_accessed_date))
							$tooltip .= "
	File last accessed date = " . $row->file_last_accessed_date;
						if (!empty($row->file_last_modified_date))
							$tooltip .= "
	File last modified date = " . $row->file_last_modified_date;
						if (!empty($row->line_count))
							$tooltip .= "
	Number of line = " . $row->line_count;
						if (!empty($row->token_count))
							$tooltip .= "
	Number of token = " . $row->token_count;
						if (!empty($row->idiological_stream))
							$tooltip .= "
	Idiological stream = " . $row->idiological_stream;
						if (!empty($row->islamic_sect))
							$tooltip .= "
	Islamic sect = " . $row->islamic_sect ."
	";					if ($tooltip != ""){
							echo "<tr>";
							if ($userdetails['Group_ID'] == 0) 
								$id = $row->id;															
							else
								$id = $row->userId;						
							echo "<td class=\"filestdhd\">$id</td>";						
	
							if(!empty($row->languages)){
								$langArr = array();
								$lang = explode(";", $row->languages);
								
								foreach ($lang as $l){
									$langArr[$l] = $l;
								}
								$first = true;
								foreach ($langArr as $l){
									if ($first){
										$languages = $l;
									}else
										$languages .= ", " . $l;  
								}	
							}else{
								$languages = "NA";
							}				
							$counted_theatre = str_ireplace(";", ", ", $row->counted_theatre);				
							$ideological_stream = str_ireplace(";", ", ", $row->ideological_stream);
							//clean duplicate anti
							$e = explode(";", $row->anti);
							$aggArr = array();
							foreach ($e as $a){
								$aggArr[$a] = $a;
							}
							$first = true;
							$aggregated_anti = "";
							foreach ($aggArr as $a){
								if ($first){
									$first = false;
									$aggregated_anti .= $a;
								}
								else							
									$aggregated_anti .= "<br>" . $a;
								
							}
							
							//clean duplicate pro
							$e = explode(";", $row->pro);
							$aggArr = array();
							foreach ($e as $a){
								$aggArr[$a] = $a;
							}
							$first = true;
							$aggregated_pro = "";
							foreach ($aggArr as $a){
								if ($first){
									$first = false;
									$aggregated_pro .= $a;
								}
								else							
									$aggregated_pro .= "<br>" . $a;
								
							}
																	
							$antipro = "";
							if (strlen($aggregated_anti) > 1){
								$antipro = "<b>Anti</b> - " . $aggregated_anti;
								if (strlen($aggregated_pro) > 1){
									$antipro .= " <br> " . "<b>Pro</b> - " . $aggregated_pro;
								}
							} elseif 	(strlen($aggregated_pro) > 1){
								$antipro .= "<b>Pro</b> - " . $aggregated_pro;
							} else{
								$antipro = "";
							}
							$data_list .= "$row->filename";
							$data_list .= ";$languages";
							$data_list .= ";$row->document_topic";
							$data_list .= ";$counted_theatre";
							$data_list .= ";$aggregated_pro";
							$data_list .= ";$aggregated_anti";
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$row->filename</td>";																			
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$languages</td>";		    	 	   					
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$row->document_topic</td>";							
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$counted_theatre</td>";							
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$aggregated_pro</td>";							
							echo "<td title=\"$tooltip\" class=\"filestdhd\">$aggregated_anti</td>";
		        			echo "<td><a href=\"javascript:goTo('document.php?dcid=" . $row->id . "')\"><img src=\"images/analyze-icon-bw.png\" width=\"24\"
													onmouseover=\"this.src='images/analyze-icon.png'; this.style.cursor='hand';\"
		        									onmouseout=\"this.src='images/analyze-icon-bw.png';\"/></a></td>";
		        			
							echo "<td><a href=\"javascript:goTo('download.php?dcid=".  $row->id. "')\"><img src=\"images/download-icon.png\" width=\"24\"
													onmouseover=\"this.src='images/download-icon-bw.png'; this.style.cursor='hand';\"
		        									onmouseout=\"this.src='images/download-icon.png';\"/></a></td>";					
							echo "</tr>";
							
							if ($saveToFile){
								//add person org and location
								$sql = "SELECT DISTINCT name FROM person_object WHERE docId=$id";								
								$res_list = $mysqli->query($sql);
								$person = "";
								$first = true;
								while ($row_list = $res_list->fetch_object()){										
									if (!empty($row_list->name)){
										if ($first){
											$person .= $row_list->name;
											$first = false;
										}else 
											$person .= "," . $row_list->name;
									}
								}	
								//add person  and location
								$sql = "SELECT DISTINCT name FROM organizational_identity WHERE docId=$id";								
								$res_list = $mysqli->query($sql);
								$org = "";
								$first = true;
								while ($row_list = $res_list->fetch_object()){										
									if (!empty($row_list->name)){
										if ($first){
											$org .= $row_list->name;
											$first = false;
										}else 
											$org .= "," . $row_list->name;
									}
								}	
								$sql = "SELECT DISTINCT name FROM place_object WHERE docId=$id";								
								$res_list = $mysqli->query($sql);
								$place = "";
								$first = true;
								while ($row_list = $res_list->fetch_object()){										
									if (!empty($row_list->name)){
										if ($first){
											$place .= $row_list->name;
											$first = false;
										}else 
											$place .= "," . $row_list->name;
									}
								}					
								$file_listwith_entity = file_put_contents("c:\\tmp\\list_data_with_entity.txt", $data_list.";".$person.";".$org.";".$place . PHP_EOL ,FILE_APPEND);
							}
							if ($userdetails['Group_ID'] == 0) 
								$endId = $row->id;
							else 
								$endId = $row->userId;	
							$file_list = file_put_contents("c:\\tmp\\list_data.txt", $data_list . PHP_EOL ,FILE_APPEND);
						}
					}		
					$line++;
														
					
				}
			}else{
				$endId = 0;
			}
			if ($userdetails['Group_ID'] == 0) 
					$sql = "SELECT max(id) as m FROM files";
				else 
					$sql = "SELECT max(userId) as m FROM files WHERE username='$username'";				
      		$res = $mysqli->query($sql);	
      		if(is_object($res)){
      			$row = $res->fetch_object();	
      			$max = $row->m;
      		}
      		sqlClose($mysqli, 'listFilesPage');
      		echo "</table>";
      echo "</div>";      	          	         	
      ?>
      
      <div class="sidebar">
        
      </div>
      <div class="clr"></div>
  </div>
  	<div class="footer">
	<?php
		if ($time == "1000000000"){		
			echo "<div align=\"center\">";
			$space = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp"; 		
			$page = ($idEnd / $numberOfLines) + 1;		
			echo "Page Number <b>" . $page . "</b>";
			echo "<br><br>";   	 
			$num = $max - ($max % $numberOfLines);      	  
	      	if (empty($idEnd) || $idEnd == -($numberOfLines) || $idEnd == 0){
	      		//start page
	      		if ($line == $numberOfLines){        				      				      	
	      			echo $space . $space . $space .$space . $space . $space .$space .$space;      			
	      			echo"<a href=\"javascript:gotopage($endId);\">next page >>></a>"; 
	      			echo "<br><br>";
	      			echo $space . $space . $space .$space . $space . $space . $space;      			     			
	      			echo"<a href=\"javascript:gotopage($num);\">End page</a>";      			      			      			
	      		}      			      			      		      			
	      	}      		
	      	elseif ($line == $numberOfLines) {      		
	      		$prev = $endId - ($numberOfLines*2);
	      		$next = $endId;
	      		if ($prev != (-$numberOfLines)){      			
	      			echo "<a href=\"javascript:gotopage($prev);\"><<< previous page</a>" . $space . 
	      				"<a href=\"javascript:gotopage($next);\">next page >>></a>" ;
	      			echo "<br><br>";      			
	      			echo "<a href=\"javascript:gotopage(0);\">Start page</a>" . $space . 
	      				"<a href=\"javascript:gotopage($num);\">End page</a>"; 
	      		}
	      		else{      			
	      			echo "<a href=\"javascript:gotopage($endId);\">next page >>></a>";  
	      			echo "<br><br>"; 
	      			echo "<a href=\"javascript:gotopage($num);\">End page</a>";      			
	      		}
	      	}
	      	else{      
	      		//end page	
	      		if ($endId == 0){
	      			$endId = $idEnd;
	      		}	      	
	      		$prev = $endId - $numberOfLines - ($endId%$numberOfLines);
	      		//echo $space . $space . $space .$space . $space . $space .$space .$space;
	      		echo "<a href=\"javascript:gotopage($prev);\"><<< previous page</a>"; 
	      		echo $space . $space . $space .$space . $space . $space .$space .$space;
	      		echo "<br><br>";       		
	      		echo "<a href=\"javascript:gotopage(0);\">Start page</a>";
	      		echo $space . $space . $space .$space . $space . $space . $space;     		     
	      	}      
	      	 echo "</div>";
		}       	 
	?>
  </div>
</div>

</body>

</html>