· 4 years ago · Jul 19, 2021, 11:54 AM
1<?php
2
3/*
4 * Copyright (C) 2020, Prodevs, - All Rights Reserved
5 * @project thatapp
6 * @file my_helper.php
7 * @author ProDevs
8 * @site <http://prodevs.io>
9 * @lastmodified 02/09/2020, 12:26 PM
10 */
11
12//To avoid redeclaring functions
13
14use Illuminate\Support\Facades\Http;
15use Illuminate\Support\Facades\Log;
16
17if (!function_exists('app_constants')) {
18 function app_constants()
19 {
20 return [
21 'TOKEN_EXPIRED' => 'You session has expired, please login to renew your session',
22
23 // AUTH
24 'TOKEN_INVALIDATED' => 'Your session has expired, please log in to continue',
25 'TOKEN_INVALID' => 'Illegal access. Please log in or register',
26 'TOKEN_GEN' => 'Successfully logged you into the app',
27 'INVALID_CREDENTIALS' => 'The login credentials you used is not valid, please check and retry.',
28 'TOKEN_REFRESHED' => 'Your session has been refreshed.',
29 'MEMBER' => 'Member details',
30 'MEMBER_NOT_FOUND' => 'Member details does not exist',
31 'TOKEN_CREATION_ERR' => 'We are sorry but we could not log you into the app. A group of experts are already on this matter. ',
32
33 // MISCELLANEOUS
34 'PROCESSING' => 'The action is being processed and would be resolved soon.',
35 'PUSH_MESSAGE' => 'Message has been sent to device.',
36
37 'RESET_EMAIL_SENT' => 'The email reset link has been successfully sent to your email. Use the link provided in the email to reset your password. ',
38 'EMAIL_FROM' => "Event Hub",
39
40 // CODE
41 'VALIDATION_EXCEPTION_CODE' => '402',
42 'TOKEN_INVALID_CODE' => '401',
43 'TOKEN_INVALIDATED_CODE' => '406',
44 'EXCEPTION_CODE' => '500',
45
46 // Exceptions
47 'VALIDATION_EXCEPTION' => 'You did not fill one or more required fields in the form. Please fill all the required fields.',
48 'INVALID_EMAIL_EXCEPTION' => 'We could not send a reset link to the email because the email does not have an account attached to it.',
49 'REG_VALIDATION_EXCEPTION' => 'The email you chose already has an account. Try logging into the app with your email and retry your registration again.',
50 'EXCEPTION' => 'This is embarrassing. Something went wrong while trying to process your request but a group of experts are already on this matter.',
51 ];
52 }
53}
54
55if (!function_exists('genericResponse')) {
56 function genericResponse($message = null, $status_code = null, $request = null, $trace = null)
57 {
58 $code = ($status_code != null) ? $status_code : "404";
59 $body = [
60 'message' => "$message",
61 'code' => $code,
62 'status_code' => $code,
63 'status' => false,
64 'trace' => $trace
65 ];
66
67
68 return response()->json($body)->setStatusCode("$code");
69 }
70}
71
72if (!function_exists('save_log')) {
73 function save_log($request, $response)
74 {
75 return \App\Models\ApiLog::create(
76 [
77 'url' => $request->fullUrl(),
78 'method' => $request->method(),
79 'data_param' => json_encode($request->all()),
80 'response' => json_encode($response),
81 ]
82 );
83 }
84}
85
86if (!function_exists('generic_logger')) {
87 function generic_logger($fullUrl = null, $method = null, $param, $response)
88 {
89 \App\Models\ApiLog::create(
90 [
91 'url' => $fullUrl,
92 'method' => $method,
93 'data_param' => json_encode($param),
94 'response' => json_encode($response),
95 ]
96 );
97 }
98}
99
100if (!function_exists('validResponse')) {
101 function validResponse($message = null, $data = [], $request = null)
102 {
103 $body = [
104 'message' => "$message",
105 'data' => $data,
106 'status' => true
107 ];
108
109 return response()->json($body)->setStatusCode("200");
110 }
111}
112
113if (!function_exists('isValidEmail')) {
114 function isValidEmail($email)
115 {
116 return (bool)filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
117 }
118}
119
120
121if (!function_exists('sendEmail')) {
122 function sendEmail($message_data, $subject, $from, $to, $type = null)
123 {
124 if (!$type) {
125 $type = "default";
126 }
127 $info['message'] = $message_data;
128 $info['from'] = $from;
129 $info['email'] = $to;
130 $info['subject'] = $subject;
131
132
133 \Illuminate\Support\Facades\Mail::send(
134 'emails.' . $type,
135 compact('message_data', 'info'),
136 function ($message) use ($info) {
137 $message->from("noreply@thatapp.com", "ThatApp");
138 $message->bcc($info['email'])->subject($info['subject']);
139 }
140 );
141 }
142}
143
144if (!function_exists('search_query_constructor')) {
145 function search_query_constructor($searchString, $col)
146 {
147 $dataArray = (array_filter(explode(" ", trim($searchString))));
148 $constructor_sql = "(";
149 if (count($dataArray) < 1) {
150 return " 1 ";
151 }
152 if (is_array($col)) {
153 foreach ($col as $col_name) {
154 if ($col_name !== $col[0]) {
155 $constructor_sql .= " OR ";
156 }
157 for ($i = 0; $i < count($dataArray); $i++) {
158 if (count($dataArray) - 1 === $i) {
159 $constructor_sql .= "$col_name LIKE '%{$dataArray[$i]}%' ";
160 } else {
161 $constructor_sql .= "$col_name LIKE '%{$dataArray[$i]}%' OR ";
162 }
163 }
164 }
165 } else {
166 for ($i = 0; $i < count($dataArray); $i++) {
167 if (count($dataArray) - 1 === $i) {
168 $constructor_sql .= "$col LIKE '%{$dataArray[$i]}%' ";
169 } else {
170 $constructor_sql .= "$col LIKE '%{$dataArray[$i]}%' OR ";
171 }
172 }
173 }
174 $constructor_sql .= ")";
175 return $constructor_sql;
176 }
177}
178
179if (!function_exists('multi_unset')) {
180 function multi_unset($array, $keys)
181 {
182 if (is_array($array)) {
183 foreach ($keys as $key) {
184 unset($array[$key]);
185 }
186
187 return $array;
188 } else {
189 return null;
190 }
191 }
192}
193
194if (!function_exists('encrypt3Des')) {
195 function encrypt3Des($data, $key = "BKhjatdfXhbTYUErbekj")
196 {
197 //Generate a key from a hash
198 $key = md5(utf8_encode($key), true);
199 //Take first 8 bytes of $key and append them to the end of $key.
200 $key .= substr($key, 0, 8);
201
202 $encData = openssl_encrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
203 return base64_encode($encData);
204 }
205}
206
207if (!function_exists('decrypt3Des')) {
208 function decrypt3Des($data, $secret = "BKhjatdfXhbTYUErbekj")
209 {
210 //Generate a key from a hash
211 $key = md5(utf8_encode($secret), true);
212 //Take first 8 bytes of $key and append them to the end of $key.
213 $key .= substr($key, 0, 8);
214 $data = base64_decode($data);
215
216 $decData = openssl_decrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
217
218 return $decData;
219 }
220}
221
222if (!function_exists('encrypt_decrypt')) {
223 function encrypt_decrypt($action, $string)
224 {
225 try {
226 $output = false;
227
228 $encrypt_method = "AES-256-CBC";
229 $secret_key = 'H899JHShjdfhjhejkse@14447DP';
230 $secret_iv = 'TYEHVn0dUIK888JSBGDD';
231
232 // hash
233 $key = hash('sha256', $secret_key);
234
235 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
236 $iv = substr(hash('sha256', $secret_iv), 0, 16);
237
238 if ($action == 'encrypt') {
239 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
240 $output = base64_encode($output);
241 } elseif ($action == 'decrypt') {
242 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
243 }
244
245 return $output;
246 } catch (\Throwable $e) {
247 return false;
248 }
249 }
250}
251
252if (!function_exists('invoice_date')) {
253 function invoice_date($date)
254 {
255 try {
256 $date = explode("T", $date)[0];
257 return date("F jS, Y", strtotime($date));
258 } catch (\Throwable $e) {
259 return "NILL";
260 }
261 }
262}
263
264if (!function_exists('unformatted_invoice_date')) {
265 function unformatted_invoice_date($date)
266 {
267 try {
268 $date = explode("T", $date)[0];
269 return $date;
270 } catch (\Throwable $e) {
271 return "NILL";
272 }
273 }
274}
275
276if (!function_exists('useJSON')) {
277 function useJSON($url, $username, $apikey, $flash, $sendername, $messagetext, $recipients)
278 {
279 $gsm = array();
280 $country_code = '234';
281 $arr_recipient = explode(',', $recipients);
282 foreach ($arr_recipient as $recipient) {
283 $mobilenumber = trim($recipient);
284 if (substr($mobilenumber, 0, 1) == '0') {
285 $mobilenumber = $country_code . substr($mobilenumber, 1);
286 } elseif (substr($mobilenumber, 0, 1) == '+') {
287 $mobilenumber = substr($mobilenumber, 1);
288 }
289 $generated_id = uniqid('int_', false);
290 $gsm['gsm'][] = array('msidn' => $mobilenumber, 'msgid' => $generated_id);
291 }
292 $message = array(
293 'sender' => $sendername,
294 'messagetext' => $messagetext,
295 'flash' => "{$flash}",
296 );
297
298 $request = array('SMS' => array(
299 'auth' => array(
300 'username' => $username,
301 'apikey' => $apikey
302 ),
303 'message' => $message,
304 'recipients' => $gsm
305 ));
306 $json_data = json_encode($request);
307 if ($json_data) {
308 $response = doPostRequest($url, $json_data, array('Content-Type: application/json'));
309 $result = json_decode($response);
310 return $result->response->status;
311 } else {
312 return false;
313 }
314 }
315}
316
317if (!function_exists('useXML')) {
318 function useXML($url, $username, $apikey, $flash, $sendername, $messagetext, $recipients)
319 {
320 $country_code = '234';
321 $arr_recipient = explode(',', $recipients);
322 $count = count($arr_recipient);
323 $msg_ids = array();
324 $recipients = '';
325
326 $xml = new SimpleXMLElement('<SMS></SMS>');
327 $auth = $xml->addChild('auth');
328 $auth->addChild('username', $username);
329 $auth->addChild('apikey', $apikey);
330
331 $msg = $xml->addChild('message');
332 $msg->addChild('sender', $sendername);
333 $msg->addChild('messagetext', $messagetext);
334 $msg->addChild('flash', $flash);
335
336 $rcpt = $xml->addChild('recipients');
337 for ($i = 0; $i < $count; $i++) {
338 $generated_id = uniqid('int_', false);
339 $generated_id = substr($generated_id, 0, 30);
340 $mobilenumber = trim($arr_recipient[$i]);
341 if (substr($mobilenumber, 0, 1) == '0') {
342 $mobilenumber = $country_code . substr($mobilenumber, 1);
343 } elseif (substr($mobilenumber, 0, 1) == '+') {
344 $mobilenumber = substr($mobilenumber, 1);
345 }
346 $gsm = $rcpt->addChild('gsm');
347 $gsm->addchild('msidn', $mobilenumber);
348 $gsm->addchild('msgid', $generated_id);
349 }
350 $xmlrequest = $xml->asXML();
351
352 if ($xmlrequest) {
353 $result = doPostRequest($url, $xmlrequest, array('Content-Type: application/xml'));
354 $xmlresponse = new SimpleXMLElement($result);
355 return $xmlresponse->status;
356 }
357 return false;
358 }
359}
360
361if (!function_exists('useHTTPGet')) {
362 function useHTTPGet($url, $username, $apikey, $flash, $sendername, $messagetext, $recipients)
363 {
364 $query_str = http_build_query(array('username' => $username, 'apikey' => $apikey, 'sender' => $sendername, 'messagetext' => $messagetext, 'flash' => $flash, 'recipients' => $recipients));
365 return file_get_contents("{$url}?{$query_str}");
366 }
367}
368
369if (!function_exists('doPostRequest')) {
370 //Function to connect to SMS sending server using HTTP POST
371 function doPostRequest($url, $arr_params, $headers = array('Content-Type: application/x-www-form-urlencoded'))
372 {
373 $response = array();
374 $final_url_data = $arr_params;
375 if (is_array($arr_params)) {
376 $final_url_data = http_build_query($arr_params, '', '&');
377 }
378 $ch = curl_init();
379 curl_setopt($ch, CURLOPT_URL, $url);
380 curl_setopt($ch, CURLOPT_POSTFIELDS, $final_url_data);
381 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
382 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
383 curl_setopt($ch, CURLOPT_POST, 1);
384 curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
385 curl_setopt($ch, CURLOPT_VERBOSE, 1);
386 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
387 $response['body'] = curl_exec($ch);
388 $response['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
389 curl_close($ch);
390 return $response['body'];
391 }
392}
393
394if (!function_exists('podio_get_item')) {
395 function podio_get_item($id, $user_id, $connector = null)
396 {
397 //go save the latest access token in the DB
398 if ($connector) {
399 $connection = \App\Models\Connectors\UserConnector::firstOrNew(array('id' => $connector->id));
400 $connection = json_decode($connection->credentials);
401 $connection->access_token = $connection->token;
402 } else {
403 $connection = \App\Models\Credentials::firstOrNew(['user_id' => $user_id]);
404 }
405 $resp = get_item($connection->access_token, $id);
406 if (!$resp) {
407 try {
408 //get new access_token
409 if ($connector) {
410 $attributes = [
411 'client_id' => config('config.podio.client'),
412 'client_secret' => config('config.podio.secret'),
413 'refresh_token' => $connection->refresh_token
414 ];
415 } else {
416 $attributes = [
417 'client_id' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id'),
418 'client_secret' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_secret'),
419 'refresh_token' => $connection->refresh_token
420 ];
421 }
422 try {
423 Podio::authenticate("refresh_token", $attributes);
424 } catch (\Throwable $e) {
425 \Bugsnag\BugsnagLaravel\Facades\Bugsnag::notifyException($e);
426 if ($attributes['client_id'] == \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id')) {
427 $attributes = [
428 'client_id' => config('config.podio.client'),
429 'client_secret' => config('config.podio.secret'),
430 'refresh_token' => $connection->refresh_token
431 ];
432 } else {
433 $attributes = [
434 'client_id' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id'),
435 'client_secret' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_secret'),
436 'refresh_token' => $connection->refresh_token
437 ];
438 }
439 Podio::authenticate("refresh_token", $attributes);
440 }
441 $oauth = Podio::$oauth;
442 if (!is_null($connector) && isset($connector->id)) {
443 \App\Models\Connectors\UserConnector::where('id', $connection->id)->update(
444 [
445 "credentials" => json_encode(
446 [
447 'token' => $oauth->access_token,
448 'ref_id' => $connection->ref_id,
449 'refresh_token' => $connection->refresh_token
450 ]
451 )
452 ]
453 );
454 } else {
455 \App\Models\Credentials::where('user_id', $user_id)->update(
456 [
457 'access_token' => $oauth->access_token
458 ]
459 );
460 }
461 $resp = get_item($oauth->access_token, $id);
462 } catch (\Throwable $e) {
463 \Bugsnag\BugsnagLaravel\Facades\Bugsnag::notifyException($e);
464 return false;
465 }
466 }
467
468 return $resp;
469 }
470}
471
472if (!function_exists('podio_get_item_filter')) {
473 function podio_get_item_filter($user_id, $app, $view, $conditions, $org_id = false, $connector = null)
474 {
475 if ($connector) {
476 $connection = \App\Models\Connectors\UserConnector::firstOrNew(array('id' => $connector->id));
477 $connection = json_decode($connection->credentials);
478 $connection->access_token = $connection->token;
479 } else {
480 $connection = \App\Models\Credentials::firstOrNew(['user_id' => $user_id]);
481 }
482
483 $resp = get_item_filter($connection->access_token, $app, $view, $conditions);
484 if (!$resp) {
485 //get new access_token
486 try {
487 if ($connector) {
488 $attributes = [
489 'client_id' => config('config.podio.client'),
490 'client_secret' => config('config.podio.secret'),
491 'refresh_token' => $connection->refresh_token
492 ];
493 } else {
494 $attributes = [
495 'client_id' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id'),
496 'client_secret' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_secret'),
497 'refresh_token' => $connection->refresh_token
498 ];
499 }
500 try {
501 Podio::authenticate("refresh_token", $attributes);
502 } catch (\Throwable $e) {
503 if ($attributes['client_id'] == \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id')) {
504 $attributes = [
505 'client_id' => config('config.podio.client'),
506 'client_secret' => config('config.podio.secret'),
507 'refresh_token' => $connection->refresh_token
508 ];
509 } else {
510 $attributes = [
511 'client_id' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_id'),
512 'client_secret' => \Illuminate\Support\Facades\Config::get('syncconfig.podio.client_secret'),
513 'refresh_token' => $connection->refresh_token
514 ];
515 }
516 echo "refreshing Token \n";
517 Podio::authenticate("refresh_token", $attributes);
518 }
519 $oauth = Podio::$oauth;
520
521 if (!is_null($connector) && isset($connector->id)) {
522 \App\Models\Connectors\UserConnector::where('id', $connection->id)->update(
523 [
524 "credentials" => json_encode(
525 [
526 'token' => $oauth->access_token,
527 'ref_id' => $connection->ref_id,
528 'refresh_token' => $connection->refresh_token
529 ]
530 )
531 ]
532 );
533 } else {
534 \App\Models\Credentials::where('user_id', $user_id)->update(
535 [
536 'access_token' => $oauth->access_token
537 ]
538 );
539 }
540
541
542 $resp = get_item_filter($connection->access_token, $app, $view, $conditions);
543 } catch (PodioRateLimitError $e) {
544 if ($org_id) {
545 \App\Models\Organization::where('org_id', $org_id)->update(
546 [
547 'status' => "Rate-limited"
548 ]
549 );
550 }
551 } catch (\Throwable $e) {
552 \Bugsnag\BugsnagLaravel\Facades\Bugsnag::notifyException($e);
553 return false;
554 }
555 }
556
557
558 return $resp;
559 }
560}
561
562if (!function_exists('get_item')) {
563 function get_item($access_token, $id)
564 {
565 $curl = curl_init();
566
567 $header[] = 'Authorization: OAuth2 ' . $access_token;
568
569 // Set some options - we are passing in a useragent too here
570 curl_setopt_array(
571 $curl,
572 [
573 CURLOPT_HTTPHEADER => $header,
574 CURLOPT_RETURNTRANSFER => 1,
575 CURLOPT_URL => 'https://api.podio.com/item/' . $id,
576 CURLOPT_SSL_VERIFYHOST => false,
577 CURLOPT_SSL_VERIFYPEER => false
578 ]
579 );
580 // Send the request & save response to $resp
581 $resp = curl_exec($curl);
582 // Close request to clear up some resources
583 curl_close($curl);
584
585 return $resp;
586 }
587}
588
589if (!function_exists('get_item_filter')) {
590 function get_item_filter($access_token, $app, $view, $conditions)
591 {
592 $items = [];
593 $payload = json_encode($conditions);
594
595 $header[] = 'Authorization: OAuth2 ' . $access_token;
596 $header[] = 'Content-Type: application/json';
597 $header[] = 'Content-Length: ' . strlen($payload);
598
599
600 // Set some options - we are passing in a useragent too here
601
602
603 $ch = curl_init('https://api.podio.com/item/app/' . $app . '/filter/' . $view);
604 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
605 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
606 curl_setopt($ch, CURLINFO_HEADER_OUT, true);
607 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
608 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
609 curl_setopt($ch, CURLOPT_POST, true);
610 curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
611
612 // Send the request & save response to $resp
613 $resp = curl_exec($ch);
614 // Close request to clear up some resources
615 curl_close($ch);
616 $resp = json_decode($resp);
617
618 if ($resp && isset($resp->items)) {
619 foreach ($resp->items as $item) {
620 $items[] = (array)$item;
621 }
622 $data = [
623 'items' => $items,
624 'total' => $resp->total
625 ];
626 return $data;
627 } else {
628 return false;
629 }
630 }
631}
632
633if (!function_exists('getMongoCollection')) {
634 function getMongoCollection($database, $collectionName)
635 {
636 $mongo = new \App\Services\MongoDatabaseManager();
637 $client = $mongo->getClient();
638 $collection = $client->selectCollection($database, $collectionName);
639 return $collection;
640 }
641}
642
643if (!function_exists('getCount')) {
644 function getCount($database, $collection, $condition = [])
645 {
646 $mongo = new \App\Services\MongoDatabaseManager();
647 $client = $mongo->getClient();
648
649 $collection = $client->selectCollection($database, $collection);
650
651 return $collection->count($condition);
652 }
653}
654
655
656if (!function_exists('getData')) {
657 function getData($database, $collection, $condition = [], $condition2 = [])
658 {
659 $mongo = new \App\Services\MongoDatabaseManager();
660 $client = $mongo->getClient();
661
662 $collection = $client->selectCollection($database, $collection);
663
664
665 $data = $collection->find($condition, $condition2);
666
667 $result = [];
668 foreach ($data as $key => $d) {
669 $result[] = json_decode(\GuzzleHttp\json_encode($d));
670 }
671 return $result;
672 }
673}
674
675if (!function_exists('getDataURL')) {
676 function getDataURL($database, $collection, $limit = 1000, $skip = 0)
677 {
678 $cURLConnection = curl_init();
679
680 curl_setopt($cURLConnection, CURLOPT_URL, 'https://workflow.thatapp.io/raw/data/' . $database . '/' . $collection . "?limit=" . $limit . "&skip=" . $skip);
681 curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
682
683 $list = curl_exec($cURLConnection);
684 curl_close($cURLConnection);
685
686 $jsonArrayResponse = json_decode($list);
687
688 return $jsonArrayResponse->items;
689 }
690}
691
692if (!function_exists('getAuthorizationNotification')) {
693 function getAuthorizationNotification($email)
694 {
695 return [
696 'email' => $email,
697 'subject' => 'Podio authorization needed',
698 'title' => 'Podio authorization is needed to proceed with your data backup',
699 'content' => 'We hope you are doing well, please take a minute of your time to run a quick validation from podio',
700 'content_footer' => 'Your podio account needs to be validated in other for us to backup your data'
701 ];
702 }
703}
704