Utility.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. * 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 int $flags
  41. * @param int $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 int $flags
  63. * @param int $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 int $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 bool $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 bool $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. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  191. $headers = @get_headers("$url[scheme]://$url[host]:$url[port]$path");
  192. if (is_array($headers)) {
  193. return $headers;
  194. }
  195. }
  196. return false;
  197. }
  198. /**
  199. * Add protocol prefix if necessary (and possible)
  200. *
  201. * @param string $url
  202. * 2010-06-02 ms
  203. */
  204. public static function autoPrefixUrl($url, $prefix = null) {
  205. if ($prefix === null) {
  206. $prefix = 'http://';
  207. }
  208. if (($pos = strpos($url, '.')) !== false) {
  209. if (strpos(substr($url, 0, $pos), '//') === false) {
  210. $url = $prefix . $url;
  211. }
  212. }
  213. return $url;
  214. }
  215. /**
  216. * Encode strings with base64_encode and also
  217. * replace chars base64 uses that would mess up the url.
  218. *
  219. * Do not use this for querystrings. Those will escape automatically.
  220. * This is only useful for named or passed params.
  221. *
  222. * @param string $string Unsafe string
  223. * @return string Encoded string
  224. * 2012-10-23 ms
  225. */
  226. public static function urlEncode($string) {
  227. return str_replace(array('/', '='), array('-', '_'), base64_encode($string));
  228. }
  229. /**
  230. * Decode strings with base64_encode and also
  231. * replace back chars base64 uses that would mess up the url.
  232. *
  233. * Do not use this for querystrings. Those will escape automatically.
  234. * This is only useful for named or passed params.
  235. *
  236. * @param string $string Safe string
  237. * @return string Decoded string
  238. * 2012-10-23 ms
  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 bool Result
  249. * 2011-11-02 ms
  250. */
  251. public static function logicalAnd($array) {
  252. if (empty($array)) {
  253. return false;
  254. }
  255. foreach ($array as $result) {
  256. if (!$result) {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. /**
  263. * Returns true if at least one value is true.
  264. * //TODO: maybe move to bootstrap?
  265. *
  266. * @param array $array
  267. * @return bool Result
  268. *
  269. * 2011-11-02 ms
  270. */
  271. public static function logicalOr($array) {
  272. foreach ($array as $result) {
  273. if ($result) {
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. /**
  280. * On non-transaction db connections it will return a deep array of bools instead of bool.
  281. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  282. *
  283. * @param array
  284. * @return bool
  285. * 2012-10-12 ms
  286. */
  287. public static function isValidSaveAll($array) {
  288. if (empty($array)) {
  289. return false;
  290. }
  291. $ret = true;
  292. foreach ($array as $key => $val) {
  293. if (is_array($val)) {
  294. $ret = $ret & Utility::logicalAnd($val);
  295. } else {
  296. $ret = $ret & $val;
  297. }
  298. }
  299. return (bool)$ret;
  300. }
  301. /**
  302. * Convenience function for automatic casting in form methods etc.
  303. * //TODO: maybe move to bootstrap?
  304. *
  305. * @param mixed $value
  306. * @param string $type
  307. * @return safe value for DB query, or NULL if type was not a valid one
  308. * 2008-12-12 ms
  309. */
  310. public static function typeCast($value, $type) {
  311. switch ($type) {
  312. case 'int':
  313. $value = (int)$value;
  314. break;
  315. case 'float':
  316. $value = (float)$value;
  317. break;
  318. case 'double':
  319. $value = (double)$value;
  320. break;
  321. case 'array':
  322. $value = (array )$value;
  323. break;
  324. case 'bool':
  325. $value = (bool)$value;
  326. break;
  327. case 'string':
  328. $value = (string )$value;
  329. break;
  330. default:
  331. return null;
  332. }
  333. return $value;
  334. }
  335. /**
  336. * Trim recursivly
  337. *
  338. * 2009-07-07 ms
  339. */
  340. public static function trimDeep($value) {
  341. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  342. return $value;
  343. }
  344. /**
  345. * h() recursivly
  346. *
  347. * 2009-07-07 ms
  348. */
  349. public static function specialcharsDeep($value) {
  350. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  351. return $value;
  352. }
  353. /**
  354. * Removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  355. *
  356. * 2009-07-07 ms
  357. */
  358. public static function paranoidDeep($value) {
  359. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  360. return $value;
  361. }
  362. /**
  363. * Transfers/removes all < > from text (remove TRUE/FALSE)
  364. *
  365. * 2009-07-07 ms
  366. */
  367. public static function htmlDeep($value) {
  368. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  369. return $value;
  370. }
  371. /**
  372. * main deep method
  373. *
  374. * 2009-07-07 ms
  375. */
  376. public static function deep($function, $value) {
  377. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  378. return $value;
  379. }
  380. /**
  381. * Flattens an array.
  382. *
  383. * @param array $array to flatten
  384. * @param boolean $perserveKeys
  385. * @return array
  386. * 2011-07-02 ms
  387. */
  388. public static function arrayFlatten($array, $preserveKeys = false) {
  389. if ($preserveKeys) {
  390. return self::_arrayFlatten($array);
  391. }
  392. if (!$array) {
  393. return array();
  394. }
  395. $result = array();
  396. foreach ($array as $key => $value) {
  397. if (is_array($value)) {
  398. $result = array_merge($result, self::arrayFlatten($value));
  399. } else {
  400. $result[$key] = $value;
  401. }
  402. }
  403. return $result;
  404. }
  405. /**
  406. * Flatten an array and preserve the keys
  407. *
  408. * @return array
  409. */
  410. protected static function _arrayFlatten($a, $f = array()) {
  411. if (!$a) {
  412. return array();
  413. }
  414. foreach ($a as $k => $v) {
  415. if (is_array($v)) {
  416. $f = self::_arrayFlatten($v, $f);
  417. } else {
  418. $f[$k] = $v;
  419. }
  420. }
  421. return $f;
  422. }
  423. /**
  424. * Similar to array_shift but on the keys of the array
  425. * like array_shift() only for keys and not values
  426. *
  427. * @param array $keyValuePairs
  428. * @return string $key
  429. * 2011-01-22 ms
  430. */
  431. public static function arrayShiftKeys(&$array) {
  432. foreach ($array as $key => $value) {
  433. unset($array[$key]);
  434. return $key;
  435. }
  436. }
  437. protected static $_counterStartTime;
  438. /**
  439. * returns microtime as float value
  440. * (to be subtracted right away)
  441. *
  442. * @return float
  443. * 2009-07-07 ms
  444. */
  445. public static function microtime($precision = 8) {
  446. return round(microtime(true), $precision);
  447. }
  448. /**
  449. * @return void
  450. * 2009-07-07 ms
  451. */
  452. public static function startClock() {
  453. self::$_counterStartTime = self::microtime();
  454. }
  455. /**
  456. * @return float
  457. * 2009-07-07 ms
  458. */
  459. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  460. $startTime = self::$_counterStartTime;
  461. if ($restartClock) {
  462. self::startClock();
  463. }
  464. return self::calcElapsedTime($startTime, self::microtime(), $precision);
  465. }
  466. /**
  467. * Returns microtime as float value
  468. * (to be subtracted right away)
  469. *
  470. * @return float
  471. * 2009-07-07 ms
  472. */
  473. public static function calcElapsedTime($start, $end, $precision = 8) {
  474. $elapsed = $end - $start;
  475. return round($elapsed, $precision);
  476. }
  477. }