Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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