Proyectos de Subversion LeadersLinked - Services

Rev

Rev 334 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Library;
6
 
7
abstract class Functions
8
{
9
    public static function utf8_decode($value)
10
    {
11
        $fromEncoding = mb_detect_encoding($value);
12
        $toEncoding ='ISO-8859-1';
13
 
14
 
15
        if($fromEncoding != $toEncoding) {
16
            $value =mb_convert_encoding($value, $toEncoding );
17
        }
18
 
19
        return $value;
20
    }
21
 
22
    public static function utf8_encode($value)
23
    {
24
        $fromEncoding = mb_detect_encoding($value);
25
        $toEncoding = 'UTF-8';
26
 
27
 
28
        if($fromEncoding != $toEncoding) {
29
            $value =mb_convert_encoding($value, $toEncoding);
30
        }
31
 
32
        return $value;
33
    }
34
 
35
    /**
36
     * @param string $value
37
     * @param array $flags
38
     * @return string
39
     */
40
    public static function sanitizeFilterString($value, array $flags = []): string
41
    {
42
        if(empty($value)) {
43
            return '';
44
        }
45
 
345 www 46
        $value = strval($value);
1 efrain 47
 
345 www 48
 
49
 
1 efrain 50
        $noQuotes = in_array(FILTER_FLAG_NO_ENCODE_QUOTES, $flags);
51
        $options = ($noQuotes ? ENT_NOQUOTES : ENT_QUOTES) | ENT_SUBSTITUTE;
52
        $optionsDecode = ($noQuotes ? ENT_QUOTES : ENT_NOQUOTES) | ENT_SUBSTITUTE;
53
 
54
        // Strip the tags
55
        $value = strip_tags($value);
56
 
57
        $value = htmlspecialchars($value, $options);
58
 
59
        // Fix that HTML entities are converted to entity numbers instead of entity name (e.g. ' -> &#34; and not ' -> &quote;)
60
        // https://stackoverflow.com/questions/64083440/use-php-htmlentities-to-convert-special-characters-to-their-entity-number-rather
61
        $value = str_replace(["&quot;", "&#039;"], ["&#34;", "&#39;"], $value);
62
 
63
        // Decode all entities
64
        $value = html_entity_decode($value, $optionsDecode);
345 www 65
 
1 efrain 66
        return trim($value);
345 www 67
 
1 efrain 68
    }
69
 
345 www 70
    /**
71
     *
72
     * @return string
73
     */
1 efrain 74
    public static function getUserIP()
75
    {
76
        $client  = isset($_SERVER['HTTP_CLIENT_IP'])  ? $_SERVER['HTTP_CLIENT_IP'] : '';
77
        $forward = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
78
        $remote  = $_SERVER['REMOTE_ADDR'];
79
 
345 www 80
        if (filter_var($client, FILTER_VALIDATE_IP)) {
1 efrain 81
            $ip = $client;
345 www 82
        } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
1 efrain 83
            $ip = $forward;
84
        } else {
85
            $ip = $remote;
86
        }
87
 
88
        return $ip;
89
    }
90
 
345 www 91
 
1 efrain 92
    /**
345 www 93
     *
1 efrain 94
     * @param string $what
95
     * @param string $date
96
     * @return string
97
     */
345 www 98
    public static function convertDate($what, $date)
99
    {
1 efrain 100
        if ($what == 'wherecond') {
101
            return date('Y-m-d', strtotime($date));
345 www 102
        } else if ($what == 'display') {
1 efrain 103
            return date('d M, Y h:i A', strtotime($date));
345 www 104
        } else if ($what == 'displayWeb') {
1 efrain 105
            return date('d M Y', strtotime($date));
345 www 106
        } else if ($what == 'onlyDate') {
1 efrain 107
            return date(PHP_DATE_FORMAT, strtotime($date));
345 www 108
        } else if ($what == 'monthYear') {
1 efrain 109
            return date(PHP_DATE_FORMAT_MONTH_YEAR, strtotime($date));
345 www 110
        } else if ($what == 'onlyMonth') {
1 efrain 111
            return date(PHP_DATE_FORMAT_MONTH, strtotime($date));
345 www 112
        } else if ($what == 'gmail') {
1 efrain 113
            return date('D, M d, Y - h:i A', strtotime($date));
345 www 114
        } else if ($what == 'onlyDateForCSV') {
1 efrain 115
            return date('M d,Y', strtotime($date));
345 www 116
        } else {
1 efrain 117
            return date('Y-m-d', strtotime($date));
118
        }
119
    }
120
 
121
    /**
122
     *
345 www 123
     * @return string[]
124
     */
125
    public static function getAllTimeZones()
126
    {
127
        $timezones =  [];
128
        $zones = \DateTimeZone::listIdentifiers();
129
 
130
        foreach ($zones as $zone) {
131
            array_push($timezones, $zone);
132
        }
133
 
134
        return $timezones;
135
    }
136
 
137
    /**
138
     *
1 efrain 139
     * @param string $timestamp
140
     * @param string $now
141
     * @return string
142
     */
143
    public static function timeAgo($timestamp, $now = '')
144
    {
145
 
345 www 146
        if ($now) {
1 efrain 147
            $datetime1 = \DateTime::createFromFormat('Y-m-d H:i:s', $now);
148
        } else {
149
            $now = date('Y-m-d H:i:s');
150
            $datetime1 = date_create($now);
151
        }
152
        $datetime2 = date_create($timestamp);
153
 
154
        $diff = date_diff($datetime1, $datetime2);
155
        $timemsg = '';
156
        if ($diff->y > 0) {
157
            $timemsg = $diff->y . ' año' . ($diff->y > 1 ? "s" : '');
158
        } else if ($diff->m > 0) {
159
            $timemsg = $diff->m . ' mes' . ($diff->m > 1 ? "es" : '');
160
        } else if ($diff->d > 0) {
161
            $timemsg = $diff->d . ' dia' . ($diff->d > 1 ? "s" : '');
162
        } else if ($diff->h > 0) {
163
            $timemsg = $diff->h . ' hora' . ($diff->h > 1 ? "s" : '');
164
        } else if ($diff->i > 0) {
165
            $timemsg = $diff->i . ' minuto' . ($diff->i > 1 ? "s" : '');
166
        } else if ($diff->s > 0) {
167
            $timemsg = $diff->s . ' segundo' . ($diff->s > 1 ? "s" : '');
168
        }
169
        if (!$timemsg) {
170
            $timemsg = "Ahora";
171
        } else {
172
            $timemsg = $timemsg . '';
173
        }
174
        return $timemsg;
175
    }
176
 
345 www 177
    /*
178
     public static function timeElapsedString(int $ptime, $now = null)
179
     {
180
     if($now)  {
181
     $etime = $now - $ptime;
182
 
183
     } else {
184
     $etime = time() - $ptime;
185
     }
186
 
187
 
188
     if ($etime < 1) {
189
     return 'LABEL_ZERO_SECOND';
190
     }
191
     $a = array(365 * 24 * 60 * 60 => 'LABEL_YEAR_SMALL',
192
     30 * 24 * 60 * 60 => 'LABEL_MONTH_SMALL',
193
     24 * 60 * 60 => 'LABEL_DAY_SMALL',
194
     60 * 60 => 'LABEL_HOUR_SMALL',
195
     60 => 'LABEL_MINUTE_SMALL',
196
     1 => 'LABEL_SECOND_SMALL'
197
     );
198
     $a_plural = array('LABEL_YEAR_SMALL' => 'LABEL_YEARS_SMALL',
199
     'LABEL_MONTH_SMALL' => 'LABEL_MONTHS_SMALL',
200
     'LABEL_DAY_SMALL' => 'LABEL_DAYS_SMALL',
201
     'LABEL_HOUR_SMALL' => 'LABEL_HOURS_SMALL',
202
     'LABEL_MINUTE_SMALL' => 'LABEL_MINUTES_SMALL',
203
     'LABEL_SECOND_SMALL' => 'LABEL_SECONDS_SMALL'
204
     );
205
 
206
     foreach ($a as $secs => $str) {
207
     $d = $etime / $secs;
208
     if ($d >= 1) {
209
     $r = round($d);
210
     return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str);
211
     }
212
     }
213
     }*/
1 efrain 214
 
215
 
216
    /**
217
     *
218
     * @param string $date1
219
     * @param string $date2
220
     * @param string $format
221
     */
345 www 222
    public static function getYears(string $date1, string $date2, string $format = 'YearMonth')
1 efrain 223
    {
224
        $date1 = new \DateTime($date1);
225
        $date2 = new \DateTime($date2);
226
        $interval = date_diff($date1, $date2);
227
        $months = $interval->m + ($interval->y * 12);
345 www 228
        return (int) ($months / 12);
1 efrain 229
    }
230
 
231
    /**
345 www 232
     *
1 efrain 233
     * @param number $length
234
     * @param string $seeds
235
     * @return string
236
     */
345 www 237
    public static function genrateRandom($length = 8, $seeds = 'alphanum')
1 efrain 238
    {
239
        $seedings = [
240
            'alpha' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
241
            'numeric' => '0123456789',
242
            'alphanum' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
243
            'hexidec' => '0123456789abcdef',
244
        ];
345 www 245
 
1 efrain 246
        if (isset($seedings[$seeds])) {
247
            $seeds = $seedings[$seeds];
248
        }
249
        list($usec, $sec) = explode(' ', microtime());
250
        $seed = (float) $sec + ((float) $usec * 100000);
345 www 251
        mt_srand($seed);
1 efrain 252
        $str = '';
253
        $seeds_count = strlen($seeds);
254
        for ($i = 0; $length > $i; $i++) {
255
            $pos = mt_rand(0, $seeds_count - 1);
256
 
257
            $str .= substr($seeds, $pos, $pos + 1);
258
        }
259
        return $str;
260
    }
261
 
262
    /**
345 www 263
     *
1 efrain 264
     * @param string $date1
265
     * @param string $date2
266
     * @param string $timeFormat
267
     * @param bool $positive
268
     * @return number
269
     */
345 www 270
    public static function getDateDiff(string $date1, string $date2, string $timeFormat = 'sec', bool $positive = false)
1 efrain 271
    {
272
        $dtTime1 = strtotime($date1);
273
        $dtTime2 = strtotime($date2);
274
        if ($positive === true) {
275
            if ($dtTime2 < $dtTime1) {
276
                $tmp = $dtTime1;
277
                $dtTime1 = $dtTime2;
278
                $dtTime2 = $tmp;
279
            }
280
        }
281
        $diff = $dtTime2 - $dtTime1;
282
        if ($timeFormat == 'sec') {
283
            return $diff;
284
        } else if ($timeFormat == 'day') {
285
            return $diff / 86400;
286
        }
287
    }
288
 
289
 
290
    /**
345 www 291
     *
1 efrain 292
     * @param string $date1
293
     * @param string $date2
294
     * @param string $format
295
     * @return string
296
     */
345 www 297
    public static function getDifference(string $date1, string $date2, string $format = 'YearMonth')
1 efrain 298
    {
299
        $difference = '';
300
        $datetime1 = date_create($date1);
301
        $datetime2 = date_create($date2);
302
        $interval = date_diff($datetime1, $datetime2);
303
        $years = $interval->format('%y');
304
        $months = $interval->format('%m');
305
        $days = $interval->format('%d');
306
        $years_text = $months_text = $days_text = '';
307
        if ($years == 1) {
308
            $years_text = '1 LABEL_YEAR';
309
        } else if ($years > 1) {
310
            $years_text = $years . ' LABEL_YEARS';
311
        }
312
        if ($months == 1) {
313
            $months_text = '1 LABEL_MONTH';
314
        } else if ($months > 1) {
315
            $months_text = $months . ' LABEL_MONTHS';
316
        }
317
        if ($days == 1) {
318
            $days_text = '1 LABEL_DAY';
319
        } else if ($days > 1) {
320
            $days_text = $days . ' LABEL_DAYS';
321
        }
322
        if ($format == 'Year') {
323
            return trim($years_text);
324
        } else if ($format == 'YearMonth') {
325
            $difference = trim($years_text) . ' ' . trim($months_text);
326
            return trim($difference);
327
        } else if ($format == 'YearMonthDay') {
328
            $difference = trim($years_text) . ' ' . trim($months_text) . ' ' . trim($days_text);
329
            return trim($difference);
330
        }
331
    }
332
 
333
    /**
345 www 334
     *
1 efrain 335
     * @param string $source
336
     * @param string $destination
337
     * @param int $quality
338
     * @return string
339
     */
345 www 340
    public static function compress(string $source, string $destination, int $quality = null)
1 efrain 341
    {
342
        $info = getimagesize($source);
343
        if ($info['mime'] == 'image/jpeg') {
344
            $image = imagecreatefromjpeg($source);
345 www 345
        } elseif ($info['mime'] == 'image/gif') {
1 efrain 346
            $image = imagecreatefromgif($source);
345 www 347
        } elseif ($info['mime'] == 'image/png') {
1 efrain 348
            $image = imagecreatefrompng($source);
349
        }
345 www 350
 
1 efrain 351
        imagejpeg($image, $destination, $quality);
352
        return $destination;
353
    }
354
 
355
    /**
345 www 356
     *
1 efrain 357
     * @param string $filename
358
     * @param string $newfilename
359
     * @param int $max_width
360
     * @param int $max_height
361
     * @param bool $withSampling
362
     * @param array $crop_coords
363
     * @return boolean
364
     */
345 www 365
    public static function resizeImage(string $filename, string $newfilename = "", int $max_width  = 0, int $max_height = 0, bool $withSampling = true, $crop_coords = array())
1 efrain 366
    {
367
        if (empty($newfilename)) {
368
            $newfilename = $filename;
369
        }
370
        $fileExtension = strtolower(self::getExt($filename));
371
        if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {
372
            $img = imagecreatefromjpeg($filename);
373
        } else if ($fileExtension == 'png') {
374
            $img = imagecreatefrompng($filename);
375
        } else if ($fileExtension == 'gif') {
376
            $img = imagecreatefromgif($filename);
377
        } else {
378
            $img = imagecreatefromjpeg($filename);
379
        }
380
        $width = imageSX($img);
381
        $height = imageSY($img);
382
        $target_width = $max_width;
383
        $target_height = $max_height;
384
        $target_ratio = $target_width / $target_height;
385
        $img_ratio = $width / $height;
386
        if (empty($crop_coords)) {
387
            if ($target_ratio > $img_ratio) {
388
                $new_height = $target_height;
389
                $new_width = $img_ratio * $target_height;
390
            } else {
391
                $new_height = $target_width / $img_ratio;
392
                $new_width = $target_width;
393
            }
394
            if ($new_height > $target_height) {
395
                $new_height = $target_height;
396
            }
397
            if ($new_width > $target_width) {
398
                $new_height = $target_width;
399
            }
400
            $new_img = imagecreatetruecolor($target_width, $target_height);
401
            $white = imagecolorallocate($new_img, 255, 255, 255);
402
            imagecolortransparent($new_img);
403
            imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);
404
            imagecopyresampled($new_img, $img, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);
405
        } else {
406
            $new_img = imagecreatetruecolor($target_width, $target_height);
407
            $white = imagecolorallocate($new_img, 255, 255, 255);
408
            imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);
409
            imagecopyresampled($new_img, $img, 0, 0, $crop_coords['x1'], $crop_coords['y1'], $target_width, $target_height, $crop_coords['x2'], $crop_coords['y2']);
410
        }
411
        if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {
412
            $createImageSave = imagejpeg($new_img, $newfilename);
413
        } else if ($fileExtension == 'png') {
414
            $createImageSave = imagepng($new_img, $newfilename);
415
        } else if ($fileExtension == 'gif') {
416
            $createImageSave = imagegif($new_img, $newfilename);
417
        } else {
418
            $createImageSave = imagejpeg($new_img, $newfilename);
419
        }
420
 
421
        return $createImageSave;
422
    }
423
 
424
    /**
345 www 425
     *
1 efrain 426
     * @param string $start
427
     * @param string $end
428
     * @return array
429
     */
345 www 430
    public static function getTimeDifference(string $start, string $end)
431
    {
1 efrain 432
        $uts = [
433
            'start' => strtotime($start),
434
            'end' => strtotime($end)
345 www 435
        ];
1 efrain 436
        if ($uts['start'] !== -1 && $uts['end'] !== -1) {
437
            if ($uts['end'] >= $uts['start']) {
438
                $diff = $uts['end'] - $uts['start'];
439
                if ($days = intval((floor($diff / 86400)))) {
440
                    $diff = $diff % 86400;
441
                }
442
                if ($hours = intval((floor($diff / 3600)))) {
443
                    $diff = $diff % 3600;
444
                }
445
                if ($minutes = intval((floor($diff / 60)))) {
446
                    $diff = $diff % 60;
447
                }
448
                $diff = intval($diff);
449
                return [
450
                    'days' => $days,
451
                    'hours' => $hours,
452
                    'minutes' => $minutes,
453
                    'seconds' => $diff
454
                ];
455
            } else {
456
                trigger_error("Ending date/time is earlier than the start date/time", E_USER_WARNING);
457
            }
458
        } else {
459
            trigger_error("Invalid date/time data detected", E_USER_WARNING);
460
        }
461
        return;
462
    }
463
 
464
    /**
345 www 465
     *
1 efrain 466
     * @param number $length
467
     * @return string
468
     */
345 www 469
    public static function generatePassword($length = 8)
1 efrain 470
    {
471
        $password = '';
472
        $possible = '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ';
473
        $maxlength = strlen($possible);
474
        if ($length > $maxlength) {
475
            $length = $maxlength;
476
        }
477
        $i = 0;
478
        while ($i < $length) {
479
            $char = substr($possible, mt_rand(0, $maxlength - 1), 1);
480
            if (!strstr($password, $char)) {
481
                $password .= $char;
482
                $i++;
483
            }
484
        }
485
        return $password;
486
    }
487
 
488
 
489
 
490
    /**
345 www 491
     *
1 efrain 492
     * @param string $date
493
     * @param boolean $time_required
494
     * @return string
495
     */
345 www 496
    public static function countRemainingDays(string $date, $time_required = true)
1 efrain 497
    {
498
        $datestr = $date;
499
        $date = strtotime($datestr);
500
        $diff = $date - time();
501
        if ($time_required) {
502
            $days = floor($diff / (60 * 60 * 24));
503
            $hours = round(($diff - $days * 60 * 60 * 24) / (60 * 60));
504
            return "$days days $hours hours remaining";
505
        } else {
506
            $days = ceil($diff / (60 * 60 * 24));
507
            return "$days days remaining";
508
        }
509
    }
510
 
511
    /**
345 www 512
     *
1 efrain 513
     * @param string $varPhoto
514
     * @param string $uploadDir
515
     * @param string $tmp_name
516
     * @param array $th_arr
517
     * @param string $file_nm
518
     * @param boolean $addExt
519
     * @param array $crop_coords
520
     * @return string|boolean
521
     */
345 www 522
    public static function generateThumbnail(string $varPhoto, string $uploadDir, string $tmp_name, $th_arr = array(), $file_nm = '', $addExt = true, $crop_coords = array())
1 efrain 523
    {
524
        $ext = '.' . strtolower(self::getExt($varPhoto));
525
        $tot_th = count($th_arr);
526
        if (($ext == ".jpg" || $ext == ".gif" || $ext == ".png" || $ext == ".bmp" || $ext == ".jpeg" || $ext == ".ico")) {
527
            if (!file_exists($uploadDir)) {
528
                mkdir($uploadDir, 0777);
529
            }
530
            if ($file_nm == '')
531
                $imagename = rand() . time();
532
                else
533
                    $imagename = $file_nm;
534
                    if ($addExt || $file_nm == '')
535
                        $imagename = $imagename . $ext;
536
                        $pathToImages = $uploadDir . $imagename;
537
                        $Photo_Source = copy($tmp_name, $pathToImages);
538
                        if ($Photo_Source) {
539
                            for ($i = 0; $i < $tot_th; $i++) {
540
                                Functions::resizeImage($uploadDir . $imagename, $uploadDir . 'th' . ($i + 1) . '_' . $imagename, $th_arr[$i]['width'], $th_arr[$i]['height'], false, $crop_coords);
541
                            }
542
                            return $imagename;
543
                        } else {
544
                            return false;
545
                        }
546
        } else {
547
            return false;
548
        }
549
    }
345 www 550
 
551
 
552
 
553
 
554
 
555
 
556
 
557
 
558
 
1 efrain 559
    /**
345 www 560
     *
561
     * @param string $dir
562
     */
563
    public static function rmDirRecursive(string $dir)
564
    {
565
        if (is_dir($dir)) {
566
            $objects = scandir($dir);
567
            foreach ($objects as $object) {
568
                if ($object != '.' && $object != '..') {
569
                    if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
570
                        self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);
571
                        rrmdir($dir . DIRECTORY_SEPARATOR . $object);
572
                    } else {
573
                        unlink($dir . DIRECTORY_SEPARATOR . $object);
574
                    }
575
                }
576
            }
577
            rmdir($dir);
578
        }
579
    }
580
 
581
    /**
582
     *
583
     * @param string $dir
584
     */
585
    public static function deleteFiles(string $dir)
586
    {
587
        if (is_dir($dir)) {
588
            $objects = scandir($dir);
589
            foreach ($objects as $object) {
590
                if ($object != '.' && $object != '..') {
591
                    if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
592
                        self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);
593
                        rrmdir($dir . DIRECTORY_SEPARATOR . $object);
594
                    } else {
595
                        unlink($dir . DIRECTORY_SEPARATOR . $object);
596
                    }
597
                }
598
            }
599
        }
600
    }
601
 
602
 
603
 
604
    /**
605
     *
606
     * @param string $address
607
     * @return  array
608
     */
609
    public static function reverseGeocode(string $address)
610
    {
611
        $array = [];
612
        $address = str_replace(" ", "+", $address);
613
        $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
614
        $ch = curl_init();
615
        curl_setopt($ch, CURLOPT_URL, $url);
616
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
617
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
618
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
619
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
620
        $response = curl_exec($ch);
621
        curl_close($ch);
622
        $json = json_decode($response);
623
 
624
        foreach ($json->results as $result) {
625
            $address1 = '';
626
            foreach ($result->address_components as $addressPart) {
627
                if ((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {
628
                    $city = $addressPart->long_name;
629
                } else if ((in_array('administrative_area_level_1', $addressPart->types)  && (in_array('political', $addressPart->types))) || (in_array('administrative_area_level_2', $addressPart->types) && (in_array('political', $addressPart->types)))) {
630
                    $state = $addressPart->long_name;
631
                } else if ((in_array('postal_code', $addressPart->types))) {
632
                    $postal_code = $addressPart->long_name;
633
                } else if ((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {
634
                    $country = $addressPart->long_name;
635
                } else {
636
                    $address1 .= $addressPart->long_name . ', ';
637
                }
638
            }
639
            if (($city != '') && ($state != '') && ($country != '')) {
640
                $address = $city . ', ' . $state . ', ' . $country;
641
            } else if (($city != '') && ($state != '')) {
642
                $address = $city . ', ' . $state;
643
            } else if (($state != '') && ($country != '')) {
644
                $address = $state . ', ' . $country;
645
            } else if ($country != '') {
646
                $address = $country;
647
            }
648
 
649
            $address1 = trim($address1, ',');
650
            $array['country'] = $country;
651
            $array['state'] = $state;
652
            $array['city'] = $city;
653
            $array['address'] = $address1;
654
            $array['postal_code'] = $postal_code;
655
        }
656
        $array['status'] = $json->status;
657
        $array['lat'] = $json->results[0]->geometry->location->lat;
658
        $array['long'] = $json->results[0]->geometry->location->lng;
659
        return $array;
660
    }
661
 
662
 
663
 
664
    /**
665
     *
666
     * @param number $number
667
     * @param number $significance
668
     * @return number|boolean
669
     */
670
    public static function ceiling($number, $significance = 1)
671
    {
672
        return (is_numeric($number) && is_numeric($significance)) ? (ceil($number / $significance) * $significance) : 0;
673
    }
674
 
675
 
676
    /**
677
     *
678
     * @param \Laminas\Http\Response $response
679
     * @param string|array $content
680
     */
681
    public static function sendResponseJson($response, $content)
682
    {
683
        if(is_array($content)) {
684
            $content = json_encode($content);
685
        }
686
 
687
 
688
        $headers = $response->getHeaders();
689
        $headers->clearHeaders();
690
        $headers->addHeaderLine('Content-type', 'application/json; charset=UTF-8');
691
 
692
        Functions::addCrossSiteToResponse($response);
693
 
694
        $response->setStatusCode(200);
695
        $response->setContent($content); //json_encode($data));
696
        $response->send();
697
        exit;
698
 
699
    }
700
 
701
 
702
    /**
1 efrain 703
     *
345 www 704
     * @param \Laminas\Http\Response $response
705
     */
706
    public static function addCrossSiteToResponse($response)
707
    {
708
        $headers = $response->getHeaders();
709
        $headers->addHeaderLine('Access-Control-Allow-Origin', '*');
710
        $headers->addHeaderLine('Access-Control-Allow-Headers', '*');
711
        $headers->addHeaderLine('Access-Control-Allow-Method', 'POST, GET, HEAD, OPTIONS');
712
        $headers->addHeaderLine('Access-Control-Max-Age', '86400');
713
    }
714
 
715
 
716
    public static function geoCodeService($key, $address, $address1, $city, $state, $zip)
717
    {
718
 
719
 
720
 
721
        $data = [];
722
        array_push($data, $address);
723
        array_push($data, $address1);
724
        array_push($data, $city);
725
        array_push($data, $state);
726
        array_push($data, $zip);
727
 
728
        $data = array_filter($data, function($value) { return !empty($value); } );
729
 
730
        $url = 'https://maps.googleapis.com/maps/api/geocode/json?' . http_build_query(['address' => implode(',', $data), 'key' => $key]);
731
 
732
 
733
        echo 'URL : ' . $url . '<br>';
734
 
735
 
736
        $ch = curl_init();
737
        curl_setopt($ch, CURLOPT_URL,$url);
738
        curl_setopt($ch, CURLOPT_POST, false);
739
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
740
        $response  = curl_exec ($ch);
741
        curl_close ($ch);
742
 
743
 
744
        $response = json_decode($response, true);
745
 
746
        $latitude   = isset($response['results'][0]['geometry']['location']['lat']) ? $response['results'][0]['geometry']['location']['lat'] : 0;
747
        $longitude  = isset($response['results'][0]['geometry']['location']['lng']) ? $response['results'][0]['geometry']['location']['lng'] : 0;
748
 
749
        return ['latitude' => $latitude, 'longitude' => $longitude];
750
    }
751
 
752
 
753
    /**
754
     *
755
     * @param string $from_date
756
     * @param string $from_timezone
757
     * @param string $to_timezone
758
     * @return string
759
     */
760
    public static function convertDateBetweenTimeZones($from_date, $from_timezone, $to_timezone)
761
    {
762
        $date = new \DateTime($from_date, new \DateTimeZone($from_timezone));
763
        $date->setTimezone(new \DateTimeZone($to_timezone));
764
        return $date->format('Y-m-d H:i:s');
765
    }
766
 
767
 
768
    /**
769
     *
770
     * @param string $from_datetime
771
     * @param string $from_timezone
772
     * @param string $to_timezone
773
     * @return string
774
     */
775
    public static function convertDateTimeBetweenTimeZones($from_datetime, $from_timezone, $to_timezone)
776
    {
777
        $date = new \DateTime($from_datetime, new \DateTimeZone($from_timezone));
778
        $date->setTimezone(new \DateTimeZone($to_timezone));
779
        return $date->format('Y-m-d H:i:s');
780
    }
781
 
782
 
783
    /*
784
    public static function timeElapsedString(int $ptime)
785
    {
786
        $etime = time() - $ptime;
787
        if ($etime < 1) {
788
            return 'LABEL_ZERO_SECOND';
789
        }
790
        $a = array(365 * 24 * 60 * 60 => 'LABEL_YEAR_SMALL',
791
            30 * 24 * 60 * 60 => 'LABEL_MONTH_SMALL',
792
            24 * 60 * 60 => 'LABEL_DAY_SMALL',
793
            60 * 60 => 'LABEL_HOUR_SMALL',
794
            60 => 'LABEL_MINUTE_SMALL',
795
            1 => 'LABEL_SECOND_SMALL'
796
        );
797
        $a_plural = array('LABEL_YEAR_SMALL' => 'LABEL_YEARS_SMALL',
798
            'LABEL_MONTH_SMALL' => 'LABEL_MONTHS_SMALL',
799
            'LABEL_DAY_SMALL' => 'LABEL_DAYS_SMALL',
800
            'LABEL_HOUR_SMALL' => 'LABEL_HOURS_SMALL',
801
            'LABEL_MINUTE_SMALL' => 'LABEL_MINUTES_SMALL',
802
            'LABEL_SECOND_SMALL' => 'LABEL_SECONDS_SMALL'
803
        );
804
 
805
        foreach ($a as $secs => $str) {
806
            $d = $etime / $secs;
807
            if ($d >= 1) {
808
                $r = round($d);
809
                return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str);
810
            }
811
        }
812
    }*/
813
 
814
 
815
 
816
 
817
 
818
    /**
819
     *
1 efrain 820
     * @param string $file
821
     * @return mixed
822
     */
823
    public static function getExt(string $file)
824
    {
825
        $path_parts = pathinfo($file);
826
        $ext = $path_parts['extension'];
827
        return $ext;
828
    }
829
 
830
 
831
    /**
832
     *
833
     * @param string $source
834
     * @param string $target_path
835
     * @param string $target_filename
836
     * @param number $target_width
837
     * @param number $target_height
838
     * @return boolean
839
     */
840
    public  static function uploadImage($source, $target_path, $target_filename, $target_width, $target_height )
841
    {
842
        try {
843
            $data = file_get_contents($source);
844
            $img = imagecreatefromstring($data);
845
 
846
            if(!file_exists($target_path)) {
179 efrain 847
                mkdir($target_path, 0755, true);
1 efrain 848
            }
849
 
850
            if($img) {
851
                list($source_width, $source_height) = getimagesize($source);
852
 
853
                $width_ratio    = $target_width / $source_width;
854
                $height_ratio   = $target_height / $source_height;
855
                if($width_ratio > $height_ratio) {
856
                    $resized_width = $target_width;
857
                    $resized_height = $source_height * $width_ratio;
858
                } else {
859
                    $resized_height = $target_height;
860
                    $resized_width = $source_width * $height_ratio;
861
                }
862
 
863
                $resized_width = round($resized_width);
864
                $resized_height = round($resized_height);
865
 
866
                $offset_width = round(($target_width - $resized_width) / 2);
867
                $offset_height = round(($target_height - $resized_height) / 2);
868
 
869
 
870
                $new_image = imageCreateTrueColor($target_width, $target_height);
871
                imageAlphaBlending($new_image, False);
872
                imageSaveAlpha($new_image, True);
873
                $transparent = imageColorAllocateAlpha($new_image, 0, 0, 0, 127);
874
                imagefill($new_image, 0, 0, $transparent);
875
                imageCopyResampled($new_image, $img , $offset_width, $offset_height, 0, 0, $resized_width, $resized_height, $source_width, $source_height);
876
 
877
 
878
                $target = $target_path . DIRECTORY_SEPARATOR . $target_filename;
879
                if(file_exists($target)) {
880
                    @unlink($target);
881
                }
882
 
883
 
884
                imagepng($new_image, $target);
885
            }
886
 
887
            unlink($source);
888
 
889
            return true;
890
 
891
        }
892
        catch (\Throwable $e)
893
        {
894
            error_log($e->getTraceAsString());
895
            return false;
896
        }
897
    }
898
 
899
 
900
    /**
901
     *
902
     * @param string $source
903
     * @param string $target_path
904
     * @param string $target_filename
905
     * @return boolean
906
     */
907
    public  static function uploadFile($source, $target_path, $target_filename)
908
    {
909
        try {
910
 
911
            $target_filename = self::normalizeString(basename($target_filename));
912
 
913
            $parts = explode('.', $target_filename);
914
            $basename = trim($parts[0]);
915
            if(strlen($basename) > 220) {
916
                $basename = substr($basename, 0, 220);
917
            }
918
            $basename = $basename . '-' . uniqid() . '.' . $parts[1];
919
            $full_filename = $target_path  . DIRECTORY_SEPARATOR . $basename;
920
 
921
 
922
            return move_uploaded_file($source, $full_filename);
923
 
924
        }
925
        catch (\Throwable $e)
926
        {
927
            error_log($e->getTraceAsString());
928
            return false;
929
        }
930
    }
931
 
932
    /**
933
     *
934
     * @param string $path
935
     * @param string $prefix
936
     * @return boolean
937
     */
938
    public static function delete($path, $prefix)
939
    {
940
        try {
941
            if (is_dir($path)){
942
                if ($dh = opendir($path)) {
943
                    while (($file = readdir($dh)) !== false)
944
                    {
945
                        if($file == '.' || $file == '..') {
946
                            continue;
947
                        }
948
 
949
                        if(strpos($file, $prefix) !== false) {
950
                            unlink($path . DIRECTORY_SEPARATOR . $file);
951
                        }
952
                    }
953
                    closedir($dh);
954
                }
955
            }
956
 
957
            return true;
958
 
959
        }
960
        catch (\Throwable $e)
961
        {
962
            error_log($e->getTraceAsString());
963
            return false;
964
        }
965
    }
966
 
967
 
968
    /**
969
     *
970
     * @param string $str
971
     * @return string
972
     */
334 www 973
    public static function normalizeString($str = '')
1 efrain 974
    {
975
        $str = strtolower($str);
976
        $str = trim($str);
977
        $str = strip_tags($str);
978
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
334 www 979
        $str = preg_replace('/[\#\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
1 efrain 980
        $str = strtolower($str);
334 www 981
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
1 efrain 982
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
983
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
984
        $str = str_replace(' ', '-', $str);
985
        $str = rawurlencode($str);
986
        $str = str_replace('%', '-', $str);
334 www 987
        $str = str_replace(['-----', '----', '---','--'], '-', $str);
988
        return trim(strtolower($str));
989
    }
990
 
991
    public static function normalizeStringFilename($str = '')
992
    {
993
        $basename  = substr($str, 0, strrpos($str, '.'));
994
        $basename  = str_replace('.', '-', $basename);
1 efrain 995
 
334 www 996
        $extension  = substr($str, strrpos($str, '.'));
1 efrain 997
 
334 www 998
        $str = $basename . $extension;
999
 
1000
        $str = strip_tags($str);
1001
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
1002
        $str = preg_replace('/[\#\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
1003
        $str = strtolower($str);
1004
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
1005
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
1006
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
1007
        $str = str_replace(' ', '-', $str);
1008
        $str = rawurlencode($str);
1009
        $str = str_replace('%', '-', $str);
1010
        $str = str_replace(['-----', '----', '---', '--'], '-', $str);
1 efrain 1011
        return trim(strtolower($str));
1012
    }
1013
 
345 www 1014
 
1 efrain 1015
 
345 www 1016
 
1 efrain 1017
    /**
1018
     *
1019
     * @return string
1020
     */
1021
    public static function genUUID()
1022
    {
1023
 
1024
        $data = random_bytes(16);
1025
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
1026
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
1027
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
1028
    }
1029
 
1030
 
1031
 
1032
 
1033
 
345 www 1034
 
1 efrain 1035
 
1036
 
1037
 
345 www 1038
 
283 www 1039
 
1 efrain 1040
 
1041
 
1042
 
1043
 
1044
 
1045
 
1046
}