Utility.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. * @static
  63. * 2009-12-22 ms
  64. */
  65. public static function cleanUrl($url, $headerRedirect = false) {
  66. if ($url == '' || $url == 'http://' || $url == 'http://www' || $url == 'http://www.') {
  67. $url = '';
  68. } else {
  69. $url = self::autoPrefixUrl($url, 'http://');
  70. }
  71. if ($headerRedirect && !empty($url)) {
  72. $headers = self::getHeaderFromUrl($url);
  73. if ($headers !== false) {
  74. $headerString = implode("\n", $headers);
  75. if ((bool)preg_match('#^HTTP/.*\s+[(301)]+\s#i', $headerString)) {
  76. foreach ($headers as $header) {
  77. if (mb_strpos($header, 'Location:') === 0) {
  78. $url = trim(hDec(mb_substr($header, 9))); // rawurldecode/urldecode ?
  79. }
  80. }
  81. }
  82. }
  83. }
  84. $length = mb_strlen($url);
  85. while (!empty($url) && mb_strrpos($url, '/') === $length - 1) {
  86. $url = mb_substr($url, 0, $length - 1);
  87. $length--;
  88. }
  89. return $url;
  90. }
  91. /**
  92. * @static
  93. * 2009-12-26 ms
  94. */
  95. public static function getHeaderFromUrl($url) {
  96. $url = @parse_url($url);
  97. if (empty($url)) {
  98. return false;
  99. }
  100. $url = array_map('trim', $url);
  101. $url['port'] = (!isset($url['port']))?80 : (int)$url['port'];
  102. $path = (isset($url['path']))?$url['path'] : '';
  103. if (empty($path)) {
  104. $path = '/';
  105. }
  106. $path .= (isset($url['query']))?"?$url[query]" : '';
  107. if (isset($url['host']) && $url['host'] != gethostbyname($url['host'])) {
  108. $headers = @get_headers("$url[scheme]://$url[host]:$url[port]$path");
  109. return (is_array($headers)?$headers : false);
  110. }
  111. return false;
  112. }
  113. /**
  114. * add protocol prefix if neccessary (and possible)
  115. * static?
  116. * 2010-06-02 ms
  117. */
  118. public function autoPrefixUrl($url, $prefix = null) {
  119. if ($prefix === null) {
  120. $prefix = 'http://';
  121. }
  122. if (($pos = strpos($url, '.')) !== false) {
  123. if (strpos(substr($url, 0, $pos), '//') === false) {
  124. $url = $prefix.$url;
  125. }
  126. }
  127. return $url;
  128. }
  129. /**
  130. * returns true only if all values are true
  131. * @return bool $result
  132. * maybe move to bootstrap?
  133. * 2011-11-02 ms
  134. */
  135. public static function logicalAnd($array) {
  136. if (empty($array)) {
  137. return false;
  138. }
  139. foreach ($array as $result) {
  140. if (!$result) {
  141. return false;
  142. }
  143. }
  144. return true;
  145. }
  146. /**
  147. * returns true if at least one value is true
  148. * @return bool $result
  149. * maybe move to bootstrap?
  150. * 2011-11-02 ms
  151. */
  152. public static function logicalOr($array) {
  153. foreach ($array as $result) {
  154. if ($result) {
  155. return true;
  156. }
  157. }
  158. return false;
  159. }
  160. /**
  161. * convinience function for automatic casting in form methods etc
  162. * @return safe value for DB query, or NULL if type was not a valid one
  163. * @static
  164. * maybe move to bootstrap?
  165. * 2008-12-12 ms
  166. */
  167. public static function typeCast($value, $type) {
  168. switch ($type) {
  169. case 'int':
  170. $value = (int)$value;
  171. break;
  172. case 'float':
  173. $value = (float)$value;
  174. break;
  175. case 'double':
  176. $value = (double)$value;
  177. break;
  178. case 'array':
  179. $value = (array )$value;
  180. break;
  181. case 'bool':
  182. $value = (bool)$value;
  183. break;
  184. case 'string':
  185. $value = (string )$value;
  186. break;
  187. default:
  188. return null;
  189. }
  190. return $value;
  191. }
  192. /**
  193. * trim recursivly
  194. *
  195. * 2009-07-07 ms
  196. */
  197. public static function trimDeep($value) {
  198. $value = is_array($value) ? array_map('self::trimDeep', $value) : trim($value);
  199. return $value;
  200. }
  201. /**
  202. * h() recursivly
  203. *
  204. * 2009-07-07 ms
  205. */
  206. public static function specialcharsDeep($value) {
  207. $value = is_array($value) ? array_map('self::specialcharsDeep', $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  208. return $value;
  209. }
  210. /**
  211. * removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array) recursivly
  212. *
  213. * 2009-07-07 ms
  214. */
  215. public static function paranoidDeep($value) {
  216. $value = is_array($value) ? array_map('self::paranoidDeep', $value) : Sanatize::paranoid($value, $this->allowedChars);
  217. return $value;
  218. }
  219. /**
  220. * transfers/removes all < > from text (remove TRUE/FALSE)
  221. *
  222. * 2009-07-07 ms
  223. */
  224. public static function htmlDeep($value) {
  225. $value = is_array($value) ? array_map('self::htmlDeep', $value) : Sanatize::html($value, $this->removeChars);
  226. return $value;
  227. }
  228. /**
  229. * main deep method
  230. *
  231. * 2009-07-07 ms
  232. */
  233. public static function deep($function, $value) {
  234. $value = is_array($value) ? array_map('self::' . $function, $value) : $function($value);
  235. return $value;
  236. }
  237. /**
  238. * Flattens an array, or returns FALSE on fail.
  239. * 2011-07-02 ms
  240. */
  241. public static function arrayFlatten($array) {
  242. if (!is_array($array)) {
  243. return false;
  244. }
  245. $result = array();
  246. foreach ($array as $key => $value) {
  247. if (is_array($value)) {
  248. $result = array_merge($result, self::arrayFlatten($value));
  249. } else {
  250. $result[$key] = $value;
  251. }
  252. }
  253. return $result;
  254. }
  255. /**
  256. * @param array $keyValuePairs
  257. * @return string $key
  258. * like array_shift() only for keys and not values
  259. * 2011-01-22 ms
  260. */
  261. public static function arrayShiftKeys(&$array) {
  262. foreach ($array as $key => $value) {
  263. unset($array[$key]);
  264. return $key;
  265. }
  266. }
  267. protected static $_counterStartTime;
  268. /**
  269. * returns microtime as float value
  270. * (to be subtracted right away)
  271. * @static
  272. * 2009-07-07 ms
  273. */
  274. public static function microtime($precision = 8) {
  275. return round(microtime(true), $precision);
  276. }
  277. /**
  278. * @return void
  279. * 2009-07-07 ms
  280. */
  281. public static function startClock() {
  282. self::$_counterStartTime = self::microtime();
  283. }
  284. /**
  285. * @static
  286. * 2009-07-07 ms
  287. */
  288. public static function returnElapsedTime($precision = 8, $restartClock = false) {
  289. $startTime = self::$_counterStartTime;
  290. if ($restartClock) {
  291. self::startClock();
  292. }
  293. return self::calcElapsedTime($startTime, self::microtime(), $precision);
  294. }
  295. /**
  296. * returns microtime as float value
  297. * (to be subtracted right away)
  298. * @static
  299. * 2009-07-07 ms
  300. */
  301. public static function calcElapsedTime($start, $end, $precision = 8) {
  302. $elapsed = $end - $start;
  303. return round($elapsed, $precision);
  304. }
  305. }