<?php
require_once dirname(__DIR__,2).'/config.php';
$outboxPath=realpath(rtrim($applicationOutboxPath,'/')).DIRECTORY_SEPARATOR;
if(!$outboxPath||!is_dir($outboxPath))exit("Invalid Path");
$now=time();
function get_executable_path($cmd,$default){$path=trim(shell_exec('command -v '.escapeshellarg($cmd)));return $path?:$default;}
$sendfaxPath=get_executable_path('sendfax','/usr/bin/sendfax');
$gsPath=get_executable_path('gs','/usr/bin/gs');
$faxstatPath=get_executable_path('faxstat','/usr/bin/faxstat');
$faxrmPath=get_executable_path('faxrm','/usr/bin/faxrm');
$xferLogPath='/var/spool/hylafax/etc/xferfaxlog';
$retryLimit=isset($fax_retry)?(int)$fax_retry:1;
$timeoutLimit=isset($fax_error_timer)?(int)$fax_error_timer:600;
if(!is_executable($sendfaxPath)||!is_executable($gsPath))exit("Required fax tools (sendfax/gs) are not executable.");
foreach(glob($outboxPath.'*.pdf') as $pdfFile){
if(strpos(realpath($pdfFile),$outboxPath)!==0)continue;
$metaFile=dirname($pdfFile).DIRECTORY_SEPARATOR.pathinfo($pdfFile,PATHINFO_FILENAME).'.meta';
if(!file_exists($metaFile))continue;
$meta=loadMeta($metaFile);
if(!$meta)continue;
$currentStatus=$meta['status']??'';
$scheduleTs=strtotime($meta['schedule']??'');
$jid=$meta['jid']??'';
if($currentStatus==='sent'&&is_numeric($jid)){
if(file_exists($xferLogPath)&&is_readable($xferLogPath)){
$logCmd=sprintf("grep '\tSEND\t' %s | grep -w %s | tail -n 1",escapeshellarg($xferLogPath),escapeshellarg($jid));
$logLine=shell_exec($logCmd);
if($logLine){
$fields=preg_split('/[\s\t]+/',trim($logLine));
$pages=0;$sendKey=array_search('SEND',$fields);
if($sendKey!==false){
for($i=$sendKey+1;$i<count($fields);$i++){
if(is_numeric($fields[$i])&&(int)$fields[$i]>10000&&isset($fields[$i+1])&&is_numeric($fields[$i+1])){$pages=(int)$fields[$i+1];break;}}}
if($pages===0){
for($j=count($fields)-1;$j>0;$j--){
if(preg_match('/^\d+:\d+:\d+$/',$fields[$j])&&isset($fields[$j-1])&&is_numeric($fields[$j-1])){$pages=(int)$fields[$j-1];break;}}}
$meta['status']='success';
$meta['pages']=$pages>0?$pages:($meta['pages']??1);
$meta['completed_time']=date('Y-m-d H:i:s');
unset($meta['error']);
saveMeta($metaFile,$meta);
continue;
}}}
if(($currentStatus==='scheduled'||$currentStatus==='sent')&&$scheduleTs){
if($now>($scheduleTs+$timeoutLimit)){
$faxstatOut=shell_exec("$faxstatPath -s 2>&1");
$targetJid=$meta['jid']??null;
$isActuallySending=false;
if($targetJid&&is_numeric($targetJid)&&preg_match('/^\s*'.$targetJid.'\s+\d+\s+\S+\s+\S+\s+([SD])/',$faxstatOut))$isActuallySending=true;
if(!$isActuallySending){
$meta['status']='failed';
$logError='';
if($targetJid&&is_numeric($targetJid)&&file_exists($xferLogPath)){
$logLine=shell_exec(sprintf("grep -w %s %s | tail -n 1",escapeshellarg($targetJid),escapeshellarg($xferLogPath)));
if($logLine){$f=preg_split('/[\s\t]+/',trim($logLine));$logError=trim($f[13]??'','" ');}}
$meta['error']=$logError!==''?$logError:"Timeout/Aborted";
$meta['failed_time']=date('Y-m-d H:i:s');
saveMeta($metaFile,$meta);
if($targetJid&&is_numeric($targetJid))shell_exec("$faxrmPath ".escapeshellarg($targetJid));
continue;
}}}
if($currentStatus==='scheduled'&&$scheduleTs&&$now>=$scheduleTs){
$number=preg_replace('/[^0-9]/','',$meta['destination']??$meta['number']??'');
if($number==='')continue;
$pathInfo=pathinfo($pdfFile);
$tiffFile=$pathInfo['dirname'].DIRECTORY_SEPARATOR.$pathInfo['filename'].'.tiff';
if(!file_exists($tiffFile)&&file_exists($pdfFile)){
shell_exec(sprintf("%s -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=tiffg4 -sOutputFile=%s %s",escapeshellarg($gsPath),escapeshellarg($tiffFile),escapeshellarg($pdfFile)));
}
if(!file_exists($tiffFile))continue;
$priority=is_numeric($meta['priority']??'')?$meta['priority']:'63';
$sendCmd=sprintf('%s -n -t %d -P %s -d %s %s 2>&1',escapeshellarg($sendfaxPath),$retryLimit,escapeshellarg($priority),escapeshellarg($number),escapeshellarg($tiffFile));
exec($sendCmd,$out,$ret);
$newJid='';
if(preg_match('/request id is (\d+)/',implode("\n",$out),$matches))$newJid=$matches[1];
$meta['status']=($ret===0&&!empty($newJid))?'sent':'failed';
$meta['jid']=$newJid;
$meta['sent_time']=date('Y-m-d H:i:s');
if($ret!==0)$meta['error']=implode("\n",$out);
saveMeta($metaFile,$meta);
}}
