diff --git a/app/Config/Acl.php b/app/Config/Acl.php index b59905ff..67edbd35 100644 --- a/app/Config/Acl.php +++ b/app/Config/Acl.php @@ -42,6 +42,7 @@ class Acl '#^/sales#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]], '#^/expense#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, STAFF_ROLE_ID]], '#^/sendDataToTPA#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID, MANAGER_ROLE_ID]], + '#^/swagger#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID, MANAGER_ROLE_ID]], diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 0129af3d..081b44cd 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -29,6 +29,8 @@ $routes->get('/chatbottest', 'ChatbotControllerNew::chatbotest'); $routes->get('/chatbot', 'ChatbotControllerNew::chatbot'); $routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']); +$routes->get('/swagger/tpa', 'SwaggerController::tpa', ['filter' => 'authMVC']); +$routes->get('/swagger/tpa-spec', 'SwaggerController::tpaSpec', ['filter' => 'authMVC']); $routes->get('/fedeploy', 'DeployController::fedeploy_view', ['filter' => 'authMVC']); $routes->post('/fedeploy', 'DeployController::fedeploy', ['filter' => 'authMVC']); $routes->get('/visitOffBoardCheck', 'EmployeeController::visitOffBoardCheck'); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index fd4a3419..9518d202 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -3785,6 +3785,14 @@ class EmployeeRestController extends AdminController $this->handleCliamFiles($file_data, $ticket_id, $ticket_message_id); + // Merge all uploaded PDFs for this ticket into a single combined PDF + try { + helper('merge_pdf'); + merge_ticket_pdfs((int) $ticket_id); + } catch (\Throwable $e) { + log_message('error', 'EmployeeRestController::initiateClaim | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage()); + } + $mail_sent_status = ($this->ticketController->sendAutoMailTrigger($ticket_id)); if (gettype($mail_sent_status) == 'array') { $message = 'Claim Iniated Successfully'; @@ -5444,6 +5452,14 @@ class EmployeeRestController extends AdminController $result = $this->handleCliamFiles($file_data, $ticket_id, null, false, true); if (! empty($result)) { + // Merge all uploaded PDFs for this ticket into a single combined PDF + try { + helper('merge_pdf'); + merge_ticket_pdfs((int) $ticket_id); + } catch (\Throwable $e) { + log_message('error', 'EmployeeRestController::uploadIRDocs | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage()); + } + // $this->ticketMaster->where('id', $ticket_id)->set(['required_docs', $required_docs])->update(); db_connect()->query( "UPDATE ticket_master SET required_docs = ? WHERE id = ?", diff --git a/app/Controllers/FhplApiController.php b/app/Controllers/FhplApiController.php index 542f461b..dfa7db1b 100644 --- a/app/Controllers/FhplApiController.php +++ b/app/Controllers/FhplApiController.php @@ -92,7 +92,7 @@ class FhplApiController extends BaseController ->join('employees e', 'e.id = tm.emp_id', 'left') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') ->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left') - ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 AND cf.mime_type='application/pdf'", 'left') + ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); diff --git a/app/Controllers/HealthIndiaApiController.php b/app/Controllers/HealthIndiaApiController.php index db356888..46b67043 100644 --- a/app/Controllers/HealthIndiaApiController.php +++ b/app/Controllers/HealthIndiaApiController.php @@ -113,7 +113,7 @@ class HealthIndiaApiController extends BaseController ->join('employees e', 'e.id = tm.emp_id', 'left') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') ->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left') - ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 AND cf.mime_type='application/pdf'", 'left') + ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); diff --git a/app/Controllers/MediAssistApiController.php b/app/Controllers/MediAssistApiController.php index 341e3f9b..cb39d93c 100644 --- a/app/Controllers/MediAssistApiController.php +++ b/app/Controllers/MediAssistApiController.php @@ -67,7 +67,7 @@ class MediAssistApiController extends BaseController ->join('employees e', 'e.id = tm.emp_id', 'left') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') ->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left') - ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 and cf.mime_type = 'application/pdf'", 'left') + ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); // single record diff --git a/app/Controllers/SwaggerController.php b/app/Controllers/SwaggerController.php index 75955f60..c84dcc08 100755 --- a/app/Controllers/SwaggerController.php +++ b/app/Controllers/SwaggerController.php @@ -1,10 +1,84 @@ base_url('assets/api.yaml'), + 'pageTitle' => 'Swagger UI', + 'swaggerPreauthorize' => [], + ]); + } + + /** + * Swagger UI for TPA external integrations OpenAPI spec (openapi/tpa-external-integrations.yaml). + * Pre-fills Authorize from the same `.env` keys the API controllers use (`getenv`). + */ + public function tpa() + { + return view('swagger/index', [ + 'specUrl' => base_url('swagger/tpa-spec'), + 'pageTitle' => 'TPA external APIs — Swagger UI', + 'swaggerPreauthorize' => $this->buildTpaSwaggerPreauthorize(), + ]); + } + + /** + * Values for Swagger UI Authorize (apiKey / basic). Uses runtime env — keep `/swagger/tpa` access-controlled. + * + * @return list> + */ + protected function buildTpaSwaggerPreauthorize(): array + { + return [ + ['kind' => 'apiKey', 'scheme' => 'MediAssistUsername', 'value' => $this->readEnvString('MEDI_ASSIST_API_USERNAME')], + ['kind' => 'apiKey', 'scheme' => 'MediAssistPassword', 'value' => $this->readEnvString('MEDI_ASSIST_API_PASSWORD')], + ['kind' => 'apiKey', 'scheme' => 'VidalSubscriptionKey', 'value' => $this->readEnvString('VIDAL_API_SUBSCRIPTION_KEY')], + ['kind' => 'apiKey', 'scheme' => 'VidalIrSubscriptionKey', 'value' => $this->readEnvString('VIDAL_SUBSCRIPTION_KEY')], + ['kind' => 'apiKey', 'scheme' => 'VidalWellnessSubscriptionKey', 'value' => $this->readEnvString('VIDAL_WELLNESS_SUBSCRIPTION_KEY')], + [ + 'kind' => 'basic', + 'scheme' => 'HealthIndiaTokenBasic', + 'username' => $this->readEnvString('HEALTH_INDIA_USERNAME'), + 'password' => $this->readEnvString('HEALTH_INDIA_PASSWORD'), + ], + ]; + } + + /** + * Read `.env` the same way as the rest of CodeIgniter (`env()` then `getenv()`). + */ + protected function readEnvString(string $key): string + { + if (function_exists('env')) { + $v = \env($key); + if ($v !== null) { + return \is_bool($v) ? '' : (string) $v; + } + } + + $g = \getenv($key); + + return $g === false ? '' : (string) $g; + } + + /** + * Serves the OpenAPI YAML from project root /openapi (not under public/). + */ + public function tpaSpec() + { + $path = ROOTPATH . 'openapi/tpa-external-integrations.yaml'; + if (! is_readable($path)) { + throw PageNotFoundException::forPageNotFound('OpenAPI spec not found.'); + } + + return $this->response + ->setHeader('Content-Type', 'application/yaml; charset=UTF-8') + ->setHeader('Cache-Control', 'public, max-age=300') + ->setBody(file_get_contents($path)); + } } \ No newline at end of file diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index 5691c819..6f64777c 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -2403,7 +2403,7 @@ class TicketController extends BaseController $claimFiles = new ClaimFilesModel(); $file_record = $claimFiles->where('id', $claim_file_id)->where('is_active', 1)->first(); - if ($file_record === null || (int) ($file_record['file_type'] ?? 0) !== 2) { + if ($file_record === null || ! in_array((int) ($file_record['file_type'] ?? 0), [2, 4], true)) { throw PageNotFoundException::forPageNotFound(); } @@ -3677,6 +3677,13 @@ class TicketController extends BaseController $employeeRest = new EmployeeRestController(); $result = $employeeRest->handleCliamFiles($file_data, $ticket_id); if(!empty($result)){ + // Merge all uploaded PDFs for this ticket into a single combined PDF + try { + helper('merge_pdf'); + merge_ticket_pdfs((int) $ticket_id); + } catch (\Throwable $e) { + log_message('error', 'TicketController::upload_url | merge_ticket_pdfs failed | ticket_id=' . $ticket_id . ' | ' . $e->getMessage()); + } return $this->respond(['status' => true, 'message' => 'File uploaded successfully ']); }else{ return $this->respond(['status' => false, 'message' => 'Failed to upload file ']); @@ -3704,7 +3711,7 @@ class TicketController extends BaseController ->select(" *, CASE - WHEN file_type = 2 AND url IS NOT NULL AND url != '' + WHEN file_type IN (2, 4) AND url IS NOT NULL AND url != '' THEN CONCAT('" . base_url('downloadClaimFile/') . "', id) ELSE url END AS url diff --git a/app/Controllers/VidalApiController.php b/app/Controllers/VidalApiController.php index d1fd6b40..889ae745 100644 --- a/app/Controllers/VidalApiController.php +++ b/app/Controllers/VidalApiController.php @@ -168,7 +168,7 @@ class VidalApiController extends BaseController ->join('policy_type pt', 'pt.id = cp.policy_type_id', 'left') ->join('employee_polices ep', 'ep.employee_id = e.id AND ep.client_policy_id = cp.id', 'left') ->join('ticket_notes tn', 'tn.ticket_id = tm.id', 'left') - ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 and cf.mime_type = 'application/pdf'", 'left') + ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); // single record diff --git a/app/Controllers/VoloApiController.php b/app/Controllers/VoloApiController.php index 63e63c6d..b1bc0a4b 100644 --- a/app/Controllers/VoloApiController.php +++ b/app/Controllers/VoloApiController.php @@ -696,7 +696,7 @@ class VoloApiController extends BaseController cf.url as filePath ') ->join('client_policy cp', 'tm.client_policy_id = cp.id', 'left') - ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 2 AND cf.mime_type = 'application/pdf'", 'left') + ->join('claim_files cf', "cf.ticket_id = tm.id AND cf.file_type = 4 AND cf.is_active = 1 AND cf.mime_type = 'application/pdf'", 'left') ->where('tm.id', $claimId) ->get() ->getRowArray(); diff --git a/app/Filters/GlobalPostFileUploadGuard.php b/app/Filters/GlobalPostFileUploadGuard.php index 5b303056..a3303e2f 100644 --- a/app/Filters/GlobalPostFileUploadGuard.php +++ b/app/Filters/GlobalPostFileUploadGuard.php @@ -10,43 +10,62 @@ use finfo; class GlobalPostFileUploadGuard implements FilterInterface { - /** - * Max file size (in bytes) → 25MB - */ protected int $maxFileSize = 25 * 1024 * 1024; - /** - * Allowed MIME types mapped to extensions - */ protected array $allowedMimeMap = [ 'image/jpeg' => ['jpg', 'jpeg'], 'image/png' => ['png'], 'image/gif' => ['gif'], 'image/webp' => ['webp'], - 'image/svg+xml' => ['svg'], + // SVG removed — dangerous without server-side sanitization 'application/pdf' => ['pdf'], 'application/msword' => ['doc'], 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'], 'application/vnd.oasis.opendocument.text' => ['odt'], - 'text/rtf' => ['rtf'], + 'text/rtf' => ['rtf'], 'application/rtf' => ['rtf'], - 'application/vnd.ms-excel' => ['xls', 'xlsx'], + 'application/vnd.ms-excel' => ['xls'], // removed xlsx from here — it has its own MIME 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'], 'application/vnd.oasis.opendocument.spreadsheet' => ['ods'], - 'text/csv' => ['csv'], + 'text/csv' => ['csv'], 'application/csv' => ['csv'], - 'text/plain' => ['txt', 'csv'], + 'text/plain' => ['txt'], // separated csv out — txt only + ]; + + protected array $magicBytes = [ + 'image/jpeg' => ["\xFF\xD8\xFF"], + 'image/png' => ["\x89PNG\r\n\x1a\n"], + 'image/gif' => ["GIF87a", "GIF89a"], + 'image/webp' => ["RIFF"], + 'application/pdf' => ["%PDF-"], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ["PK\x03\x04"], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ["PK\x03\x04"], + 'application/vnd.oasis.opendocument.text' => ["PK\x03\x04"], + 'application/vnd.oasis.opendocument.spreadsheet' => ["PK\x03\x04"], + 'application/msword' => ["\xD0\xCF\x11\xE0"], + 'application/vnd.ms-excel' => ["\xD0\xCF\x11\xE0"], ]; protected array $blockedExtensions = [ - 'php', 'phtml', 'html', 'pht', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'phps', - 'cgi', 'fcgi', 'pl', 'py', 'rb', 'lua', 'tcl', 'go', 'rs', 'jar', 'class', - 'exe', 'dll', 'com', 'bat', 'cmd', 'msi', 'vbs', 'ps1', 'scr', - 'sh', 'bash', 'zsh', 'apk', 'app', 'deb', 'rpm', 'bin', 'run', - 'js', 'mjs', 'jsp', 'asp', 'aspx', 'cer', 'swf', - 'env', 'ini', 'user.ini', 'htaccess', 'htpasswd', 'conf', 'config', 'log', 'sql', - 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso', - 'lnk', 'url', 'reg', 'sys', 'drv', 'vxd', 'tmp', 'bak', 'old', 'backup', 'key', 'pem' + 'php', 'phtml', 'html', 'htm', 'pht', 'phar', + 'php3', 'php4', 'php5', 'php7', 'php8', 'phps', + 'cgi', 'fcgi', 'pl', 'py', 'rb', 'lua', 'tcl', + 'go', 'rs', 'jar', 'class', + 'exe', 'dll', 'com', 'bat', 'cmd', 'msi', + 'vbs', 'ps1', 'ps2', 'scr', 'hta', + 'sh', 'bash', 'zsh', 'fish', + 'apk', 'app', 'deb', 'rpm', + 'bin', 'run', 'elf', + 'js', 'mjs', 'ts', 'jsx', 'tsx', + 'jsp', 'jspx', 'asp', 'aspx', 'ascx', 'ashx', 'axd', + 'cer', 'swf', 'xhtml', + 'env', 'ini', 'user.ini', 'htaccess', 'htpasswd', + 'conf', 'config', 'log', 'sql', 'db', 'sqlite', + 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso', 'cab', + 'lnk', 'url', 'reg', 'sys', 'drv', 'vxd', + 'tmp', 'bak', 'old', 'backup', + 'key', 'pem', 'p12', 'pfx', 'crt', 'csr', + 'xml', 'xsl', 'xslt', 'svg', ]; public function before(RequestInterface $request, $arguments = null) @@ -68,8 +87,8 @@ class GlobalPostFileUploadGuard implements FilterInterface private function validateFileInput($fileData, string $inputName): void { if (is_array($fileData)) { - foreach ($fileData as $file) { - $this->validateSingleFile($file, $inputName); + foreach ($fileData as $key => $item) { + $this->validateFileInput($item, $inputName . '[' . $key . ']'); } } else { $this->validateSingleFile($fileData, $inputName); @@ -78,7 +97,7 @@ class GlobalPostFileUploadGuard implements FilterInterface private function validateSingleFile($file, string $inputName): void { - $request = Services::request(); + $request = Services::request(); $clientIp = $request->getIPAddress(); $uri = $request->getUri()->getPath(); @@ -86,45 +105,211 @@ class GlobalPostFileUploadGuard implements FilterInterface if ($file->getError() === UPLOAD_ERR_INI_SIZE || $file->getError() === UPLOAD_ERR_FORM_SIZE) { $this->block("File exceeds server-side size limit", $clientIp, $uri, $inputName, $file->getClientName(), 'unknown', 'unknown', 0); } - return; + return; } - $originalName = $file->getClientName(); - $extension = strtolower($file->getExtension()); - $mime = $file->getMimeType(); - $size = $file->getSize(); + $originalName = $file->getClientName(); + $clientExtension = strtolower($file->getClientExtension()); + $tempPath = $file->getTempName(); + $size = $file->getSize(); - // --- 1. Fixed Null Byte & Path Traversal Check --- - if (preg_match('/\0|[\/\\\]/', $originalName)) { - $this->block("Malicious filename characters", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + // echo $file->getExtension(); + // echo '@@@@@@@@@@@@@@@@@@@@@@@'; + // echo $file->getMimeType(); + // --- 1. Null Byte & Path Traversal Check --- + if (preg_match('/\0|[\/\\\\]/', $originalName)) { + $this->block("Malicious filename characters", $clientIp, $uri, $inputName, $originalName, 'unknown', $clientExtension, $size); } - // --- 2. Double Extension Attack Check --- - if (preg_match('/\.(php|html|phtml|phar|exe|sh|bat|cmd|js|jsp|asp|aspx|py|pl)\./i', $originalName)) { - $this->block("Double extension attack", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + // --- 2. Filename length check --- + if (strlen($originalName) > 255) { + $this->block("Filename too long", $clientIp, $uri, $inputName, substr($originalName, 0, 100) . '...', 'unknown', $clientExtension, $size); } - // --- 3. Forbidden Extension --- - if (in_array($extension, $this->blockedExtensions, true)) { - $this->block("Forbidden extension", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + // --- 3. Double/Multiple Extension Attack --- + $nameParts = explode('.', $originalName); + if (count($nameParts) > 2) { + $allExtensions = array_slice($nameParts, 1); + foreach ($allExtensions as $part) { + if (in_array(strtolower($part), $this->blockedExtensions, true)) { + $this->block("Double/multiple extension attack detected", $clientIp, $uri, $inputName, $originalName, 'unknown', $clientExtension, $size); + } + } } - // --- 4. File Size Limit --- + // --- 4. Forbidden Extension --- + if (in_array($clientExtension, $this->blockedExtensions, true)) { + $this->block("Forbidden extension", $clientIp, $uri, $inputName, $originalName, 'unknown', $clientExtension, $size); + } + + // --- 5. File Size Limit --- if ($size > $this->maxFileSize) { - $this->block("File too large", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + $this->block("File too large", $clientIp, $uri, $inputName, $originalName, 'unknown', $clientExtension, $size); } - // --- 5. MIME Allow-list Check --- - if (!array_key_exists($mime, $this->allowedMimeMap)) { - $this->block("MIME type not allowed ($mime)", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + // --- 6. Real MIME Detection via finfo on actual temp file --- + $finfo = new finfo(FILEINFO_MIME_TYPE); + $detectedMime = $finfo->file($tempPath); + + // --- 7. Resolve Expected MIME From Extension --- + $expectedMime = null; + + foreach ($this->allowedMimeMap as $mime => $extensions) { + + if (in_array($clientExtension, $extensions, true)) { + $expectedMime = $mime; + break; + } } - // --- 6. MIME-Extension Consistency --- - if (!in_array($extension, $this->allowedMimeMap[$mime], true)) { - $this->block("MIME-extension mismatch", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + if ($expectedMime === null) { + $this->block( + "Extension not allowed", + $clientIp, + $uri, + $inputName, + $originalName, + $detectedMime, + $clientExtension, + $size + ); + } + + // --- 8. Magic Bytes Deep Validation --- + // validate using EXPECTED MIME instead of detected MIME + $this->validateMagicBytes( + $tempPath, + $expectedMime, + $clientIp, + $uri, + $inputName, + $originalName, + $clientExtension, + $size + ); + + // // --- 9. Embedded Code Scan --- + // $this->scanForEmbeddedCode( + // $tempPath, + // $expectedMime, + // $clientIp, + // $uri, + // $inputName, + // $originalName, + // $clientExtension, + // $size + // ); + + // --- 10. Final MIME Validation --- + // strict match only: generic octet-stream is not accepted + if ($detectedMime !== $expectedMime) { + $this->block( + "MIME-extension mismatch", + $clientIp, + $uri, + $inputName, + $originalName, + $detectedMime, + $clientExtension, + $size + ); + } + + // --- 10. Embedded Code Scan --- + // $this->scanForEmbeddedCode($tempPath, $detectedMime, $clientIp, $uri, $inputName, $originalName, $clientExtension, $size); + } + + private function validateMagicBytes( + string $tempPath, + string $mime, + string $ip, + string $uri, + string $field, + string $filename, + string $ext, + int $size + ): void { + if (!isset($this->magicBytes[$mime])) { + return; + } + // echo $mime;print_r($this->magicBytes[$mime]); + $handle = fopen($tempPath, 'rb'); + if (!$handle) { + $this->block("Cannot read uploaded file", $ip, $uri, $field, $filename, $mime, $ext, $size); + } + + $header = fread($handle, 12); + fclose($handle); + + $matched = false; + foreach ($this->magicBytes[$mime] as $signature) { + if (str_starts_with($header, $signature)) { + $matched = true; + break; + } + } + // echo $matched;die; + // WebP special case: RIFF....WEBP + if ($mime === 'image/webp') { + $matched = (substr($header, 0, 4) === 'RIFF' && substr($header, 8, 4) === 'WEBP'); + } + + if (!$matched) { + $this->block("Magic bytes mismatch for MIME: $mime", $ip, $uri, $field, $filename, $mime, $ext, $size); } } + private function scanForEmbeddedCode( + string $tempPath, + string $mime, + string $ip, + string $uri, + string $field, + string $filename, + string $ext, + int $size + ): void { + $scanLimit = 1024 * 1024; + + $content = ''; + if ($size <= $scanLimit) { + $content = file_get_contents($tempPath); + } else { + $handle = fopen($tempPath, 'rb'); + if ($handle) { + $content = fread($handle, 10240); + fseek($handle, -10240, SEEK_END); + $content .= fread($handle, 10240); + fclose($handle); + } + } + + if (empty($content)) { + return; + } + + $dangerousPatterns = [ + '/<\?php/i', + '/<\?=/i', + '/<\?/i', + '/<%/i', + '/block("Embedded code pattern detected in file", $ip, $uri, $field, $filename, $mime, $ext, $size); + } + } + } + + // block() signature and body kept EXACTLY as original — only $ext source changed upstream private function block(string $reason, string $ip, string $uri, string $field, string $filename, string $mime, string $ext, int $size): void { log_message('critical', @@ -144,4 +329,4 @@ class GlobalPostFileUploadGuard implements FilterInterface } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {} -} \ No newline at end of file +} diff --git a/app/Filters/GlobalPostFileUploadGuard_OLD.php b/app/Filters/GlobalPostFileUploadGuard_OLD.php new file mode 100644 index 00000000..75d7588b --- /dev/null +++ b/app/Filters/GlobalPostFileUploadGuard_OLD.php @@ -0,0 +1,150 @@ + ['jpg', 'jpeg'], + 'image/png' => ['png'], + 'image/gif' => ['gif'], + 'image/webp' => ['webp'], + 'image/svg+xml' => ['svg'], + 'application/pdf' => ['pdf'], + 'application/msword' => ['doc'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'], + 'application/vnd.oasis.opendocument.text' => ['odt'], + 'text/rtf' => ['rtf'], + 'application/rtf' => ['rtf'], + 'application/vnd.ms-excel' => ['xls', 'xlsx'], + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'], + 'application/vnd.oasis.opendocument.spreadsheet' => ['ods'], + 'text/csv' => ['csv'], + 'application/csv' => ['csv'], + 'text/plain' => ['txt', 'csv'], + ]; + + protected array $blockedExtensions = [ + 'php', 'phtml', 'html', 'pht', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'phps', + 'cgi', 'fcgi', 'pl', 'py', 'rb', 'lua', 'tcl', 'go', 'rs', 'jar', 'class', + 'exe', 'dll', 'com', 'bat', 'cmd', 'msi', 'vbs', 'ps1', 'scr', + 'sh', 'bash', 'zsh', 'apk', 'app', 'deb', 'rpm', 'bin', 'run', + 'js', 'mjs', 'jsp', 'asp', 'aspx', 'cer', 'swf', + 'env', 'ini', 'user.ini', 'htaccess', 'htpasswd', 'conf', 'config', 'log', 'sql', + 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso', + 'lnk', 'url', 'reg', 'sys', 'drv', 'vxd', 'tmp', 'bak', 'old', 'backup', 'key', 'pem' + ]; + + public function before(RequestInterface $request, $arguments = null) + { + if ($request->getMethod() !== 'post') { + return; + } + + $files = $request->getFiles(); + if (empty($files)) { + return; + } + + foreach ($files as $inputName => $fileData) { + $this->validateFileInput($fileData, $inputName); + } + } + + private function validateFileInput($fileData, string $inputName): void + { + if (is_array($fileData)) { + foreach ($fileData as $file) { + $this->validateSingleFile($file, $inputName); + } + } else { + $this->validateSingleFile($fileData, $inputName); + } + } + + private function validateSingleFile($file, string $inputName): void + { + $request = Services::request(); + $clientIp = $request->getIPAddress(); + $uri = $request->getUri()->getPath(); + + if (!$file->isValid()) { + if ($file->getError() === UPLOAD_ERR_INI_SIZE || $file->getError() === UPLOAD_ERR_FORM_SIZE) { + $this->block("File exceeds server-side size limit", $clientIp, $uri, $inputName, $file->getClientName(), 'unknown', 'unknown', 0); + } + return; + } + + $originalName = $file->getClientName(); + $extension = strtolower($file->getExtension()); + $client_extension = strtolower($file->getClientExtension()); + $mime = $file->getMimeType(); + $size = $file->getSize(); + + echo $extension.' - '.$client_extension;die; + + // --- 1. Fixed Null Byte & Path Traversal Check --- + if (preg_match('/\0|[\/\\\]/', $originalName)) { + $this->block("Malicious filename characters", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + + // --- 2. Double Extension Attack Check --- + if (preg_match('/\.(php|html|phtml|phar|exe|sh|bat|cmd|js|jsp|asp|aspx|py|pl)\./i', $originalName)) { + $this->block("Double extension attack", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + + // --- 3. Forbidden Extension --- + if (in_array($extension, $this->blockedExtensions, true)) { + $this->block("Forbidden extension", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + + // --- 4. File Size Limit --- + if ($size > $this->maxFileSize) { + $this->block("File too large", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + + // --- 5. MIME Allow-list Check --- + if (!array_key_exists($mime, $this->allowedMimeMap)) { + $this->block("MIME type not allowed ($mime)", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + + // --- 6. MIME-Extension Consistency --- + if (!in_array($extension, $this->allowedMimeMap[$mime], true)) { + $this->block("MIME-extension mismatch", $clientIp, $uri, $inputName, $originalName, $mime, $extension, $size); + } + } + + private function block(string $reason, string $ip, string $uri, string $field, string $filename, string $mime, string $ext, int $size): void + { + log_message('critical', + '[UPLOAD_BLOCKED] {reason} | IP: {ip} | URI: {uri} | Field: {field} | File: {file} | MIME: {mime} | EXT: {ext} | SIZE: {size}', + ['reason'=>$reason, 'ip'=>$ip, 'uri'=>$uri, 'field'=>$field, 'file'=>$filename, 'mime'=>$mime, 'ext'=>$ext, 'size'=>$size] + ); + + $response = Services::response(); + $response->setStatusCode(403) + ->setJSON([ + 'status' => 'error', + 'message' => 'File upload rejected: Security policy violation.' . ($reason ? " Reason: $reason." : ''), + 'debug' => (ENVIRONMENT === 'development') ? $reason : null + ]) + ->send(); + exit; + } + + public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {} +} \ No newline at end of file diff --git a/app/Helpers/merge_pdf_helper.php b/app/Helpers/merge_pdf_helper.php new file mode 100644 index 00000000..9316017f --- /dev/null +++ b/app/Helpers/merge_pdf_helper.php @@ -0,0 +1,194 @@ + true, + 'created_by' => null, + 'ticket_type' => 1, + 'include_file_types' => [2, 3], + ]; + + $result = [ + 'status' => false, + 'merged_file_id' => null, + 'file_name' => null, + 'pages' => 0, + 'source_count' => 0, + 'message' => '', + ]; + + if ($ticket_master_id <= 0) { + $result['message'] = 'Invalid ticket_master_id'; + return $result; + } + + $claimFiles = new ClaimFilesModel(); + + $rows = $claimFiles + ->where('ticket_id', $ticket_master_id) + ->where('is_active', 1) + ->where('mime_type', 'application/pdf') + ->whereIn('file_type', $opts['include_file_types']) + ->orderBy('id', 'ASC') + ->findAll(); + + if (empty($rows)) { + $result['status'] = true; + $result['message'] = 'No PDF files to merge'; + return $result; + } + + $uploadDir = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR + . 'uploads' . DIRECTORY_SEPARATOR + . 'claim_files' . DIRECTORY_SEPARATOR; + + $sourcePaths = []; + foreach ($rows as $row) { + $name = ! empty($row['url']) ? $row['url'] : ($row['file_name'] ?? ''); + if (empty($name)) { + continue; + } + // url column may sometimes hold a full URL; we only care about the file basename on disk. + $full = $uploadDir . basename($name); + if (is_file($full) && is_readable($full)) { + $sourcePaths[] = $full; + } else { + log_message('error', "merge_ticket_pdfs | missing PDF on disk | claim_file_id={$row['id']} | path={$full}"); + } + } + + if (empty($sourcePaths)) { + $result['message'] = 'No readable PDF files on disk'; + return $result; + } + + $result['source_count'] = count($sourcePaths); + + $tempDir = rtrim(WRITEPATH, '/\\') . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'mpdf'; + if (! is_dir($tempDir)) { + @mkdir($tempDir, 0775, true); + } + + $mergedName = 'merged_' . $ticket_master_id . '_' . time() . '_' . bin2hex(random_bytes(5)) . '.pdf'; + $mergedPath = $uploadDir . $mergedName; + + try { + $mpdf = new Mpdf([ + 'tempDir' => $tempDir, + 'mode' => 'utf-8', + ]); + + $totalPages = 0; + foreach ($sourcePaths as $src) { + try { + $pageCount = $mpdf->setSourceFile($src); + for ($p = 1; $p <= $pageCount; $p++) { + $tplId = $mpdf->importPage($p); + $size = $mpdf->getTemplateSize($tplId); + $mpdf->AddPageByArray([ + 'orientation' => ($size['width'] > $size['height']) ? 'L' : 'P', + 'sheet-size' => [$size['width'], $size['height']], + ]); + $mpdf->useTemplate($tplId); + $totalPages++; + } + } catch (\Throwable $e) { + log_message('error', "merge_ticket_pdfs | failed to import {$src} | " . $e->getMessage()); + } + } + + if ($totalPages === 0) { + $result['message'] = 'All source PDFs failed to import'; + return $result; + } + + $mpdf->Output($mergedPath, Destination::FILE); + } catch (\Throwable $e) { + log_message('error', 'merge_ticket_pdfs | mpdf failure | ticket_id=' . $ticket_master_id . ' | ' . $e->getMessage()); + $result['message'] = 'Merge failed: ' . $e->getMessage(); + return $result; + } + + if (! is_file($mergedPath)) { + $result['message'] = 'Merged file was not created'; + return $result; + } + + if ($opts['replace']) { + $claimFiles + ->where('ticket_id', $ticket_master_id) + ->where('file_type', MERGED_CLAIM_FILE_TYPE) + ->where('is_active', 1) + ->set(['is_active' => 0]) + ->update(); + } + + $insertData = [ + 'ticket_id' => $ticket_master_id, + 'ticket_type' => $opts['ticket_type'], + 'file_type' => MERGED_CLAIM_FILE_TYPE, + 'doc_name' => 'MERGED_CLAIM_DOCS_PDF', + 'file_name' => $mergedName, + 'url' => $mergedName, + 'mime_type' => 'application/pdf', + 'is_active' => 1, + ]; + if (! empty($opts['created_by'])) { + $insertData['created_by'] = $opts['created_by']; + } + + $insertedId = $claimFiles->insert($insertData); + + if (! $insertedId) { + log_message('error', 'merge_ticket_pdfs | DB insert failed for merged file | ticket_id=' . $ticket_master_id); + @unlink($mergedPath); + $result['message'] = 'Failed to register merged file in claim_files'; + return $result; + } + + log_message( + 'info', + "merge_ticket_pdfs | OK | ticket_id={$ticket_master_id} | sources={$result['source_count']} | pages={$totalPages} | claim_file_id={$insertedId}" + ); + + $result['status'] = true; + $result['merged_file_id'] = (int) $insertedId; + $result['file_name'] = $mergedName; + $result['pages'] = $totalPages; + $result['message'] = 'Merged successfully'; + return $result; + } +} diff --git a/app/Views/DashBoard.php b/app/Views/DashBoard.php index 5e2b1ee1..561e8098 100755 --- a/app/Views/DashBoard.php +++ b/app/Views/DashBoard.php @@ -185,6 +185,27 @@ + +
@@ -222,9 +243,6 @@ -