Proyectos de Subversion LeadersLinked - Services

Rev

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