Utility.php 14 KB

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