<?php
require_once('../../config.php');
if(!isset($_SESSION['user'])||!has_permission('inboxdownload')){header("Location:".($applicationBaseDir??'/')."login.php");exit;}
$receivedToken=$_GET['csrf']??'';
if(empty($_SESSION['csrf'])||$receivedToken!==$_SESSION['csrf']){header("Location:".($applicationBaseDir??'/')."fax_inbox.php?msg=".urlencode(__('Invalid security token')));exit;}
set_time_limit(240);
ignore_user_abort(true);
$dir=$_GET['dir']??'';
if($dir!==''&&!preg_match('/^[a-zA-Z0-9_\-\/]+$/',$dir)){header("Location:".($applicationBaseDir??'/')."fax_inbox.php?msg=".urlencode(__('Invalid directory')));exit;}
$fax=isset($_GET['fax'])?basename($_GET['fax']):'';
$type=strtolower($_GET['type']??'pdf');
if(!in_array($type,['pdf','tif','tiff'],true))$type='pdf';
if(empty($fax)){
header("Location:".($applicationBaseDir??'/')."fax_inbox.php?msg=".urlencode(__('File name is required')));
exit;
}
$baseArchivePath=realpath(rtrim($applicationArchivePath,'/\\'));
$filenameBase=pathinfo($fax,PATHINFO_FILENAME);
$typeMap=['pdf'=>['pdf'],'tiff'=>['tiff','tif'],'tif'=>['tif','tiff']];
$extensions=$typeMap[$type]??['pdf'];
$realPath='';
foreach($extensions as $ext){
$tryPath=$baseArchivePath
.($dir?DIRECTORY_SEPARATOR.$dir:'')
.DIRECTORY_SEPARATOR
.$filenameBase.'.'.$ext;
if(file_exists($tryPath)){$realPath=realpath($tryPath);break;}}
if(!$realPath||!is_file($realPath)||!str_starts_with($realPath,$baseArchivePath.DIRECTORY_SEPARATOR)){
header("Location:".($applicationBaseDir??'/')."fax_inbox.php?msg=".urlencode(__('File not found or access denied')));
exit;
}
$metaFile=dirname($realPath).DIRECTORY_SEPARATOR.pathinfo($realPath,PATHINFO_FILENAME).'.meta';
if(is_file($metaFile)){$meta=loadMeta($metaFile);if(!is_array($meta))$meta=[];$meta['read']=true;saveMeta($metaFile,$meta);}
$finfo=finfo_open(FILEINFO_MIME_TYPE);
$mimeType=finfo_file($finfo,$realPath);
finfo_close($finfo);
$allowedMime=['application/pdf','image/tiff','image/tif','image/x-tiff'];
if(!in_array($mimeType,$allowedMime)){header("Location:".($applicationBaseDir??'/')."fax_inbox.php?msg=".urlencode(__('Invalid file type')));exit;}
while(ob_get_level())ob_end_clean();
header('Content-Type:application/octet-stream');
header('X-Content-Type-Options:nosniff');
$encodedName=rawurlencode(basename($realPath));
header("Content-Disposition:attachment;filename=\"$encodedName\";filename*=UTF-8''$encodedName");
header('Content-Length:'.filesize($realPath));
header('Cache-Control:private,no-transform,no-store,must-revalidate');
header('Pragma:no-cache');
header('Expires:0');
$handle=fopen($realPath,'rb');
if($handle){fpassthru($handle);fclose($handle);}else{header("HTTP/1.1 500 Internal Server Error");exit(__('File open failed'));}
exit;
