Utility.php 12 KB

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