Utility.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. App::uses('Sanitize', 'Utility');
  3. App::uses('Router', 'Routing');
  4. /**
  5. * Main class for all app-wide utility methods
  6. *
  7. * @author Mark Scherer
  8. * @license MIT
  9. * 2012-02-27 ms
  10. */
  11. class Utility {
  12. /**
  13. * Clean implementation of inArray to avoid false positives.
  14. *
  15. * in_array itself has some PHP flaws regarding cross-type comparison:
  16. * - in_array('50x', array(40, 50, 60)) would be true!
  17. * - in_array(50, array('40x', '50x', '60x')) would be true!
  18. *
  19. * @param mixed $needle
  20. * @param array $haystack
  21. * @return bool Success
  22. */
  23. public static function inArray($needle, $haystack) {
  24. $strict = !is_numeric($needle);
  25. return in_array((string)$needle, $haystack, $strict);
  26. }
  27. /**
  28. * Multibyte analogue of preg_match_all() function. Only that this returns the result.
  29. * By default this works properly with UTF8 strings.
  30. *
  31. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  32. *
  33. * Example: /some(.*)pattern/u
  34. *
  35. * @param string $pattern The pattern to use.
  36. * @param string $subject The string to match.
  37. * @param int $flags
  38. * @param int $offset
  39. * @return array Result
  40. */
  41. public static function pregMatchAll($pattern, $subject, $flags = PREG_SET_ORDER, $offset = null) {
  42. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  43. preg_match_all($pattern, $subject, $matches, $flags, $offset);
  44. return $matches;
  45. }
  46. /**
  47. * Multibyte analogue of preg_match() function. Only that this returns the result.
  48. * By default this works properly with UTF8 strings.
  49. *
  50. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  51. *
  52. * Example: /some(.*)pattern/u
  53. *
  54. * @param string $pattern The pattern to use.
  55. * @param string $subject The string to match.
  56. * @param int $flags
  57. * @param int $offset
  58. * @return array Result
  59. */
  60. public static function pregMatch($pattern, $subject, $flags = null, $offset = null) {
  61. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  62. preg_match($pattern, $subject, $matches, $flags, $offset);
  63. return $matches;
  64. }
  65. /**
  66. * Multibyte analogue of str_split() function.
  67. * By default this works properly with UTF8 strings.
  68. *
  69. * @param string $text
  70. * @param int $length
  71. * @return array Result
  72. */
  73. public static function strSplit($str, $length = 1) {
  74. if ($length < 1) {
  75. return false;
  76. }
  77. $result = array();
  78. $space_key = null;
  79. $c = mb_strlen($str);
  80. for ($i = 0; $i < $c; $i += $length) {
  81. $result[] = mb_substr($str, $i, $length);
  82. }
  83. return $result;
  84. }
  85. /**
  86. * Will escape a string to be used as a regular expression pattern.
  87. *
  88. * - Escapes the following
  89. * - \ ^ . $ | ( ) [ ] * + ? { } ,
  90. *
  91. * - Example
  92. * - Utility::patternEscape('http://www.example.com/s?q=php.net+docs')
  93. * - http:\/\/www\.example\.com\/s\?q=php\.net\+docs
  94. *
  95. * @see http://www.php.net/manual/en/function.preg-replace.php#92456
  96. * @author alammar at gmail dot com
  97. *
  98. * @param string $str the stuff you want escaped
  99. * @return string the escaped string
  100. */
  101. public static function patternEscape($str) {
  102. $patterns = array(
  103. '/\//', '/\^/', '/\./', '/\$/', '/\|/',
  104. '/\(/', '/\)/', '/\[/', '/\]/', '/\*/',
  105. '/\+/', '/\?/', '/\{/', '/\}/', '/\,/'
  106. );
  107. $replace = array('\/', '\^', '\.', '\$', '\|', '\(', '\)',
  108. '\[', '\]', '\*', '\+', '\?', '\{', '\}', '\,');
  109. return preg_replace($patterns, $replace, $str);
  110. }
  111. /**
  112. * get the current ip address
  113. * @param bool $safe
  114. * @return string $ip
  115. * 2011-11-02 ms
  116. */
  117. public static function getClientIp($safe = null) {
  118. if ($safe === null) {
  119. $safe = false;
  120. }
  121. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  122. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  123. } else {
  124. if (env('HTTP_CLIENT_IP')) {
  125. $ipaddr = env('HTTP_CLIENT_IP');
  126. } else {
  127. $ipaddr = env('REMOTE_ADDR');
  128. }
  129. }
  130. if (env('HTTP_CLIENTADDRESS')) {
  131. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  132. if (!empty($tmpipaddr)) {
  133. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  134. }
  135. }
  136. return trim($ipaddr);
  137. }
  138. /**
  139. * get the current referer
  140. * @param bool $full (defaults to false and leaves the url untouched)
  141. * @return string $referer (local or foreign)
  142. * 2011-11-02 ms
  143. */
  144. public static function getReferer($full = false) {
  145. $ref = env('HTTP_REFERER');
  146. $forwarded = env('HTTP_X_FORWARDED_HOST');
  147. if ($forwarded) {
  148. $ref = $forwarded;
  149. }
  150. if (empty($ref)) {
  151. return $ref;
  152. }
  153. if ($full) {
  154. $ref = Router::url($full);
  155. }
  156. return $ref;
  157. }
  158. /**
  159. * remove unnessary stuff + add http:// for external urls
  160. * TODO: protocol to lower!
  161. *
  162. * @param string $url
  163. * @return string Cleaned Url
  164. * 2009-12-22 ms
  165. */
  166. public static function cleanUrl($url, $headerRedirect = false) {
  167. if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
  168. $url = '';
  169. } else {
  170. $url = self::autoPrefixUrl($url, 'http://');
  171. }
  172. if ($headerRedirect && !empty($url)) {
  173. $headers = self::getHeaderFromUrl($url);
  174. if ($headers !== false) {
  175. $headerString = implode("\n", $headers);
  176. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  177. foreach ($headers as $header) {
  178. if (mb_strpos($header, 'Location:') === 0) {
  179. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  180. }
  181. }
  182. }
  183. }
  184. }
  185. $length = mb_strlen($url);
  186. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  187. $url = mb_substr($url, 0, $length - 1);
  188. $length--;
  189. }
  190. return $url;
  191. }
  192. /**
  193. * Parse headers
  194. *
  195. * @param string $url
  196. * @return mixed array of headers or FALSE on failure
  197. * 2009-12-26 ms
  198. */
  199. public static function getHeaderFromUrl($url) {
  200. $url = @parse_url($url);
  201. if (empty($url)) {
  202. return false;
  203. }
  204. $url = array_map('trim', $url);
  205. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  206. $path = (isset($url['path'])) ? $url['path'] : '';
  207. if (empty($path)) {
  208. $path = '/';
  209. }
  210. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  211. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  212. $headers = @get_headers("$url[scheme]://$url[host]:$url[port]$path");
  213. if (is_array($headers)) {
  214. return $headers;
  215. }
  216. }
  217. return false;
  218. }
  219. /**
  220. * add protocol prefix if necessary (and possible)
  221. *
  222. * @param string $url
  223. * 2010-06-02 ms
  224. */
  225. public static function autoPrefixUrl($url, $prefix = null) {
  226. if ($prefix === null) {
  227. $prefix = 'http://';
  228. }
  229. if (($pos = strpos($url, '.')) !== false) {
  230. if (strpos(substr($url, 0, $pos), '//') === false) {
  231. $url = $prefix . $url;
  232. }
  233. }
  234. return $url;
  235. }
  236. /**
  237. * Encode strings with base64_encode and also
  238. * replace chars base64 uses that would mess up the url.
  239. *
  240. * Do not use this for querystrings. Those will escape automatically.
  241. * This is only useful for named or passed params.
  242. *
  243. * @param string $string Unsafe string
  244. * @return string Encoded string
  245. * 2012-10-23 ms
  246. */
  247. public static function urlEncode($string) {
  248. return str_replace(array('/', '='), array('-', '_'), base64_encode($string));
  249. }
  250. /**
  251. * Decode strings with base64_encode and also
  252. * replace back chars base64 uses that would mess up the url.
  253. *
  254. * Do not use this for querystrings. Those will escape automatically.
  255. * This is only useful for named or passed params.
  256. *
  257. * @param string $string Safe string
  258. * @return string Decoded string
  259. * 2012-10-23 ms
  260. */
  261. public static function urlDecode($string) {
  262. return base64_decode(str_replace(array('-', '_'), array('/', '='), $string));
  263. }
  264. /**
  265. * Returns true only if all values are true.
  266. * //TODO: maybe move to bootstrap?
  267. *
  268. * @param array $array
  269. * @return bool $result
  270. * 2011-11-02 ms
  271. */
  272. public static function logicalAnd($array) {
  273. if (empty($array)) {
  274. return false;
  275. }
  276. foreach ($array as $result) {
  277. if (!$result) {
  278. return false;
  279. }
  280. }
  281. return true;
  282. }
  283. /**
  284. * Returns true if at least one value is true.
  285. * //TODO: maybe move to bootstrap?
  286. *
  287. * @param array $array
  288. * @return bool $result
  289. *
  290. * 2011-11-02 ms
  291. */
  292. public static function logicalOr($array) {
  293. foreach ($array as $result) {
  294. if ($result) {
  295. return true;
  296. }
  297. }
  298. return false;
  299. }
  300. /**
  301. * On non-transaction db connections it will return a deep array of bools instead of bool.
  302. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  303. *
  304. * @param array
  305. * @return bool
  306. * 2012-10-12 ms
  307. */
  308. public static function isValidSaveAll($array) {
  309. if (empty($array)) {
  310. return false;
  311. }
  312. $ret = true;
  313. foreach ($array as $key => $val) {
  314. if (is_array($val)) {
  315. $ret = $ret & Utility::logicalAnd($val);
  316. } else {
  317. $ret = $ret & $val;
  318. }
  319. }
  320. return (bool)$ret;
  321. }
  322. /**
  323. * Convenience function for automatic casting in form methods etc.
  324. * //TODO: maybe move to bootstrap?
  325. *
  326. * @param mixed $value
  327. * @param string $type
  328. * @return safe value for DB query, or NULL if type was not a valid one
  329. * 2008-12-12 ms
  330. */
  331. public static function typeCast($value, $type) {
  332. switch ($type) {
  333. case 'int':
  334. $value = (int)$value;
  335. break;
  336. case 'float':
  337. $value = (float)$value;
  338. break;
  339. case 'double':
  340. $value = (double)$value;
  341. break;
  342. case 'array':
  343. $value = (array )$value;
  344. break;
  345. case 'bool':
  346. $value = (bool)$value;
  347. break;
  348. case 'string':
  349. $value = (string )$value;
  350. break;
  351. default:
  352. return null;
  353. }
  354. return $value;
  355. }
  356. /**
  357. * Trim recursivly
  358. *
  359. * 2009-07-07 ms
  360. */
  361. public static function trimDeep($value) {
  362. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  363. return $value;
  364. }
  365. /**
  366. * h() recursivly
  367. *
  368. * 2009-07-07 ms
  369. */
  370. public static function specialcharsDeep($value) {
  371. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  372. return $value;
  373. }
  374. /**
  375. * Removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  376. *
  377. * 2009-07-07 ms
  378. */
  379. public static function paranoidDeep($value) {
  380. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  381. return $value;
  382. }
  383. /**
  384. * Transfers/removes all < > from text (remove TRUE/FALSE)
  385. *
  386. * 2009-07-07 ms
  387. */
  388. public static function htmlDeep($value) {
  389. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  390. return $value;
  391. }
  392. /**
  393. * main deep method
  394. *
  395. * 2009-07-07 ms
  396. */
  397. public static function deep($function, $value) {
  398. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  399. return $value;
  400. }
  401. /**
  402. * Flattens an array.
  403. *
  404. * @param array $array to flatten
  405. * @param boolean $perserveKeys
  406. * @return array
  407. * 2011-07-02 ms
  408. */
  409. public static function arrayFlatten($array, $preserveKeys = false) {
  410. if ($preserveKeys) {
  411. return self::_arrayFlatten($array);
  412. }
  413. if (!$array) {
  414. return array();
  415. }
  416. $result = array();
  417. foreach ($array as $key => $value) {
  418. if (is_array($value)) {
  419. $result = array_merge($result, self::arrayFlatten($value));
  420. } else {
  421. $result[$key] = $value;
  422. }
  423. }
  424. return $result;
  425. }
  426. /**
  427. * Flatten an array and preserve the keys
  428. *
  429. * @return array
  430. */
  431. protected static function _arrayFlatten($a, $f = array()) {
  432. if (!$a) {
  433. return array();
  434. }
  435. foreach ($a as $k => $v) {
  436. if (is_array($v)) {
  437. $f = self::_arrayFlatten($v, $f);
  438. } else {
  439. $f[$k] = $v;
  440. }
  441. }
  442. return $f;
  443. }
  444. /**
  445. * Similar to array_shift but on the keys of the array
  446. * like array_shift() only for keys and not values
  447. *
  448. * @param array $keyValuePairs
  449. * @return string $key
  450. * 2011-01-22 ms
  451. */
  452. public static function arrayShiftKeys(&$array) {
  453. foreach ($array as $key => $value) {
  454. unset($array[$key]);
  455. return $key;
  456. }
  457. }
  458. protected static $_counterStartTime;
  459. /**
  460. * returns microtime as float value
  461. * (to be subtracted right away)
  462. *
  463. * @return float
  464. * 2009-07-07 ms
  465. */
  466. public static function microtime($precision = 8) {
  467. return round(microtime(true), $precision);
  468. }
  469. /**
  470. * @return void
  471. * 2009-07-07 ms
  472. */
  473. public static function startClock() {
  474. self::$_counterStartTime = self::microtime();
  475. }
  476. /**
  477. * @return float
  478. * 2009-07-07 ms
  479. */
  480. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  481. $startTime = self::$_counterStartTime;
  482. if ($restartClock) {
  483. self::startClock();
  484. }
  485. return self::calcElapsedTime($startTime, self::microtime(), $precision);
  486. }
  487. /**
  488. * Returns microtime as float value
  489. * (to be subtracted right away)
  490. *
  491. * @return float
  492. * 2009-07-07 ms
  493. */
  494. public static function calcElapsedTime($start, $end, $precision = 8) {
  495. $elapsed = $end - $start;
  496. return round($elapsed, $precision);
  497. }
  498. }