Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6056 | Rev 6749 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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