Proyectos de Subversion LeadersLinked - Backend

Rev

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