1: <?php
2:
3: 4: 5: 6:
7:
8: namespace RTdev\RTphp;
9:
10: 11: 12: 13: 14: 15:
16: class RTutil {
17:
18: 19: 20: 21: 22: 23:
24: public static function addr2LatLng($address) {
25:
26: if (is_array($address)) {
27:
28: $address = implode(', ', $address);
29: }
30:
31: if (!empty($address)) {
32:
33: $url = sprintf('http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false', str_replace(' ', '+', (string) $address));
34: $output = json_decode(file_get_contents($url));
35:
36: return array(
37: 'latitude' => $output->results[0]->geometry->location->lat,
38: 'longitude' => $output->results[0]->geometry->location->lng
39: );
40: }
41: return array('latitude' => 0, 'longitude' => 0);
42: }
43:
44: 45: 46: 47: 48: 49: 50:
51: public static function latLng2Addr($lat, $lng) {
52:
53: $nlat = (string) $lat;
54: $nlng = (string) $lng;
55:
56: if (!empty($nlat) && !empty($nlng)) {
57:
58: $url = sprintf('http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&sensor=false', trim($nlat), trim($nlng));
59: $output = json_decode(file_get_contents($url));
60: return ($output->status == 'OK') ? $output->results[1]->formatted_address : '';
61: }
62: return '';
63: }
64:
65: 66: 67: 68: 69: 70:
71: public static function isAlphanumeric($v) {
72:
73: return (is_string($v) && preg_match('/^[a-zA-Z ]*$/', $v));
74: }
75:
76: 77: 78: 79: 80: 81:
82: public static function isEmail($v) {
83:
84: return (is_string($v) && !empty($v) && filter_var($v, FILTER_VALIDATE_EMAIL));
85: }
86:
87: 88: 89: 90: 91: 92: 93:
94: public static function isEndsWith($v1, $v2) {
95:
96: return (!is_string($v1) || !is_string($v2)) ? FALSE : (substr($v1, - strlen($v2)) === $v2);
97: }
98:
99: 100: 101: 102: 103: 104:
105: public static function isGeoStr($v) {
106:
107: return (is_string($v) && preg_match('/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/', $v));
108: }
109:
110: 111: 112: 113: 114: 115:
116: public static function isHttps($trust_proxy_headers = FALSE) {
117:
118:
119: if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
120:
121: return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
122: }
123:
124: return (boolean) $trust_proxy_headers && isset($_SERVER['X-FORWARDED-PROTO']) && $_SERVER['X-FORWARDED-PROTO'] == 'https';
125: }
126:
127: 128: 129: 130: 131: 132: 133:
134: public static function isStartsWith($v1, $v2) {
135:
136: return (!is_string($v1) || !is_string($v2)) ? FALSE : (strpos($v1, $v2) === 0);
137: }
138:
139: 140: 141: 142: 143: 144: 145: 146:
147: public static function isStrContains($v1, $v2, $ignoreCase = TRUE) {
148:
149: return (!is_string($v1) || !is_string($v2)) ? FALSE : ((boolean) $ignoreCase ? stripos($v1, $v2) !== FALSE : strpos($v1, $v2) !== FALSE);
150: }
151:
152: 153: 154: 155: 156: 157:
158: public static function isUrl($v) {
159:
160: return (is_string($v) && preg_match('/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i', $v));
161: }
162:
163: 164: 165: 166: 167: 168: 169:
170: public static function csv2Arr($fullFpath) {
171:
172: return ($r = file_get_contents($fullFpath)) ? array_map('str_getcsv', preg_split('/\r*\n+|\r+/', $r)) : array();
173: }
174:
175: 176: 177: 178: 179: 180: 181: 182:
183: public static function force1Spc($v) {
184:
185: if (is_array($v)) {
186:
187: foreach ($v as $key => $element) {
188:
189: $v[$key] = self::force1Spc($element);
190: }
191: return $v;
192: }
193: else {
194: return preg_replace('/\s+/', ' ', (string) $v);
195: }
196: }
197:
198: 199: 200: 201: 202: 203:
204: public static function hex2Str($hex) {
205:
206: if (is_string($hex) && ctype_xdigit($hex)) {
207:
208: $str = '';
209: $max = strlen($hex) - 1;
210:
211: for ($i = 0; $i < $max;) {
212:
213: $str .= chr(hexdec($hex[$i] . $hex[$i + 1]));
214: $i += 2;
215: }
216: return $str;
217: }
218: return $hex;
219: }
220:
221: 222: 223: 224: 225: 226: 227:
228: public static function multiStr2Hex($str, $multiply = 0) {
229:
230: $nstr = (string) $str;
231: $max = (int) $multiply;
232:
233: for ($i = 0; ++$i <= $max;) {
234:
235: $nstr = self::str2Hex($nstr);
236: }
237: return $nstr;
238: }
239:
240: 241: 242: 243: 244: 245:
246: public static function ordinal($num) {
247:
248: $nnum = (int) $num;
249: $ends = array('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th');
250: return ((($nnum % 100) >= 11) && (($nnum % 100) <= 13)) ? $nnum . 'th' : (($nnum) ? $nnum . $ends[$nnum % 10] : $nnum);
251: }
252:
253: 254: 255: 256: 257: 258: 259:
260: public static function str2Bool($str, $default = FALSE) {
261:
262: $nstr = (string) $str;
263: $y = 'true|t|1|yeah|yes|y|okay|ok|ya|sure|agree|on|open|right|correct|known|success|positive|win|like|good|safe|do|does|have|approve';
264: $n = 'false|f|0|nope|no|n|never|none|non|not|disagree|off|close|wrong|incorrect|unknown|fail|negative|lose|unlike|bad|unsafe|don\'t|doesn\'t|haven\'t|reject';
265: return (preg_match('/^(' . $y . ')$/i', $nstr)) ? TRUE : (preg_match('/^(' . $n . ')$/i', $nstr) ? FALSE : (boolean) $default);
266: }
267:
268: 269: 270: 271: 272: 273:
274: public static function str2Hex($str) {
275:
276: $nstr = (string) $str;
277: $hex = '';
278: $max = strlen($nstr);
279:
280: for ($i = -1; ++$i < $max;) {
281:
282: $hex .= dechex(ord($nstr[$i]));
283: }
284: return $hex;
285: }
286:
287: 288: 289: 290: 291: 292: 293: 294: 295:
296: public static function truncate($v, $len = 0, $append = '...', $safemode = FALSE) {
297:
298: $nv = (string) $v;
299: $nlen = (int) $len;
300:
301: if (strlen($nv) > $nlen) {
302:
303: if ((boolean) $safemode) {
304:
305: $last = strrpos($ret = substr($nv, 0, $nlen), ' ');
306: $nret = ($last !== FALSE && $nv != $ret) ? substr($ret, 0, $last) : $ret;
307: return ($nret != strlen($nv)) ? $nret .= $append : $nret;
308: }
309: return substr($nv, 0, ($nlen - strlen($append))) . $append;
310: }
311: return $nv;
312: }
313:
314: 315: 316: 317: 318: 319: 320: 321: 322: 323:
324: public static function calPercentage($numerator, $denominator, $decimals = 2, $dec_point = '.', $thousands_sep = ',') {
325:
326: return number_format(($numerator / $denominator) * 100, $decimals, $dec_point, $thousands_sep);
327: }
328:
329: 330: 331: 332: 333:
334: public static function getIP() {
335:
336: $ip = '';
337:
338: if ($_SERVER) {
339:
340: if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
341:
342: $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
343: }
344: elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
345:
346: $ip = $_SERVER['HTTP_CLIENT_IP'];
347: }
348: else {
349: $ip = $_SERVER['REMOTE_ADDR'];
350: }
351: }
352: else {
353: if (getenv('HTTP_X_FORWARDED_FOR')) {
354:
355: $ip = getenv('HTTP_X_FORWARDED_FOR');
356: }
357: elseif (getenv('HTTP_CLIENT_IP')) {
358:
359: $ip = getenv('HTTP_CLIENT_IP');
360: }
361: else {
362: $ip = getenv('REMOTE_ADDR');
363: }
364: }
365: return $ip;
366: }
367:
368: 369: 370: 371: 372:
373: public static function getCurrentURL() {
374:
375: $url = ($ishttps = self::isHttps()) ? 'https://' : 'http://';
376:
377: if (isset($_SERVER['PHP_AUTH_USER'])) {
378:
379: $url .= $_SERVER['PHP_AUTH_USER'];
380:
381: if (isset($_SERVER['PHP_AUTH_PW'])) {
382:
383: $url .= ':' . $_SERVER['PHP_AUTH_PW'];
384: }
385: $url .= '@';
386: }
387: $url .= $_SERVER['HTTP_HOST'];
388:
389: if (($ishttps && ($_SERVER['SERVER_PORT'] != 443)) || (!$ishttps && ($_SERVER['SERVER_PORT'] != 80))) {
390:
391: $url .= ':' . $_SERVER['SERVER_PORT'];
392: }
393:
394:
395: if (!isset($_SERVER['REQUEST_URI'])) {
396:
397:
398: $url .= $_SERVER['PHP_SELF'];
399:
400: if (isset($_SERVER['QUERY_STRING'])) {
401:
402: $url .= '?' . $_SERVER['QUERY_STRING'];
403: }
404: }
405: else {
406: $url .= $_SERVER['REQUEST_URI'];
407: }
408: return $url;
409: }
410:
411: 412: 413: 414: 415: 416: 417: 418: 419:
420: public static function getDateRange($from, $to, $adjust = 1, $format = 'Y-m-d') {
421:
422: $nfrom = (is_numeric($from) || is_float($from) || is_double($from)) ? (int) $from : strtotime($from);
423: $nto = (is_numeric($to) || is_float($to) || is_double($to)) ? (int) $to : strtotime($to);
424:
425: if ($nfrom > $nto) {
426:
427: $nfrom ^= $nto ^= $nfrom ^= $nto;
428: }
429:
430: if (!is_string($format) || empty($format)) {
431:
432: $format = 'Y-m-d';
433: }
434: $dates = array();
435: $step = '+' . ((int) $adjust == 0 ? 1 : (int) $adjust) . ' day';
436:
437: for (; $nfrom <= $nto;) {
438:
439: $dates[] = date($format, $nfrom);
440: $nfrom = strtotime($step, $nfrom);
441: }
442: return $dates;
443: }
444:
445: 446: 447: 448: 449: 450:
451: public static function getFileExt($filename) {
452:
453: return pathinfo((string) $filename, PATHINFO_EXTENSION);
454: }
455:
456: 457: 458: 459: 460: 461: 462:
463: public static function getVisitorInfo() {
464:
465: $ip = self::getIP();
466: $userAgent = $_SERVER['HTTP_USER_AGENT'];
467: $agent = json_decode(file_get_contents(sprintf('http://www.useragentstring.com/?uas=%s&getJSON=all', urlencode($userAgent))), TRUE);
468: $geoip = unserialize(file_get_contents(sprintf('http://www.geoplugin.net/php.gp?ip=%s', $ip)));
469:
470: return array(
471: 'ip' => $ip,
472: 'agent_type' => $agent['agent_type'],
473: 'agent_name' => $agent['agent_name'],
474: 'agent_version' => $agent['agent_version'],
475: 'os' => sprintf('%s %s', $agent['os_name'], str_replace('_', '.', $agent['os_versionNumber'])),
476: 'agent_full' => $userAgent,
477: 'referer' => $_SERVER['HTTP_REFERER'],
478: 'lat' => $geoip['geoplugin_latitude'],
479: 'long' => $geoip['geoplugin_longitude'],
480: 'country_code' => $geoip['geoplugin_countryCode'],
481: 'country' => $geoip['geoplugin_countryName'],
482: 'region' => $geoip['geoplugin_regionName'],
483: 'city' => $geoip['geoplugin_city'],
484: 'currency_code' => $geoip['geoplugin_currencyCode'],
485: 'currency_symbol' => $geoip['geoplugin_currencySymbol'],
486: 'currency_converter' => $geoip['geoplugin_currencyConverter'],
487: 'address' => self::latLng2Addr($geoip['geoplugin_latitude'], $geoip['geoplugin_longitude'])
488: );
489: }
490:
491: 492: 493: 494: 495: 496: 497: 498: 499: 500:
501: public static function humanTimeDiff($from, $to, $sep = ' ', $ends_with = '', $precision = 6) {
502:
503: $nfrom = (is_numeric($from) || is_float($from) || is_double($from)) ? (int) $from : strtotime($from);
504: $nto = (is_numeric($to) || is_float($to) || is_double($to)) ? (int) $to : strtotime($to);
505:
506: if ($nfrom > $nto) {
507:
508: $nfrom ^= $nto ^= $nfrom ^= $nto;
509: }
510: $nprecision = ((int) $precision < 0) ? 1 : (int) $precision;
511:
512: $intervals = array(
513: 'year',
514: 'month',
515: 'day',
516: 'hour',
517: 'minute',
518: 'second'
519: );
520: $times = $diffs = array();
521: $count = 0;
522:
523: foreach ($intervals as $interval) {
524:
525: $time = strtotime('+1 ' . $interval, $nfrom);
526:
527: for ($add = 1, $looped = 0; $nto >= $time;) {
528:
529: $time = strtotime('+' . ++$add . ' ' . $interval, $nfrom);
530: $looped++;
531: }
532: $nfrom = strtotime('+' . $looped . ' ' . $interval, $nfrom);
533: $diffs[$interval] = $looped;
534: }
535:
536: foreach ($diffs as $interval => $value) {
537:
538: if ($count >= $nprecision) {
539:
540: break;
541: }
542: if ($value > 0) {
543:
544: $times[] = $value . ' ' . ($value != 1 ? $interval .= 's' : $interval);
545: $count++;
546: }
547: }
548: return implode((string) $sep, $times) . (string) $ends_with;
549: }
550:
551: 552: 553: 554: 555: 556: 557:
558: public static function randPword($level = 1, $len = 6) {
559:
560: $nlevel = (int) $level;
561: $nlen = ((int) $len <= 0) ? 1 : (int) $len;
562: $vowels = 'aeuy';
563: $consonants = '0123456789bdghjmnpqrstvz';
564:
565: if ($nlevel <= 0) {
566:
567: return str_pad(rand(1, 999999), $len, '0', STR_PAD_LEFT);
568: }
569: if ($nlevel >= 2) {
570:
571: $consonants .= '0123456789BDGHJLMNPQRSTVWXZ';
572: }
573: if ($nlevel >= 3) {
574:
575: $vowels .= 'AEUY';
576: }
577: if ($nlevel >= 4) {
578:
579: $consonants .= '23456789';
580: }
581: if ($nlevel >= 5) {
582:
583: $consonants .= '@#$%';
584: }
585: $password = '';
586: $alt = time() % 2;
587:
588: for ($i = -1; ++$i < $nlen;) {
589:
590: if ($alt == 1) {
591:
592: $password .= $consonants[(rand() % strlen($consonants))];
593: $alt = 0;
594: }
595: else {
596: $password .= $vowels[(rand() % strlen($vowels))];
597: $alt = 1;
598: }
599: }
600: return $password;
601: }
602:
603: 604: 605: 606: 607: 608: 609:
610: public static function shuffleArr($array, $multiply = 1) {
611:
612: if (is_array($array)) {
613:
614: $multiply = (int) $multiply;
615:
616: for ($i = 0; ++$i <= $multiply;) {
617:
618: shuffle($array);
619: }
620: }
621: return $array;
622: }
623:
624: 625: 626: 627: 628: 629: 630:
631: public static function sortDateTime($data, $order = 'ASC') {
632:
633: if (!is_array($data)) {
634:
635: trigger_error(sprintf('%s Expects parameter 1 to be array. %s given.', __METHOD__, gettype($data)));
636: return $data;
637: }
638:
639: if ((string) $order == 'DESC') {
640:
641: usort(self::rtarray_unique($data), function($a, $b) {
642:
643: return strtotime($b) - strtotime($a);
644: });
645: }
646: else {
647: usort(self::rtarray_unique($data), function($a, $b) {
648:
649: return strtotime($a) - strtotime($b);
650: });
651: }
652: return $data;
653: }
654:
655: 656: 657: 658: 659: 660:
661: public static function logger($msg, $file = '__log') {
662:
663: $fp = fopen((empty($file) ? '__log' : (string) $file), 'a');
664: fwrite($fp, sprintf('[%s Asia/Kuala_Lumpur] %s', date('d-M-Y H:i:s'), (string) $msg));
665: fclose($fp);
666: }
667:
668: 669: 670: 671: 672: 673: 674: 675:
676: public static function rtarray_column($data = NULL, $colKey = NULL, $indexKey = NULL) {
677:
678: if (version_compare(PHP_VERSION, '5.5.0,', '>=') || function_exists('array_column')) {
679:
680: return array_column($data, $colKey, $indexKey);
681: }
682:
683: if (!is_array($data) || (!is_int($colKey) && !is_float($colKey) && !is_string($colKey) && $colKey !== NULL && !(is_object($colKey) && method_exists($colKey, '__toString'))) || (isset($indexKey) && !is_int($indexKey) && !is_float($indexKey) && !is_string($indexKey) && !(is_object($indexKey) && method_exists($indexKey, '__toString')))) {
684:
685: $msg = '%s Expects parameter 1 to be array, parameter 2 to be string or int and parameter 3 to be NULL, string or int. %s, %s, %s given.';
686: trigger_error(sprintf($msg, __METHOD__, gettype($data), gettype($colKey), gettype($indexKey)));
687: return array();
688: }
689: $params = $data;
690: $colParams = ($colKey !== NULL) ? (string) $colKey : NULL;
691: $indexKeyParams = NULL;
692:
693: if (isset($indexKey)) {
694:
695: $indexKeyParams = (is_float($indexKey) || is_int($indexKey)) ? (int) $indexKey : (string) $indexKey;
696: }
697: $result = array();
698:
699: foreach ($params as $row) {
700:
701: $key = $value = NULL;
702: $keySet = $valueSet = FALSE;
703:
704: if ($indexKeyParams !== NULL && array_key_exists($indexKeyParams, $row)) {
705:
706: $keySet = TRUE;
707: $key = (string) $row[$indexKeyParams];
708: }
709:
710: if ($colParams === NULL) {
711:
712: $valueSet = TRUE;
713: $value = $row;
714: }
715: elseif (is_array($row) && array_key_exists($colParams, $row)) {
716:
717: $valueSet = TRUE;
718: $value = $row[$colParams];
719: }
720:
721: if ($valueSet) {
722:
723: ($keySet) ? $result[$key] = $value : $result[] = $value;
724: }
725: }
726: return $result;
727: }
728:
729: 730: 731: 732: 733: 734: 735:
736: public static function rtarray_filter_key($array, $callback) {
737:
738: if (!is_array($array) || !is_callable($callback)) {
739:
740: trigger_error(sprintf('%s Expects parameter 1 to be array and parameter 2 to be Callable function', __METHOD__));
741: return $array;
742: }
743: return array_intersect_key($array, array_flip(array_filter(array_keys($array), $callback)));
744: }
745:
746: 747: 748: 749: 750: 751: 752:
753: public static function rtarray_flatten(array $array, $preserve_k = TRUE) {
754:
755: $npreserve_k = (boolean) $preserve_k;
756: $flattened = array();
757:
758: array_walk_recursive($array, function($v, $k) use (&$flattened, $npreserve_k) {
759:
760: if ($npreserve_k && !is_int($k)) {
761:
762: $flattened[$k] = $v;
763: }
764: else {
765: $flattened[] = $v;
766: }
767: });
768: return $flattened;
769: }
770:
771: 772: 773: 774: 775: 776:
777: public static function rtarray_unique($array) {
778:
779: return (is_array($array)) ? array_keys(array_flip($array)) : $array;
780: }
781:
782: }
783: