<?php
require_once(__DIR__.'/../../config.php');
require_once(__DIR__.'/../../include/plugin/push.lib.php');
if(php_sapi_name()!=='cli')die("This script is for CLI/Cron only.\n");
$spoolDir=realpath(rtrim($applicationSpoolDir,'/'));
$archivePath=realpath(rtrim($applicationArchivePath,'/'));
if(!$spoolDir||!$archivePath)die("Error: Invalid Spool or Archive directory.\n");
function cmd_path($cmd){$p=shell_exec("command -v ".escapeshellarg($cmd));return $p?trim($p):null;}
$tiff2pdf=cmd_path('tiff2pdf');
if(!$tiff2pdf)die("Error: tiff2pdf not found.\n");
$files=glob($spoolDir.'/*.{tif,tiff,TIF,TIFF}',GLOB_BRACE);
if(empty($files)){echo "No faxes to process.\n";exit;}
$logFile='/var/spool/hylafax/etc/xferfaxlog';
foreach($files as $inputFile){
$nomeFax=basename($inputFile);
echo "Processing: $nomeFax ... ";
$recvTime=null;$caller='unknown';$pages=0;$jid=null;
if(is_readable($logFile)){
$lines=file($logFile,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$lines=array_slice($lines,-3000);
foreach(array_reverse($lines) as $line){
if(!str_contains($line,"\tRECV\t"))continue;
if(!str_contains($line,$nomeFax))continue;
$f=explode("\t",$line);
if(count($f)<11)continue;
$dt=DateTime::createFromFormat('m/d/y H:i',trim($f[0]));
if($dt)$recvTime=$dt->format('Y-m-d H:i:s');
$raw=trim($f[8]??'','" ');$num=preg_replace('/\D/','',$raw);
if($num!=='')$caller=$num;
$pages=intval($f[10]??0);$jid=trim($f[2]);break;
}}
if(!$recvTime)$recvTime=date('Y-m-d H:i:s',filemtime($inputFile));
$ts=strtotime($recvTime);
$fnameTime=date('Ymd_Hi',$ts);
do{
$uid=bin2hex(random_bytes(4));
$base=$fnameTime.'_'.$caller.'_'.$uid;
$pdfFile=$archivePath.'/'.$base.'.pdf';
$tifFile=$archivePath.'/'.$base.'.tiff';
$metaFile=$archivePath.'/'.$base.'.meta';
}while(file_exists($pdfFile));
if(!copy($inputFile,$tifFile)){echo "Copy failed.\n";continue;}
$cmd=escapeshellarg($tiff2pdf)." -o ".escapeshellarg($pdfFile)." ".escapeshellarg($tifFile)." 2>&1";
exec($cmd,$out,$ret);
if($ret!==0||!is_file($pdfFile)){@unlink($tifFile);echo "Conversion failed.\n";continue;}
$status=($jid&&$recvTime)?'success':'unknown';
$meta=['uid'=>$uid,'jid'=>$jid,'received_time'=>$recvTime,'caller'=>$caller,'pages'=>$pages,'status'=>$status];
if(saveMeta($metaFile,$meta)){
$title=__('📠 New Fax Received');
$body=sprintf(__('Caller : %s / pages : %d '),$caller,$pages);
sendPushToAll($title,$body,"/fax_inbox.php");
@unlink($inputFile);@chmod($tifFile,0666);@chmod($pdfFile,0666);@chmod($metaFile,0666);
echo "Success: $base.pdf\n";
}else echo "Meta save failed.\n";
}
