Utility.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. */
  10. class Utility {
  11. /**
  12. * Clean implementation of inArray to avoid false positives.
  13. *
  14. * in_array itself has some PHP flaws regarding cross-type comparison:
  15. * - in_array('50x', array(40, 50, 60)) would be true!
  16. * - in_array(50, array('40x', '50x', '60x')) would be true!
  17. *
  18. * @param mixed $needle
  19. * @param array $haystack
  20. * @return boolean Success
  21. */
  22. public static function inArray($needle, $haystack) {
  23. $strict = !is_numeric($needle);
  24. return in_array((string)$needle, $haystack, $strict);
  25. }
  26. /**
  27. * Tokenizes a string using $separator.
  28. *
  29. * Options
  30. * - clean: true/false (defaults to true and removes empty tokens and whitespace)
  31. *
  32. * @param string $data The data to tokenize
  33. * @param string $separator The token to split the data on.
  34. * @param array $options
  35. * @return void
  36. */
  37. public static function tokenize($data, $separator = ',', $options = array()) {
  38. $defaults = array(
  39. 'clean' => true
  40. );
  41. $options += $defaults;
  42. if (empty($data)) {
  43. return array();
  44. }
  45. $tokens = explode($separator, $data);
  46. if (empty($tokens) || !$options['clean']) {
  47. return $tokens;
  48. }
  49. foreach ($tokens as $key => $token) {
  50. if ($token === '') {
  51. unset($tokens[$key]);
  52. }
  53. }
  54. return array_map('trim', $tokens);
  55. }
  56. /**
  57. * Multibyte analogue of preg_match_all() function. Only that this returns the result.
  58. * By default this works properly with UTF8 strings.
  59. *
  60. * Do not forget to use preg_quote() first on strings that could potentially contain
  61. * unescaped characters.
  62. *
  63. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  64. *
  65. * Example: /some(.*)pattern/u
  66. *
  67. * @param string $pattern The pattern to use.
  68. * @param string $subject The string to match.
  69. * @param integer $flags
  70. * @param integer $offset
  71. * @return array Result
  72. */
  73. public static function pregMatchAll($pattern, $subject, $flags = PREG_SET_ORDER, $offset = null) {
  74. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  75. preg_match_all($pattern, $subject, $matches, $flags, $offset);
  76. return $matches;
  77. }
  78. /**
  79. * Multibyte analogue of preg_match() function. Only that this returns the result.
  80. * By default this works properly with UTF8 strings.
  81. *
  82. * Do not forget to use preg_quote() first on strings that could potentially contain
  83. * unescaped characters.
  84. *
  85. * Note that you still need to add the u modifier (for UTF8) to your pattern yourself.
  86. *
  87. * Example: /some(.*)pattern/u
  88. *
  89. * @param string $pattern The pattern to use.
  90. * @param string $subject The string to match.
  91. * @param integer $flags
  92. * @param integer $offset
  93. * @return array Result
  94. */
  95. public static function pregMatch($pattern, $subject, $flags = null, $offset = null) {
  96. $pattern = substr($pattern, 0, 1) . '(*UTF8)' . substr($pattern, 1);
  97. preg_match($pattern, $subject, $matches, $flags, $offset);
  98. return $matches;
  99. }
  100. /**
  101. * Multibyte analogue of str_split() function.
  102. * By default this works properly with UTF8 strings.
  103. *
  104. * @param string $text
  105. * @param integer $length
  106. * @return array Result
  107. */
  108. public static function strSplit($str, $length = 1) {
  109. if ($length < 1) {
  110. return false;
  111. }
  112. $result = array();
  113. $c = mb_strlen($str);
  114. for ($i = 0; $i < $c; $i += $length) {
  115. $result[] = mb_substr($str, $i, $length);
  116. }
  117. return $result;
  118. }
  119. /**
  120. * Get the current IP address.
  121. *
  122. * @param boolean $safe
  123. * @return string IP address
  124. */
  125. public static function getClientIp($safe = true) {
  126. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  127. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  128. } else {
  129. if (env('HTTP_CLIENT_IP')) {
  130. $ipaddr = env('HTTP_CLIENT_IP');
  131. } else {
  132. $ipaddr = env('REMOTE_ADDR');
  133. }
  134. }
  135. if (env('HTTP_CLIENTADDRESS')) {
  136. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  137. if (!empty($tmpipaddr)) {
  138. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  139. }
  140. }
  141. return trim($ipaddr);
  142. }
  143. /**
  144. * Get the current referrer if available.
  145. *
  146. * @param boolean $full (defaults to false and leaves the url untouched)
  147. * @return string referer (local or foreign)
  148. */
  149. public static function getReferer($full = false) {
  150. $ref = env('HTTP_REFERER');
  151. $forwarded = env('HTTP_X_FORWARDED_HOST');
  152. if ($forwarded) {
  153. $ref = $forwarded;
  154. }
  155. if (empty($ref)) {
  156. return $ref;
  157. }
  158. if ($full) {
  159. $ref = Router::url($ref, $full);
  160. }
  161. return $ref;
  162. }
  163. /**
  164. * Remove unnessary stuff + add http:// for external urls
  165. * TODO: protocol to lower!
  166. *
  167. * @param string $url
  168. * @return string Cleaned Url
  169. */
  170. public static function cleanUrl($url, $headerRedirect = false) {
  171. if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
  172. $url = '';
  173. } else {
  174. $url = self::autoPrefixUrl($url, 'http://');
  175. }
  176. if ($headerRedirect && !empty($url)) {
  177. $headers = self::getHeaderFromUrl($url);
  178. if ($headers !== false) {
  179. $headerString = implode("\n", $headers);
  180. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  181. foreach ($headers as $header) {
  182. if (mb_strpos($header, 'Location:') === 0) {
  183. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  184. }
  185. }
  186. }
  187. }
  188. }
  189. $length = mb_strlen($url);
  190. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  191. $url = mb_substr($url, 0, $length - 1);
  192. $length--;
  193. }
  194. return $url;
  195. }
  196. /**
  197. * Parse headers from a specific URL content.
  198. *
  199. * @param string $url
  200. * @return mixed array of headers or FALSE on failure
  201. */
  202. public static function getHeaderFromUrl($url) {
  203. $url = @parse_url($url);
  204. if (empty($url)) {
  205. return false;
  206. }
  207. $url = array_map('trim', $url);
  208. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  209. $path = (isset($url['path'])) ? $url['path'] : '';
  210. if (empty($path)) {
  211. $path = '/';
  212. }
  213. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  214. $defaults = array(
  215. 'http' => array(
  216. 'header' => "Accept: text/html\r\n" .
  217. "Connection: Close\r\n" .
  218. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
  219. )
  220. );
  221. stream_context_get_default($defaults);
  222. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  223. $url = "$url[scheme]://$url[host]$url[port]$path";
  224. $headers = get_headers($url);
  225. if (is_array($headers)) {
  226. return $headers;
  227. }
  228. }
  229. return false;
  230. }
  231. /**
  232. * Add protocol prefix if necessary (and possible)
  233. *
  234. * @param string $url
  235. */
  236. public static function autoPrefixUrl($url, $prefix = null) {
  237. if ($prefix === null) {
  238. $prefix = 'http://';
  239. }
  240. if (($pos = strpos($url, '.')) !== false) {
  241. if (strpos(substr($url, 0, $pos), '//') === false) {
  242. $url = $prefix . $url;
  243. }
  244. }
  245. return $url;
  246. }
  247. /**
  248. * Encode strings with base64_encode and also
  249. * replace chars base64 uses that would mess up the url.
  250. *
  251. * Do not use this for querystrings. Those will escape automatically.
  252. * This is only useful for named or passed params.
  253. *
  254. * @param string $string Unsafe string
  255. * @return string Encoded string
  256. */
  257. public static function urlEncode($string) {
  258. return str_replace(array('/', '='), array('-', '_'), base64_encode($string));
  259. }
  260. /**
  261. * Decode strings with base64_encode and also
  262. * replace back chars base64 uses that would mess up the url.
  263. *
  264. * Do not use this for querystrings. Those will escape automatically.
  265. * This is only useful for named or passed params.
  266. *
  267. * @param string $string Safe string
  268. * @return string Decoded string
  269. */
  270. public static function urlDecode($string) {
  271. return base64_decode(str_replace(array('-', '_'), array('/', '='), $string));
  272. }
  273. /**
  274. * Returns true only if all values are true.
  275. * //TODO: maybe move to bootstrap?
  276. *
  277. * @param array $array
  278. * @return boolean Result
  279. */
  280. public static function logicalAnd($array) {
  281. if (empty($array)) {
  282. return false;
  283. }
  284. foreach ($array as $result) {
  285. if (!$result) {
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. /**
  292. * Returns true if at least one value is true.
  293. * //TODO: maybe move to bootstrap?
  294. *
  295. * @param array $array
  296. * @return boolean Result
  297. *
  298. */
  299. public static function logicalOr($array) {
  300. foreach ($array as $result) {
  301. if ($result) {
  302. return true;
  303. }
  304. }
  305. return false;
  306. }
  307. /**
  308. * On non-transaction db connections it will return a deep array of bools instead of bool.
  309. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  310. *
  311. * @param array
  312. * @return boolean
  313. */
  314. public static function isValidSaveAll($array) {
  315. if (empty($array)) {
  316. return false;
  317. }
  318. $ret = true;
  319. foreach ($array as $key => $val) {
  320. if (is_array($val)) {
  321. $ret = $ret & Utility::logicalAnd($val);
  322. } else {
  323. $ret = $ret & $val;
  324. }
  325. }
  326. return (bool)$ret;
  327. }
  328. /**
  329. * Convenience function for automatic casting in form methods etc.
  330. * //TODO: maybe move to bootstrap?
  331. *
  332. * @param mixed $value
  333. * @param string $type
  334. * @return safe value for DB query, or NULL if type was not a valid one
  335. */
  336. public static function typeCast($value, $type) {
  337. switch ($type) {
  338. case 'int':
  339. $value = (int)$value;
  340. break;
  341. case 'float':
  342. $value = (float)$value;
  343. break;
  344. case 'double':
  345. $value = (double)$value;
  346. break;
  347. case 'array':
  348. $value = (array)$value;
  349. break;
  350. case 'bool':
  351. $value = (bool)$value;
  352. break;
  353. case 'string':
  354. $value = (string)$value;
  355. break;
  356. default:
  357. return null;
  358. }
  359. return $value;
  360. }
  361. /**
  362. * Trim recursivly
  363. *
  364. */
  365. public static function trimDeep($value) {
  366. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  367. return $value;
  368. }
  369. /**
  370. * h() recursivly
  371. *
  372. */
  373. public static function specialcharsDeep($value) {
  374. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  375. return $value;
  376. }
  377. /**
  378. * Removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  379. *
  380. */
  381. public static function paranoidDeep($value) {
  382. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  383. return $value;
  384. }
  385. /**
  386. * Transfers/removes all < > from text (remove TRUE/FALSE)
  387. *
  388. */
  389. public static function htmlDeep($value) {
  390. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  391. return $value;
  392. }
  393. /**
  394. * Main deep method
  395. *
  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. * Expands the values of an array of strings into a deep array.
  403. * Opposite of flattenList().
  404. *
  405. * It needs at least a single separator to be present in all values
  406. * as the key would otherwise be undefined. If data can contain such key-less
  407. * rows, use $undefinedKey to avoid an exception being thrown. But it will
  408. * effectivly collide with other values in that same key then.
  409. *
  410. * So `Some.Deep.Value` becomes `array('Some' => array('Deep' => array('Value')))`.
  411. *
  412. * @param array $data
  413. * @param string $separator
  414. * @param string $undefinedKey
  415. * @return array
  416. */
  417. public static function expandList(array $data, $separator = '.', $undefinedKey = null) {
  418. $result = array();
  419. foreach ($data as $value) {
  420. $keys = explode($separator, $value);
  421. $value = array_pop($keys);
  422. $keys = array_reverse($keys);
  423. if (!isset($keys[0])) {
  424. if ($undefinedKey === null) {
  425. throw new RuntimeException('Key-less values are not supported without $undefinedKey.');
  426. }
  427. $keys[0] = $undefinedKey;
  428. }
  429. $child = array($keys[0] => array($value));
  430. array_shift($keys);
  431. foreach ($keys as $k) {
  432. $child = array(
  433. $k => $child
  434. );
  435. }
  436. $result = Set::merge($result, $child);
  437. }
  438. return $result;
  439. }
  440. /**
  441. * Flattens a deep array into an array of strings.
  442. * Opposite of expandList().
  443. *
  444. * So `array('Some' => array('Deep' => array('Value')))` becomes `Some.Deep.Value`.
  445. *
  446. * Note that primarily only string should be used.
  447. * However, boolean values are casted to int and thus
  448. * both boolean and integer values also supported.
  449. *
  450. * @param array $data
  451. * @return array
  452. */
  453. public static function flattenList(array $data, $separator = '.') {
  454. $result = array();
  455. $stack = array();
  456. $path = null;
  457. reset($data);
  458. while (!empty($data)) {
  459. $key = key($data);
  460. $element = $data[$key];
  461. unset($data[$key]);
  462. if (is_array($element) && !empty($element)) {
  463. if (!empty($data)) {
  464. $stack[] = array($data, $path);
  465. }
  466. $data = $element;
  467. reset($data);
  468. $path .= $key . $separator;
  469. } else {
  470. if (is_bool($element)) {
  471. $element = (int)$element;
  472. }
  473. $result[] = $path . $element;
  474. }
  475. if (empty($data) && !empty($stack)) {
  476. list($data, $path) = array_pop($stack);
  477. reset($data);
  478. }
  479. }
  480. return $result;
  481. }
  482. /**
  483. * Force-flattens an array.
  484. *
  485. * Careful with this method. It can lose information.
  486. * The keys will not be changed, thus possibly overwrite each other.
  487. *
  488. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  489. *
  490. * @param array $array to flatten
  491. * @param boolean $perserveKeys
  492. * @return array
  493. */
  494. public static function arrayFlatten($array, $preserveKeys = false) {
  495. if ($preserveKeys) {
  496. return self::_arrayFlatten($array);
  497. }
  498. if (!$array) {
  499. return array();
  500. }
  501. $result = array();
  502. foreach ($array as $key => $value) {
  503. if (is_array($value)) {
  504. $result = array_merge($result, self::arrayFlatten($value));
  505. } else {
  506. $result[$key] = $value;
  507. }
  508. }
  509. return $result;
  510. }
  511. /**
  512. * Force-flattens an array and preserves the keys.
  513. *
  514. * Careful with this method. It can lose information.
  515. * The keys will not be changed, thus possibly overwrite each other.
  516. *
  517. * //TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
  518. *
  519. * @param array $a
  520. * @param array $f
  521. * @return array
  522. */
  523. protected static function _arrayFlatten($a, $f = array()) {
  524. if (!$a) {
  525. return array();
  526. }
  527. foreach ($a as $k => $v) {
  528. if (is_array($v)) {
  529. $f = self::_arrayFlatten($v, $f);
  530. } else {
  531. $f[$k] = $v;
  532. }
  533. }
  534. return $f;
  535. }
  536. /**
  537. * Similar to array_shift but on the keys of the array
  538. * like array_shift() only for keys and not values
  539. *
  540. * @param array $keyValuePairs
  541. * @return string key
  542. */
  543. public static function arrayShiftKeys(&$array) {
  544. foreach ($array as $key => $value) {
  545. unset($array[$key]);
  546. return $key;
  547. }
  548. }
  549. protected static $_counterStartTime;
  550. /**
  551. * Returns microtime as float value
  552. * (to be subtracted right away)
  553. *
  554. * @param int $precision
  555. * @return float
  556. */
  557. public static function microtime($precision = 8) {
  558. return round(microtime(true), $precision);
  559. }
  560. /**
  561. * @return void
  562. */
  563. public static function startClock() {
  564. self::$_counterStartTime = self::microtime();
  565. }
  566. /**
  567. * @param int $precision
  568. * @param boolean $restartClock
  569. * @return float
  570. */
  571. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  572. $startTime = self::$_counterStartTime;
  573. if ($restartClock) {
  574. self::startClock();
  575. }
  576. return self::calcElapsedTime($startTime, self::microtime(), $precision);
  577. }
  578. /**
  579. * Returns microtime as float value
  580. * (to be subtracted right away)
  581. *
  582. * @param int $start
  583. * @param int $end
  584. * @param int $precision
  585. * @return float
  586. */
  587. public static function calcElapsedTime($start, $end, $precision = 8) {
  588. $elapsed = $end - $start;
  589. return round($elapsed, $precision);
  590. }
  591. }