Proyectos de Subversion LeadersLinked - Backend

Rev

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