Utility.php 12 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. */
  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. $space_key = null;
  84. $c = mb_strlen($str);
  85. for ($i = 0; $i < $c; $i += $length) {
  86. $result[] = mb_substr($str, $i, $length);
  87. }
  88. return $result;
  89. }
  90. /**
  91. * Get the current IP address.
  92. *
  93. * @param boolean $safe
  94. * @return string IP address
  95. */
  96. public static function getClientIp($safe = true) {
  97. if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
  98. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  99. } else {
  100. if (env('HTTP_CLIENT_IP')) {
  101. $ipaddr = env('HTTP_CLIENT_IP');
  102. } else {
  103. $ipaddr = env('REMOTE_ADDR');
  104. }
  105. }
  106. if (env('HTTP_CLIENTADDRESS')) {
  107. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  108. if (!empty($tmpipaddr)) {
  109. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  110. }
  111. }
  112. return trim($ipaddr);
  113. }
  114. /**
  115. * Get the current referrer if available.
  116. *
  117. * @param boolean $full (defaults to false and leaves the url untouched)
  118. * @return string referer (local or foreign)
  119. */
  120. public static function getReferer($full = false) {
  121. $ref = env('HTTP_REFERER');
  122. $forwarded = env('HTTP_X_FORWARDED_HOST');
  123. if ($forwarded) {
  124. $ref = $forwarded;
  125. }
  126. if (empty($ref)) {
  127. return $ref;
  128. }
  129. if ($full) {
  130. $ref = Router::url($ref, $full);
  131. }
  132. return $ref;
  133. }
  134. /**
  135. * Remove unnessary stuff + add http:// for external urls
  136. * TODO: protocol to lower!
  137. *
  138. * @param string $url
  139. * @return string Cleaned Url
  140. */
  141. public static function cleanUrl($url, $headerRedirect = false) {
  142. if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
  143. $url = '';
  144. } else {
  145. $url = self::autoPrefixUrl($url, 'http://');
  146. }
  147. if ($headerRedirect && !empty($url)) {
  148. $headers = self::getHeaderFromUrl($url);
  149. if ($headers !== false) {
  150. $headerString = implode("\n", $headers);
  151. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  152. foreach ($headers as $header) {
  153. if (mb_strpos($header, 'Location:') === 0) {
  154. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  155. }
  156. }
  157. }
  158. }
  159. }
  160. $length = mb_strlen($url);
  161. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  162. $url = mb_substr($url, 0, $length - 1);
  163. $length--;
  164. }
  165. return $url;
  166. }
  167. /**
  168. * Parse headers from a specific URL content.
  169. *
  170. * @param string $url
  171. * @return mixed array of headers or FALSE on failure
  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. $defaults = array(
  186. 'http' => array(
  187. 'header' => "Accept: text/html\r\n" .
  188. "Connection: Close\r\n" .
  189. "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
  190. )
  191. );
  192. stream_context_get_default($defaults);
  193. if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
  194. $url = "$url[scheme]://$url[host]$url[port]$path";
  195. $headers = get_headers($url);
  196. if (is_array($headers)) {
  197. return $headers;
  198. }
  199. }
  200. return false;
  201. }
  202. /**
  203. * Add protocol prefix if necessary (and possible)
  204. *
  205. * @param string $url
  206. */
  207. public static function autoPrefixUrl($url, $prefix = null) {
  208. if ($prefix === null) {
  209. $prefix = 'http://';
  210. }
  211. if (($pos = strpos($url, '.')) !== false) {
  212. if (strpos(substr($url, 0, $pos), '//') === false) {
  213. $url = $prefix . $url;
  214. }
  215. }
  216. return $url;
  217. }
  218. /**
  219. * Encode strings with base64_encode and also
  220. * replace chars base64 uses that would mess up the url.
  221. *
  222. * Do not use this for querystrings. Those will escape automatically.
  223. * This is only useful for named or passed params.
  224. *
  225. * @param string $string Unsafe string
  226. * @return string Encoded string
  227. */
  228. public static function urlEncode($string) {
  229. return str_replace(array('/', '='), array('-', '_'), base64_encode($string));
  230. }
  231. /**
  232. * Decode strings with base64_encode and also
  233. * replace back chars base64 uses that would mess up the url.
  234. *
  235. * Do not use this for querystrings. Those will escape automatically.
  236. * This is only useful for named or passed params.
  237. *
  238. * @param string $string Safe string
  239. * @return string Decoded string
  240. */
  241. public static function urlDecode($string) {
  242. return base64_decode(str_replace(array('-', '_'), array('/', '='), $string));
  243. }
  244. /**
  245. * Returns true only if all values are true.
  246. * //TODO: maybe move to bootstrap?
  247. *
  248. * @param array $array
  249. * @return boolean Result
  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 boolean Result
  268. *
  269. */
  270. public static function logicalOr($array) {
  271. foreach ($array as $result) {
  272. if ($result) {
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. /**
  279. * On non-transaction db connections it will return a deep array of bools instead of bool.
  280. * So we need to call this method inside the modified saveAll() method to return the expected single bool there, too.
  281. *
  282. * @param array
  283. * @return boolean
  284. */
  285. public static function isValidSaveAll($array) {
  286. if (empty($array)) {
  287. return false;
  288. }
  289. $ret = true;
  290. foreach ($array as $key => $val) {
  291. if (is_array($val)) {
  292. $ret = $ret & Utility::logicalAnd($val);
  293. } else {
  294. $ret = $ret & $val;
  295. }
  296. }
  297. return (bool)$ret;
  298. }
  299. /**
  300. * Convenience function for automatic casting in form methods etc.
  301. * //TODO: maybe move to bootstrap?
  302. *
  303. * @param mixed $value
  304. * @param string $type
  305. * @return safe value for DB query, or NULL if type was not a valid one
  306. */
  307. public static function typeCast($value, $type) {
  308. switch ($type) {
  309. case 'int':
  310. $value = (int)$value;
  311. break;
  312. case 'float':
  313. $value = (float)$value;
  314. break;
  315. case 'double':
  316. $value = (double)$value;
  317. break;
  318. case 'array':
  319. $value = (array )$value;
  320. break;
  321. case 'bool':
  322. $value = (bool)$value;
  323. break;
  324. case 'string':
  325. $value = (string )$value;
  326. break;
  327. default:
  328. return null;
  329. }
  330. return $value;
  331. }
  332. /**
  333. * Trim recursivly
  334. *
  335. */
  336. public static function trimDeep($value) {
  337. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  338. return $value;
  339. }
  340. /**
  341. * h() recursivly
  342. *
  343. */
  344. public static function specialcharsDeep($value) {
  345. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  346. return $value;
  347. }
  348. /**
  349. * Removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  350. *
  351. */
  352. public static function paranoidDeep($value) {
  353. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  354. return $value;
  355. }
  356. /**
  357. * Transfers/removes all < > from text (remove TRUE/FALSE)
  358. *
  359. */
  360. public static function htmlDeep($value) {
  361. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  362. return $value;
  363. }
  364. /**
  365. * Main deep method
  366. *
  367. */
  368. public static function deep($function, $value) {
  369. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  370. return $value;
  371. }
  372. /**
  373. * Flattens an array.
  374. *
  375. * @param array $array to flatten
  376. * @param boolean $perserveKeys
  377. * @return array
  378. */
  379. public static function arrayFlatten($array, $preserveKeys = false) {
  380. if ($preserveKeys) {
  381. return self::_arrayFlatten($array);
  382. }
  383. if (!$array) {
  384. return array();
  385. }
  386. $result = array();
  387. foreach ($array as $key => $value) {
  388. if (is_array($value)) {
  389. $result = array_merge($result, self::arrayFlatten($value));
  390. } else {
  391. $result[$key] = $value;
  392. }
  393. }
  394. return $result;
  395. }
  396. /**
  397. * Flatten an array and preserve the keys
  398. *
  399. * @return array
  400. */
  401. protected static function _arrayFlatten($a, $f = array()) {
  402. if (!$a) {
  403. return array();
  404. }
  405. foreach ($a as $k => $v) {
  406. if (is_array($v)) {
  407. $f = self::_arrayFlatten($v, $f);
  408. } else {
  409. $f[$k] = $v;
  410. }
  411. }
  412. return $f;
  413. }
  414. /**
  415. * Similar to array_shift but on the keys of the array
  416. * like array_shift() only for keys and not values
  417. *
  418. * @param array $keyValuePairs
  419. * @return string key
  420. */
  421. public static function arrayShiftKeys(&$array) {
  422. foreach ($array as $key => $value) {
  423. unset($array[$key]);
  424. return $key;
  425. }
  426. }
  427. protected static $_counterStartTime;
  428. /**
  429. * Returns microtime as float value
  430. * (to be subtracted right away)
  431. *
  432. * @return float
  433. */
  434. public static function microtime($precision = 8) {
  435. return round(microtime(true), $precision);
  436. }
  437. /**
  438. * @return void
  439. */
  440. public static function startClock() {
  441. self::$_counterStartTime = self::microtime();
  442. }
  443. /**
  444. * @return float
  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. */
  459. public static function calcElapsedTime($start, $end, $precision = 8) {
  460. $elapsed = $end - $start;
  461. return round($elapsed, $precision);
  462. }
  463. }