Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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