Proyectos de Subversion LeadersLinked - Services

Rev

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

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