Utility.php 12 KB

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