Utility.php 11 KB

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