PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/Common.php

http://github.com/Xeoncross/micromvc
PHP | 520 lines | 207 code | 80 blank | 233 comment | 17 complexity | b350e08cf7de98f105c6cd1559fd2faf MD5 | raw file
  1. <?php
  2. /**
  3. * Core Bootstrap
  4. *
  5. * This file contains all common system functions and View and Controller classes.
  6. *
  7. * @package MicroMVC
  8. * @author David Pennington
  9. * @copyright (c) 2011 MicroMVC Framework
  10. * @license http://micromvc.com/license
  11. ********************************** 80 Columns *********************************
  12. */
  13. /**
  14. * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
  15. *
  16. * @param string $event name
  17. * @param mixed $value the optional value to pass to each callback
  18. * @param mixed $callback the method or function to call - FALSE to remove all callbacks for event
  19. */
  20. function event($event, $value = NULL, $callback = NULL)
  21. {
  22. static $events;
  23. // Adding or removing a callback?
  24. if($callback !== NULL)
  25. {
  26. if($callback)
  27. {
  28. $events[$event][] = $callback;
  29. }
  30. else
  31. {
  32. unset($events[$event]);
  33. }
  34. }
  35. elseif(isset($events[$event])) // Fire a callback
  36. {
  37. foreach($events[$event] as $function)
  38. {
  39. $value = call_user_func($function, $value);
  40. }
  41. return $value;
  42. }
  43. }
  44. /**
  45. * Fetch a config value from a module configuration file
  46. *
  47. * @param string $file name of the config
  48. * @param boolean $clear to clear the config object
  49. * @return object
  50. */
  51. function config($file = 'Config', $clear = FALSE)
  52. {
  53. static $configs = array();
  54. if($clear)
  55. {
  56. unset($configs[$file]);
  57. return;
  58. }
  59. if(empty($configs[$file]))
  60. {
  61. //$configs[$file] = new \Micro\Config($file);
  62. require(SP . 'Config/' . $file . EXT);
  63. $configs[$file] = (object) $config;
  64. //print dump($configs);
  65. }
  66. return $configs[$file];
  67. }
  68. /**
  69. * Return an HTML safe dump of the given variable(s) surrounded by "pre" tags.
  70. * You can pass any number of variables (of any type) to this function.
  71. *
  72. * @param mixed
  73. * @return string
  74. */
  75. function dump()
  76. {
  77. $string = '';
  78. foreach(func_get_args() as $value)
  79. {
  80. $string .= '<pre>' . h($value === NULL ? 'NULL' : (is_scalar($value) ? $value : print_r($value, TRUE))) . "</pre>\n";
  81. }
  82. return $string;
  83. }
  84. /**
  85. * Safely fetch a $_POST value, defaulting to the value provided if the key is
  86. * not found.
  87. *
  88. * @param string $key name
  89. * @param mixed $default value if key is not found
  90. * @param boolean $string TRUE to require string type
  91. * @return mixed
  92. */
  93. function post($key, $default = NULL, $string = FALSE)
  94. {
  95. if(isset($_POST[$key]))
  96. {
  97. return $string ? (string)$_POST[$key] : $_POST[$key];
  98. }
  99. return $default;
  100. }
  101. /**
  102. * Safely fetch a $_GET value, defaulting to the value provided if the key is
  103. * not found.
  104. *
  105. * @param string $key name
  106. * @param mixed $default value if key is not found
  107. * @param boolean $string TRUE to require string type
  108. * @return mixed
  109. */
  110. function get($key, $default = NULL, $string = FALSE)
  111. {
  112. if(isset($_GET[$key]))
  113. {
  114. return $string ? (string)$_GET[$key] : $_GET[$key];
  115. }
  116. return $default;
  117. }
  118. /**
  119. * Safely fetch a $_SESSION value, defaulting to the value provided if the key is
  120. * not found.
  121. *
  122. * @param string $k the post key
  123. * @param mixed $d the default value if key is not found
  124. * @return mixed
  125. */
  126. function session($k, $d = NULL)
  127. {
  128. return isset($_SESSION[$k]) ? $_SESSION[$k] : $d;
  129. }
  130. /**
  131. * Create a random 32 character MD5 token
  132. *
  133. * @return string
  134. */
  135. function token()
  136. {
  137. return md5(str_shuffle(chr(mt_rand(32, 126)) . uniqid() . microtime(TRUE)));
  138. }
  139. /**
  140. * Write to the application log file using error_log
  141. *
  142. * @param string $message to save
  143. * @return bool
  144. */
  145. function log_message($message)
  146. {
  147. $path = SP . 'Storage/Log/' . date('Y-m-d') . '.log';
  148. // Append date and IP to log message
  149. return error_log(date('H:i:s ') . getenv('REMOTE_ADDR') . " $message\n", 3, $path);
  150. }
  151. /**
  152. * Send a HTTP header redirect using "location" or "refresh".
  153. *
  154. * @param string $url the URL string
  155. * @param int $c the HTTP status code
  156. * @param string $method either location or redirect
  157. */
  158. function redirect($url = NULL, $code = 302, $method = 'location')
  159. {
  160. if(strpos($url, '://') === FALSE)
  161. {
  162. $url = site_url($url);
  163. }
  164. //print dump($url);
  165. header($method == 'refresh' ? "Refresh:0;url = $url" : "Location: $url", TRUE, $code);
  166. }
  167. /*
  168. * Return the full URL to a path on this site or another.
  169. *
  170. * @param string $uri may contain another sites TLD
  171. * @return string
  172. *
  173. function site_url($uri = NULL)
  174. {
  175. return (strpos($uri, '://') === FALSE ? \Micro\URL::get() : '') . ltrim($uri, '/');
  176. }
  177. */
  178. /**
  179. * Return the full URL to a location on this site
  180. *
  181. * @param string $path to use or FALSE for current path
  182. * @param array $params to append to URL
  183. * @return string
  184. */
  185. function site_url($path = NULL, array $params = NULL)
  186. {
  187. // In PHP 5.4, http_build_query will support RFC 3986
  188. return DOMAIN . ($path ? '/'. trim($path, '/') : PATH)
  189. . ($params ? '?'. str_replace('+', '%20', http_build_query($params, TRUE, '&')) : '');
  190. }
  191. /**
  192. * Return the current URL with path and query params
  193. *
  194. * @return string
  195. *
  196. function current_url()
  197. {
  198. return DOMAIN . getenv('REQUEST_URI');
  199. }
  200. */
  201. /**
  202. * Convert a string from one encoding to another encoding
  203. * and remove invalid bytes sequences.
  204. *
  205. * @param string $string to convert
  206. * @param string $to encoding you want the string in
  207. * @param string $from encoding that string is in
  208. * @return string
  209. */
  210. function encode($string, $to = 'UTF-8', $from = 'UTF-8')
  211. {
  212. // ASCII is already valid UTF-8
  213. if($to == 'UTF-8' AND is_ascii($string))
  214. {
  215. return $string;
  216. }
  217. // Convert the string
  218. return @iconv($from, $to . '//TRANSLIT//IGNORE', $string);
  219. }
  220. /**
  221. * Tests whether a string contains only 7bit ASCII characters.
  222. *
  223. * @param string $string to check
  224. * @return bool
  225. */
  226. function is_ascii($string)
  227. {
  228. return ! preg_match('/[^\x00-\x7F]/S', $string);
  229. }
  230. /**
  231. * Encode a string so it is safe to pass through the URL
  232. *
  233. * @param string $string to encode
  234. * @return string
  235. */
  236. function base64_url_encode($string = NULL)
  237. {
  238. return strtr(base64_encode($string), '+/=', '-_~');
  239. }
  240. /**
  241. * Decode a string passed through the URL
  242. *
  243. * @param string $string to decode
  244. * @return string
  245. */
  246. function base64_url_decode($string = NULL)
  247. {
  248. return base64_decode(strtr($string, '-_~', '+/='));
  249. }
  250. /**
  251. * Convert special characters to HTML safe entities.
  252. *
  253. * @param string $string to encode
  254. * @return string
  255. */
  256. function h($string)
  257. {
  258. return htmlspecialchars($string, ENT_QUOTES, 'utf-8');
  259. }
  260. /**
  261. * Filter a valid UTF-8 string so that it contains only words, numbers,
  262. * dashes, underscores, periods, and spaces - all of which are safe
  263. * characters to use in file names, URI, XML, JSON, and (X)HTML.
  264. *
  265. * @param string $string to clean
  266. * @param bool $spaces TRUE to allow spaces
  267. * @return string
  268. */
  269. function sanitize($string, $spaces = TRUE)
  270. {
  271. $search = array(
  272. '/[^\w\-\. ]+/u', // Remove non safe characters
  273. '/\s\s+/', // Remove extra whitespace
  274. '/\.\.+/', '/--+/', '/__+/' // Remove duplicate symbols
  275. );
  276. $string = preg_replace($search, array(' ', ' ', '.', '-', '_'), $string);
  277. if( ! $spaces)
  278. {
  279. $string = preg_replace('/--+/', '-', str_replace(' ', '-', $string));
  280. }
  281. return trim($string, '-._ ');
  282. }
  283. /**
  284. * Create a SEO friendly URL string from a valid UTF-8 string.
  285. *
  286. * @param string $string to filter
  287. * @return string
  288. */
  289. function sanitize_url($string)
  290. {
  291. return urlencode(mb_strtolower(sanitize($string, FALSE)));
  292. }
  293. /**
  294. * Filter a valid UTF-8 string to be file name safe.
  295. *
  296. * @param string $string to filter
  297. * @return string
  298. */
  299. function sanitize_filename($string)
  300. {
  301. return sanitize($string, FALSE);
  302. }
  303. /**
  304. * Return a SQLite/MySQL/PostgreSQL datetime string
  305. *
  306. * @param int $timestamp
  307. */
  308. function sql_date($timestamp = NULL)
  309. {
  310. return date('Y-m-d H:i:s', $timestamp ?: time());
  311. }
  312. /**
  313. * Make a request to the given URL using cURL.
  314. *
  315. * @param string $url to request
  316. * @param array $options for cURL object
  317. * @return object
  318. */
  319. function curl_request($url, array $options = NULL)
  320. {
  321. $ch = curl_init($url);
  322. $defaults = array(
  323. CURLOPT_HEADER => 0,
  324. CURLOPT_RETURNTRANSFER => 1,
  325. CURLOPT_TIMEOUT => 5,
  326. );
  327. // Connection options override defaults if given
  328. curl_setopt_array($ch, (array) $options + $defaults);
  329. // Create a response object
  330. $object = new stdClass;
  331. // Get additional request info
  332. $object->response = curl_exec($ch);
  333. $object->error_code = curl_errno($ch);
  334. $object->error = curl_error($ch);
  335. $object->info = curl_getinfo($ch);
  336. curl_close($ch);
  337. return $object;
  338. }
  339. /**
  340. * Create a RecursiveDirectoryIterator object
  341. *
  342. * @param string $dir the directory to load
  343. * @param boolean $recursive to include subfolders
  344. * @return object
  345. */
  346. function directory($dir, $recursive = TRUE)
  347. {
  348. $i = new \RecursiveDirectoryIterator($dir);
  349. if( ! $recursive) return $i;
  350. return new \RecursiveIteratorIterator($i, \RecursiveIteratorIterator::SELF_FIRST);
  351. }
  352. /**
  353. * Make sure that a directory exists and is writable by the current PHP process.
  354. *
  355. * @param string $dir the directory to load
  356. * @param string $chmod value as octal
  357. * @return boolean
  358. */
  359. function directory_is_writable($dir, $chmod = 0755)
  360. {
  361. // If it doesn't exist, and can't be made
  362. if(! is_dir($dir) AND ! mkdir($dir, $chmod, TRUE)) return FALSE;
  363. // If it isn't writable, and can't be made writable
  364. if(! is_writable($dir) AND !chmod($dir, $chmod)) return FALSE;
  365. return TRUE;
  366. }
  367. /**
  368. * Convert any given variable into a SimpleXML object
  369. *
  370. * @param mixed $object variable object to convert
  371. * @param string $root root element name
  372. * @param object $xml xml object
  373. * @param string $unknown element name for numeric keys
  374. * @param string $doctype XML doctype
  375. */
  376. function to_xml($object, $root = 'data', $xml = NULL, $unknown = 'element', $doctype = "<?xml version = '1.0' encoding = 'utf-8'?>")
  377. {
  378. if(is_null($xml))
  379. {
  380. $xml = simplexml_load_string("$doctype<$root/>");
  381. }
  382. foreach((array) $object as $k => $v)
  383. {
  384. if(is_int($k))
  385. {
  386. $k = $unknown;
  387. }
  388. if(is_scalar($v))
  389. {
  390. $xml->addChild($k, h($v));
  391. }
  392. else
  393. {
  394. $v = (array) $v;
  395. $node = array_diff_key($v, array_keys(array_keys($v))) ? $xml->addChild($k) : $xml;
  396. self::from($v, $k, $node);
  397. }
  398. }
  399. return $xml;
  400. }
  401. /**
  402. * Return an IntlDateFormatter object using the current system locale
  403. *
  404. * @param string $locale string
  405. * @param integer $datetype IntlDateFormatter constant
  406. * @param integer $timetype IntlDateFormatter constant
  407. * @param string $timezone Time zone ID, default is system default
  408. * @return IntlDateFormatter
  409. */
  410. function __date($locale = NULL, $datetype = IntlDateFormatter::MEDIUM, $timetype = IntlDateFormatter::SHORT, $timezone = NULL)
  411. {
  412. return new IntlDateFormatter($locale ?: setlocale(LC_ALL, 0), $datetype, $timetype, $timezone);
  413. }
  414. /**
  415. * Format the given string using the current system locale
  416. * Basically, it's sprintf on i18n steroids.
  417. *
  418. * @param string $string to parse
  419. * @param array $params to insert
  420. * @return string
  421. */
  422. function __($string, array $params = NULL)
  423. {
  424. return msgfmt_format_message(setlocale(LC_ALL, 0), $string, $params);
  425. }
  426. /**
  427. * Color output text for the CLI
  428. *
  429. * @param string $text to color
  430. * @param string $color of text
  431. * @param string $background color
  432. */
  433. function colorize($text, $color, $bold = FALSE)
  434. {
  435. // Standard CLI colors
  436. $colors = array_flip(array(30 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'black'));
  437. // Escape string with color information
  438. return"\033[" . ($bold ? '1' : '0') . ';' . $colors[$color] . "m$text\033[0m";
  439. }
  440. // End