<?php


require_once '../../autoload.php';
session_write_close();
ignore_user_abort(true);
set_time_limit(0);


$thefile = __FILE__ . '.sem';


function file_exists_safe($file) {
    if (!$fd = fopen($file, 'xb')) {
        return true;  // the file already exists
    }
    fclose($fd);  // the file is now created, we don't need the file handler
    return false;
}

function shutdown($file)
{
  unlink($file) ;
}
if($_GET['querytype'] == 'timer')
{

	register_shutdown_function('shutdown',$thefile);

	if (file_exists_safe($thefile)) {
		error_log('Order Query : process already running => canceled');
		$xml =  '<orderlist><data>';
		$xml .= '<message>Process already running</message>';
		$xml .= '<status>2</status>';
		$xml .= '<jobid>-1</jobid>';
		$xml .= '</data></orderlist>';

		header('Content-Type: text/xml; charset=UTF-8');
		echo $xml;
		exit();
	}

	$fh = fopen($thefile, 'wb');
	fclose($fh);

}

$jobid = -1;
$jobidlist = [];
$sql = "delete from joblist where service=5 and status = 2 and remaining <= 0 and to_date(sdatetime,'YYYYMMDD000000') <= (now() - interval '20 day')::date;";

if(isset($_GET['querytype']) && in_array($_GET['querytype'],array('user','timer')))
{
  if($_GET['querytype'] == 'user')
  {
    $sql .= "insert into joblist(sdatetime,service,status,info1,info2,remaining)
  	select to_char(now(),'YYYYMMDDHH24MISS'),5,0,stuid,pro_id::text,1 from study where stu_id = {$_GET['stuid']} returning job_id";
  }else{
    $sql .= "select job_id from joblist where service = 5 and remaining > 0 and to_date('{$_GET['datefrom']}','YYYYMMDD') <=  to_date(sdatetime,'YYYYMMDD000000')
     and  to_date(sdatetime,'YYYYMMDD000000') <= to_date('{$_GET['dateto']}','YYYYMMDD') order by remaining desc";
  }
}else{
  error_log("order_querypacs: bad GET parameter");
  exit();
}

//	error_log($sql);

$conn = get_dbconnection();
if($query = pg_query($conn,$sql))
{
  while($row = pg_fetch_row($query)){
      $jobreq = new stdClass();
      $jobreq->jobid = $row[0];
      $jobreq->histo = false;
      $jobidlist[] = $jobreq;
  }
}else{
  error_log("failed:".$sql);
  exit();
}
//setcookie(session_name(),session_id(),time() + 10, "", "", false, true);

$xml = '<orderlist>';
if (session_id()) {
	session_commit();
}
// 2. store current session id
session_name("eoDACS");
session_start();
$current_session_id = session_id();
session_commit();

for($value=reset($jobidlist); key($jobidlist)!==null; $value=next($jobidlist)) {

  session_name("eoDACS");
  session_start();
  session_regenerate_id();
  $_SESSION['loggedin'] = TRUE;
  $session_id_to_destroy = session_id();
  $opts = array('http' => array('header'=> 'Cookie: ' . session_name().'='.session_id()."\r\n"));

  $xmlresult = '';
    //commandes
    $url = $config_servernameorip.$EODACS_ROOT."/dbconnector/query/querypacs.php?jobid={$value->jobid}";


	if(isset($_SERVER['HTTPS']))
  {
   // $url = $config_servernameorip.$_GET['url'];
   $arrContextOptions=array(
        "ssl"=>array(
              "verify_peer"=>false,
              "verify_peer_name"=>false,
          ),
          'http' => array('header'=> 'Cookie: ' . session_name().'='.session_id()."\r\n")
      );
     session_write_close();
     $xmlresult .= file_get_contents($url, false, stream_context_create($arrContextOptions));

  }else
  {
  	session_write_close();
  	$xmlresult .= file_get_contents($url,false,stream_context_create($opts));
  }


  $xmldom = simplexml_load_string($xmlresult);

    $updatemess = explode('|', $xmldom->dbupdatemessage);
    if($value->histo == false && $updatemess[0] == 'patidchanged' && $xmldom->status == '2')
    {
          $sqlhisto = "insert into joblist(sdatetime,service,status,info1,info2,remaining,comment)
        select to_char(now(),'YYYYMMDDHH24MISS'),5,0,stuid,pro_id::text,1,'autogenerated - patient merge/modify' from study where pat_id = {$updatemess[1]} returning job_id;";
        if($query = pg_query($conn,$sqlhisto))
        {
          while($row = pg_fetch_row($query)){
            $jobreq = new stdClass();
            $jobreq->jobid = $row[0];
            $jobreq->histo = true;
            $jobidlist[] = $jobreq;
          }
        }
        //$xml .= '<patidold>'.$updatemess[1].'</patidold>';
        //$xml .= '<patidnew>'.$updatemess[2].'</patidnew>';
    }
    $xml .= $xmlresult;
  // 3. hijack then destroy session specified.
  session_id($session_id_to_destroy);
  session_start();
  session_destroy();
  session_commit();

  usleep($GLOBALS['query_delay_request_in_us']);
}
$xml.= '</orderlist>';
session_id($current_session_id);
session_start();
session_commit();

header('Content-Type: text/xml; charset=UTF-8');
echo $xml;

?>
