Proyectos de Subversion LeadersLinked - Services

Rev

Rev 179 | Rev 334 | 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);
283 www 230
 
1 efrain 231
        $latitude   = isset($response['results'][0]['geometry']['location']['lat']) ? $response['results'][0]['geometry']['location']['lat'] : 0;
232
        $longitude  = isset($response['results'][0]['geometry']['location']['lng']) ? $response['results'][0]['geometry']['location']['lng'] : 0;
283 www 233
 
1 efrain 234
        return ['latitude' => $latitude, 'longitude' => $longitude];
235
    }
236
 
237
    /**
238
     *
239
     * @return string[]
240
     */
241
    public static function getAllTimeZones()
242
    {
243
        $timezones =  [];
244
        $zones = \DateTimeZone::listIdentifiers();
245
 
246
        foreach($zones as $zone)
247
        {
248
            array_push($timezones, $zone);
249
 
250
        }
251
 
252
        return $timezones;
253
    }
254
 
255
    /**
256
     *
257
     * @param string $from_date
258
     * @param string $from_timezone
259
     * @param string $to_timezone
260
     * @return string
261
     */
262
    public static function convertDateBetweenTimeZones($from_date, $from_timezone, $to_timezone)
263
    {
264
        $date = new \DateTime($from_date, new \DateTimeZone($from_timezone));
265
        $date->setTimezone(new \DateTimeZone($to_timezone));
266
        return $date->format('Y-m-d H:i:s');
267
    }
268
 
269
 
270
    /**
271
     *
272
     * @param string $from_datetime
273
     * @param string $from_timezone
274
     * @param string $to_timezone
275
     * @return string
276
     */
277
    public static function convertDateTimeBetweenTimeZones($from_datetime, $from_timezone, $to_timezone)
278
    {
279
        $date = new \DateTime($from_datetime, new \DateTimeZone($from_timezone));
280
        $date->setTimezone(new \DateTimeZone($to_timezone));
281
        return $date->format('Y-m-d H:i:s');
282
    }
283
 
284
 
285
    /*
286
    public static function timeElapsedString(int $ptime)
287
    {
288
        $etime = time() - $ptime;
289
        if ($etime < 1) {
290
            return 'LABEL_ZERO_SECOND';
291
        }
292
        $a = array(365 * 24 * 60 * 60 => 'LABEL_YEAR_SMALL',
293
            30 * 24 * 60 * 60 => 'LABEL_MONTH_SMALL',
294
            24 * 60 * 60 => 'LABEL_DAY_SMALL',
295
            60 * 60 => 'LABEL_HOUR_SMALL',
296
            60 => 'LABEL_MINUTE_SMALL',
297
            1 => 'LABEL_SECOND_SMALL'
298
        );
299
        $a_plural = array('LABEL_YEAR_SMALL' => 'LABEL_YEARS_SMALL',
300
            'LABEL_MONTH_SMALL' => 'LABEL_MONTHS_SMALL',
301
            'LABEL_DAY_SMALL' => 'LABEL_DAYS_SMALL',
302
            'LABEL_HOUR_SMALL' => 'LABEL_HOURS_SMALL',
303
            'LABEL_MINUTE_SMALL' => 'LABEL_MINUTES_SMALL',
304
            'LABEL_SECOND_SMALL' => 'LABEL_SECONDS_SMALL'
305
        );
306
 
307
        foreach ($a as $secs => $str) {
308
            $d = $etime / $secs;
309
            if ($d >= 1) {
310
                $r = round($d);
311
                return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str);
312
            }
313
        }
314
    }*/
315
 
316
 
317
    /**
318
     *
319
     * @param string $date1
320
     * @param string $date2
321
     * @param string $format
322
     */
323
    public static function getYears(string $date1, string $date2, string $format = 'YearMonth')
324
    {
325
        $date1 = new \DateTime($date1);
326
        $date2 = new \DateTime($date2);
327
        $interval = date_diff($date1, $date2);
328
        $months = $interval->m + ($interval->y * 12);
329
        return(int) ($months / 12);
330
    }
331
 
332
    /**
333
     *
334
     * @param number $length
335
     * @param string $seeds
336
     * @return string
337
     */
338
    public static function genrateRandom($length = 8, $seeds = 'alphanum')
339
    {
340
        $seedings = [
341
            'alpha' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
342
            'numeric' => '0123456789',
343
            'alphanum' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
344
            'hexidec' => '0123456789abcdef',
345
        ];
346
 
347
        if (isset($seedings[$seeds])) {
348
            $seeds = $seedings[$seeds];
349
        }
350
        list($usec, $sec) = explode(' ', microtime());
351
        $seed = (float) $sec + ((float) $usec * 100000);
352
 
353
 
354
 
355
        mt_srand(intval($seed));
356
        $str = '';
357
        $seeds_count = strlen($seeds);
358
        for ($i = 0; $length > $i; $i++) {
359
            $pos = mt_rand(0, $seeds_count - 1);
360
 
361
            $str .= substr($seeds, $pos, $pos + 1);
362
        }
363
        return $str;
364
    }
365
 
366
    /**
367
     *
368
     * @param string $date1
369
     * @param string $date2
370
     * @param string $timeFormat
371
     * @param bool $positive
372
     * @return number
373
     */
374
    public static function getDateDiff(string $date1, string $date2, string $timeFormat = 'sec', bool $positive = false)
375
    {
376
 
377
 
378
 
379
        $dtTime1 = strtotime($date1);
380
        $dtTime2 = strtotime($date2);
381
 
382
 
383
        if ($positive === true) {
384
            if ($dtTime2 < $dtTime1) {
385
                $tmp = $dtTime1;
386
                $dtTime1 = $dtTime2;
387
                $dtTime2 = $tmp;
388
            }
389
        }
390
        $diff = $dtTime2 - $dtTime1;
391
 
392
        /*
393
        echo 'date1 = ' . $date1 . '<br>';
394
        echo 'date2 = ' . $date2 . '<br>';
395
        echo 'dtTime1 = ' . $dtTime1 . '<br>';
396
        echo 'dtTime2 = ' . $dtTime2 . '<br>';
397
        echo 'diff = '.  $diff . '<br>';
398
        exit;
399
        */
400
 
401
        if ($timeFormat == 'sec') {
402
            return $diff;
403
        } else if ($timeFormat == 'day') {
404
            return $diff / 86400;
405
        }
406
    }
407
 
408
 
409
    /**
410
     *
411
     * @param string $date1
412
     * @param string $date2
413
     * @param string $format
414
     * @return string
415
     */
416
    public static function getDifference(string $date1, string $date2, string $format = 'YearMonth')
417
    {
418
        $difference = '';
419
        $datetime1 = date_create($date1);
420
        $datetime2 = date_create($date2);
421
        $interval = date_diff($datetime1, $datetime2);
422
        $years = $interval->format('%y');
423
        $months = $interval->format('%m');
424
        $days = $interval->format('%d');
425
        $years_text = $months_text = $days_text = '';
426
        if ($years == 1) {
427
            $years_text = '1 LABEL_YEAR';
428
        } else if ($years > 1) {
429
            $years_text = $years . ' LABEL_YEARS';
430
        }
431
        if ($months == 1) {
432
            $months_text = '1 LABEL_MONTH';
433
        } else if ($months > 1) {
434
            $months_text = $months . ' LABEL_MONTHS';
435
        }
436
        if ($days == 1) {
437
            $days_text = '1 LABEL_DAY';
438
        } else if ($days > 1) {
439
            $days_text = $days . ' LABEL_DAYS';
440
        }
441
        if ($format == 'Year') {
442
            return trim($years_text);
443
        } else if ($format == 'YearMonth') {
444
            $difference = trim($years_text) . ' ' . trim($months_text);
445
            return trim($difference);
446
        } else if ($format == 'YearMonthDay') {
447
            $difference = trim($years_text) . ' ' . trim($months_text) . ' ' . trim($days_text);
448
            return trim($difference);
449
        }
450
    }
451
 
452
    /**
453
     *
454
     * @param string $source
455
     * @param string $destination
456
     * @param int $quality
457
     * @return string
458
     */
459
    public static function compress(string $source, string $destination, int $quality = null)
460
    {
461
        $info = getimagesize($source);
462
        if ($info['mime'] == 'image/jpeg') {
463
            $image = imagecreatefromjpeg($source);
464
        }
465
        elseif ($info['mime'] == 'image/gif') {
466
            $image = imagecreatefromgif($source);
467
        }
468
        elseif ($info['mime'] == 'image/png') {
469
            $image = imagecreatefrompng($source);
470
        }
471
 
472
        imagejpeg($image, $destination, $quality);
473
        return $destination;
474
    }
475
 
476
    /**
477
     *
478
     * @param string $filename
479
     * @param string $newfilename
480
     * @param int $max_width
481
     * @param int $max_height
482
     * @param bool $withSampling
483
     * @param array $crop_coords
484
     * @return boolean
485
     */
486
    public static function resizeImage(string $filename, string $newfilename = "", int $max_width  = 0, int $max_height = 0, bool $withSampling = true, $crop_coords = array())
487
    {
488
        if (empty($newfilename)) {
489
            $newfilename = $filename;
490
        }
491
        $fileExtension = strtolower(self::getExt($filename));
492
        if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {
493
            $img = imagecreatefromjpeg($filename);
494
        } else if ($fileExtension == 'png') {
495
            $img = imagecreatefrompng($filename);
496
        } else if ($fileExtension == 'gif') {
497
            $img = imagecreatefromgif($filename);
498
        } else {
499
            $img = imagecreatefromjpeg($filename);
500
        }
501
        $width = imageSX($img);
502
        $height = imageSY($img);
503
        $target_width = $max_width;
504
        $target_height = $max_height;
505
        $target_ratio = $target_width / $target_height;
506
        $img_ratio = $width / $height;
507
        if (empty($crop_coords)) {
508
            if ($target_ratio > $img_ratio) {
509
                $new_height = $target_height;
510
                $new_width = $img_ratio * $target_height;
511
            } else {
512
                $new_height = $target_width / $img_ratio;
513
                $new_width = $target_width;
514
            }
515
            if ($new_height > $target_height) {
516
                $new_height = $target_height;
517
            }
518
            if ($new_width > $target_width) {
519
                $new_height = $target_width;
520
            }
521
            $new_img = imagecreatetruecolor($target_width, $target_height);
522
            $white = imagecolorallocate($new_img, 255, 255, 255);
523
            imagecolortransparent($new_img);
524
            imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);
525
            imagecopyresampled($new_img, $img, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);
526
        } else {
527
            $new_img = imagecreatetruecolor($target_width, $target_height);
528
            $white = imagecolorallocate($new_img, 255, 255, 255);
529
            imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);
530
            imagecopyresampled($new_img, $img, 0, 0, $crop_coords['x1'], $crop_coords['y1'], $target_width, $target_height, $crop_coords['x2'], $crop_coords['y2']);
531
        }
532
        if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {
533
            $createImageSave = imagejpeg($new_img, $newfilename);
534
        } else if ($fileExtension == 'png') {
535
            $createImageSave = imagepng($new_img, $newfilename);
536
        } else if ($fileExtension == 'gif') {
537
            $createImageSave = imagegif($new_img, $newfilename);
538
        } else {
539
            $createImageSave = imagejpeg($new_img, $newfilename);
540
        }
541
 
542
        return $createImageSave;
543
    }
544
 
545
    /**
546
     *
547
     * @param string $start
548
     * @param string $end
549
     * @return array
550
     */
551
    public static function getTimeDifference(string $start, string $end) {
552
        $uts = [
553
            'start' => strtotime($start),
554
            'end' => strtotime($end)
555
        ];
556
        if ($uts['start'] !== -1 && $uts['end'] !== -1) {
557
            if ($uts['end'] >= $uts['start']) {
558
                $diff = $uts['end'] - $uts['start'];
559
                if ($days = intval((floor($diff / 86400)))) {
560
                    $diff = $diff % 86400;
561
                }
562
                if ($hours = intval((floor($diff / 3600)))) {
563
                    $diff = $diff % 3600;
564
                }
565
                if ($minutes = intval((floor($diff / 60)))) {
566
                    $diff = $diff % 60;
567
                }
568
                $diff = intval($diff);
569
                return [
570
                    'days' => $days,
571
                    'hours' => $hours,
572
                    'minutes' => $minutes,
573
                    'seconds' => $diff
574
                ];
575
            } else {
576
                trigger_error("Ending date/time is earlier than the start date/time", E_USER_WARNING);
577
            }
578
        } else {
579
            trigger_error("Invalid date/time data detected", E_USER_WARNING);
580
        }
581
        return;
582
    }
583
 
584
    /**
585
     *
586
     * @param number $length
587
     * @return string
588
     */
589
    public static function generatePassword($length = 8)
590
    {
591
        $password = '';
592
        $possible = '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ';
593
        $maxlength = strlen($possible);
594
        if ($length > $maxlength) {
595
            $length = $maxlength;
596
        }
597
        $i = 0;
598
        while ($i < $length) {
599
            $char = substr($possible, mt_rand(0, $maxlength - 1), 1);
600
            if (!strstr($password, $char)) {
601
                $password .= $char;
602
                $i++;
603
            }
604
        }
605
        return $password;
606
    }
607
 
608
 
609
 
610
    /**
611
     *
612
     * @param string $date
613
     * @param boolean $time_required
614
     * @return string
615
     */
616
    public static function countRemainingDays(string $date, $time_required = true)
617
    {
618
        $datestr = $date;
619
        $date = strtotime($datestr);
620
        $diff = $date - time();
621
        if ($time_required) {
622
            $days = floor($diff / (60 * 60 * 24));
623
            $hours = round(($diff - $days * 60 * 60 * 24) / (60 * 60));
624
            return "$days days $hours hours remaining";
625
        } else {
626
            $days = ceil($diff / (60 * 60 * 24));
627
            return "$days days remaining";
628
        }
629
    }
630
 
631
    /**
632
     *
633
     * @param string $varPhoto
634
     * @param string $uploadDir
635
     * @param string $tmp_name
636
     * @param array $th_arr
637
     * @param string $file_nm
638
     * @param boolean $addExt
639
     * @param array $crop_coords
640
     * @return string|boolean
641
     */
642
    public static function generateThumbnail(string $varPhoto, string $uploadDir, string $tmp_name, $th_arr = array(), $file_nm = '', $addExt = true, $crop_coords = array())
643
    {
644
        $ext = '.' . strtolower(self::getExt($varPhoto));
645
        $tot_th = count($th_arr);
646
        if (($ext == ".jpg" || $ext == ".gif" || $ext == ".png" || $ext == ".bmp" || $ext == ".jpeg" || $ext == ".ico")) {
647
            if (!file_exists($uploadDir)) {
648
                mkdir($uploadDir, 0777);
649
            }
650
            if ($file_nm == '')
651
                $imagename = rand() . time();
652
                else
653
                    $imagename = $file_nm;
654
                    if ($addExt || $file_nm == '')
655
                        $imagename = $imagename . $ext;
656
                        $pathToImages = $uploadDir . $imagename;
657
                        $Photo_Source = copy($tmp_name, $pathToImages);
658
                        if ($Photo_Source) {
659
                            for ($i = 0; $i < $tot_th; $i++) {
660
                                Functions::resizeImage($uploadDir . $imagename, $uploadDir . 'th' . ($i + 1) . '_' . $imagename, $th_arr[$i]['width'], $th_arr[$i]['height'], false, $crop_coords);
661
                            }
662
                            return $imagename;
663
                        } else {
664
                            return false;
665
                        }
666
        } else {
667
            return false;
668
        }
669
    }
670
    /**
671
     *
672
     * @param string $file
673
     * @return mixed
674
     */
675
    public static function getExt(string $file)
676
    {
677
        $path_parts = pathinfo($file);
678
        $ext = $path_parts['extension'];
679
        return $ext;
680
    }
681
 
682
 
683
    /**
684
     *
685
     * @param string $source
686
     * @param string $target_path
687
     * @param string $target_filename
688
     * @param number $target_width
689
     * @param number $target_height
690
     * @return boolean
691
     */
692
    public  static function uploadImage($source, $target_path, $target_filename, $target_width, $target_height )
693
    {
694
        try {
695
            $data = file_get_contents($source);
696
            $img = imagecreatefromstring($data);
697
 
698
            if(!file_exists($target_path)) {
179 efrain 699
                mkdir($target_path, 0755, true);
1 efrain 700
            }
701
 
702
            if($img) {
703
                list($source_width, $source_height) = getimagesize($source);
704
 
705
                $width_ratio    = $target_width / $source_width;
706
                $height_ratio   = $target_height / $source_height;
707
                if($width_ratio > $height_ratio) {
708
                    $resized_width = $target_width;
709
                    $resized_height = $source_height * $width_ratio;
710
                } else {
711
                    $resized_height = $target_height;
712
                    $resized_width = $source_width * $height_ratio;
713
                }
714
 
715
                $resized_width = round($resized_width);
716
                $resized_height = round($resized_height);
717
 
718
                $offset_width = round(($target_width - $resized_width) / 2);
719
                $offset_height = round(($target_height - $resized_height) / 2);
720
 
721
 
722
                $new_image = imageCreateTrueColor($target_width, $target_height);
723
                imageAlphaBlending($new_image, False);
724
                imageSaveAlpha($new_image, True);
725
                $transparent = imageColorAllocateAlpha($new_image, 0, 0, 0, 127);
726
                imagefill($new_image, 0, 0, $transparent);
727
                imageCopyResampled($new_image, $img , $offset_width, $offset_height, 0, 0, $resized_width, $resized_height, $source_width, $source_height);
728
 
729
 
730
                $target = $target_path . DIRECTORY_SEPARATOR . $target_filename;
731
                if(file_exists($target)) {
732
                    @unlink($target);
733
                }
734
 
735
 
736
                imagepng($new_image, $target);
737
            }
738
 
739
            unlink($source);
740
 
741
            return true;
742
 
743
        }
744
        catch (\Throwable $e)
745
        {
746
            error_log($e->getTraceAsString());
747
            return false;
748
        }
749
    }
750
 
751
 
752
    /**
753
     *
754
     * @param string $source
755
     * @param string $target_path
756
     * @param string $target_filename
757
     * @return boolean
758
     */
759
    public  static function uploadFile($source, $target_path, $target_filename)
760
    {
761
        try {
762
 
763
            $target_filename = self::normalizeString(basename($target_filename));
764
 
765
            $parts = explode('.', $target_filename);
766
            $basename = trim($parts[0]);
767
            if(strlen($basename) > 220) {
768
                $basename = substr($basename, 0, 220);
769
            }
770
            $basename = $basename . '-' . uniqid() . '.' . $parts[1];
771
            $full_filename = $target_path  . DIRECTORY_SEPARATOR . $basename;
772
 
773
 
774
            return move_uploaded_file($source, $full_filename);
775
 
776
        }
777
        catch (\Throwable $e)
778
        {
779
            error_log($e->getTraceAsString());
780
            return false;
781
        }
782
    }
783
 
784
    /**
785
     *
786
     * @param string $path
787
     * @param string $prefix
788
     * @return boolean
789
     */
790
    public static function delete($path, $prefix)
791
    {
792
        try {
793
            if (is_dir($path)){
794
                if ($dh = opendir($path)) {
795
                    while (($file = readdir($dh)) !== false)
796
                    {
797
                        if($file == '.' || $file == '..') {
798
                            continue;
799
                        }
800
 
801
                        if(strpos($file, $prefix) !== false) {
802
                            unlink($path . DIRECTORY_SEPARATOR . $file);
803
                        }
804
                    }
805
                    closedir($dh);
806
                }
807
            }
808
 
809
            return true;
810
 
811
        }
812
        catch (\Throwable $e)
813
        {
814
            error_log($e->getTraceAsString());
815
            return false;
816
        }
817
    }
818
 
819
 
820
    /**
821
     *
822
     * @param string $str
823
     * @return string
824
     */
825
    public static function normalizeString ($str = '')
826
    {
827
        $str = strtolower($str);
828
        $str = trim($str);
829
        $str = strip_tags($str);
830
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
831
        $str = preg_replace('/[\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
832
        $str = strtolower($str);
833
        $str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
834
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
835
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
836
        $str = str_replace(' ', '-', $str);
837
        $str = rawurlencode($str);
838
        $str = str_replace('%', '-', $str);
839
        $str = str_replace(['-----','----','---', '--'], '-', $str);
840
 
841
 
842
        return trim(strtolower($str));
843
    }
844
 
845
 
846
 
847
 
848
    /**
849
     *
850
     * @return string
851
     */
852
    public static function genUUID()
853
    {
854
 
855
        $data = random_bytes(16);
856
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
857
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
858
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
859
    }
860
 
861
 
862
 
863
 
864
 
865
    /**
866
     *
867
     * @param string $dir
868
     */
869
    public static function rmDirRecursive(string $dir)
870
    {
871
        if (is_dir($dir)) {
872
            $objects = scandir($dir);
873
            foreach ($objects as $object)
874
            {
875
                if ($object != '.' && $object != '..') {
876
                    if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
877
                        self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);
878
                        rrmdir($dir . DIRECTORY_SEPARATOR . $object);
879
                    } else {
880
                        unlink($dir . DIRECTORY_SEPARATOR . $object);
881
                    }
882
                }
883
            }
884
            rmdir($dir);
885
        }
886
    }
887
 
888
    /**
889
     *
890
     * @param string $dir
891
     */
892
    public static function deleteFiles(string $dir)
893
    {
894
        if (is_dir($dir)) {
895
            $objects = scandir($dir);
896
            foreach ($objects as $object)
897
            {
898
                if ($object != '.' && $object != '..') {
899
                    if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
900
                        self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);
901
                        rrmdir($dir . DIRECTORY_SEPARATOR . $object);
902
                    } else {
903
                        unlink($dir . DIRECTORY_SEPARATOR . $object);
904
                    }
905
                }
906
            }
907
        }
908
    }
909
 
910
 
911
 
912
    /**
913
     *
914
     * @param string $address
915
     * @return  array
916
     */
917
    public static function reverseGeocode(string $address)
918
    {
919
        $array = [];
920
        $address = str_replace(" ", "+", $address);
921
        $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
922
        $ch = curl_init();
923
        curl_setopt($ch, CURLOPT_URL, $url);
924
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
925
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
926
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
927
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
928
        $response = curl_exec($ch);
929
        curl_close($ch);
930
        $json = json_decode($response);
283 www 931
 
1 efrain 932
        foreach ($json->results as $result) {
933
            $address1='';
934
            foreach($result->address_components as $addressPart)
935
            {
936
                if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {
937
                    $city = $addressPart->long_name;
938
                }
939
                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)))){
940
                    $state = $addressPart->long_name;
941
                } else if((in_array('postal_code', $addressPart->types))){
942
                    $postal_code = $addressPart->long_name;
943
                } else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {
944
                    $country = $addressPart->long_name;
945
                } else {
946
                    $address1 .= $addressPart->long_name.', ';
947
                }
948
            }
949
            if(($city != '') && ($state != '') && ($country != '')) {
950
                $address = $city.', '.$state.', '.$country;
951
            } else if(($city != '') && ($state != '')) {
952
                $address = $city.', '.$state;
953
            } else if(($state != '') && ($country != '')) {
954
                $address = $state.', '.$country;
955
            } else if($country != '') {
956
                $address = $country;
957
            }
958
 
959
            $address1=trim($address1, ',');
960
            $array['country']=$country;
961
            $array['state']=$state;
962
            $array['city']=$city;
963
            $array['address']=$address1;
964
            $array['postal_code']=$postal_code;
965
        }
966
        $array['status']=$json->status;
967
        $array['lat'] = $json->results[0]->geometry->location->lat;
968
        $array['long'] = $json->results[0]->geometry->location->lng;
969
        return $array;
970
    }
971
 
972
 
973
 
974
    /**
975
     *
976
     * @param number $number
977
     * @param number $significance
978
     * @return number|boolean
979
     */
980
    public static function ceiling($number, $significance = 1)
981
    {
982
        return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number / $significance) * $significance) : 0;
983
    }
984
 
985
 
986
 
987
 
988
 
989
 
990
}