FIX_VAPT_ISSUE_FILE_UPLOAD_VALIDTION

This commit is contained in:
velz 2026-02-26 15:47:16 +05:30
parent 9404a7a5bc
commit 83e0595530
13 changed files with 1662 additions and 1718 deletions

View File

@ -115,4 +115,19 @@ define('ACCOUNT_MANAGER_ROLE_ID', 3);
define('STAFF_ROLE_ID', 4); define('STAFF_ROLE_ID', 4);
define('HEAD_ROLE_ID', 5); define('HEAD_ROLE_ID', 5);
/**
* @Upload Allowed Extensions by Business Context
*/
define('UPLOAD_ALLOWED_EXTENSIONS', [
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg',
'pdf', 'doc', 'docx', 'odt', 'rtf',
'xls', 'xlsx', 'ods', 'csv', 'txt',
]);
define('UPLOAD_EXT_IMAGES', ['jpg', 'jpeg', 'png']);
define('UPLOAD_EXT_KYC_DOCS', ['pdf', 'jpg', 'jpeg', 'png']);
define('UPLOAD_EXT_CLAIM_DOCS', ['pdf', 'jpg', 'jpeg', 'png']);
define('UPLOAD_EXT_POLICY_DOCS', ['pdf', 'jpg', 'jpeg', 'png', 'xls', 'xlsx']);
define('UPLOAD_EXT_LEAD_FILES', ['xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png']);
define('UPLOAD_EXT_EXCEL', ['xls', 'xlsx', 'ods', 'csv']);
define('UPLOAD_EXT_MAIL_ATTACHMENTS', ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx']);

View File

@ -101,23 +101,22 @@ class AppContentManagementController extends AdminController
$file = $this->request->getFile('advertise_image'); $file = $this->request->getFile('advertise_image');
$client_id = $sanitized_post_data['client_id'] ?? null; $client_id = $sanitized_post_data['client_id'] ?? null;
//1) original file name for vaildations
$fileName = $file->getClientName(); //original file name for vaildations
$existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first();
if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); }
//skip 1) and use this
// $fileName = $file->getRandomName(); // Same Name Multiple time upload means different name
if (!$file || !$file->isValid()) { if (!$file || !$file->isValid()) {
return $this->respond(['status' => false, 'message' => 'No file uploaded or invalid file.'], 400); return $this->respond(['status' => false, 'message' => 'No file uploaded or invalid file.'], 400);
} }
// $uploadPath = WRITEPATH . 'uploads/advertiseImage/'; if (!validate_upload_extension($file, UPLOAD_EXT_IMAGES)) {
return $this->respond(['status' => false, 'message' => 'Only JPG, JPEG, PNG files are allowed.'], 400);
}
$fileName = sanitize_upload_filename($file->getClientName());
$existing = $this->addImgModel->where('name', $fileName)->where('client_id', $client_id)->where('is_active', 1)->first();
if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); }
$uploadPath = ROOTPATH . 'public/uploads/add_image_upload/'; $uploadPath = ROOTPATH . 'public/uploads/add_image_upload/';
if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true); if (!is_dir($uploadPath)) mkdir($uploadPath, 0755, true);
$file->move($uploadPath, $fileName); $file->move($uploadPath, $fileName);
$id = $sanitized_post_data['add_image_id'] ?? null; $id = $sanitized_post_data['add_image_id'] ?? null;

View File

@ -26,6 +26,13 @@ class ClaimsUploadController extends BaseController
], 400); ], 400);
} }
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->respond([
'status' => 'failed',
'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.'
], 400);
}
$data = [ $data = [
'client_id' => $this->request->getPost('client_id'), 'client_id' => $this->request->getPost('client_id'),
'tpa_id' => $this->request->getPost('tpa_id'), 'tpa_id' => $this->request->getPost('tpa_id'),

View File

@ -1051,7 +1051,7 @@ class ClientController extends AdminController
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$data = $this->request->getPost(); $data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data); $sanitized_post_data = sanitizeInputArrayAdvanced($data);
$sanitized_post_data['created_by'] = get_session_userid(); $sanitized_post_data['created_by'] = get_session_userid();
@ -1149,7 +1149,7 @@ class ClientController extends AdminController
$this->myLogger->logme('error', 'edit client general info function called'); $this->myLogger->logme('error', 'edit client general info function called');
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('client_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$id = $this->request->getPost('PrimaryKey'); $id = $this->request->getPost('PrimaryKey');
$data = $this->request->getPost(); $data = $this->request->getPost();
@ -1191,7 +1191,7 @@ class ClientController extends AdminController
// print_r($data); die; // print_r($data); die;
unset($data['file_name']); unset($data['file_name']);
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$File = file_Upload($this->request->getFile('file_name'), $uploadFilePath); $File = file_Upload($this->request->getFile('file_name'), $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($File)) { if (!empty($File)) {
$data['file_name'] = $File; $data['file_name'] = $File;
@ -1257,7 +1257,7 @@ class ClientController extends AdminController
$file = $this->request->getFile('file_name'); $file = $this->request->getFile('file_name');
$fileName = file_Upload($file, $uploadFilePath); $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) { if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName; $sanitized_data['file_name'] = $fileName;
@ -1313,7 +1313,7 @@ class ClientController extends AdminController
$file = $this->request->getFile('file_name'); $file = $this->request->getFile('file_name');
$fileName = file_Upload($file, $uploadFilePath); $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) { if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName; $sanitized_data['file_name'] = $fileName;
@ -1400,7 +1400,7 @@ class ClientController extends AdminController
$file = $this->request->getFile('file_name'); $file = $this->request->getFile('file_name');
$uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents'; $uploadFilePath = WRITEPATH . 'uploads/client_kyc_documents';
$fileName = file_Upload($file, $uploadFilePath); $fileName = file_Upload($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!empty($fileName)) { if (!empty($fileName)) {
$sanitized_data['file_name'] = $fileName; $sanitized_data['file_name'] = $fileName;
@ -1472,7 +1472,7 @@ class ClientController extends AdminController
if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) { if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
$new_file_name = file_Upload($uploadedFile, $uploadFilePath); $new_file_name = file_Upload($uploadedFile, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if (!$new_file_name) { if (!$new_file_name) {
return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200); return $this->respond(['status' => false, 'code' => 500, 'message' => 'New file upload failed on server.'], 200);
} }
@ -3479,7 +3479,7 @@ class ClientController extends AdminController
if (!empty($docName) && $file->isValid() && !$file->hasMoved()) { if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
// Upload the file // Upload the file
$uploadedFileName = file_Upload_for_lead($file, $uploadFilePath); $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath, UPLOAD_EXT_KYC_DOCS);
if ($uploadedFileName) { if ($uploadedFileName) {
// Prepare data for each document upload // Prepare data for each document upload

File diff suppressed because it is too large Load Diff

View File

@ -1035,7 +1035,7 @@ class LeadsController extends BaseController
$multi_file_data = []; $multi_file_data = [];
foreach ($files as $index => $value) { foreach ($files as $index => $value) {
$file_name = file_Upload_for_lead($value, $uploadFilePath); $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES);
$multi_file_data[] = [ $multi_file_data[] = [
'file_name' => $file_name, 'file_name' => $file_name,
'docs_name' => $docs_names[$index], 'docs_name' => $docs_names[$index],

View File

@ -367,7 +367,7 @@ class MasterController extends AdminController
} }
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$data = $this->request->getPost(); $data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data); $sanitized_post_data = sanitizeInputArrayAdvanced($data);
@ -593,7 +593,7 @@ class MasterController extends AdminController
} }
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('insurer_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$data = $this->request->getPost(); $data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($data); $sanitized_post_data = sanitizeInputArrayAdvanced($data);
$id = $sanitized_post_data['PrimaryKey']; $id = $sanitized_post_data['PrimaryKey'];
@ -974,11 +974,11 @@ class MasterController extends AdminController
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$template_bg_path = ROOTPATH . 'public/uploads/template_bg'; $template_bg_path = ROOTPATH . 'public/uploads/template_bg';
$front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path); $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES);
$back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES);
$eCardTemplate = $sanitized_post_data['ecard_content']; $eCardTemplate = $sanitized_post_data['ecard_content'];
@ -1264,11 +1264,11 @@ class MasterController extends AdminController
$uploadFilePath = ROOTPATH . 'public/uploads/logo/'; $uploadFilePath = ROOTPATH . 'public/uploads/logo/';
$file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath); $file_name = file_Upload($this->request->getFile('tpa_logo'), $uploadFilePath, UPLOAD_EXT_IMAGES);
$template_bg_path = ROOTPATH . 'public/uploads/template_bg'; $template_bg_path = ROOTPATH . 'public/uploads/template_bg';
$front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path); $front_card_file_name = file_Upload($this->request->getFile('fc'), $template_bg_path, UPLOAD_EXT_IMAGES);
$back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path); $back_card_file_name = file_Upload($this->request->getFile('bc'), $template_bg_path, UPLOAD_EXT_IMAGES);
$id = $sanitized_post_data['PrimaryKey'] ?? null; $id = $sanitized_post_data['PrimaryKey'] ?? null;

View File

@ -364,7 +364,7 @@ class NotificationController extends AdminController
// Define upload path and attempt file upload // Define upload path and attempt file upload
$uploadFilePath = WRITEPATH . 'uploads/attachments'; $uploadFilePath = WRITEPATH . 'uploads/attachments';
$uploadedFile = $this->request->getFile('file'); $uploadedFile = $this->request->getFile('file');
$fileName = file_Upload_for_lead($uploadedFile, $uploadFilePath); // Assume file_Upload handles file saving $fileName = file_Upload_for_lead($uploadedFile, $uploadFilePath, UPLOAD_EXT_MAIL_ATTACHMENTS);
if ($fileName) { if ($fileName) {
// Prepare data for insertion // Prepare data for insertion

View File

@ -3411,7 +3411,7 @@ class PolicyTransactionController extends BaseController
if (!empty($docName) && $file->isValid() && !$file->hasMoved()) { if (!empty($docName) && $file->isValid() && !$file->hasMoved()) {
// Upload the file // Upload the file
$uploadedFileName = file_Upload_for_lead($file, $uploadFilePath); $uploadedFileName = file_Upload_for_lead($file, $uploadFilePath, UPLOAD_EXT_POLICY_DOCS);
if ($uploadedFileName) { if ($uploadedFileName) {
// Prepare data for each document upload // Prepare data for each document upload

View File

@ -104,6 +104,10 @@ class RuleImportController extends AdminController
return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']); return $this->response->setJSON(['status'=>false,'message'=>'No file uploaded or upload error']);
} }
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->response->setJSON(['status'=>false,'message'=>'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.']);
}
// Move uploaded file to writable temp location // Move uploaded file to writable temp location
$tmpPath = WRITEPATH . 'uploads/' . $file->getRandomName(); $tmpPath = WRITEPATH . 'uploads/' . $file->getRandomName();
$file->move(WRITEPATH . 'uploads', $file->getName()); // keep original name inside uploads $file->move(WRITEPATH . 'uploads', $file->getName()); // keep original name inside uploads
@ -140,6 +144,10 @@ class RuleImportController extends AdminController
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file uploaded or upload error.'], 200); return $this->respond(['status' => false, 'code' => 404, 'message' => 'No file uploaded or upload error.'], 200);
} }
if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Only Excel/CSV files (xls, xlsx, ods, csv) are allowed.'], 200);
}
// --------------------------------------------------------- // ---------------------------------------------------------
// 2. Read POST fields // 2. Read POST fields
// --------------------------------------------------------- // ---------------------------------------------------------

View File

@ -3237,7 +3237,7 @@ class TicketController extends BaseController
$file_data = []; $file_data = [];
if(isset($get_file_data) && !empty($get_file_data)){ if(isset($get_file_data) && !empty($get_file_data)){
$file_path = WRITEPATH . 'uploads/claim_files/'; $file_path = WRITEPATH . 'uploads/claim_files/';
$file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name); $file_data = multi_file_Upload($get_file_data, $file_path, $get_docs_name, UPLOAD_EXT_CLAIM_DOCS);
} }
if(!empty($file_data)){ if(!empty($file_data)){
@ -3932,7 +3932,7 @@ class TicketController extends BaseController
if ($is_moved) { if ($is_moved) {
$file_path = WRITEPATH.'uploads/claims_mis'; $file_path = WRITEPATH.'uploads/claims_mis';
$filename = file_Upload_for_lead($file, $file_path); $filename = file_Upload_for_lead($file, $file_path, UPLOAD_EXT_EXCEL);
$fileSize = $file->getSize(); // File size in bytes $fileSize = $file->getSize(); // File size in bytes
$fileSize = $fileSize / (1024 * 1024); // Convert to MB $fileSize = $fileSize / (1024 * 1024); // Convert to MB
@ -3983,7 +3983,7 @@ class TicketController extends BaseController
} }
$file_path = WRITEPATH.'uploads/claims_mis'; $file_path = WRITEPATH.'uploads/claims_mis';
$file_name = file_Upload_for_lead($file, $file_path); $file_name = file_Upload_for_lead($file, $file_path, UPLOAD_EXT_EXCEL);
if(!empty($file_name)){ if(!empty($file_name)){
$data['file_name'] = $file_name; $data['file_name'] = $file_name;

View File

@ -1010,7 +1010,14 @@ class UserController extends AdminController
if ($file && $file->isValid() && !$file->hasMoved()) { if ($file && $file->isValid() && !$file->hasMoved()) {
$originalName = $file->getClientName(); if (!validate_upload_extension($file, UPLOAD_EXT_EXCEL)) {
return $this->response->setJSON([
'status' => 'error',
'message' => 'Only Excel files (xls, xlsx, ods, csv) are allowed.',
])->setStatusCode(400);
}
$originalName = sanitize_upload_filename($file->getClientName());
$extension = $file->getExtension(); $extension = $file->getExtension();
$fileName = pathinfo($originalName, PATHINFO_FILENAME) . '_' . date('Ymd_His') . '.' . $extension; $fileName = pathinfo($originalName, PATHINFO_FILENAME) . '_' . date('Ymd_His') . '.' . $extension;

View File

@ -1,16 +1,14 @@
<?php <?php
use App\Models\ClientModel; use App\Controllers\ApiServiceController;
use App\Models\UserTeamsModel;
use App\Models\FileModel;
use App\Models\BatchFileModelFileModel;
use App\Controllers\GoogleDriveController; use App\Controllers\GoogleDriveController;
use App\Models\BatchFileModel; use App\Models\BatchFileModel;
use App\Controllers\ApiServiceController; use App\Models\FileModel;
use App\Models\TicketMasterModel; use App\Models\TicketMasterModel;
use App\Models\UserTeamsModel;
// File: app/Helpers/Uuid_helper.php // File: app/Helpers/Uuid_helper.php
if (!function_exists('generate_uuid')) { if (! function_exists('generate_uuid')) {
function generate_uuid($version = 4, $format = 'hex') function generate_uuid($version = 4, $format = 'hex')
{ {
$data = random_bytes(16); $data = random_bytes(16);
@ -26,7 +24,7 @@ if (!function_exists('generate_uuid')) {
} }
} }
if (!function_exists('change_date_format2')) { if (! function_exists('change_date_format2')) {
function change_date_format2($data, $source_format, $output_format) function change_date_format2($data, $source_format, $output_format)
{ {
@ -53,13 +51,47 @@ if (!function_exists('change_date_format2')) {
} }
} }
if (!function_exists('file_Upload')) { if (! function_exists('sanitize_upload_filename')) {
function file_Upload($fileToUpload, $filepath) function sanitize_upload_filename(string $fileName): string
{ {
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { $fileName = preg_replace('/[\x00-\x1F\x7F]/u', '', $fileName);
$fileToUpload->move($filepath); $fileName = preg_replace('/[\x{00A0}\x{200B}-\x{200D}\x{FEFF}\x{00AD}\x{2060}\x{180E}\x{2028}\x{2029}]/u', '', $fileName);
$fileName = $fileToUpload->getName(); $fileName = preg_replace('/[\/\\\\:*?"<>|;`${}()\'&!#]/', '', $fileName);
$fileName = preg_replace('/[\s\x{00A0}\x{200B}-\x{200D}\x{FEFF}]/u', '', $fileName); $fileName = preg_replace('/\.{2,}/', '.', $fileName);
$fileName = trim($fileName, ". \t\n\r");
if ($fileName === '' || strlen($fileName) > 200) {
$fileName = time() . '_' . bin2hex(random_bytes(8));
}
return $fileName;
}
}
if (! function_exists('validate_upload_extension')) {
function validate_upload_extension($file, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS): bool
{
$ext = strtolower($file->getClientExtension());
if (! in_array($ext, $allowedExtensions, true)) {
log_message('critical', '[UPLOAD_HELPER] Blocked extension: {ext} | File: {name}', [
'ext' => $ext,
'name' => $file->getClientName(),
]);
return false;
}
return true;
}
}
if (! function_exists('file_Upload')) {
function file_Upload($fileToUpload, $filepath, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS)
{
if ($fileToUpload !== null && $fileToUpload->isValid() && ! $fileToUpload->hasMoved()) {
if (! validate_upload_extension($fileToUpload, $allowedExtensions)) {
return "";
}
$fileName = sanitize_upload_filename($fileToUpload->getName());
$fileToUpload->move($filepath, $fileName);
return $fileName; return $fileName;
} else { } else {
return ""; return "";
@ -67,12 +99,15 @@ if (!function_exists('file_Upload')) {
} }
} }
if (!function_exists('file_Upload_for_lead')) { if (! function_exists('file_Upload_for_lead')) {
function file_Upload_for_lead($fileToUpload, $filepath) function file_Upload_for_lead($fileToUpload, $filepath, array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS)
{ {
if ($fileToUpload !== null && $fileToUpload->isValid() && !$fileToUpload->hasMoved()) { if ($fileToUpload !== null && $fileToUpload->isValid() && ! $fileToUpload->hasMoved()) {
$fileToUpload->move($filepath); if (! validate_upload_extension($fileToUpload, $allowedExtensions)) {
$fileName = $fileToUpload->getName(); return "";
}
$fileName = sanitize_upload_filename($fileToUpload->getName());
$fileToUpload->move($filepath, $fileName);
return $fileName; return $fileName;
} else { } else {
return ""; return "";
@ -115,8 +150,8 @@ if (!function_exists('file_Upload_for_lead')) {
// } // }
// function for only using in the Flutter Claim File Upload // function for only using in the Flutter Claim File Upload
if (!function_exists('multi_file_Upload')) { if (! function_exists('multi_file_Upload')) {
function multi_file_Upload($fileToUpload, $filepath, $docs_name = []) function multi_file_Upload($fileToUpload, $filepath, $docs_name = [], array $allowedExtensions = UPLOAD_ALLOWED_EXTENSIONS)
{ {
$uploadedFiles = []; $uploadedFiles = [];
@ -127,26 +162,32 @@ if (!function_exists('multi_file_Upload')) {
// If file is itself an array (multiple under same input name) // If file is itself an array (multiple under same input name)
if (is_array($file)) { if (is_array($file)) {
foreach ($file as $index => $f) { foreach ($file as $index => $f) {
if ($f !== null && $f->isValid() && !$f->hasMoved()) { if ($f !== null && $f->isValid() && ! $f->hasMoved()) {
$fileRandomName = $f->getRandomName(); // safer unique name if (! validate_upload_extension($f, $allowedExtensions)) {
$fileName = $f->getName(); continue;
}
$fileRandomName = $f->getRandomName();
$fileName = sanitize_upload_filename($f->getName());
$f->move($filepath, $fileRandomName); $f->move($filepath, $fileRandomName);
$uploadedFiles[] = [ $uploadedFiles[] = [
'file_name' => $fileName, 'file_name' => $fileName,
'doc_name' => $docs_name[$index] ?? $fileName, 'doc_name' => $docs_name[$index] ?? $fileName,
// 'file_path' => $filepath . $fileRandomName 'file_path' => $fileRandomName,
'file_path' => $fileRandomName
]; ];
} }
} }
} else { } else {
// Single file // Single file
if ($file !== null && $file->isValid() && !$file->hasMoved()) { if ($file !== null && $file->isValid() && ! $file->hasMoved()) {
$fileName = $file->getRandomName(); if (! validate_upload_extension($file, $allowedExtensions)) {
$file->move($filepath, $fileName); continue;
}
$fileName = sanitize_upload_filename($file->getName());
$diskName = $file->getRandomName();
$file->move($filepath, $diskName);
$uploadedFiles[] = [ $uploadedFiles[] = [
'file_name' => $fileName, 'file_name' => $fileName,
'file_path' => $filepath . $fileName 'file_path' => $filepath . $diskName,
]; ];
} }
} }
@ -156,8 +197,7 @@ if (!function_exists('multi_file_Upload')) {
} }
} }
if (! function_exists('file_unlink')) {
if (!function_exists('file_unlink')) {
function file_unlink($filepath) function file_unlink($filepath)
{ {
if (is_file($filepath) && file_exists($filepath)) { if (is_file($filepath) && file_exists($filepath)) {
@ -166,7 +206,7 @@ if (!function_exists('file_unlink')) {
} }
} }
if (!function_exists('compressImage')) { if (! function_exists('compressImage')) {
function compressImage($file, $destinationPath, $newWidth = 100, $newHeight = 100) function compressImage($file, $destinationPath, $newWidth = 100, $newHeight = 100)
{ {
// Load the image manipulation library // Load the image manipulation library
@ -181,8 +221,9 @@ if (!function_exists('compressImage')) {
} }
} }
if (!function_exists('fancy_date_time_format')) { if (! function_exists('fancy_date_time_format')) {
function fancy_date_time_format($datetime,$return_type = 'fancy') { function fancy_date_time_format($datetime, $return_type = 'fancy')
{
date_default_timezone_set('Asia/Kolkata'); date_default_timezone_set('Asia/Kolkata');
$currentDateTime = new DateTime(); $currentDateTime = new DateTime();
@ -215,7 +256,7 @@ if (!function_exists('fancy_date_time_format')) {
} }
if(!function_exists('check_string_date')){ if (! function_exists('check_string_date')) {
function check_string_date($str) function check_string_date($str)
{ {
if (DateTime::createFromFormat('Y-m-d H:i:s', $str) !== false) { if (DateTime::createFromFormat('Y-m-d H:i:s', $str) !== false) {
@ -225,9 +266,10 @@ if(!function_exists('check_string_date')){
} }
} }
if (!function_exists('generate_download_link')) { if (! function_exists('generate_download_link')) {
function generate_download_link($rand_string) { function generate_download_link($rand_string)
{
// Generate the link using provided emp_code and client_policy_id // Generate the link using provided emp_code and client_policy_id
$link = htmlspecialchars(base_url('download-e-card/' . $rand_string)); $link = htmlspecialchars(base_url('download-e-card/' . $rand_string));
@ -238,8 +280,9 @@ if (!function_exists('generate_download_link')) {
} }
} }
if (!function_exists('generate_random_alphanumeric')) { if (! function_exists('generate_random_alphanumeric')) {
function generate_random_alphanumeric($length = 12) { function generate_random_alphanumeric($length = 12)
{
$random_string = ''; $random_string = '';
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$random_ascii = rand(0, 61); $random_ascii = rand(0, 61);
@ -256,7 +299,7 @@ if (!function_exists('generate_random_alphanumeric')) {
} }
} }
if (!function_exists('get_base64_image')) { if (! function_exists('get_base64_image')) {
function get_base64_image($path) function get_base64_image($path)
{ {
@ -273,8 +316,9 @@ if (!function_exists('get_base64_image')) {
} }
} }
if (!function_exists('format_indian_number')) { if (! function_exists('format_indian_number')) {
function format_indian_number($number) { function format_indian_number($number)
{
// Round the number to two decimal places // Round the number to two decimal places
$number = isset($number) ? $number : 0; $number = isset($number) ? $number : 0;
$number = round($number, 2); $number = round($number, 2);
@ -306,8 +350,9 @@ if (!function_exists('format_indian_number')) {
} }
} }
if (!function_exists('get_username')) { if (! function_exists('get_username')) {
function get_username($user_id) { function get_username($user_id)
{
// Connect to the database // Connect to the database
$db = \Config\Database::connect(); $db = \Config\Database::connect();
@ -325,16 +370,18 @@ if (!function_exists('get_username')) {
} }
} }
if (!function_exists('get_role_id')) { if (! function_exists('get_role_id')) {
function get_role_id() { function get_role_id()
{
$role_id = isset(get_session_userdata()->role) ? get_session_userdata()->role : null; $role_id = isset(get_session_userdata()->role) ? get_session_userdata()->role : null;
return $role_id; return $role_id;
} }
} }
if (!function_exists('teams')) { if (! function_exists('teams')) {
function teams() { function teams()
{
// Load the UserTeamsModel // Load the UserTeamsModel
$teamModel = new \App\Models\UserTeamsModel(); $teamModel = new \App\Models\UserTeamsModel();
// Get the user ID from the session // Get the user ID from the session
@ -348,7 +395,7 @@ if (!function_exists('teams')) {
// log_message('info', 'User Teams: ' . json_encode($user_teams)); // Optionally log it // log_message('info', 'User Teams: ' . json_encode($user_teams)); // Optionally log it
// Check if the result is not empty // Check if the result is not empty
if (!empty($user_teams)) { if (! empty($user_teams)) {
// Extract only the 'team_id' values // Extract only the 'team_id' values
$team_ids = array_column($user_teams, 'team_id'); $team_ids = array_column($user_teams, 'team_id');
return $team_ids; // Return array of team IDs return $team_ids; // Return array of team IDs
@ -358,10 +405,9 @@ if (!function_exists('teams')) {
} }
} }
if (! function_exists('generate_client_code')) {
function generate_client_code($string = 'GC')
if (!function_exists('generate_client_code')) { {
function generate_client_code($string = 'GC') {
$clientModel = new \App\Models\ClientModel(); $clientModel = new \App\Models\ClientModel();
@ -378,8 +424,9 @@ if (!function_exists('generate_client_code')) {
} }
} }
if (!function_exists('generate_tsi_code')) { if (! function_exists('generate_tsi_code')) {
function generate_tsi_code($type) { function generate_tsi_code($type)
{
$PolicyTransactionModel = new \App\Models\PolicyTransactionModel(); $PolicyTransactionModel = new \App\Models\PolicyTransactionModel();
@ -390,9 +437,9 @@ if (!function_exists('generate_tsi_code')) {
$month = date('m'); $month = date('m');
$string = 'P'; $string = 'P';
if($type == 2){ if ($type == 2) {
$string2 = 'R'; $string2 = 'R';
}else{ } else {
$string2 = 'F'; $string2 = 'F';
} }
@ -404,34 +451,36 @@ if (!function_exists('generate_tsi_code')) {
} }
} }
if (!function_exists('generateRandomCode')) { if (! function_exists('generateRandomCode')) {
function generateRandomCode($prefix = 'RTL-', $length = 6) { function generateRandomCode($prefix = 'RTL-', $length = 6)
{
// Generate a random number with the specified length // Generate a random number with the specified length
$randomNumber = str_pad(mt_rand(0, pow(10, $length)-1), $length, '0', STR_PAD_LEFT); $randomNumber = str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
// Return the code with the prefix // Return the code with the prefix
return $prefix . $randomNumber; return $prefix . $randomNumber;
} }
} }
if (!function_exists('excelFileGDriveUpload')) { if (! function_exists('excelFileGDriveUpload')) {
function excelFileGDriveUpload($file_id, $table_name) { function excelFileGDriveUpload($file_id, $table_name)
{
$doc_type = "UPLOADS"; $doc_type = "UPLOADS";
$uploadFilePath = WRITEPATH . 'uploads/' . ($table_name == 'batch_file' ? 'import_excel' : 'excel'); $uploadFilePath = WRITEPATH . 'uploads/' . ($table_name == 'batch_file' ? 'import_excel' : 'excel');
$models = [ $models = [
'batch_file' => [ 'batch_file' => [
'model' => new BatchFileModel(), 'model' => new BatchFileModel(),
'select' => "client_id, client_policy_id, file_name" 'select' => "client_id, client_policy_id, file_name",
], ],
'files' => [ 'files' => [
'model' => new FileModel(), 'model' => new FileModel(),
'select' => "client_id, policy_id as client_policy_id, file_name" 'select' => "client_id, policy_id as client_policy_id, file_name",
], ],
]; ];
if (!array_key_exists($table_name, $models)) { if (! array_key_exists($table_name, $models)) {
return; return;
} }
@ -442,8 +491,6 @@ if (!function_exists('excelFileGDriveUpload')) {
->where('is_active', 1) ->where('is_active', 1)
->first(); ->first();
if ($data) { if ($data) {
$uploadFilePath .= '/' . $data['file_name']; $uploadFilePath .= '/' . $data['file_name'];
// dd($data, $uploadFilePath); // dd($data, $uploadFilePath);
@ -452,44 +499,45 @@ if (!function_exists('excelFileGDriveUpload')) {
$result = $GoogleDriveController->uploadFiletoGdrive( $result = $GoogleDriveController->uploadFiletoGdrive(
// client_id : $data['client_id'], // client_id : $data['client_id'],
client_policy_id: $data['client_policy_id'], client_policy_id: $data['client_policy_id'],
doc_type : $doc_type, doc_type: $doc_type,
file_path : $uploadFilePath, file_path: $uploadFilePath,
file_name : $data['file_name'] file_name: $data['file_name']
); );
// dd($result); // dd($result);
return true; return true;
}else{ } else {
return false; return false;
} }
} }
} }
if(!function_exists('checkFamilyFloaters')){ if (! function_exists('checkFamilyFloaters')) {
function checkFamilyFloaters($policy_premium_data, $client_policy_data, $emp_data){ function checkFamilyFloaters($policy_premium_data, $client_policy_data, $emp_data)
{
if($policy_premium_data['premium_type'] == 1){ if ($policy_premium_data['premium_type'] == 1) {
//only family floater //only family floater
if ($emp_data['relationship'] == 'Self') { if ($emp_data['relationship'] == 'Self') {
return true; return true;
} }
if($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3){ if ($client_policy_data['policy_type_id'] == 3 && $client_policy_data['is_addon'] == 3) {
if($emp_data['rata_premimum'] > 0){ if ($emp_data['rata_premimum'] > 0) {
return true; return true;
}else{ } else {
return false; return false;
} }
} }
return false; return false;
}else{ } else {
//individual //individual
return true; return true;
} }
@ -497,10 +545,10 @@ if(!function_exists('checkFamilyFloaters')){
} }
} }
if (!function_exists('numberToWords')) { if (! function_exists('numberToWords')) {
function numberToWords($number) function numberToWords($number)
{ {
$words = array( $words = [
'0' => 'Zero', '0' => 'Zero',
'1' => 'One', '1' => 'One',
'2' => 'Two', '2' => 'Two',
@ -528,30 +576,30 @@ if (!function_exists('numberToWords')) {
'60' => 'Sixty', '60' => 'Sixty',
'70' => 'Seventy', '70' => 'Seventy',
'80' => 'Eighty', '80' => 'Eighty',
'90' => 'Ninety' '90' => 'Ninety',
); ];
if ($number < 21) { if ($number < 21) {
return $words[$number]; return $words[$number];
} }
if ($number < 100) { if ($number < 100) {
$tens = (int)($number / 10) * 10; $tens = (int) ($number / 10) * 10;
$units = $number % 10; $units = $number % 10;
return $words[$tens] . ($units ? ' ' . $words[$units] : ''); return $words[$tens] . ($units ? ' ' . $words[$units] : '');
} }
if ($number < 1000) { if ($number < 1000) {
$hundreds = (int)($number / 100); $hundreds = (int) ($number / 100);
$remainder = $number % 100; $remainder = $number % 100;
return $words[$hundreds] . ' Hundred' . ($remainder ? ' and ' . numberToWords($remainder) : ''); return $words[$hundreds] . ' Hundred' . ($remainder ? ' and ' . numberToWords($remainder) : '');
} }
$levels = array('', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion'); $levels = ['', ' Thousand', ' Million', ' Billion', ' Trillion', ' Quadrillion', ' Quintillion'];
for ($i = 0, $unit = 1; $i < count($levels); $i++, $unit *= 1000) { for ($i = 0, $unit = 1; $i < count($levels); $i++, $unit *= 1000) {
if ($number < $unit * 1000) { if ($number < $unit * 1000) {
$current = (int)($number / $unit); $current = (int) ($number / $unit);
$remainder = $number % $unit; $remainder = $number % $unit;
return numberToWords($current) . $levels[$i] . ($remainder ? ' ' . numberToWords($remainder) : ''); return numberToWords($current) . $levels[$i] . ($remainder ? ' ' . numberToWords($remainder) : '');
} }
@ -561,7 +609,7 @@ if (!function_exists('numberToWords')) {
} }
} }
if (!function_exists('print_rr')) { if (! function_exists('print_rr')) {
function print_rr($data) function print_rr($data)
{ {
echo "<pre>"; echo "<pre>";
@ -570,7 +618,7 @@ if (!function_exists('print_rr')) {
} }
} }
if (!function_exists('get_server_details')) { if (! function_exists('get_server_details')) {
/** /**
* Get the hostname and server name. * Get the hostname and server name.
* *
@ -588,7 +636,7 @@ if (!function_exists('get_server_details')) {
} }
} }
if (!function_exists('isJsonString')) { if (! function_exists('isJsonString')) {
function isJsonString($input) function isJsonString($input)
{ {
@ -597,16 +645,18 @@ if (!function_exists('isJsonString')) {
} }
} }
if (!function_exists('isValidDate')) { if (! function_exists('isValidDate')) {
function isValidDate($date, $format) { function isValidDate($date, $format)
{
$parsed_date = DateTime::createFromFormat($format, $date); $parsed_date = DateTime::createFromFormat($format, $date);
return $parsed_date && $parsed_date->format($format) === $date; return $parsed_date && $parsed_date->format($format) === $date;
} }
} }
if (!function_exists('change_date_format')) { if (! function_exists('change_date_format')) {
function change_date_format($date_str, $source_format = null, $output_format = 'Y-m-d') { function change_date_format($date_str, $source_format = null, $output_format = 'Y-m-d')
{
$date_str = trim($date_str); $date_str = trim($date_str);
// Allowed date formats // Allowed date formats
@ -649,7 +699,7 @@ if (!function_exists('change_date_format')) {
// Case 1: Source and Output formats are provided // Case 1: Source and Output formats are provided
if ($source_format !== null && $output_format !== null) { if ($source_format !== null && $output_format !== null) {
$date = DateTime::createFromFormat($source_format, $date_str); $date = DateTime::createFromFormat($source_format, $date_str);
if (!$date) { if (! $date) {
// throw new Exception("Invalid date string for source format: $source_format"); // throw new Exception("Invalid date string for source format: $source_format");
// log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
return null; return null;
@ -660,7 +710,7 @@ if (!function_exists('change_date_format')) {
// Case 2: Source format is provided, Output format is null // Case 2: Source format is provided, Output format is null
if ($source_format !== null && $output_format === null) { if ($source_format !== null && $output_format === null) {
$date = DateTime::createFromFormat($source_format, $date_str); $date = DateTime::createFromFormat($source_format, $date_str);
if (!$date) { if (! $date) {
// throw new Exception("Invalid date string for source format: $source_format"); // throw new Exception("Invalid date string for source format: $source_format");
// log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}"); // log_message('error', "❌ Date format error : Invalid date string | Params => date_str: {$date_str}, source_format: {$source_format}, output_format: {$output_format}");
return null; return null;
@ -726,20 +776,20 @@ if (!function_exists('change_date_format')) {
// } // }
// } // }
if (!function_exists('check_pay_by_employee_or_company')) { if (! function_exists('check_pay_by_employee_or_company')) {
function check_pay_by_employee_or_company($policy_terms = null, $relationship = null) function check_pay_by_employee_or_company($policy_terms = null, $relationship = null)
{ {
// dd($policy_terms, $relationship); // dd($policy_terms, $relationship);
if (!$policy_terms || !($policy_terms = json_decode($policy_terms, true))) { if (! $policy_terms || ! ($policy_terms = json_decode($policy_terms, true))) {
return 0; return 0;
} }
// dd($policy_terms, $relationship); // dd($policy_terms, $relationship);
if (!isset($policy_terms['is_payable_employee'])) { if (! isset($policy_terms['is_payable_employee'])) {
return 0; return 0;
} }
@ -757,7 +807,7 @@ if (!function_exists('check_pay_by_employee_or_company')) {
'father' => 'elders', 'father' => 'elders',
'mother' => 'elders', 'mother' => 'elders',
'father_in_law' => 'elders', 'father_in_law' => 'elders',
'mother_in_law' => 'elders' 'mother_in_law' => 'elders',
]; ];
if (array_key_exists($relationship, $relationshipMap)) { if (array_key_exists($relationship, $relationshipMap)) {
@ -771,10 +821,10 @@ if (!function_exists('check_pay_by_employee_or_company')) {
} }
if (!function_exists('is_json_string')) { if (! function_exists('is_json_string')) {
function is_json_string($string) function is_json_string($string)
{ {
if (!is_string($string)) { if (! is_string($string)) {
return false; return false;
} }
@ -783,7 +833,7 @@ if (!function_exists('is_json_string')) {
} }
} }
if (!function_exists('check_cd_entry_exist')) { if (! function_exists('check_cd_entry_exist')) {
function check_cd_entry_exist($params) function check_cd_entry_exist($params)
{ {
$db = db_connect(); $db = db_connect();
@ -823,7 +873,7 @@ if (!function_exists('check_cd_entry_exist')) {
if (count($entries) > 1) { if (count($entries) > 1) {
// Only one entry found (truncated) // Only one entry found (truncated)
return true; return true;
}else{ } else {
return false; return false;
} }
} else { } else {
@ -838,7 +888,7 @@ if (!function_exists('check_cd_entry_exist')) {
->get() ->get()
->getRowArray(); ->getRowArray();
if (!empty($entry)) { if (! empty($entry)) {
return true; return true;
} }
} }
@ -847,7 +897,7 @@ if (!function_exists('check_cd_entry_exist')) {
} }
} }
if (!function_exists('expected_amount_calc')) { if (! function_exists('expected_amount_calc')) {
function expected_amount_calc($data, $index) function expected_amount_calc($data, $index)
{ {
$agreed_amount = (float) ($data['agreed_amount'][$index] ?? 0); $agreed_amount = (float) ($data['agreed_amount'][$index] ?? 0);
@ -859,12 +909,11 @@ if (!function_exists('expected_amount_calc')) {
$standard_tp_per = (float) ($data['standard_tp'][$index] ?? 0); $standard_tp_per = (float) ($data['standard_tp'][$index] ?? 0);
$standard_tep_per = (float) ($data['standard_ter'][$index] ?? 0); $standard_tep_per = (float) ($data['standard_ter'][$index] ?? 0);
if ($data['bro_payable_by'] == 0) {
if($data['bro_payable_by'] == 0){
$base_premium = (float) ($data['co_premium'][$index] ?? 0); $base_premium = (float) ($data['co_premium'][$index] ?? 0);
$third_part_premium = (float) ($data['co_tp_premium'][$index] ?? 0); $third_part_premium = (float) ($data['co_tp_premium'][$index] ?? 0);
$terrisom_premium = (float) ($data['co_ter_premium'][$index] ?? 0); $terrisom_premium = (float) ($data['co_ter_premium'][$index] ?? 0);
}else{ } else {
$base_premium = (float) ($data['base_premium'][$index] ?? 0); $base_premium = (float) ($data['base_premium'][$index] ?? 0);
$third_part_premium = (float) ($data['tp_premium'][$index] ?? 0); $third_part_premium = (float) ($data['tp_premium'][$index] ?? 0);
$terrisom_premium = (float) ($data['ter_premium'][$index] ?? 0); $terrisom_premium = (float) ($data['ter_premium'][$index] ?? 0);
@ -892,21 +941,21 @@ if (!function_exists('expected_amount_calc')) {
} }
} }
if (!function_exists('getFileIfExists')) { if (! function_exists('getFileIfExists')) {
function getFileIfExists($path) function getFileIfExists($path)
{ {
return file_exists(FCPATH . $path) ? base_url($path) : ''; return file_exists(FCPATH . $path) ? base_url($path) : '';
} }
} }
if (!function_exists('removeNumberFormatting')) { if (! function_exists('removeNumberFormatting')) {
function removeNumberFormatting($number) function removeNumberFormatting($number)
{ {
return (float) str_replace(',', '', trim($number)); return (float) str_replace(',', '', trim($number));
} }
} }
if (!function_exists('formatKey')) { if (! function_exists('formatKey')) {
function formatKey($key, $len = 3) function formatKey($key, $len = 3)
{ {
$words = explode('_', $key); $words = explode('_', $key);
@ -917,7 +966,7 @@ if (!function_exists('formatKey')) {
} }
} }
if (!function_exists('getMimeTypeByFileName')) { if (! function_exists('getMimeTypeByFileName')) {
function getMimeTypeByFileName($file_name) function getMimeTypeByFileName($file_name)
{ {
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
@ -943,7 +992,7 @@ if (!function_exists('getMimeTypeByFileName')) {
} }
} }
if (!function_exists('validateExcelFile')) { if (! function_exists('validateExcelFile')) {
function validateExcelFile($file) function validateExcelFile($file)
{ {
@ -963,7 +1012,7 @@ if (!function_exists('validateExcelFile')) {
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.spreadsheet',
'application/zip', 'application/zip',
'application/octet-stream' 'application/octet-stream',
]; ];
$allowedExtensions = ['xls', 'xlsx', 'ods', 'xlsm']; $allowedExtensions = ['xls', 'xlsx', 'ods', 'xlsm'];
@ -981,23 +1030,24 @@ if (!function_exists('validateExcelFile')) {
} }
} }
if (!function_exists('generate_ecard_download_link_based_on_tpa')) { if (! function_exists('generate_ecard_download_link_based_on_tpa')) {
function generate_ecard_download_link_based_on_tpa($params) { function generate_ecard_download_link_based_on_tpa($params)
{
$apiServiceController = new ApiServiceController(); $apiServiceController = new ApiServiceController();
$data = $apiServiceController->ecardRequest($params, $return_type = 'internal'); $data = $apiServiceController->ecardRequest($params, $return_type = 'internal');
log_message('error', 'E-card request call from the helper for mail send'); log_message('error', 'E-card request call from the helper for mail send');
if(isset($data['eCardDownload']) && !empty($data['eCardDownload'])){ if (isset($data['eCardDownload']) && ! empty($data['eCardDownload'])) {
return $data['eCardDownload']; return $data['eCardDownload'];
}else{ } else {
return $data['message']; return $data['message'];
} }
} }
} }
if (!function_exists('canSendOtp')) { if (! function_exists('canSendOtp')) {
function canSendOtp(array $row, int $limitSeconds = 60): array function canSendOtp(array $row, int $limitSeconds = 60): array
{ {
// If OTP does not exist → allow // If OTP does not exist → allow
@ -1015,7 +1065,7 @@ if (!function_exists('canSendOtp')) {
if ($currentTime < $allowedAfter) { if ($currentTime < $allowedAfter) {
return [ return [
'allowed' => false, 'allowed' => false,
'retry_after' => $allowedAfter - $currentTime 'retry_after' => $allowedAfter - $currentTime,
]; ];
} }
@ -1023,14 +1073,14 @@ if (!function_exists('canSendOtp')) {
} }
} }
if (!function_exists('checkDuplicateClaim')) { if (! function_exists('checkDuplicateClaim')) {
function checkDuplicateClaim(array $params): bool function checkDuplicateClaim(array $params): bool
{ {
$ticketMaster = new TicketMasterModel(); $ticketMaster = new TicketMasterModel();
$query = $ticketMaster->where('is_active', 1); $query = $ticketMaster->where('is_active', 1);
if(empty($params['doa']) && empty($params['claim_amount'])){ if (empty($params['doa']) && empty($params['claim_amount'])) {
return false; return false;
} }
@ -1043,26 +1093,25 @@ if (!function_exists('checkDuplicateClaim')) {
} }
} }
if (!$hasValidCondition) { if (! $hasValidCondition) {
return false; return false;
} }
$result = $query->countAllResults(); $result = $query->countAllResults();
// print_r($ticketMaster->getLastQuery()->getQuery()); die; // print_r($ticketMaster->getLastQuery()->getQuery()); die;
if($result > 0){ return true; }else{ return false; } if ($result > 0) {return true;} else {return false;}
} }
} }
function getRealClientIP() function getRealClientIP()
{ {
$request = service('request'); $request = service('request');
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) { if (! empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
return $_SERVER['HTTP_CF_CONNECTING_IP']; return $_SERVER['HTTP_CF_CONNECTING_IP'];
} }
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]; return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
} }
@ -1097,16 +1146,13 @@ function generateFingerprint(bool $exclude_ua = false): string
$ipGroup = 'unknown'; $ipGroup = 'unknown';
} }
if($exclude_ua){ if ($exclude_ua) {
return hash('sha256', $ipGroup); return hash('sha256', $ipGroup);
} }
return hash('sha256', $ua . '|' . $ipGroup); return hash('sha256', $ua . '|' . $ipGroup);
} }
if (! function_exists('convertGoogleDriveToDownloadLink')) {
if (!function_exists('convertGoogleDriveToDownloadLink')) {
function convertGoogleDriveToDownloadLink(?string $url): ?string function convertGoogleDriveToDownloadLink(?string $url): ?string
{ {
if (empty($url)) { if (empty($url)) {
@ -1120,7 +1166,7 @@ if (!function_exists('convertGoogleDriveToDownloadLink')) {
$patterns = [ $patterns = [
'#https?://drive\.google\.com/file/d/([^/]+)/?#', '#https?://drive\.google\.com/file/d/([^/]+)/?#',
'#https?://drive\.google\.com/open\?id=([^&]+)#', '#https?://drive\.google\.com/open\?id=([^&]+)#',
'#https?://drive\.google\.com/uc\?id=([^&]+)#' '#https?://drive\.google\.com/uc\?id=([^&]+)#',
]; ];
foreach ($patterns as $pattern) { foreach ($patterns as $pattern) {
@ -1137,7 +1183,7 @@ if (!function_exists('convertGoogleDriveToDownloadLink')) {
} }
} }
if (!function_exists('get_cd_balance')) { if (! function_exists('get_cd_balance')) {
function get_cd_balance(): array function get_cd_balance(): array
{ {
$session = session(); $session = session();
@ -1151,7 +1197,7 @@ if (!function_exists('get_cd_balance')) {
} }
} }
if (!function_exists('clear_cd_balance_session')) { if (! function_exists('clear_cd_balance_session')) {
function clear_cd_balance_session(): void function clear_cd_balance_session(): void
{ {
$session = session(); $session = session();
@ -1164,15 +1210,24 @@ if (!function_exists('clear_cd_balance_session')) {
} }
} }
if (!function_exists('format_gender_v2')) { if (! function_exists('format_gender_v2')) {
function format_gender_v2($gender) { function format_gender_v2($gender)
if (empty($gender)) return null; {
if (empty($gender)) {
return null;
}
$g = strtoupper(trim($gender)); $g = strtoupper(trim($gender));
// Direct-ah check pannuvom // Direct-ah check pannuvom
if (str_starts_with($g, 'M')) return 'M'; // Male, M if (str_starts_with($g, 'M')) {
if (str_starts_with($g, 'F')) return 'F'; // Female, F return 'M';
}
// Male, M
if (str_starts_with($g, 'F')) {
return 'F';
}
// Female, F
// Others, Transgender, O - ivatrai 'O' ena return seiyum // Others, Transgender, O - ivatrai 'O' ena return seiyum
if (str_starts_with($g, 'O') || str_starts_with($g, 'T')) { if (str_starts_with($g, 'O') || str_starts_with($g, 'T')) {
@ -1183,20 +1238,22 @@ if (!function_exists('format_gender_v2')) {
} }
} }
if (!function_exists('map_relationship')) { if (! function_exists('map_relationship')) {
/** /**
* Employee -> self, WIFE -> spouse ena maatri return seiyum. * Employee -> self, WIFE -> spouse ena maatri return seiyum.
*/ */
function map_relationship($relation) { function map_relationship($relation)
if (empty($relation)) return ''; {
if (empty($relation)) {
return '';
}
// Case prechanai varaamal irukka lowercase-kku maatri check seivom // Case prechanai varaamal irukka lowercase-kku maatri check seivom
$r = strtolower(trim($relation)); $r = strtolower(trim($relation));
if ($r == 'employee') { if ($r == 'employee') {
return 'self'; return 'self';
} } else if ($r == 'wife') {
else if ($r == 'wife') {
return 'spouse'; return 'spouse';
} }
@ -1205,13 +1262,12 @@ if (!function_exists('map_relationship')) {
} }
} }
/** /**
* Extract identity from POST body or GET params. * Extract identity from POST body or GET params.
* Looks for 'email' or 'mobile_number'. * Looks for 'email' or 'mobile_number'.
*/ */
function resolveIdentity($request): ?string function resolveIdentity($request): ?string
{ {
// Try POST body first // Try POST body first
$email = $request->getPost('email'); $email = $request->getPost('email');
// print_r($email);die; // print_r($email);die;
@ -1232,8 +1288,7 @@ if (!function_exists('map_relationship')) {
$email = $req_data->email ?? null; $email = $req_data->email ?? null;
if (!$email) if (! $email) {
{
$email = $req_data->email_id ?? null; $email = $req_data->email_id ?? null;
} }
// return trim($email); // return trim($email);
@ -1248,41 +1303,35 @@ if (!function_exists('map_relationship')) {
} }
return null; return null;
} }
function recordRateLimitFailure(string $context = 'authApi'): void
function recordRateLimitFailure(string $context = 'authApi'): void {
{
/** @var IncomingRequest $request */ /** @var IncomingRequest $request */
$request = \Config\Services::request(); $request = \Config\Services::request();
$limiter = \Config\Services::limiter(); // or your custom limiter service $limiter = \Config\Services::limiter(); // or your custom limiter service
$fingerprint = $request->getVar('rateLimitFingerprint') $fingerprint = $request->getVar('rateLimitFingerprint') ?? generateFingerprint(exclude_ua: true);
?? generateFingerprint(exclude_ua: true);
$identity = $request->getVar('rateLimitIdentity') ?? resolveIdentity($request);
$identity = $request->getVar('rateLimitIdentity')
?? resolveIdentity($request);
// Record IP-level failure // Record IP-level failure
$limiter->recordIpFailure($fingerprint); $limiter->recordIpFailure($fingerprint);
// Record user-level failure // Record user-level failure
if (!empty($identity)) { if (! empty($identity)) {
$limiter->recordUserFailure($identity, $context); $limiter->recordUserFailure($identity, $context);
} }
} }
if (! function_exists('getCurrentFinancialYear')) {
if (!function_exists('getCurrentFinancialYear')) {
function getCurrentFinancialYear() function getCurrentFinancialYear()
{ {
// Get current year and month // Get current year and month
$date = new DateTime(); $date = new DateTime();
$currentYear = (int)$date->format('Y'); $currentYear = (int) $date->format('Y');
$currentMonth = (int)$date->format('m'); $currentMonth = (int) $date->format('m');
// If month is Jan, Feb, or March, we are still in the previous year's FY // If month is Jan, Feb, or March, we are still in the previous year's FY
if ($currentMonth < 4) { if ($currentMonth < 4) {
@ -1295,13 +1344,12 @@ if (!function_exists('map_relationship')) {
return $startYear . '-' . $endYear; return $startYear . '-' . $endYear;
} }
} }
if (! function_exists('format_financial_year')) {
if (!function_exists('format_financial_year')) {
function format_financial_year(string $financialYear): string function format_financial_year(string $financialYear): string
{ {
if (empty($financialYear) || !str_contains($financialYear, '-')) { if (empty($financialYear) || ! str_contains($financialYear, '-')) {
return $financialYear; return $financialYear;
} }
@ -1313,27 +1361,24 @@ if (!function_exists('map_relationship')) {
return "APR " . $startYear . " - MAR " . $endYear; return "APR " . $startYear . " - MAR " . $endYear;
} }
} }
if (! function_exists('add_google_calender_event')) {
if(!function_exists('add_google_calender_event')){ function add_google_calender_event($data)
function add_google_calender_event($data){ {
$calendar = new \App\Libraries\GoogleCalendarService(); $calendar = new \App\Libraries\GoogleCalendarService();
// Check if user is authenticated without passing tokens manually // Check if user is authenticated without passing tokens manually
if (!$calendar->isReady()) { if (! $calendar->isReady()) {
return ['status' => 'failed', 'code' => '404' , 'message' => 'Google Access Token Expired']; return ['status' => 'failed', 'code' => '404', 'message' => 'Google Access Token Expired'];
} }
try { try {
$response = $calendar->createEvent($data); $response = $calendar->createEvent($data);
return ['status' => 'success', 'code' => '200' , 'message' => 'Follow-up Saved', 'response' => $response]; return ['status' => 'success', 'code' => '200', 'message' => 'Follow-up Saved', 'response' => $response];
} catch (\Exception $e) { } catch (\Exception $e) {
return ['status' => 'failed', 'code' => '500' , 'message' => 'Error: ' . $e->getMessage()]; return ['status' => 'failed', 'code' => '500', 'message' => 'Error: ' . $e->getMessage()];
} }
} }
} }