Utility.php 12 KB

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