Root Zanli
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
home
/
o5t6x7pgljbm
/
public_html
/
admin_new2
/
app
/
Libraries
/
Filename :
Helpers.php
back
Copy
<?php namespace App\Libraries; use App\Models\Admin; use App\Models\Group; use Validator; use App\Models\SPWalletTransaction; use App\Models\User; use App\Services\EmailService; use DB; use Config; use Carbon\Carbon; use DateTime; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Session; use Illuminate\Support\Str; use League\Csv\Reader; use Ramsey\Uuid\Uuid; class Helpers { public function __construct() { //do some stuff } static function successResponse($array, $response, $message) { $array['ResponseCode'] = $response; $array['ResponseMsg'] = $message; Log::debug("Success Response: ". print_r($array, true)); return response()->json($array); } static function responseMessage($response, $message) { Log::debug("Response: ". print_r(['Code' => $response, 'Message' => $message], true)); return response()->json([ "ResponseCode" => $response, "ResponseMsg"=> $message ]); } public static function validatorErrorResponse($request, $path_params, $rules) { $validator = Validator::make(array_merge($request->all(), $path_params), $rules); if($validator->fails()){ $data['errors'] = $validator->errors(); $result = Helpers::successResponse($data, 422, 'Please validate request.'); return array('flag' => 1, 'response' => $result); } return array('flag' => 0); } static function sendPushIOS($device_udid_array, $title, $message, $type, $id="") { $pem_file = Config::get('constants.app.ios-pem-file-path'); $pem_secret = Config::get('constants.app.ios-passphrase'); $apns_topic = 'com.CoinsForCollege'; $tAlert = $message; $tBadge = 0; $tSound = 'default'; $tPayload = array( "title" => $title, "body" => $message, "type" => $type, "id" => $id, ); $tBody['aps'] = array ('alert' => $tAlert,'badge' => $tBadge,'sound' => $tSound); $tBody ['payload'] = $tPayload; $tBody = json_encode($tBody); foreach ($device_udid_array as $key => $device_token) { if(strlen($device_token) == 64){ if(!empty($device_token)){ $url = "https://api.push.apple.com/3/device/$device_token"; //$url = "https://api.sandbox.push.apple.com/3/device/$device_token"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $tBody); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); curl_setopt($ch, CURLOPT_HTTPHEADER, array("apns-topic: $apns_topic")); curl_setopt($ch, CURLOPT_SSLCERT, $pem_file); curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $pem_secret); $response = curl_exec($ch); //print_r($response);exit; $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); } } } } static function sendPushAndroid($device_udid_array, $title, $message, $type, $id="") { // echo print_r($device_udid_array).'-'.$title.'-'.$message;exit; $url = 'https://fcm.googleapis.com/fcm/send'; $fields = array( 'registration_ids' => $device_udid_array, /* 'to' => $device_udid_array,*/ 'data' => array( "title" => $title, "body" => $message, "type" => $type, "id" => $id, ), /*'notification' => array( "title" => 'Coins', "text" => $message ),*/ ); $headers = array( 'Authorization: key=' . Config::get('constants.app.android-auth-key'), 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { // die('Curl failed: ' . curl_error($ch)); } curl_close($ch); //return $result; } static function storeNotifications($from_user_id, $to_user_ids, $title, $message, $table_name, $field_id) { return DB::table('notifications')->insert([ 'from_user_id' => $from_user_id, 'to_user_ids' => implode(",", $to_user_ids), 'title' => $title, 'message' => $message, 'table_name' => $table_name, 'field_id' => $field_id, 'created_at' => date("Y-m-d H:i:s") ]); } public static function dateDiffForHumans($date) { $fromDate = Carbon::parse($date)->addDays(1); $toDate = Carbon::now(); $days = $toDate->diffInDays($fromDate, false); if($days == 1){ return 'Due Tomorrow'; } else if($days == 0){ return 'Due Today'; } else if($days > 0){ return 'Due in '. $days.' days'; } else if($days == -1){ return 'Past Due by '. abs($days).' day'; } else if($days < -1){ return 'Past Due by '. abs($days) .' days'; } else { return $fromDate->diffForHumans(['options' => Carbon::ONE_DAY_WORDS]); } } public static function dueByStrForHumans($date) { $fromDate = Carbon::parse($date)->addDays(1); $toDate = Carbon::now(); $days = $toDate->diffInDays($fromDate, false); if($days == 1){ return 'Tomorrow'; } else if($days == 0){ return 'Today'; } else if($days > 0){ return $days.' Days'; } else if($days == -1){ return 'Past Due by '. abs($days).' day'; } else if($days < -1){ return 'Past Due by '. abs($days) .' days'; } else { return $fromDate->diffForHumans(['options' => Carbon::ONE_DAY_WORDS]); } } public static function expiresInStrForHumans($date) { $fromDate = Carbon::parse($date)->addDays(1); $toDate = Carbon::now(); $days = $toDate->diffInDays($fromDate, false); if($days == 1){ return 'Expires by Tomorrow'; } else if($days == 0){ return 'Expires Today'; } else if($days > 0){ return 'Expires in '. $days.' days'; } else if($days == -1){ return 'Expired '. abs($days).' day ago'; } else if($days < -1){ return 'Expired '. abs($days) .' days ago'; } else { return $fromDate->diffForHumans(['options' => Carbon::ONE_DAY_WORDS]); } } static function notifyFromSchool($title, $message, $school, $users = []){ if(empty($users)){ Log::debug("not notifying via email, as user list is empty"); return; } $toAddresses[] = ['email' => 'info@rewardsforeducation.com', 'name' => 'Info @ RewardsForEducation']; $toBccAddresses = []; foreach($users AS $user){ $toBccAddresses[] = ['email' => $user->email, 'name' => $user->full_name]; } $subject = 'You Have a New Message from '. $school->school_name; $data = [ 'schoolName' => $school->school_name, 'message' => $message, ]; $emailContent = view('EmailTemplates.notification_from_school', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( null, null, $subject, $emailContent, $toAddresses, [], $toBccAddresses ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskAssignment($task, $parentUser, $childUser){ if(!empty($childUser->email)){ Log::debug("not notifying via email, as email is not preset"); return; } $toEmail = $childUser->email; $toName = $childUser->full_name; $subject = 'New Task Assigned'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, 'assignedBy' => $parentUser->full_name ]; $emailContent = view('EmailTemplates.task_assignment_notify_to_child', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskCompleted($task, $parentUser, $childUser){ $toEmail = $parentUser->email; $toName = $parentUser->full_name; $subject = 'Task Claimed'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, 'assignedTo' => $childUser->full_name ]; $emailContent = view('EmailTemplates.task_completed_notify_to_parent', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskApproved($task, $parentUser, $childUser){ if(!empty($childUser->email)){ Log::debug("not notifying via email, as email is not preset"); return; } $toEmail = $childUser->email; $toName = $childUser->full_name; $subject = 'Task Approved'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, ]; $emailContent = view('EmailTemplates.task_approved_notify_to_child', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskRejected($task, $parentUser, $childUser){ if(!empty($childUser->email)){ Log::debug("not notifying via email, as email is not preset"); return; } $toEmail = $childUser->email; $toName = $childUser->full_name; $subject = 'Task Rejected'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, ]; $emailContent = view('EmailTemplates.task_rejected_notify_to_child', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskStatusChange($task, $parentUser, $changedBy, $newStatus){ $toEmail = $parentUser->email; $toName = $parentUser->full_name; $subject = 'Task Status Change'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, 'currentStatus' => $newStatus, 'updatedBy' => $changedBy->email, ]; $emailContent = view('EmailTemplates.task_status_change_notification_to_parent', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } static function notifyTaskRevokeChange($task, $parentUser, $childUser){ $toEmail = $parentUser->email; $toName = $parentUser->full_name; $subject = 'Task Moved to Pending'; $data = [ 'recipientName' => $toName, 'taskName' => $task->task_title, 'childName' => $childUser->full_name, ]; $emailContent = view('EmailTemplates.task_revoked_notify_parent', $data)->render(); $emailService = new EmailService(); $emailResponse = $emailService->sendEmail( $toEmail, $toName, $subject, $emailContent ); if(!$emailResponse['success']){ Log::error("failure in sending email: ". $emailResponse['message']); } else { Log::debug("email sent successfully: ". $emailResponse['message']); } } public static function daysToHumanCalenderTerm($days) { if ($days < 1) { return 'less than a day'; } $units = [ 'year' => 365, 'month' => 30, 'week' => 7, 'day' => 1, ]; $result = ''; foreach ($units as $unit => $value) { if ($days >= $value) { $count = floor($days / $value); $result .= "$count $unit" . ($count > 1 ? 's' : '') . ' '; $days %= $value; } } return trim($result); } public static function eventDateTimeToHumanReadable($eventDate) { $eventDateTime = new DateTime($eventDate); $currentDateTime = new DateTime(); $interval = $eventDateTime->diff($currentDateTime); $daysDifference = $interval->days; if ($daysDifference < 1) { $hoursDifference = $interval->h + ($interval->i / 60); if ($hoursDifference < 1) { $minutesDifference = $interval->i; return intval($minutesDifference)." minute" . ($minutesDifference >= 2 ? 's' : '') . ' ago'; } else { return intval($hoursDifference)." hour" . ($hoursDifference >= 2 ? 's' : '') . ' ago'; } } else { return $eventDateTime->format('h:i A | jS M Y'); } } public static function shouldShowParentView(User $user, $group_id){ $currentGroup = Group::where('group_id', $group_id)->first(); if($currentGroup->owner_user_id == $user->user_id){ return true; } $members = $currentGroup->members; if($members != null && count($members) > 0){ foreach($members AS $member){ if($member->member_user_id == $user->user_id){ if($member->role != null && in_array($member->role->name, ['PARENT', 'SOCIAL_WORKER', 'OWNER'])){ return true; } } } } return false; } public static function formatDecimanPoints($number_to_format, $digits_after_decimal_point){ return rtrim(sprintf('%.'.$digits_after_decimal_point.'F', $number_to_format), ''); } public static function formatDecimanPointsTUIT($tuit_balance){ return rtrim(sprintf('%.3F', $tuit_balance), ''); } public static function formatDecimanPointsSP($sp_balance){ return $sp_balance; } public static function getNumericUUID(){ // Generate a UUID $uuid = Uuid::uuid4(); // Convert the UUID to a hexadecimal string $hexUuid = $uuid->toString(); // Remove the hyphens from the hexadecimal UUID $hexUuidWithoutHyphens = str_replace('-', '', $hexUuid); // Convert the hexadecimal UUID to a numeric representation $numericUuid = base_convert($hexUuidWithoutHyphens, 16, 10); $numericUuid = str_pad(substr($numericUuid, 0, 11), 11, '0', STR_PAD_RIGHT); return $numericUuid; } public static function getStringUUID(){ // Generate a UUID $uuid = Uuid::uuid4(); // Convert the UUID to a hexadecimal string $hexUuid = $uuid->toString(); return $hexUuid; } public static function fromMbToHumanReadable($mb_value){ $value_human_str = ""; $mb_value = floatval($mb_value); if($mb_value >= 1024.0){ //GB $value_human_str = ( $mb_value / 1024 ) ." GB"; } else if($mb_value > 1.0){ //MB $value_human_str = ( $mb_value ) ." MB"; } else if(($mb_value * 1024) > 1.0){ //KB $value_human_str = ( $mb_value * 1024.0 ) ." KB"; } else if(($mb_value * 1024.0 * 1024 ) > 1.0){ //Bytes $value_human_str = ( $mb_value * 1024.0 * 1024.0) ." Bytes"; } else if($mb_value == 0){ $value_human_str = "0 Bytes"; } return $value_human_str; } public static function getCsvFileInfo($file) { // Get the file size $fileSize = $file->getSize(); // Get the path of the file $filePath = $file->getRealPath(); // Create a CSV reader instance $csv = Reader::createFromPath($filePath, 'r'); $csv->setHeaderOffset(0); // Assuming the first row is the header // Count the number of rows $rowCount = iterator_count($csv->getRecords()) + 1; // +1 to include the header row return [ 'fileSize' => $fileSize, 'rowCount' => $rowCount, ]; } public static function getFirstDateOfMonth($yearMonth) { // Create a DateTime object from the 'yyyy-mm' string $date = DateTime::createFromFormat('Y-m', $yearMonth); // Set the day to 1 to get the first date of the month $date->setDate($date->format('Y'), $date->format('m'), 1); // Return the date in 'Y-m-d' format return $date->format('Y-m-d'); } public static function getFilterOptionsForTasksFromSession(){ $task_filter_options = Session::get('taskFilterOptions', []); return $task_filter_options; } public static function updateFilterOptionsForTasksInSession($group_id, $goal_id, $task_type, $visible_to){ $task_filter_options = [ "group_id" => $group_id, "goal_id" => $goal_id, "task_type" => $task_type, "visible_to" => $visible_to]; Session::put('taskFilterOptions', $task_filter_options); } public static function getFilterOptionsForProductsFromSession(){ $product_filter_options = Session::get('productFilterOptions', []); return $product_filter_options; } public static function updateFilterOptionsForProductsInSession($product_category_id, $visible_to){ $product_filter_options = [ "product_category_id" => $product_category_id, "visible_to" => $visible_to]; Session::put('productFilterOptions', $product_filter_options); } public static function isValidEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) !== false; } public static function getCurrentSchool(Admin $user){ $school = $user->schools && count($user->schools) > 0 ? $user->schools[0] : null; return $school; } public static function countWeekends($month, $year) { // Create a Carbon instance for the first day of the month $startOfMonth = Carbon::create($year, $month, 1); $endOfMonth = $startOfMonth->copy()->endOfMonth(); $saturdays = 0; $sundays = 0; // Iterate through each day of the month for ($date = $startOfMonth; $date->lte($endOfMonth); $date->addDay()) { if ($date->isSaturday()) { $saturdays++; } if ($date->isSunday()) { $sundays++; } } // return [ // 'saturdays' => $saturdays, // 'sundays' => $sundays, // ]; return $saturdays+$sundays; } }