Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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