<?php

if (session_status() == PHP_SESSION_NONE) {
    if(!isset($_SESSION)) session_start();
}

include("loginCheckPoint.php");
require_once("demosettings.php");
include_once 'write_log.php';
require_once 'sqlUtils.php';
require_once 'asyncRequst.php';
require_once 'parseUtils.php';
require_once 'OSSpecific.php';

global $databaseName;
global $metadata_path;


global $linuxPath,$linuxXmlPath,$linuxSourceFolder;

$mysqli = sqlCreateConnection("Send Folder");
$username = $_SESSION['username'];

if(empty($folderPath)) { //also defined in autoSendFolder.php
    $folderPath = filter_input(INPUT_GET, "folderPath");
}

$isEmail = filter_input(INPUT_GET, "isEmail")  ?? null;
$groupTag = filter_input(INPUT_GET, "groupTag");
$tag = filter_input(INPUT_GET, "tag");
$user = $_SESSION['username'];
$canAnalyzeFolder = getUserPermission(CAN_ANALYZER_FOLDER);
if (!$canAnalyzeFolder) {
    die("User is not authorized to analyze folders");
}

is_dir("$xml_results_path") || mkdir_full("$xml_results_path", 0777, true);

$isFolderService = getSystemSettingsProp($mysqli, "isFolderService");

/**Run the request below to the java folder service*/	
 if($isFolderService) {
    write_to_log("INFO", "Running with doc server");
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        write_to_log("ERROR", "error writing to socket: " . $errormsg);
        return false;
    }
    global $folderServiceHost, $folderServicePort;
    $ip = $folderServiceHost;
    $result1 = socket_connect($socket, $ip, $folderServicePort);
    if ($result1 === false) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        write_to_log("ERROR", "Error writing to FolderService [host:$ip port:$folderServicePort]: " . $errormsg);
        return false;
    }
    $path = $docserverPath;
    $xmlpath = $docserverxmlpath; 
    $sourchFolder = $docserversourcefolder; 
    
    $dbDetails = connectDetails($databaseName);
    $req = sprintf("<IVEnvelope><AnalyzeFolder 
		uploadedFilesPath=\"%s\" 
		path=\"%s\" 
		username=\"%s\" 
		sourcePath=\"%s\" 
		xmlResults=\"%s\" 
        tagGroup=\"%s\" 
        tag=\"%s\" 
        db_username=\"%s\"
		db_password=\"%s\"
		db_name=\"%s\"
		db_host=\"%s\"
		db_port=\"%s\"
                isEmail=\"%s\"/></IVEnvelope>",			
		$path,
		$folderPath,
		$user,
		$sourchFolder,
		$xmlpath,
        $groupTag,
        $tag,
		$dbDetails["user"],
		$dbDetails["pwd"],
		$dbDetails["db"], 
		$dbDetails["host"],
		$dbDetails["port"],
                $isEmail);		
	
    $result2 = socket_write($socket, $req, strlen($req));
    if ($result2 === false) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        write_to_log("ERROR", "error writing to socket: " . $errormsg);
        return false;
    }


    $output = "";
    $numRetries = 0;
    while (true) {

        $read = socket_read($socket, 1024);
        if ($read === FALSE) {

            if ($numRetries++ < 3) {

                sleep(1);
                continue;
            } else {

                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);
                write_to_log("ERROR", "error reading from socket: $errormsg");
                return false;
            }
        }
        $output = $output . $read;
        $ending = strpos($output, "</IVEnvelope>");
        if ($ending !== false) {
            break;
        }
    }

    $IVEnvelope = simplexml_load_string($output);
    write_to_log("INFO", $output);
    $replyUsername = (string) $IVEnvelope->Reply['username'];
    write_to_log("INFO", $replyUsername);
    
    sqlClose($mysqli, 'sendFolder - docserver');    
    
    /*     * END OF SERVICE COMMUNICATION */
    $tries = 0;

    return;
}
	write_to_log("INFO","sendFolder running without doc server on $folderPath");	
	if(!empty($groupTag) || !empty($tag)) {
            write_to_log("ERROR","Tagging uploaded folder not supported w/o Folder-service");
        }
	$folderPath = uploadedFileAbsolutPath($folderPath);
	$dir = OSSpecific::getInstance()->getDirectoryIterator($folderPath);
	$sql = "UPDATE user_status SET isRunning=1 WHERE username=\"$user\"";
	$res = sqlQuery($mysqli, $sql);
	$intuscanHost = getSystemSettingsProp($mysqli, "intuscanHost");
	$intuscanPort = getSystemSettingsProp($mysqli, "intuscanPort"); 
	$intuscanArray = array("$intuscanHost:$intuscanPort");
	
	$numOfIntuscan = count($intuscanArray);
	
	$folderScanDate = date(DATE_ATOM);

	$i = 0;	
	//$sql = "SET @numErrors = 0;\r\n";
	$sql = "";
	$prevFolder = "";
	
	foreach ($dir as $fn) {
		$fileName = $mysqli->real_escape_string($fn->getFilename());
		$shortFileName = $mysqli->real_escape_string($fn->getShortFilename());
		$subfolderPath = uploadedFileRelativePath(realpath($fn->getPath()));
		$folderPathSql = $mysqli->real_escape_string($subfolderPath);
		$dateColumns = "";
		$dateValues = "";
		foreach (array("ctime" => "file_creation_date", "mtime" => "file_last_modified_date", "atime" => "file_last_accessed_date") as $key => $column)
		{
			$stat = $fn->getStat();
			if (!$stat || !array_key_exists($key, $stat))
				continue;
			
			$dateColumns .= ", $column";
			$dateValues .= ", '" . date('Y-m-d H:i:s', $stat[$key]) ."'";
		}
		
		$userId = getUserId($mysqli,$user,$userId ?? null,$i);
		if(!empty($params)){ //NEW UI
		    $sql .= "INSERT INTO files (username, filename, shortFileName, origFolder $dateColumns,userId,results) VALUES ('$user', '$fileName', '$shortFileName', '$folderPathSql' $dateValues,$userId,'$params');\r\n";
		}
		else{
		    $sql .= "INSERT INTO files (username, filename, shortFileName, origFolder $dateColumns,userId) VALUES ('$user', '$fileName', '$shortFileName', '$folderPathSql' $dateValues,$userId);\r\n";	    
		}

		$sql .= "SET @docId = LAST_INSERT_ID();\r\n";
		$insertFolders = $prevFolder != $folderPathSql;
		$prevFolder = $folderPathSql;
		$sql .= createSqlInsertDocPath($mysqli, "@docId", $subfolderPath, $folderScanDate, $user, $insertFolders);

		$i++;
		//if ($i >= 1000) //sometimes mysql server is "gone away" for a bulk of 1000 inserts, and reducing inserts to 100 helps
		if ($i >= 100)
		{
			sqlMultiQuery($mysqli, $sql);
			$sql = "";
			$i = 0;
		}
	}
	if ($i) {
            sqlMultiQuery($mysqli, $sql);
        }

$file_id = 1;
	foreach ($intuscanArray as $ip_port_str){
		$ip_port = explode(":", $ip_port_str, 2);
		$serverIP = $ip_port[0];
		$port = $ip_port[1];
		$i = 1;
		while ($i <= 3){        	
			write_to_log("INFO", "current senddoc folder: $CURRENT_SOURCE_FOLDER");
                    

                        asyncRequst::getInstance()->sendDocAsync($PHP_FOLDER, $i, $user, $serverIP, $port, $file_id, $isEmail);
                        //$asyncReq::$req->sendDocAsync($PHP_FOLDER, $i, $user, $serverIP, $port, $file_id, $isEmail);
                        //sendDocAsync($PHP_FOLDER, $i, $user, $serverIP, $port, $file_id, $isEmail);
			$i++;
		}
		//if ($file_id == 1)
		//	pclose(popen("start /B $CURRENT_SOURCE_FOLDER\\ExtractNamesFromEmails.bat \"$PHP_FOLDER\"", "r"));      
		$file_id++;
	}	
	$tries = 0;
	
    sqlClose($mysqli, 'sendFolder - not docserver');
    return;
    exit();	