$email, 'role' => $role, 'exp' => $now + ($expiryMinutes * 60), 'iat' => $now, ]; return JWT::encode($payload, $secretKey, 'HS256'); } function stopMessage($data, $mobile, $templates){ $templateId = $data['templateId'] ?? ($data['templateDetails']['templateId'] ?? ''); if(strlen($mobile) == 10){ $mobile_number = $mobile; }else if(strlen($mobile) == 12 ){ $mobile_number = substr($mobile,2); }else{ return false; } $lastMonth = now()->subMonth(); // Get the date representing one month ago $merchantId = \App\ConsumerApplication::where('mobile_number', $mobile_number)->whereDate('created_at', '>=', $lastMonth)->orderByDesc('created_at')->limit(1)->value('merchant_id'); if (empty($merchantId)){ $merchantId = \App\ConsumerApplication::where('co_applicant_mobile_number', $mobile_number)->whereDate('created_at', '>=', $lastMonth)->orderByDesc('created_at')->limit(1)->value('merchant_id'); } if (!empty($merchantId) && ($merchantId==_env("Finsall_id"))){ if (in_array($templateId, $templates)) { return false; } return true; } return false; } function send_sms($mobile_number, $data, $checkUser = false) { if($checkUser){ $isExist = \App\User::where('mobile_number', $mobile_number)->where('id',922)->first(['id']); if (isset($isExist->id)) { return false; } } if (stopMessage($data,$mobile_number,getSMSTemplates())){ return true; } if(!isset($data['service'])){ $data['service'] = false; } $message = isset($data['message']) ? $data['message'] : $data; $messageWhatsapp = urlencode($message); $resobj = new \App\_SMSService(); $resp = $resobj->sms_service($mobile_number, $data); $res = $resp['resp']; $smsLogID = $resp['smsLogID']; if (!isset($data['whatsapp_not']) && !isset($data['OTP'])) { try { $messagetype = ((isset($data['message_type'])) && $data['message_type'] == "payment") ? $data['message_type'] : ""; $start_time = time(); if (!isset($data['message'])){ if (is_array($data)){ $data = array_merge($data, ['message' => $message]); }else{ unset($data); $data['message'] = $message; } }else{ $data['message'] = $message; } if (!isset($data['smsLogID'])){ if (is_array($data)){ $data = array_merge($data, ['smsLogID' => $smsLogID]); }else{ unset($data); $data['smsLogID'] = $smsLogID; } }else{ $data['smsLogID'] = $smsLogID; } // sendWhatsAppMessage($mobile_number, $data, $messagetype); (new \App\Services())->log('Zoko', ['status' => true, 'service_count' => 0, 'start_time' => $start_time]); } catch (\Exception $e) { (new \App\Slack(new \Illuminate\Http\Request(['title' => 'Whatsapp Error', 'fields' => ['mobile_number' => $mobile_number, 'message' => $messageWhatsapp, 'error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $_id, 'id_type' => $id_type]])))->send(); } } return (isset($res) ? $res->getBody() : true); } function sendWhatsAppMessage($mobile_number, $message, $messagetype = ""){ if(strlen($mobile_number) == 10){ $mobile_number = "91" . $mobile_number; }else if(strlen($mobile_number) > 12 || strlen($mobile_number) < 10){ return false; } if (stopMessage($message,$mobile_number,getWhatsAppTemplates())){ return true; } if (isset($message['templateDetails']) &&!is_array($message['templateDetails'])) { $message['templateDetails'] = []; $message['templateDetails']['templateid'] = $message['templateDetails']->templateid ?? ''; } if (!empty($message['templateId']) ||!empty($message['templateDetails']['templateid'])) { $templateId = $message['templateId'] ?? $message['templateDetails']['templateid'] ?? ''; $messageBody = ''; if (!empty($message['messageString'])) { $messageBody = $message['messageString']; } elseif (!empty($message['message'])) { $messageBody = $message['message']; } else { $args = $message['args'] ?? []; $messageBody = Templates::getTemplateBody($templateId, $args); } if (!empty($messageBody) || $messageBody != "") { $request = new \Illuminate\Http\Request([ 'templateId' => $templateId, 'templateArgs' => $message['args'] ?? '', 'caption' => isset($message['caption']) ? $message['caption'] : '', 'templateType' => isset($message['templateType']) ? $message['templateType'] : '', 'message_type' => $messagetype, 'to' => $mobile_number, 'messageString' => $messageBody, 'templateLanguage' => isset($message['templateLanguage']) ? $message['templateLanguage'] : 'en' ]); $whatsApp = new \App\WhatsApp($request); $response = $whatsApp->sendMessage(); $whatsApp->serviceLogs($mobile_number, $request->input(), $response); if((isset($response->statusText) && $response->statusText == 'Accepted') && isset($message['smsLogID']) && $message['smsLogID'] > 0){ \App\SMSLogs::where('id', $message['smsLogID'])->update(['isWhatsapp' => 1]); } } } if ((!isset($response) || !isset($response->statusText)) || (isset($response->statusText) && $response->statusText != 'Accepted')){ //sendWhatsAppFromZoko($mobile_number, $message, $messagetype = ""); } } function getWhatsAppTemplates(){ return ["admin_app_received_1_v2","disbursed_customer_with_doc_wl","disbursement_c1","feedback_c1"]; } function getSMSTemplates(){ return ["1307166902770611470"]; } function sendWhatsAppFromZoko($mobile_number, $message, $messagetype = ""){ if($mobile_number) { $message = is_array($message) ? $message['message'] : $message; $mobile_number_array = explode(",", $mobile_number); if($messagetype == "payment"){ $api_key = "1d5c76ee-2d2f-4413-b8fe-72f32022ec0d"; }else{ $api_key = "516d8057-74b0-4e76-b04a-84151dcbc824"; } foreach ($mobile_number_array as $mobile_number) { if(strlen($mobile_number) < 12){ $mobile_number = "91".$mobile_number; } $data = json_encode(array("messagePlatform" => "WHATSAPP", "messsageType" => "TEXT", "number" => $mobile_number, "message" => urldecode($message), "imageCaption" => "")); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://notify.zoko.io/v1/notification/push", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => array( "Content-Type: application/json", "apikey: ".$api_key, "accept: application/json", "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); } } } //function wall_encrypt($message) //{ // $components = explode( '|:|', $message );; // if(!isset($components[1])) { // $max_msg_size = 100000000; // $message = substr($message, 0, $max_msg_size); // // $password = 'CRDRIAF'; // // $salt = sha1(mt_rand()); // // $iv = substr(sha1(mt_rand()), 0, 16); // // $encrypted = openssl_encrypt( // "$message", 'aes-256-cbc', "$salt|:|$password", null, $iv // ); // // return str_replace('/', '*#', "$salt|:|$iv|:|$encrypted"); // }else{ // return $message; // } //} function wall_encrypt($message, $type = false, $key = '') { try { if ($key == ''){ $key ='CRDRIAF'; } $cipher = "AES-128-CBC"; //$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC"); //$iv = openssl_random_pseudo_bytes($ivlen); $iv = "lksdasfsaskllopl"; $ciphertext_raw = openssl_encrypt($message, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv); $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true); $value = base64_encode($iv . $hmac . $ciphertext_raw); return $value; }catch (\Throwable $e){ return $message; } } function wall_decrypt($msg_bundle, $type = false, $key = '') { if (!is_string($msg_bundle) || empty($msg_bundle)) { return ($type) ? false : $msg_bundle; } if ($key == ''){ $key ='CRDRIAF'; } try { $c = base64_decode($msg_bundle); $ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC"); //AES-256-CBC $iv = substr($c, 0, $ivlen); $hmac = substr($c, $ivlen, $sha2len = 32); $ciphertext_raw = substr($c, $ivlen + $sha2len); $value = openssl_decrypt($ciphertext_raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv); $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true); if (hash_equals($hmac, $calcmac)) { return $value; }else{ return ($type) ? false : $msg_bundle; } }catch(\Throwable $e){ return ($type) ? false : $msg_bundle; } } function is_image($path) { $a = getimagesize($path); $image_type = $a[2]; if (in_array($image_type, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) { return true; } return false; } function _env($key, $default = ''){ return env($key) ? wall_decrypt(env($key)) : $default; } function idStringtoArray($id){ if($id != 0) { if (!is_array($id)) { $application_id[] = $id; } else { $application_id = $id; } }else{ $application_id = ""; } return $application_id; } function getHolidayList(){ // $holidays = \App\HolidayList::get(); $holiday_list = array(); // foreach ($holidays as $holiday){ // array_push($holiday_list,$holiday->date); // } return $holiday_list; } function saveComment($_comment, $id, $user_id){ $comment = new \App\Comments(); $comment->application_id = $id; if(\Illuminate\Support\Facades\Input::get('request_review')){ $comment->show_merchant = 1; }else{ $comment->show_merchant = 0; } $comment->user_id = $user_id; $comment->comment = $_comment; $comment->save(); } function Log_file($log){ $fp = fopen(storage_path().'/'.time().'_log_file.txt', 'w'); fwrite($fp, $log."\n"); fclose($fp); } function getAvaibleAdvisor($pincode){ if ($pincode) { $data = \App\Zone::leftJoin("users", \DB::raw("FIND_IN_SET(zones.id,users.zones)"), ">", \DB::raw("'0'"))->whereRaw("FIND_IN_SET($pincode,pincodes)")->whereNull('users.deleted_at')->get(['users.id']); $user_ids = array(); if ($data) { foreach ($data as $users) { if (isset($users->id)) { array_push($user_ids, $users->id); } } } } return isset($user_ids) ? $user_ids : []; } function send_mail($email, $body, $subject){ if($email){ $body = str_replace('
', '', str_replace('Best Regards,', '', str_replace('Team Credit Fair', '', $body))); \Illuminate\Support\Facades\Mail::send('emails.reminders.basic_reminder', ['body'=> $body] , function ($message) use ($email, $subject) { $message->to(explode(',',$email))->subject($subject); }); } } if ( ! function_exists( 'money_format' ) ) { function money_format($format, $number) { if(!$number) return $number; $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/'; if (setlocale(LC_MONETARY, 0) == 'C') { setlocale(LC_MONETARY, ''); } $locale = localeconv(); preg_match_all($regex, $format, $matches, PREG_SET_ORDER); foreach ($matches as $fmatch) { $value = floatval($number); $flags = array( 'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ', 'nogroup' => preg_match('/\^/', $fmatch[1]) > 0, 'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+', 'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0, 'isleft' => preg_match('/\-/', $fmatch[1]) > 0 ); $width = (isset($fmatch[2]) && trim($fmatch[2]) !== '') ? (int)$fmatch[2] : 0; $left = (isset($fmatch[3]) && trim($fmatch[3]) !== '') ? (int)$fmatch[3] : 0; $defaultFrac = (isset($locale['int_frac_digits']) && $locale['int_frac_digits'] >= 0 && $locale['int_frac_digits'] <= 10) ? (int)$locale['int_frac_digits'] : 2; $right = (isset($fmatch[4]) && trim($fmatch[4]) !== '') ? (int)$fmatch[4] : $defaultFrac; $conversion = $fmatch[5]; $positive = true; if ($value < 0) { $positive = false; $value *= -1; } $letter = $positive ? 'p' : 'n'; $prefix = $suffix = $cprefix = $csuffix = $signal = ''; $signal = $positive ? ($locale['positive_sign'] ?? '') : ($locale['negative_sign'] ?? '-'); $signPosn = $locale["{$letter}_sign_posn"] ?? 1; switch (true) { case $signPosn == 1 && $flags['usesignal'] == '+': $prefix = $signal; break; case $signPosn == 2 && $flags['usesignal'] == '+': $suffix = $signal; break; case $signPosn == 3 && $flags['usesignal'] == '+': $cprefix = $signal; break; case $signPosn == 4 && $flags['usesignal'] == '+': $csuffix = $signal; break; case $flags['usesignal'] == '(': case $signPosn == 0: $prefix = '('; $suffix = ')'; break; } if (!$flags['nosimbol']) { $currency = $cprefix . ($conversion == 'i' ? ($locale['int_curr_symbol'] ?? '') : ($locale['currency_symbol'] ?? '')) . $csuffix; } else { $currency = ''; } $space = !empty($locale["{$letter}_sep_by_space"]) ? ' ' : ''; $decPoint = !empty($locale['mon_decimal_point']) ? $locale['mon_decimal_point'] : (!empty($locale['decimal_point']) ? $locale['decimal_point'] : '.'); $thousandSep = $flags['nogroup'] ? '' : (!empty($locale['mon_thousands_sep']) ? $locale['mon_thousands_sep'] : (!empty($locale['thousands_sep']) ? $locale['thousands_sep'] : ',')); $value = number_format( $value, $right, $decPoint, $thousandSep ); $value = explode($decPoint, $value); $n = strlen($prefix) + strlen($currency) + strlen($value[0]); if ($left > 0 && $left > $n) { $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0]; } $value = implode($decPoint, $value); if (!empty($locale["{$letter}_cs_precedes"])) { $value = $prefix . $currency . $space . $value . $suffix; } else { $value = $prefix . $value . $space . $currency . $suffix; } if ($width > 0) { $value = str_pad( $value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT ); } $format = str_replace($fmatch[0], $value, $format); } return $format; } if ( ! function_exists( 'updateProgressBar' ) ) { function updateProgressBar($current, $total, $process = 'Process', $length = 50) { $percent = ($total > 0) ? ($current / $total) * 100 : 100; $barLength = max(0, intval($percent / 100 * $length) - 1); $bar = "[" . str_repeat("=", $barLength) . ">"; $bar .= str_repeat(" ", max(0, $length - strlen($bar))) . "]"; $bar .= sprintf(" %d%% (%d/%d)", $percent, $current, $total); echo "\r$process"; echo "\r$bar"; if ($current == $total) { echo PHP_EOL; } } } } function sendFCMNotification($data){ $request = new \Illuminate\Http\Request($data); new \App\FCMNotification($request); } function getPageRoute($request){ $route = Route::getRoutes()->match($request); return $route->uri(); } if (!function_exists('str_slug')) { function str_slug($title, $separator = '-', $language = 'en') { return \Illuminate\Support\Str::slug($title, $separator, $language); } } if (!function_exists('str_random')) { function str_random($length = 16) { return \Illuminate\Support\Str::random($length); } } if (!function_exists('array_get')) { function array_get($array, $key, $default = null) { return \Illuminate\Support\Arr::get($array, $key, $default); } } if (!function_exists('array_set')) { function array_set(&$array, $key, $value) { return \Illuminate\Support\Arr::set($array, $key, $value); } } if (!function_exists('array_has')) { function array_has($array, $keys) { return \Illuminate\Support\Arr::has($array, $keys); } } if (!function_exists('starts_with')) { function starts_with($haystack, $needles) { return \Illuminate\Support\Str::startsWith($haystack, $needles); } } if (!function_exists('ends_with')) { function ends_with($haystack, $needles) { return \Illuminate\Support\Str::endsWith($haystack, $needles); } } if (!function_exists('str_limit')) { function str_limit($value, $limit = 100, $end = '...') { return \Illuminate\Support\Str::limit($value, $limit, $end); } } if (!function_exists('str_finish')) { function str_finish($value, $cap) { return \Illuminate\Support\Str::finish($value, $cap); } } if (!function_exists('str_is')) { function str_is($pattern, $value) { return \Illuminate\Support\Str::is($pattern, $value); } } if (!function_exists('str_plural')) { function str_plural($value, $count = 2) { return \Illuminate\Support\Str::plural($value, $count); } } if (!function_exists('str_singular')) { function str_singular($value) { return \Illuminate\Support\Str::singular($value); } } if (!function_exists('str_before')) { function str_before($subject, $search) { return \Illuminate\Support\Str::before($subject, $search); } } if (!function_exists('str_after')) { function str_after($subject, $search) { return \Illuminate\Support\Str::after($subject, $search); } } if (!function_exists('snake_case')) { function snake_case($value, $delimiter = '_') { return \Illuminate\Support\Str::snake($value, $delimiter); } } if (!function_exists('kebab_case')) { function kebab_case($value) { return \Illuminate\Support\Str::kebab($value); } } if (!function_exists('camel_case')) { function camel_case($value) { return \Illuminate\Support\Str::camel($value); } } if (!function_exists('studly_case')) { function studly_case($value) { return \Illuminate\Support\Str::studly($value); } } if (!function_exists('title_case')) { function title_case($value) { return \Illuminate\Support\Str::title($value); } } if (!function_exists('array_only')) { function array_only($array, $keys) { return \Illuminate\Support\Arr::only($array, $keys); } } if (!function_exists('array_except')) { function array_except($array, $keys) { return \Illuminate\Support\Arr::except($array, $keys); } } if (!function_exists('array_pull')) { function array_pull(&$array, $key, $default = null) { return \Illuminate\Support\Arr::pull($array, $key, $default); } } if (!function_exists('array_first')) { function array_first($array, ?callable $callback = null, $default = null) { return \Illuminate\Support\Arr::first($array, $callback, $default); } } if (!function_exists('array_last')) { function array_last($array, ?callable $callback = null, $default = null) { return \Illuminate\Support\Arr::last($array, $callback, $default); } } if (!function_exists('array_forget')) { function array_forget(&$array, $keys) { return \Illuminate\Support\Arr::forget($array, $keys); } } if (!function_exists('array_wrap')) { function array_wrap($value) { return \Illuminate\Support\Arr::wrap($value); } } if (!function_exists('array_collapse')) { function array_collapse($array) { return \Illuminate\Support\Arr::collapse($array); } } if (!function_exists('array_divide')) { function array_divide($array) { return \Illuminate\Support\Arr::divide($array); } } if (!function_exists('array_sort')) { function array_sort($array, $callback = null) { return \Illuminate\Support\Arr::sort($array, $callback); } } if (!function_exists('array_sort_recursive')) { function array_sort_recursive($array, $options = SORT_REGULAR) { return \Illuminate\Support\Arr::sortRecursive($array, $options); } } /** * Flysystem v3 Compatibility Helper * * In Flysystem v1 (Laravel 8 and below), $s3->listContents() returned a plain * PHP array where each item was an associative array with a 'path' key. * * In Flysystem v3 (Laravel 9+), it returns a DirectoryListing object (iterable) * where each item is a StorageAttributes object accessed via ->path() method. * * This helper normalises the result back to the old v1 format so that all * existing code using $item['path'] continues to work without modification. * * Usage (replace all $s3->listContents($path) calls with this): * $list = s3ListContents($s3, $path); * $list = s3ListContents($s3, $path, true); // recursive * * @param \League\Flysystem\Filesystem $s3 The Flysystem filesystem instance * @param string $path The directory path to list * @param bool $deep Whether to list recursively (default: false) * @return array Array of ['path' => string, 'type' => string, ...] */ if (!function_exists('s3ListContents')) { function s3ListContents($s3, string $path, bool $deep = false): array { try { $listing = $s3->listContents($path, $deep); // Flysystem v3 returns a DirectoryListing object — convert to array $items = []; foreach ($listing as $item) { if (is_array($item)) { // Already v1-style array (shouldn't happen on v3, but safe fallback) $items[] = $item; } else { // Flysystem v3 StorageAttributes object $itemPath = $item->path(); $pathInfo = pathinfo($itemPath); $items[] = [ 'path' => $itemPath, 'dirname' => $pathInfo['dirname'] ?? '', 'basename' => $pathInfo['basename'] ?? '', 'extension' => $pathInfo['extension'] ?? '', 'filename' => $pathInfo['filename'] ?? '', 'type' => $item instanceof \League\Flysystem\FileAttributes ? 'file' : 'dir', 'timestamp' => method_exists($item, 'lastModified') ? $item->lastModified() : null, 'size' => ($item instanceof \League\Flysystem\FileAttributes) ? $item->fileSize() : null, ]; } } return $items; } catch (\Exception $e) { \Illuminate\Support\Facades\Log::warning('s3ListContents failed', [ 'path' => $path, 'error' => $e->getMessage(), ]); return []; } } } /** * Flysystem v3 Safe File Getter * * In Flysystem v3 (Laravel 9+), calling $s3->get() on a non-existent file * throws League\Flysystem\UnableToReadFile instead of returning false (v1 behavior). * This helper safely catches any error and returns false if the file is missing or unreadable. * * @param mixed $s3 * @param string $path * @return string|false */ if (!function_exists('s3GetSafe')) { function s3GetSafe($s3, string $path) { try { return $s3->get($path); } catch (\Throwable $e) { \Illuminate\Support\Facades\Log::warning('s3GetSafe: file read failed', [ 'path' => $path, 'error' => $e->getMessage(), ]); return false; } } } /** * Carbon v3 Compatibility Date Helpers * * In Carbon 3 (Laravel 12), rawAddUnit enforces strict (int|float) parameter types. * Passing string values from request input or uncasted database columns throws a fatal TypeError. * These helpers guarantee integer casting before invoking Carbon arithmetic. */ if (!function_exists('carbonAddMonths')) { function carbonAddMonths($date, $months) { $d = ($date instanceof \Carbon\Carbon) ? $date->copy() : \Carbon\Carbon::parse($date); return $d->addMonths((int) $months); } } if (!function_exists('carbonSubMonths')) { function carbonSubMonths($date, $months) { $d = ($date instanceof \Carbon\Carbon) ? $date->copy() : \Carbon\Carbon::parse($date); return $d->subMonths((int) $months); } } if (!function_exists('carbonAddDays')) { function carbonAddDays($date, $days) { $d = ($date instanceof \Carbon\Carbon) ? $date->copy() : \Carbon\Carbon::parse($date); return $d->addDays((int) $days); } } if (!function_exists('carbonSubDays')) { function carbonSubDays($date, $days) { $d = ($date instanceof \Carbon\Carbon) ? $date->copy() : \Carbon\Carbon::parse($date); return $d->subDays((int) $days); } } /** * Safe Temporary File Path Generator * * Guarantees a writable temporary path across both host and containerized (Docker) environments, * preventing SplFileInfo::getSize() 'stat failed' exceptions when writing temp downloads. * * @param string $extension * @param string $prefix * @return string */ if (!function_exists('safeTempFilePath')) { function safeTempFilePath(string $extension = 'tmp', string $prefix = ''): string { $candidates = [ storage_path('app/temp'), storage_path('app'), storage_path(), sys_get_temp_dir(), ]; $targetDir = sys_get_temp_dir(); foreach ($candidates as $dir) { if (!is_dir($dir)) { @mkdir($dir, 0775, true); } if (is_dir($dir) && is_writable($dir)) { $targetDir = $dir; break; } } $filename = ($prefix ? $prefix . '_' : '') . time() . '_' . bin2hex(random_bytes(5)) . '.' . ltrim($extension, '.'); return rtrim($targetDir, '/') . '/' . $filename; } }