Utility.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. * get the current ip address
  87. * @param bool $safe
  88. * @return string $ip
  89. * 2011-11-02 ms
  90. */
  91. public static function getClientIp($safe = null) {
  92. if ($safe === null) {
  93. $safe = false;
  94. }
  95. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  96. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  97. } else {
  98. if (env('HTTP_CLIENT_IP')) {
  99. $ipaddr = env('HTTP_CLIENT_IP');
  100. } else {
  101. $ipaddr = env('REMOTE_ADDR');
  102. }
  103. }
  104. if (env('HTTP_CLIENTADDRESS')) {
  105. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  106. if (!empty($tmpipaddr)) {
  107. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  108. }
  109. }
  110. return trim($ipaddr);
  111. }
  112. /**
  113. * get the current referer
  114. * @param bool $full (defaults to false and leaves the url untouched)
  115. * @return string $referer (local or foreign)
  116. * 2011-11-02 ms
  117. */
  118. public static function getReferer($full = false) {
  119. $ref = env('HTTP_REFERER');
  120. $forwarded = env('HTTP_X_FORWARDED_HOST');
  121. if ($forwarded) {
  122. $ref = $forwarded;
  123. }
  124. if (empty($ref)) {
  125. return $ref;
  126. }
  127. if ($full) {
  128. $ref = Router::url($full);
  129. }
  130. return $ref;
  131. }
  132. /**
  133. * remove unnessary stuff + add http:// for external urls
  134. * TODO: protocol to lower!
  135. *
  136. * @param string $url
  137. * @return string Cleaned Url
  138. * 2009-12-22 ms
  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
  168. *
  169. * @param string $url
  170. * @return mixed array of headers or FALSE on failure
  171. * 2009-12-26 ms
  172. */
  173. public static function getHeaderFromUrl($url) {
  174. $url = @parse_url($url);
  175. if (empty($url)) {
  176. return false;
  177. }
  178. $url = array_map('trim', $url);
  179. $url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
  180. $path = (isset($url['path'])) ? $url['path'] : '';
  181. if (empty($path)) {
  182. $path = '/';
  183. }
  184. $path .= (isset($url['query'])) ? "?$url[query]" : '';
  185. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  186. $headers = @get_headers("$url[scheme]://$url[host]:$url[port]$path");
  187. if (is_array($headers)) {
  188. return $headers;
  189. }
  190. }
  191. return false;
  192. }
  193. /**
  194. * add protocol prefix if necessary (and possible)
  195. *
  196. * @param string $url
  197. * 2010-06-02 ms
  198. */
  199. public static function autoPrefixUrl($url, $prefix = null) {
  200. if ($prefix === null) {
  201. $prefix = 'http://';
  202. }
  203. if (($pos = strpos($url, '.')) !== false) {
  204. if (strpos(substr($url, 0, $pos), '//') === false) {
  205. $url = $prefix . $url;
  206. }
  207. }
  208. return $url;
  209. }
  210. /**
  211. * encode strings with base64_encode and also
  212. * replace chars base64 uses that would mess up the url
  213. *
  214. * @param string $string Unsafe string
  215. * @return string Encoded string
  216. * 2012-10-23 ms
  217. */
  218. public static function urlEncode($string) {
  219. return str_replace(array('/', '='), array('-', '_'), base64_encode($string));
  220. }
  221. /**
  222. * decode strings with base64_encode and also
  223. * replace back chars base64 uses that would mess up the url
  224. *
  225. * @param string $string Safe string
  226. * @return string Decoded string
  227. * 2012-10-23 ms
  228. */
  229. public static function urlDecode($string) {
  230. return base64_decode(str_replace(array('-', '_'), array('/', '='), $string));
  231. }
  232. /**
  233. * returns true only if all values are true
  234. *
  235. * @param array $array
  236. * @return bool $result
  237. * maybe move to bootstrap?
  238. * 2011-11-02 ms
  239. */
  240. public static function logicalAnd($array) {
  241. if (empty($array)) {
  242. return false;
  243. }
  244. foreach ($array as $result) {
  245. if (!$result) {
  246. return false;
  247. }
  248. }
  249. return true;
  250. }
  251. /**
  252. * returns true if at least one value is true
  253. *
  254. * @param array $array
  255. * @return bool $result
  256. * maybe move to bootstrap?
  257. * 2011-11-02 ms
  258. */
  259. public static function logicalOr($array) {
  260. foreach ($array as $result) {
  261. if ($result) {
  262. return true;
  263. }
  264. }
  265. return false;
  266. }
  267. /**
  268. * On non-transaction db connections it will return a deep array of bools instead of bool
  269. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too
  270. *
  271. * @param array
  272. * @return bool
  273. * 2012-10-12 ms
  274. */
  275. public static function isValidSaveAll($array) {
  276. if (empty($array)) {
  277. return false;
  278. }
  279. $ret = true;
  280. foreach ($array as $key => $val) {
  281. if (is_array($val)) {
  282. $ret = $ret & Utility::logicalAnd($val);
  283. } else {
  284. $ret = $ret & $val;
  285. }
  286. }
  287. return (bool)$ret;
  288. }
  289. /**
  290. * Convenience function for automatic casting in form methods etc
  291. *
  292. * @param mixed $value
  293. * @param string $type
  294. * @return safe value for DB query, or NULL if type was not a valid one
  295. * maybe move to bootstrap?
  296. * 2008-12-12 ms
  297. */
  298. public static function typeCast($value, $type) {
  299. switch ($type) {
  300. case 'int':
  301. $value = (int)$value;
  302. break;
  303. case 'float':
  304. $value = (float)$value;
  305. break;
  306. case 'double':
  307. $value = (double)$value;
  308. break;
  309. case 'array':
  310. $value = (array )$value;
  311. break;
  312. case 'bool':
  313. $value = (bool)$value;
  314. break;
  315. case 'string':
  316. $value = (string )$value;
  317. break;
  318. default:
  319. return null;
  320. }
  321. return $value;
  322. }
  323. /**
  324. * trim recursivly
  325. *
  326. * 2009-07-07 ms
  327. */
  328. public static function trimDeep($value) {
  329. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  330. return $value;
  331. }
  332. /**
  333. * h() recursivly
  334. *
  335. * 2009-07-07 ms
  336. */
  337. public static function specialcharsDeep($value) {
  338. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  339. return $value;
  340. }
  341. /**
  342. * removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  343. *
  344. * 2009-07-07 ms
  345. */
  346. public static function paranoidDeep($value) {
  347. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  348. return $value;
  349. }
  350. /**
  351. * transfers/removes all < > from text (remove TRUE/FALSE)
  352. *
  353. * 2009-07-07 ms
  354. */
  355. public static function htmlDeep($value) {
  356. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  357. return $value;
  358. }
  359. /**
  360. * main deep method
  361. *
  362. * 2009-07-07 ms
  363. */
  364. public static function deep($function, $value) {
  365. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  366. return $value;
  367. }
  368. /**
  369. * Flattens an array
  370. *
  371. * @param array $array to flatten
  372. * @param boolean $perserveKeys
  373. * @return array
  374. * 2011-07-02 ms
  375. */
  376. public static function arrayFlatten($array, $preserveKeys = false) {
  377. if ($preserveKeys) {
  378. return self::_arrayFlatten($array);
  379. }
  380. if (!$array) {
  381. return array();
  382. }
  383. $result = array();
  384. foreach ($array as $key => $value) {
  385. if (is_array($value)) {
  386. $result = array_merge($result, self::arrayFlatten($value));
  387. } else {
  388. $result[$key] = $value;
  389. }
  390. }
  391. return $result;
  392. }
  393. /**
  394. * Flatten an array and preserve the keys
  395. * @return array
  396. */
  397. public static function _arrayFlatten($a, $f = array()) {
  398. if (!$a) {
  399. return array();
  400. }
  401. foreach ($a as $k => $v) {
  402. if (is_array($v)) {
  403. $f = self::_arrayFlatten($v, $f);
  404. } else {
  405. $f[$k] = $v;
  406. }
  407. }
  408. return $f;
  409. }
  410. /**
  411. * Similar to array_shift but on the keys of the array
  412. *
  413. * @param array $keyValuePairs
  414. * @return string $key
  415. * like array_shift() only for keys and not values
  416. * 2011-01-22 ms
  417. */
  418. public static function arrayShiftKeys(&$array) {
  419. foreach ($array as $key => $value) {
  420. unset($array[$key]);
  421. return $key;
  422. }
  423. }
  424. protected static $_counterStartTime;
  425. /**
  426. * returns microtime as float value
  427. * (to be subtracted right away)
  428. *
  429. * @return float
  430. * 2009-07-07 ms
  431. */
  432. public static function microtime($precision = 8) {
  433. return round(microtime(true), $precision);
  434. }
  435. /**
  436. * @return void
  437. * 2009-07-07 ms
  438. */
  439. public static function startClock() {
  440. self::$_counterStartTime = self::microtime();
  441. }
  442. /**
  443. * @return float
  444. * 2009-07-07 ms
  445. */
  446. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  447. $startTime = self::$_counterStartTime;
  448. if ($restartClock) {
  449. self::startClock();
  450. }
  451. return self::calcElapsedTime($startTime, self::microtime(), $precision);
  452. }
  453. /**
  454. * returns microtime as float value
  455. * (to be subtracted right away)
  456. *
  457. * @return float
  458. * 2009-07-07 ms
  459. */
  460. public static function calcElapsedTime($start, $end, $precision = 8) {
  461. $elapsed = $end - $start;
  462. return round($elapsed, $precision);
  463. }
  464. }