Utility.php 7.3 KB

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