Proyectos de Subversion LeadersLinked - Backend

Rev

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

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