PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/bootstrap.php

https://github.com/agilehands/micromvc
PHP | 466 lines | 140 code | 71 blank | 255 comment | 5 complexity | 643ced57473594ea16b893bc32034077 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. * @packageMicroMVC
  8. * @authorDavid Pennington
  9. * @copyright(c) 2010 MicroMVC Framework
  10. * @licensehttp://micromvc.com/license
  11. ********************************** 80 Columns *********************************
  12. */
  13. /**
  14. * Record memory usage and timestamp and then return difference next run (and restart)
  15. *
  16. * @return array
  17. */
  18. function benchmark()
  19. {
  20. static$t,$m;$a=array((microtime(true)-$t),(memory_get_usage()-$m));$t=microtime(true);$m=memory_get_usage();return$a;
  21. }
  22. /**
  23. * System registry object for storing global values
  24. *
  25. * @param string $k the object name
  26. * @param mixed $v the object value
  27. * @return mixed
  28. */
  29. function registry($k,$v=null)
  30. {
  31. static$o;return(func_num_args()>1?$o[$k]=$v:(isset($o[$k])?$o[$k]:NULL));
  32. }
  33. /**
  34. * Set a message to show to the user (error, warning, success, or message).
  35. *
  36. * @param string $type of message
  37. * @param string $v the message to store
  38. */
  39. function message($type = NULL, $v = NULL)
  40. {
  41. static$m=array();$h='';if($v)$m[$type][]=$v;elseif($type){if(isset($m[$type]))foreach($m[$type] as$v)$h.="<div class=\"$type\">$v</div>";}else foreach($m as$t=>$d)foreach($d as$v)$h.="<div class=\"$t\">$v</div>";return$h;
  42. }
  43. /**
  44. * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
  45. *
  46. * @param string $k the name of the event to run
  47. * @param mixed $v the optional value to pass to each callback
  48. * @param mixed $callback the method or function to call - FALSE to remove all callbacks for event
  49. */
  50. function event($k, $v = NULL, $callback = NULL)
  51. {
  52. static$e;if($callback!==NULL)if($callback)$e[$k][]=$callback;else unset($e[$k]);elseif(isset($e[$k]))foreach($e[$k]as$f)$v=call_user_func($f,$v);return$v;
  53. }
  54. /**
  55. * Fetch a config value
  56. *
  57. * @param string $k the language key name
  58. * @param string $m the module name
  59. * @return string
  60. */
  61. function config($k,$m='system')
  62. {
  63. static $c;$c[$m]=empty($c[$m])?require(SP.($m!='system'?"$m/":'').'config'.EXT):$c[$m];return($k?$c[$m][$k]:$c[$m]);
  64. }
  65. /**
  66. * Fetch the language text for the given line.
  67. *
  68. * @param string $k the language key name
  69. * @param string $m the module name
  70. * @return string
  71. */
  72. function lang($k,$m='system')
  73. {
  74. return lang::get($k,$m);
  75. }
  76. /**
  77. * Returns the current URL path string (if valid)
  78. * PHP before 5.3.3 throws E_WARNING for bad uri in parse_url()
  79. *
  80. * @param int $k the key of URL segment to return
  81. * @param mixed $d the default if the segment isn't found
  82. * @return string
  83. */
  84. function url($k = NULL, $d = NULL)
  85. {
  86. static$s;if(!$s){foreach(array('REQUEST_URI','PATH_INFO','ORIG_PATH_INFO')as$v){preg_match('/^\/[\w\-~\/\.+%]{1,600}/',server($v),$p);if(!empty($p)){$s=explode('/',trim($p[0],'/'));break;}}}if($s)return($k!==NULL?(isset($s[$k])?$s[$k]:$d):implode('/',$s));
  87. }
  88. /**
  89. * Automatically load the given class
  90. *
  91. * @param string $class name
  92. */
  93. function __autoload($class)
  94. {
  95. require(SP.mb_strtolower((strpos($class,'_')===FALSE?'system/':'').str_replace('_','/',$class.EXT)));
  96. }
  97. /**
  98. * Return an HTML safe dump of the given variable(s) surrounded by "pre" tags.
  99. * You can pass any number of variables (of any type) to this function.
  100. *
  101. * @param mixed
  102. * @return string
  103. */
  104. function dump()
  105. {
  106. $s='';foreach(func_get_args()as$v){$s.='<pre>'.h($v===NULL?'NULL':(is_scalar($v)?$v:print_r($v,1)))."</pre>\n";}return$s;
  107. }
  108. /**
  109. * Safely get a value or return default if not set
  110. *
  111. * @param mixed $v value to get
  112. * @param mixed $d default if value is not set
  113. * @return mixed
  114. */
  115. function v(&$v, $d = NULL)
  116. {
  117. return isset($v)?$v:$d;
  118. }
  119. /**
  120. * Safely fetch a $_POST value, defaulting to the value provided if the key is
  121. * not found.
  122. *
  123. * @param string $k the key name
  124. * @param mixed $d the default value if key is not found
  125. * @param boolean $s true to require string type
  126. * @return mixed
  127. */
  128. function post($k, $d = NULL, $s = FALSE)
  129. {
  130. if(isset($_POST[$k]))return$s?str($_POST[$k],$d):$_POST[$k];return$d;
  131. }
  132. /**
  133. * Safely fetch a $_GET value, defaulting to the value provided if the key is
  134. * not found.
  135. *
  136. * @param string $k the key name
  137. * @param mixed $d the default value if key is not found
  138. * @param boolean $s true to require string type
  139. * @return mixed
  140. */
  141. function get($k, $d = NULL, $s = FALSE)
  142. {
  143. if(isset($_GET[$k]))return$s?str($_GET[$k],$d):$_GET[$k];return$d;
  144. }
  145. /**
  146. * Safely fetch a $_SERVER value, defaulting to the value provided if the key is
  147. * not found.
  148. *
  149. * @param string $k the key name
  150. * @param mixed $d the default value if key is not found
  151. * @return mixed
  152. */
  153. function server($k, $d = NULL)
  154. {
  155. return isset($_SERVER[$k])?$_SERVER[$k]:$d;
  156. }
  157. /**
  158. * Safely fetch a $_SESSION value, defaulting to the value provided if the key is
  159. * not found.
  160. *
  161. * @param string $k the post key
  162. * @param mixed $d the default value if key is not found
  163. * @return mixed
  164. */
  165. function session($k, $d = NULL)
  166. {
  167. return isset($_SESSION[$k])?$_SESSION[$k]:$d;
  168. }
  169. /**
  170. * Create a random 32 character MD5 token
  171. *
  172. * @return string
  173. */
  174. function token()
  175. {
  176. return md5(str_shuffle(chr(mt_rand(32, 126)).uniqid().microtime(TRUE)));
  177. }
  178. /**
  179. * Write to the log file
  180. *
  181. * @param string $m the message to save
  182. * @return bool
  183. */
  184. function log_message($m)
  185. {
  186. if(!$fp=@fopen(SP.config('log_path').date('Y-m-d').'.log','a'))return 0;$m=date('H:i:s ').h(server('REMOTE_ADDR'))." $m\n";flock($fp,LOCK_EX);fwrite($fp,$m);flock($fp,LOCK_UN);fclose($fp);return 1;
  187. }
  188. /**
  189. * Send a HTTP header redirect using "location" or "refresh".
  190. *
  191. * @param string $uri the URI string
  192. * @param int $c the HTTP status code
  193. * @param string $method either location or redirect
  194. */
  195. function redirect($u='',$c=302,$m='location')
  196. {
  197. $u=site_url($u);header($m=='refresh'?"Refresh:0;url=$u":"Location: $u",TRUE,$c);
  198. }
  199. /**
  200. * Type cast a scalar variable into an a valid integer between the given min/max values.
  201. * If the value is not a valid numeric value then min will be returned.
  202. *
  203. * @param int $int the value to convert
  204. * @param int $default the default value to assign
  205. * @param int $min the lowest value allowed
  206. * @return int|null
  207. */
  208. function int($int, $min = NULL, $max = NULL)
  209. {
  210. $i=is_numeric($int)?(int)$int:$min;if($min!==NULL&&$i<$min)$i=$min;if($max!==NULL&&$i>$max)$i=$max;return$i;
  211. }
  212. /**
  213. * Type cast the given variable into a string - on fail return default.
  214. *
  215. * @param mixed $string the value to convert
  216. * @param string $default the default value to assign
  217. * @return string
  218. */
  219. function str($str, $default = '')
  220. {
  221. return(is_scalar($str)?(string)$str:$default);
  222. }
  223. /**
  224. * Return the full URL to a path on this site or another.
  225. *
  226. * @param string $uri may contain another sites TLD
  227. * @return string
  228. */
  229. function site_url($uri = NULL)
  230. {
  231. return (strpos($uri,'://')===FALSE?DOMAIN.'/':'').$uri;
  232. }
  233. /**
  234. * Return the full URL to the theme folder
  235. *
  236. * @param string $uri
  237. * @return string
  238. */
  239. function theme_url($uri = NULL)
  240. {
  241. return site_url(config('theme').'/'. $uri);
  242. }
  243. /**
  244. * Return the full URL to a module view file
  245. *
  246. * @param string $uri
  247. * @return string
  248. *
  249. function module_url($uri, $module)
  250. {
  251. return site_url("$module/view/$uri");
  252. }
  253. */
  254. /**
  255. * Convert a string from one encoding to another encoding
  256. * and remove invalid bytes sequences.
  257. *
  258. * @param string $string to convert
  259. * @param string $to encoding you want the string in
  260. * @param string $from encoding that string is in
  261. * @return string
  262. */
  263. function encode($string,$to='UTF-8',$from='UTF-8')
  264. {
  265. return$to==='UTF-8'&&is_ascii($string)?$string:@iconv($from,$to.'//TRANSLIT//IGNORE',$string);
  266. }
  267. /**
  268. * Tests whether a string contains only 7bit ASCII characters.
  269. *
  270. * @param string $string to check
  271. * @return bool
  272. */
  273. function is_ascii($string)
  274. {
  275. return!preg_match('/[^\x00-\x7F]/S',$string);
  276. }
  277. /**
  278. * Encode a string so it is safe to pass through the URI
  279. *
  280. * @param string $string to encode
  281. * @return string
  282. */
  283. function base64_url_encode($string = NULL)
  284. {
  285. return strtr(base64_encode($string),'+/=','-_~');
  286. }
  287. /**
  288. * Decode a string passed through the URI
  289. *
  290. * @param string $string to encode
  291. * @return string
  292. */
  293. function base64_url_decode($string = NULL)
  294. {
  295. return base64_decode(strtr($string,'-_~','+/='));
  296. }
  297. /**
  298. * Convert special characters to HTML safe entities.
  299. *
  300. * @param string $str the string to encode
  301. * @return string
  302. */
  303. function h($data)
  304. {
  305. return htmlspecialchars($data,ENT_QUOTES,'utf-8');
  306. }
  307. /**
  308. * Checks that the given IP address is not a bad bot listed in the Http:BL
  309. *
  310. * @see http://www.projecthoneypot.org/
  311. * @param string $ip address (IP4 only!)
  312. * @param string $key Http:BL API key
  313. * @param integer $threat_level bettween 0 and 255
  314. * @param integer $max_age number of days since last activity
  315. */
  316. function bad_bot($ip, $key, $threat_level = 20, $max_age = 30)
  317. {
  318. if($ip=='127.0.0.1')return;$ip=implode('.',array_reverse(explode('.',$ip)));if($ip=gethostbyname("$key.$ip.dnsbl.httpbl.org")){$ip=explode('.',$ip);return$ip[0]==127&&$ip[3]&&$ip[2]>=$threat_level&&$ip[1]<=$max_age;}
  319. }
  320. /** USE TIME CLASS
  321. * Return a SQLite/MySQL/PostgreSQL datetime string
  322. *
  323. * @param int $t timestamp
  324. *
  325. function sql_date($t = NULL)
  326. {
  327. return date('Y-m-d H:i:s',$t?$t:time());
  328. }
  329. */
  330. /*
  331. * Core Classes
  332. */
  333. /**
  334. * Controller Class
  335. */
  336. class Controller
  337. {
  338. public $template = 'layout';
  339. /**
  340. * Override PHP's default error handling if in debug mode
  341. */
  342. public function __construct()
  343. {
  344. if(config('debug_mode')){set_error_handler(array('error','handler'));register_shutdown_function(array('error','fatal'));set_exception_handler(array('error','exception'));}
  345. }
  346. /**
  347. * Show a 404 error page
  348. */
  349. public function show_404()
  350. {
  351. headers_sent()||header('HTTP/1.0 404 Page Not Found');$this->content=new View('404');
  352. }
  353. /**
  354. * Render the final layout template
  355. */
  356. public function render()
  357. {
  358. headers_sent()||header('Content-Type: text/html; charset=utf-8');$l=new View($this->template);$l->set((array)$this);print$l;$l=0;if(config('debug_mode'))print new View('debug','system');
  359. }
  360. }
  361. /**
  362. * View Class
  363. * @author http://github.com/tweetmvc/tweetmvc-app
  364. */
  365. class View
  366. {
  367. /**
  368. * Returns a new view object for the given view.
  369. *
  370. * @param string $f the view file to load
  371. * @param string $m the module name (blank for current theme)
  372. */
  373. public function __construct($f, $m = NULL)
  374. {
  375. $this->__f=SP.($m?$m:config('theme'))."/view/".$f.EXT;
  376. }
  377. /**
  378. * Set an array of values
  379. *
  380. * @param array $a array of values
  381. */
  382. public function set($a)
  383. {
  384. foreach($a as$k=>$v)$this->$k=$v;
  385. }
  386. /**
  387. * Return the view's HTML
  388. * @return string
  389. */
  390. public function __toString()
  391. {
  392. ob_start();extract((array)$this);require$__f;return ob_get_clean();
  393. }
  394. }
  395. // END