Ngiler SH3LL 360
Home
Information
Create File
Create Folder
:
/
home
/
tbf
/
membrubackend
/
app
/
Helpers
/
Information Server
MySQL :
OFF
Perl :
OFF
CURL :
ON
WGET :
OFF
PKEXEC :
OFF
Directive
Local Value
IP Address
89.40.16.97
System
Linux server.atelieruldeit.ro 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64
User
tbf
PHP Version
7.3.33
Software
Apache
Doc root
Writable
close
Edit File :
general.php
| Size :
31.08
KB
Copy
<?php use App\Models\KeyResult; use App\Models\CronjobMail; use App\Models\User; use App\Models\Role; use App\Models\CronjobActiveCampaign; use App\Models\Objective; use Carbon\Carbon; use App\Models\Instance; use App\Mail\NewInvoice; use App\Mail\ResendInvoice; use App\Repositories\InvoiceRepository; use App\Models\EnrolledCourse; function addToActiveCampaign($data){ $url = env('ACTIVE_CAMPAIGN_HOST') . "/admin/api.php?api_action=contact_sync&api_key=" . env('ACTIVE_CAMPAIGN_KEY') . "&api_output=json"; $cURLConnection = curl_init($url); curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data); curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true); $apiResponse = curl_exec($cURLConnection); curl_close($cURLConnection); // $apiResponse - available data from the API request $jsonArrayResponse = json_decode($apiResponse, true); } function removeTagActiveCampaign($data){ $url = env('ACTIVE_CAMPAIGN_HOST') . "/admin/api.php?api_action=contact_tag_remove&api_key=" . env('ACTIVE_CAMPAIGN_KEY') . "&api_output=json"; $cURLConnection = curl_init($url); curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data); curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true); $apiResponse = curl_exec($cURLConnection); curl_close($cURLConnection); // $apiResponse - available data from the API request $jsonArrayResponse = json_decode($apiResponse, true); } function newUserCreatedMail($user, $password, $alreadyRegisteredUser){ // change the language according to user language App::setLocale($user->language); $course_name = str_replace('Curs:','',$user->instance->package->name); $subject = "[".$course_name."] Acces curs"; $data = [ 'name' => $user->email, 'password' => $password, 'login_url' => "https://tbf.learnworlds.com/", 'admin_name' => $user->getFullName(), 'already_registered' => $alreadyRegisteredUser, 'course_name' => $course_name ]; createCronjobMail($user->email, $subject, $data, CronjobMail::NEW_USER_CREATED, $user->language); } function sendInvoiceToClientFirstTime($invoice, $email){ $subject = "[Membru TBF] Factura fiscală"; $data = []; $filename = $invoice->series."-".$invoice->number.'.pdf'; if ($invoice->currency == "EUR") { $pdf = PDF::loadView('invoices.download_eur', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); }elseif ($invoice->currency == "USD") { $pdf = PDF::loadView('invoices.download_usd', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); }else{ $pdf = PDF::loadView('invoices.download', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); } try { Mail::to($email)->send(New NewInvoice($subject, $data, $pdf, $filename)); }catch(\Exception $e){ Log::critical($e); } } function sendInvoiceToClient($invoice, $emails){ $subject = "[Membru TBF] Factura fiscală"; $data = []; $filename = $invoice->series."-".$invoice->number.'.pdf'; if ($invoice->currency == "EUR") { $pdf = PDF::loadView('invoices.download_eur', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); }elseif ($invoice->currency == "USD") { $pdf = PDF::loadView('invoices.download_usd', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); }else{ $pdf = PDF::loadView('invoices.download', compact('invoice'))->save(public_path('invoices/'.$filename))->stream(); } try { Mail::to(explode(',', $emails))->send(New ResendInvoice($subject, $data, $pdf, $filename)); }catch(\Exception $e){ Log::critical($e); } } function newUserCantPay($user){ $instance = $user->instance; $package = $instance->package; $subject = "[Important] Plată eșuată"; $data = [ 'landing_page_url' => $package->landing_page_url, 'course_name' => $package->name, 'limited_offer' => $package->compare_at_price_euro ? true : false ]; createCronjobMail($user->email, $subject, $data, CronjobMail::NEW_USER_CANTPAY, $user->language); } function setStatus($entity){ if($entity->percent >= 100) { if($entity instanceof KeyResult && $entity->status != $entity::STATUS_FINISHED){ $status = $entity::STATUS_ACTIVE; }else{ $status = $entity::STATUS_FINISHED; } }elseif (Carbon::now() < $entity->start_date) { $status = $entity::STATUS_UPCOMING; }elseif (Carbon::now() > Carbon::parse($entity->end_date)->endOfDay()) { $status = $entity::STATUS_OVERDUE; }else { $status = $entity::STATUS_ACTIVE; } return $status; } function calculateKeyResultPercentage($value, $keyResult){ switch ($keyResult->progress_type) { case $keyResult::TYPE_GROW: $percent = 100 - (($keyResult->target - $value) / (($keyResult->target - $keyResult->start_value) / 100)); return $percent; case $keyResult::TYPE_DECREASE: $percent = 100 - (($value - $keyResult->target) / (($keyResult->start_value - $keyResult->target) / 100)); return $percent; } } function calculateObjectivePercentage($objective){ $keyResults = $objective->key_results; if($keyResults->count()){ $procentajPondere = 100 / $keyResults->count(); $keyResultsPercent = $keyResults->sum(function ($keyResult) { if($keyResult->percent > 100){ return 100; }elseif($keyResult->percent < 0){ return 0; } return $keyResult->percent; }); $percent = $keyResultsPercent * $procentajPondere / 100; } return isset($percent) ? $percent : 0; } function assignedToObjectiveMail($user, $objective){ // change the language according to user language App::setLocale($user->language); $subject = __('general.assigned_to_objective.subject', ['name' => $objective->name]); $data = [ 'name' => $objective->name, 'description' => $objective->description, 'start_date' => Carbon::parse($objective->start_date)->isoFormat('D MMM YYYY'), 'end_date' => Carbon::parse($objective->end_date)->isoFormat('D MMM YYYY'), 'total_days' => Carbon::parse($objective->start_date)->startOfDay()->diffInDays($objective->end_date), 'objective_link' => config('app.fe_url').'/obiectiv/'.$objective->slug ]; createCronjobMail($user->email, $subject, $data, CronjobMail::ASSIGNED_TO_OBJECTIVE, $user->language); } function assignedToKeyResultMail($user, $keyResult){ // change the language according to user language App::setLocale($user->language); $subject = __('general.assigned_to_key_result.subject', ['name' => $keyResult->name]); $data = [ 'name' => $keyResult->name, 'description' => $keyResult->description, 'progress_type' => __('general.mail.'.$keyResult->progress_type, [ 'start_value' => $keyResult->start_value, 'target' => $keyResult->target, ]), 'measurement' => $keyResult->measurement, 'start_date' => Carbon::parse($keyResult->start_date)->isoFormat('D MMM YYYY'), 'end_date' => Carbon::parse($keyResult->end_date)->isoFormat('D MMM YYYY'), 'total_days' => Carbon::parse($keyResult->start_date)->startOfDay()->diffInDays($keyResult->end_date), 'key_result_link' => config('app.fe_url').'/obiectiv/'.$keyResult->objective->slug.'/'.$keyResult->id.'/actualizari', 'objective_name' => $keyResult->objective->name ]; createCronjobMail($user->email, $subject, $data, CronjobMail::ASSIGNED_TO_KEY_RESULT, $user->language); } function modifiedColumns($entity){ $allColumns = ['name', 'description', 'start_date', 'end_date', 'master_goal_id', 'objective_id', 'measurement', 'unity', 'target', 'start_value', 'progress_type']; $modifiedColumns = Arr::where($allColumns, function ($item) use ($entity){ if($entity->wasChanged($item)){ return $item; } }); return $modifiedColumns ? implode(',', $modifiedColumns) : null; } function modifiedColumnsTranslated($columns){ $columns = explode(',', $columns); $columnsTranslated = []; foreach($columns as $column){ $columnsTranslated[] = __('general.columns.'.$column); } return implode(',', $columnsTranslated); } function betweenUsersLimit($instance){ $userLimit = $instance->package->user_limit; if($userLimit == 0){ return true; } return $userLimit > $instance->users->count() ? true : false; } function betweenObjectivesLimit($instance){ $objectiveLimit = $instance->package->objective_limit; $activeObjectives = $instance->objectives->where('status', Objective::STATUS_ACTIVE)->count(); if($objectiveLimit == 0){ return true; } return $objectiveLimit > $activeObjectives ? true : false; } function betweenKeyResultsLimit($instance){ $keyResultLimit = $instance->package->results_limit; if($keyResultLimit == 0){ return true; } return $keyResultLimit > $instance->key_results->count() ? true : false; } function betweenLimit($instance){ $userLimit = $instance->package->user_limit; $objectiveLimit = $instance->package->objective_limit; $activeObjectives = $instance->objectives->where('status', Objective::STATUS_ACTIVE)->count(); if(($userLimit == 0) && $objectiveLimit == 0){ return true; } return ($userLimit >= $instance->users->count() && ($objectiveLimit >= $activeObjectives || $objectiveLimit == 0)) ? true : false; } function dailyNotificationReport($user, $data){ // change the language according to user language App::setLocale($user->language); $subject = __('general.daily_notification_report.subject', ['today_date' => Carbon::today()->isoFormat('DD/MM/Y')]); createCronjobMail($user->email, $subject, $data, CronjobMail::DAILY_NOTIFICATION_REPORT, $user->language); } function entitySetNull($entities, $column){ $entities->each(function($entity) use ($column) { $entity->update([$column => null]); }); } function entityDelete($entities){ $entities->each(function($entity) { $entity->delete(); }); } function cardErrorTranslated($e){ return Lang::has('general.card_error.'.$e->getErrorCode()) ? __('general.card_error.'.$e->getErrorCode()) : $e->getMessage(); } function checkIfPrizeAvailable($user) { $userWinningPeriods = $user->user_winning_periods; foreach($userWinningPeriods as $userWinningPeriod) { if(Carbon::parse($userWinningPeriod->min_date)->toDateString() < Carbon::today() && Carbon::today() < Carbon::parse($userWinningPeriod->max_date)->toDateString()) { // check number of promises $promisesCount = $user->promises->whereBetween('created_at',[Carbon::parse($userWinningPeriod->min_date)->startOfDay(),Carbon::parse($userWinningPeriod->max_date)->endOfDay()])->count(); // generate number of chances $dailyChances = $userWinningPeriod->partner_prize->days_step > 0 ? round(100/$userWinningPeriod->partner_prize->days_step,0) : 0; $chances = []; $i = 1; while ($i <= $promisesCount*$dailyChances) { $chances[] = rand(1,100); $i += 1; } $pickedNumber = rand(1,100); // check if one of the chances is picked if(in_array($pickedNumber, $chances)) { // update $userWinningPeriod with new timeframe $userWinningPeriod->update([ 'min_date' => Carbon::parse($userWinningPeriod->max_date)->addDay(1)->toDateString(), 'max_date' =>Carbon::parse($userWinningPeriod->max_date)->addDay(31)->toDateString() ]); // create a coupon $user->user_partner_prizes()->create([ 'partner_prize_id' => $userWinningPeriod->partner_prize_id, 'code' => $userWinningPeriod->partner_prize->prefix.Carbon::today()->format('md') ]); // return $prize return [ 'prize' => $userWinningPeriod->partner_prize ]; } } // this is temporarry for razvan return [ 'prize' => $userWinningPeriod->partner_prize ]; } return ['prize' => $user->user_winning_periods->first() ? $user->user_winning_periods->first()->partner_prize : null]; } function newUserCreatedPromiseTimeMail($user){ // change the language according to user language App::setLocale($user->language); $subject = __('general.new_user_created_promise_time.subject', ['promise_time' => $user->promise_time]); $data = [ 'promise_time' => $user->promise_time, ]; createCronjobMail($user->email, $subject, $data, CronjobMail::NEW_USER_CREATED_PROMISE_TIME, $user->language); } function newKeyResultForYourObjectiveMail($keyResult){ $objective = $keyResult->objective; // change the language according to user language App::setLocale($objective->user->language); $subject = __('general.new_key_result_for_your_objective.subject', ['name' => $keyResult->name]); $data = [ 'name' => $keyResult->name, 'description' => $keyResult->description, 'responsible' => $keyResult->user->getFullName(), 'progress_type' => __('general.mail.'.$keyResult->progress_type, [ 'start_value' => $keyResult->start_value, 'target' => $keyResult->target, ]), 'measurement' => $keyResult->measurement, 'start_date' => Carbon::parse($keyResult->start_date)->isoFormat('D MMM YYYY'), 'end_date' => Carbon::parse($keyResult->end_date)->isoFormat('D MMM YYYY'), 'total_days' => Carbon::parse($keyResult->start_date)->startOfDay()->diffInDays($keyResult->end_date), 'key_result_link' => config('app.fe_url').'/obiectiv/'.$keyResult->objective->slug.'/'.$keyResult->id.'/actualizari', 'objective_name' => $objective->name ]; createCronjobMail($objective->user->email, $subject, $data, CronjobMail::NEW_KEY_RESULT_FOR_YOUR_OBJECTIVE, $objective->user->language); } function newKeyResultCommentMail($user, $keyResultComment){ $keyResult = $keyResultComment->key_result; $entrepreneurId = $user->instance->users->first()->id; // change the language according to user language App::setLocale($keyResult->user->language); $subject = __('general.new_key_result_comment.subject', ['user_last_name' => $user->last_name]); $data = [ 'user_full_name' => $user->getFullName(), 'status' => __('general.mail.'.$keyResultComment->status), 'message' => $keyResultComment->message, 'key_result_name' => $keyResult->name, 'message_link' => config('app.fe_url').'/obiectiv/'.$keyResult->objective->slug.'/'.$keyResult->id.'/comentarii', 'reply_email' => $user->id == $entrepreneurId ? $keyResult->user->email : 0, ]; createCronjobMail($keyResult->user->email, $subject, $data, CronjobMail::NEW_KEY_RESULT_COMMENT, $keyResult->user->language); } function newKeyResultLogMail($keyResultLog){ $keyResult = $keyResultLog->key_result; // change the language according to user language App::setLocale($keyResult->objective->user->language); $subject = __('general.new_key_result_log.subject'); $data = [ 'user_full_name' => $keyResultLog->user->getFullName(), 'key_result_name' => $keyResult->name, 'value' => $keyResultLog->value, 'unity' => $keyResult->unity, 'key_result_percent' => round($keyResultLog->key_result_percent), 'description' => $keyResultLog->description, 'progress_type' => __('general.mail.'.$keyResult->progress_type, [ 'start_value' => $keyResult->start_value, 'target' => $keyResult->target, ]), 'status' => __('general.mail.'.$keyResultLog->status), 'key_result_link' => config('app.fe_url').'/obiectiv/'.$keyResult->objective->slug.'/'.$keyResult->id.'/actualizari', ]; createCronjobMail($keyResult->objective->user->email, $subject, $data, CronjobMail::NEW_KEY_RESULT_LOG, $keyResult->objective->user->language); } function notSetPromiseMail($user){ // change the language according to user language App::setLocale($user->language); $subject = __('general.not_set_promise.subject'); $data = [ 'promise_time' => $user->promise_time, 'set_promise_link' => config('app.fe_url').'/dashboard' ]; createCronjobMail($user->email, $subject, $data, CronjobMail::NOT_SET_PROMISE, $user->language); } function createCronjobMail($sendTo, $subject, $body, $type, $language){ CronjobMail::create([ 'send_to' => $sendTo, 'subject' => $subject, 'body' => json_encode($body), 'type' => $type, 'language' => $language, ]); } function createCronjobActiveCampaign($user, $tag){ if($user){ $data = [ 'email' => $user->email, 'first_name' => $user->getFullName(), // full name 'tags' => $tag, 'FIRSTNAME' => $user->first_name, // for sendinblue 'LASTNAME' => $user->last_name, // for sendinblue ]; CronjobActiveCampaign::create(['data' => json_encode($data)]); } } function setPrivateObjectiveId($user, $objectiveId){ $privateObjIds = array_filter(explode(',', $user->private_objective_ids)); array_push($privateObjIds, $objectiveId); $user->update(['private_objective_ids' => implode(',', $privateObjIds)]); } function removePrivateObjectiveId($user, $objectiveId){ $privateObjIds = array_filter(explode(',', $user->private_objective_ids)); if(in_array($objectiveId, $privateObjIds)){ $positionOfId = array_search($objectiveId, $privateObjIds); unset($privateObjIds[$positionOfId]); $user->update(['private_objective_ids' => implode(',', $privateObjIds)]); } } function checkManagerAccess($masterGoalId, $user){ return in_array($masterGoalId, explode(',', $user->manager_master_goal_ids)); } function isPrivateObjective($objectiveId, $user){ return in_array($objectiveId, explode(',', $user->private_objective_ids)); } function setAccessManagerToMasterGoal($userIds, $masterGoalIdsArr){ $users = User::whereIn('id', $userIds)->get(); foreach($users as $user){ $managerMasterGoalIds = array_filter(explode(',', $user->manager_master_goal_ids)); $managerMasterGoalIds = array_unique(array_merge($managerMasterGoalIds, $masterGoalIdsArr)); $user->update(['manager_master_goal_ids' => implode(',', $managerMasterGoalIds)]); } } function removeAccessManagerFromMasterGoal($userIds, $masterGoalIdsArr){ $users = User::whereIn('id', $userIds)->get(); foreach($users as $user){ $userMasterGoalIds = $user->manager_master_goal_ids; if($userMasterGoalIds){ $managerMasterGoalIds = array_filter(explode(',', $userMasterGoalIds)); $managerMasterGoalIds = array_diff($managerMasterGoalIds, $masterGoalIdsArr); $user->update(['manager_master_goal_ids' => $managerMasterGoalIds ? implode(',', $managerMasterGoalIds) : null]); } } } function setAccessManagerToMasterGoalParent($instance, $parentMasterGoalId, $masterGoalIdsArr){ $users = $instance->users->where('role_id', Role::ROLE_MANAGER); foreach($users as $user){ $userMasterGoalIds = explode(',', $user->manager_master_goal_ids); if(in_array($parentMasterGoalId, $userMasterGoalIds)){ $managerMasterGoalIds = array_filter($userMasterGoalIds); $managerMasterGoalIds = array_unique(array_merge($managerMasterGoalIds, $masterGoalIdsArr)); $user->update(['manager_master_goal_ids' => implode(',', $managerMasterGoalIds)]); } } } function removeAccessManagerToMasterGoalParent($instance, $parentMasterGoalId, $masterGoalIdsArr){ $users = $instance->users->where('role_id', Role::ROLE_MANAGER); foreach($users as $user){ $userMasterGoalIds = explode(',', $user->manager_master_goal_ids); if(in_array($parentMasterGoalId, $userMasterGoalIds)){ $managerMasterGoalIds = array_filter($userMasterGoalIds); $managerMasterGoalIds = array_diff($managerMasterGoalIds, $masterGoalIdsArr); $user->update(['manager_master_goal_ids' => $managerMasterGoalIds ? implode(',', $managerMasterGoalIds) : null]); } } } function isPrivateMasterGoal($masterGoalId, $user){ return in_array($masterGoalId, explode(',', $user->private_master_goal_ids)) && !in_array($masterGoalId, explode(',', $user->manager_master_goal_ids)); } function setPrivateMasterGoalId($user, $masterGoalId){ $privateMasterGoalIds = array_filter(explode(',', $user->private_master_goal_ids)); array_push($privateMasterGoalIds, $masterGoalId); $user->update(['private_master_goal_ids' => implode(',', $privateMasterGoalIds)]); } function updateUserPrivateObjectiveIds($instance){ $users = $instance->users; // first remove all private objective ids that remian in case it was deleted while there was a bug. $users->each(function ($user) { $user->update(['private_objective_ids' => null]); }); // get objectives that are private $instance->objectives->where('is_private', 1)->each(function ($objective) use ($users) { // set objective_private_ids for all users except the responsible one $users->where('id', '!=', $objective->user_id)->each(function ($user) use ($objective) { // check if the user is already a manager on that master goal of objective if($user->isManager() && checkManagerAccess($objective->master_goal_id, $user)){ return true; } // check if this user is responsible for key results that are assigned to this objective if(!in_array($user->id, $objective->key_results->pluck('user_id')->toArray())){ $privateObjIds = array_filter(explode(',', $user->private_objective_ids)); array_push($privateObjIds, $objective->id); $user->update(['private_objective_ids' => implode(',', $privateObjIds)]); } }); }); } function cardDetailsStripe($customerId){ $cardDetailsStripe = null; try{ $cardDetailsStripe = Stripe::cards()->all($customerId)['data'][0]; }catch(\Exception $e){ // } return $cardDetailsStripe; } function generateIntercomSignInToken($userEmail) { return hash_hmac( 'sha256', // hash function $userEmail, // user's email config('app.intercom_secret_token') // secret key (keep safe!) ); } function compareSubscriptions() { $instances = Instance::whereIn('status', [Instance::STATUS_ACTIVE, Instance::STATUS_GRACE_PERIOD])->whereNull('free_period')->get(); $today = Carbon::today(); $instancesWithoutActiveSubscription = []; foreach($instances as $instance){ $entrepreneur = $instance->users->first(); $exceptionEmails = [ 'popescu.alex@tbf.ro', 'popalexandru06@yahoo.com', 'alex.popescu@tbf.ro', 'popalexandru06@gmail.com', 'aaa@com.com', 'john.doe@tbf.ro', 'dorel.avram@tbf.ro', 'mihai@antonadvertising.ro', ]; // check for entrepreneur emails not to be in our list if($entrepreneur && !in_array($entrepreneur->email, $exceptionEmails)){ $subscriptions = null; try{ $subscriptions = Stripe::subscriptions()->all($instance->stripe_customer_id); }catch(\Exception $e){ // } $activeSubscriptions = 0; if($subscriptions){ foreach ($subscriptions['data'] as $subscription) { if($subscription['status'] == 'active'){ $activeSubscriptions += 1; } } } if($activeSubscriptions == 0){ // check what day of grace period is the instance if($instance->status == Instance::STATUS_GRACE_PERIOD){ $gracePeriodDay = Carbon::parse($instance->grace_period_date)->diffInDays($today); }else{ $gracePeriodDay = null; } $instancesWithoutActiveSubscription[] = [ 'name' => $entrepreneur->last_name.' '.$entrepreneur->first_name, 'email' => $entrepreneur->email, 'instance_id' => $instance->id, 'grace_period_day' => $gracePeriodDay, ]; } } } return $instancesWithoutActiveSubscription; } function updateCustomerData($instance, $email){ try { Stripe::customers()->update($instance->stripe_customer_id, [ 'email' => $email, 'name' => $instance->company_name ? $instance->company_name : $instance->name, 'phone' => $instance->phone, 'metadata' => [ 'Nr. reg' => $instance->reg_no, 'CNP' => $instance->cnp, 'instance_id' => $instance->id ], ]); }catch(\Exception $e){ // } // check tax id is valid and add to customer if($instance->cui){ // check if there is any tax ID try { $taxIDs = Stripe::customerTaxIds()->all($instance->stripe_customer_id); } catch (Cartalyst\Stripe\Exception\MissingParameterException $e) { return [ 'status' => 'error', 'errors' => [ 'cui' => "CUI Invalid" ] ]; } // delete old tax ID if(isset($taxIDs['data'][0])){ try { Stripe::customerTaxIds()->delete($instance->stripe_customer_id, $taxIDs['data'][0]['id']); } catch (Cartalyst\Stripe\Exception\MissingParameterException $e) { return [ 'status' => 'error', 'errors' => [ 'cui' => "CUI Invalid" ] ]; } } // create tax ID try { Stripe::customerTaxIds()->create($instance->stripe_customer_id, [ 'type' => 'eu_vat', 'value' => $instance->cui ]); } catch (Cartalyst\Stripe\Exception\MissingParameterException $e) { return [ 'status' => 'error', 'errors' => [ 'cui' => "CUI Invalid" ] ]; } } } function addToListSendInBlue($data, $listID){ $url = "https://api.sendinblue.com/v3/contacts/lists/".$listID."/contacts/add"; $cURLConnection = curl_init($url); curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, json_encode([ 'emails' => [ $data['email'] ] ])); curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true); curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, [ 'accept: */*', 'content-type: application/json', 'api-key: '.env('SENDINBLUE_KEY'), ]); $apiResponse = curl_exec($cURLConnection); curl_close($cURLConnection); // $apiResponse - available data from the API request $response = json_decode($apiResponse, true); } function createContactSendInBlue($data, $listID){ $url = "https://api.sendinblue.com/v3/contacts"; $cURLConnection = curl_init($url); curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, json_encode([ 'email' => $data['email'], 'attributes' => [ 'FIRSTNAME' => $data['FIRSTNAME'], 'LASTNAME' => $data['LASTNAME'], ], 'listIds' => [ $listID ], ])); curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true); curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, [ 'accept: */*', 'content-type: application/json', 'api-key: '.env('SENDINBLUE_KEY'), ]); $apiResponse = curl_exec($cURLConnection); curl_close($cURLConnection); // $apiResponse - available data from the API request $response = json_decode($apiResponse, true); // check if the contact already existed and add it to list if(!isset($response['id'])){ addToListSendInBlue($data, $listID); } } function learworldsInit($user, $password){ $accessToken = config('app.learn_world_access_token'); // Your APP Access Token $clientId = config('app.learn_world_client_id'); // Your Client Id $package = $user->instance->package; $alreadyRegisteredUser = EnrolledCourse::where('email',$user->email)->first(); if(!$alreadyRegisteredUser){ $data = [ 'username' => $user->email, 'password' => $password, 'email' => $user->email ]; // create a new user $result = learnworldsPostRequest('/users', $accessToken, $clientId, $data); // check if everything was successful if(!$result['success']) { foreach ($result['errors'] as $error) { Log::critical($error['context'] . ': ' . $error['message']); } return true; } // Grab the user's id $userId = $result['user']['id']; $enrolled = EnrolledCourse::create([ 'email' => $user->email, 'learn_world_user_id' => $userId, 'learn_world_course_slug' => $package->learn_world_course_slug ]); }else{ $userId = $alreadyRegisteredUser->learn_world_user_id; } // Setup Post data $data = [ 'user' => $userId, 'product' => $package->learn_world_course_slug, 'justification' => $package->name ]; // Enroll user in course $result = learnworldsPostRequest('/user-product', $accessToken, $clientId, $data); Log::critical($result); // check if everything was successful if(!$result['success']) { foreach ($result['errors'] as $error) { Log::critical($error['context'] . ': ' . $error['message']); } return true; } return $alreadyRegisteredUser ? true : false; } function learnworldsPostRequest($uri, $token, $clientId, $data) { Log::critical("Date spre learnworld"); Log::critical($data); $post = ['data' => json_encode($data)]; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => config('app.learn_world_url') . $uri, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => [ "authorization: Bearer {$token}", "lw-client: {$clientId}", ], )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { Log::critical("Acest user are deja cont pe learnworld"); } return json_decode($response, true); }
Back