Proyectos de Subversion LeadersLinked - Services

Rev

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