Utility.php 8.8 KB

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