Proyectos de Subversion LeadersLinked - Backend

Rev

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