<?php

if(!isset($_SESSION)) session_start();

include_once("config.php");
include_once("sqlTable.php");
include("loginCheckPoint.php");
include_once("authorizations.php");
require_once("demosettings.php");
//include_once($_SERVER['DOCUMENT_ROOT']. "/iventitymatcherhtm/bsw/utils.php");
include_once 'write_log.php';

//exec("taskkill /fi \"WindowTitle eq joseki2*\"");
//die("here");
$userdetails = fetchUserDetails($_SESSION['username']);

// global $AUTH;
$AUTH = getGroupsAuth();

$userAuth = $AUTH[$userdetails['Group_ID']]['permissions'];

$canAnalyzeFolder = $userAuth['canAnalyzeFolder'];

$sync = $_REQUEST["sync"];
$clean = $_REQUEST["clean"];
//in case background.php executes this file (home.php) to sync doc persons - it passes docId as first parameter
$docId = $argv[1];

/*if ($docId) $sync = 1;
else {*/
$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);	
$sql = "UPDATE files
		SET results=\"\""; 			
								
$res = $mysqli->query($sql);
sqlClose($mysqli, 'home');
//}

/*if ($sync == 1)
{
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	$query = "SELECT * FROM person_object";
	$docAppend = " WHERE";
	if ($userdetails['Group_ID'] != 0)
	{
		$query .= " WHERE username='$userdetails[Username]'";
		$docAppend = " AND";
	}
	//append docId to where - for synching this doc persons only
	if ($docId)
		$query .= $docAppend . " docId = " . $docId;
		
	$res = $mysqli->query($query);
	$arr_obj = array();
	$r = $res->fetch_object();
	if (!empty($r)){		
		$i = 0;
		$arr_obj[$i++] = $r;
		while ($res_obj = $res->fetch_object())
		{
			$arr_obj[$i++] = $res_obj; 
		}				
		
		if (is_dir("c:/tmp"))
			$filepath = "c:/tmp/";		
		else 
			$filepath = "c:/temp/";
		//if ($userdetails['Group_ID'] == 0)
			$filename = "DOCEX Entities DB.tsv";
		//else 
		//	$filename = "DOCEX Entities DB-" . $userdetails[Username] .  ".tsv";

		//if only synch docId = create a filename with docId
		if ($docId)
			$filename = str_replace(".tsv", "." . $docId . ".tsv", $filename);
		
		unlink($filepath.$filename);
		foreach ($arr_obj as $obj)
		{
			file_put_contents($filepath.$filename, $obj->id , FILE_APPEND);		
			file_put_contents($filepath.$filename, "\t" . $obj->name . "\n", FILE_APPEND);		
		}
		//delete current watch list (unless appending docId to existing watch list)
		if (!$docId)
		{
		//if ($userdetails['Group_ID'] == 0)
			deleteWatchList("DOCEX Entities DB",$entityMatcher);
		//else 
		//	deleteWatchList("DOCEX Entities DB-" . $userdetails[Username],$entityMatcher);
		}
		$success = loadList($filepath,$filename,$entityMatcher, $docId);
		if (!$success) write_to_log("ERROR", "LoadList failed: " . $errormsg);
		unlink($filepath.$filename);
		//file_put_contents("c:/tmp/DOCEX Entities DB.xml",convertTsvToXml($filepath,$filename));
	}
	//docId is available only when synching from background.php - then can exit after sync
	if ($docId)
		exit;

}else*/if ($clean == 2){	
	global $info_log_file;
	global $warrning_log_file;
	global $error_log_file;
	global $trace_log_file;
	
	unlink($info_log_file);
	unlink($error_log_file);	
	unlink($warrning_log_file);
	unlink($trace_log_file);
// 	if ($userdetails['Group_ID'] == 0){
// 		//echo "allow deleting all data for administraor";
// 		createDB();
// 	}
// 	else
// 		cleanDBSpecificUser($userdetails[Username]);
		
	deleteDirectory($metadata_path);    

	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	$sql="CREATE TABLE Test(FirstName CHAR(30),LastName CHAR(30),Age INT)";
	$res = $mysqli->query($sql);
	/*$res = $mysqli->query("select Username from usercake_users");	
	while ($r = $res->fetch_object()){		
		deleteWatchList("DOCEX Entities DB-".$r->Username,"127.0.0.1");
	}*/
	//deleteWatchList("DOCEX Entities DB",$entityMatcher);
	/*$res = $mysqli->query("DROP TABLE files");	
	$res = $mysqli->query("DROP TABLE person_object");
	$res = $mysqli->query("DROP TABLE date");
	$res = $mysqli->query("DROP TABLE misc_object");
	$res = $mysqli->query("DROP TABLE organizational_identity");
	$res = $mysqli->query("DROP TABLE place_object");
			
	deleteWatchList("DOCEX Entities DB","127.0.0.1");
	// cmd : taskkill /IM java.exe
	$res= exec('tasklist /v /fo csv | findstr /i "java"');
	if (empty($res)){
		
	}else{		
		$arr = explode(',', $res);
		$pid = $arr[1];
		$res = exec("taskkill /PID " . $pid);				
	}*/
	
}	

function deleteDirectory($dirPath) {
    if (is_dir($dirPath)) {
        $objects = scandir($dirPath);
        foreach ($objects as $object) {
            if ($object != "." && $object !="..") {
                if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
                    deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                } else {
                    unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                }
            }
        }
    reset($objects);
    //rmdir($dirPath);
    }
}

?>
<!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="jquery-ui/development-bundle/themes/base/jquery.ui.all.css">
<script src="jquery/jquery.js" type="text/javascript"></script>
<script src="jquery/jquery-ui.custom.js" type="text/javascript"></script>
<script src="jquery/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.tabs.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.effects.core.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.effects.blind.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.core.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.position.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.autocomplete.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="jquery-ui/development-bundle/ui/jquery.ui.sortable.js"></script>
<script type="text/javascript" src="dist/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="dist/plugins/jqplot.donutRenderer.min.js"></script>
<script src="js/ivcommon.js"></script>
<script type="text/javascript">

$(document).ready(function(){
	  var data = [
	    ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14], 
	    ['Out of home', 16],['Commuting', 7], ['Orientation', 9]
	  ];
	  var plot1 = jQuery.jqplot ('chart1', [data], 
	    { 
	      seriesDefaults: {
	        // Make this a pie chart.
	        renderer: jQuery.jqplot.PieRenderer, 
	        rendererOptions: {
	          // Put data labels on the pie slices.
	          // By default, labels show the percentage of the slice.
	          showDataLabels: true
	        }
	      }, 
	      legend: { show:true, location: 'e' }
	    }
	  );
	});
	
function submitform()
{
	document.getElementById("divCheckbox").style.display='block';		
  	document.form2.submit();
}

function submitTextform()
{		
  	document.formText.submit();
}

function submitURLorm()
{
	document.formURL.submit();	
}
function gotolink()
{
	gotoPage("listFilesPage", {"refresh": true});
	document.form3.submit();	
}

function cleanAll()
{
	if (confirm('Are you shure you want to delete all data?')){
		window.location.href = 'home.php?clean=2';		
	}	
}

</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 $_SESSION["username"] ?></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 class="mainbar" id="mainbar">       
      <?php
      	$err = $_REQUEST["err"];
      	if($err > 0){
      		if($err == 1){
      			$msg = "The input file exceeded the size limit. Please select a file with size up to 1 MBytes and try again.";
      		}else if($err == 2){
      			$msg = "Nothing to process. Please provide input data and try again.";
      		}
      	}
      	if(strlen($msg) > 0){
      		echo "<div class=\"errmsg\"><b>". $msg . "</b></div>";
      	}
      ?>
      <div class="article">
       <form action="senddocEngAjx.php" method="post" id="form1" enctype="multipart/form-data">
		<ol><li>
		<label for="name"><b><h3>Analyse File</h3></b></label>
          <input id="file" name="file" type="file" class="text" />
          	<br>
           <input type="submit" name="imageField" id="imageField" src="images/submit.gif" class="send" OnClick="l.style.visibility='visible';"/>
			<br><br>                  
        </form>
		</div>
		<?php 
			if ($canAnalyzeFolder){
				echo "<div class=\"article\">";
					echo "<form action=\"sendFolder.php\" method=\"post\" name=\"form2\" id=\"form2\">";
						echo "<ol><li>";
						echo "<label for=\"name\"><b><h3>Analyse Folder</h3></b></label>";
		          		echo "<input id=\"folderPath\" name=\"folderPath\" type=\"input\" class=\"text\" />";
		          		echo "<br>";	          	          			          			          		
	           			echo "<input type=\"button\" value=\"Analyse Folder\" name=\"imageField\" id=\"imageField\" src=\"images/submit.gif\" class=\"send\" OnClick=\"javascript: submitform()\"/>";
						echo "<br>";
						echo "<div id=\"divCheckbox\" style=\"display: none;\">";
							echo "<br>";
							echo "<a href=\"javascript:gotolink();\">Click here to see Analysed files</a>";					
						echo "</div>";
						echo "<br>"; 	          					
	        		echo "</form>";
	    		echo "</div>"; 
			} 
	    ?>
	    <div class="article"> 
	    	<ol><li> 
	      	<form  action="senddocEngAjx.php" method="post" name="formURL">     
		      	<label for="name"><b><h3>Analyse URL</h3></b></label>
		      	<input id="AnalyseURL" name="AnalyseURL" type="input" class="text" />
				<br><br>
				<input type="button" value="Analyse URL" name="AnalyseURLButton" id="AnalyseURLButton" src="images/submit.gif" class="send" OnClick="javascript: submitURLorm()"/>				
			</form>			
			</li></ol>
	     </div>
	     
	     <div class="article">  
	      	<form  action="senddocEngAjx.php" method="post" name="formText">     
		      	<label for="name"><b><h3>Text Analysis</h3></b></label>
				<textarea id="AnalyseText" name="AnalyseText" style="width:300px; height:100px;"></textarea><br></br>
				<input type="button" value="Analyse Text" name="AnalyseTextButton" id="AnalyseTextButton" src="images/submit.gif" class="send" OnClick="javascript: submitTextform()"/>
			</form>			
	     </div>       
	     
        <div class="article">
		<?php
			$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
			
			if ($userdetails['Group_ID'] == 0)
				$res = $mysqli->query("SELECT COUNT(id) as i FROM files");
			else 			
				$res = $mysqli->query("SELECT COUNT(id) as i FROM files WHERE username='" . $userdetails['Username'] . "'");
			if (!empty($res))	{
				$row = $res->fetch_object();
			
				echo "<h2>General Statistics</h2><br>";			
				echo "<br>";
				echo  "Analysed" . "<span style=\"color:red;\"><b>" . " " . $row->i . "</b></span> documents<br><br>";
			}
			//echo  "<b>" . 'Totalersons' . "</b> Person found<br><br>";
			//echo  "<b>" . 'TotalknownPersons' . "</b> Known Person found<br><br>";								
			
			sqlClose($mysqli, 'home');
			
		?>
		
      </div>
      
      
      <div class="clr"></div>
  </div>
<?php 
	if ($clean == 1){
		echo "<script type=\"text/javascript\">";
			echo "cleanAll();";
		echo "</script>"; 
	}
?>
  
</div>
</body>

</html>