PageRenderTime 68ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/limonade.php

https://github.com/sanemat/ktsukishima
PHP | 2237 lines | 1239 code | 231 blank | 767 comment | 203 complexity | 45b1d2ce1bec4a871c385e0eac5c6281 MD5 | raw file
Possible License(s): MIT

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. # ============================================================================ #
  3. /**
  4. * L I M O N A D E
  5. *
  6. * a PHP micro framework.
  7. *
  8. * For more informations: {@link http://github/sofadesign/limonade}
  9. *
  10. * @author Fabrice Luraine
  11. * @copyright Copyright (c) 2009 Fabrice Luraine
  12. * @license http://opensource.org/licenses/mit-license.php The MIT License
  13. * @package limonade
  14. */
  15. # ----------------------------------------------------------------------- #
  16. # Copyright (c) 2009 Fabrice Luraine #
  17. # #
  18. # Permission is hereby granted, free of charge, to any person #
  19. # obtaining a copy of this software and associated documentation #
  20. # files (the "Software"), to deal in the Software without #
  21. # restriction, including without limitation the rights to use, #
  22. # copy, modify, merge, publish, distribute, sublicense, and/or sell #
  23. # copies of the Software, and to permit persons to whom the #
  24. # Software is furnished to do so, subject to the following #
  25. # conditions: #
  26. # #
  27. # The above copyright notice and this permission notice shall be #
  28. # included in all copies or substantial portions of the Software. #
  29. # #
  30. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, #
  31. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES #
  32. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND #
  33. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #
  34. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, #
  35. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
  36. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR #
  37. # OTHER DEALINGS IN THE SOFTWARE. #
  38. # ============================================================================ #
  39. # ============================================================================ #
  40. # 0. PREPARE #
  41. # ============================================================================ #
  42. ## CONSTANTS __________________________________________________________________
  43. /**
  44. * Limonade version
  45. */
  46. define('LIMONADE', '0.4.5');
  47. define('LIM_START_MICROTIME', (float)substr(microtime(), 0, 10));
  48. define('LIM_SESSION_NAME', 'Fresh_and_Minty_Limonade_App');
  49. define('LIM_SESSION_FLASH_KEY', '_lim_flash_messages');
  50. define('E_LIM_HTTP', 32768);
  51. define('E_LIM_PHP', 65536);
  52. define('E_LIM_DEPRECATED', 35000);
  53. define('NOT_FOUND', 404);
  54. define('SERVER_ERROR', 500);
  55. define('ENV_PRODUCTION', 10);
  56. define('ENV_DEVELOPMENT', 100);
  57. define('X-SENDFILE', 10);
  58. define('X-LIGHTTPD-SEND-FILE', 20);
  59. # for PHP 5.3.0 <
  60. if(!defined('E_DEPRECATED')) define('E_DEPRECATED', 8192);
  61. if(!defined('E_USER_DEPRECATED')) define('E_USER_DEPRECATED', 16384);
  62. ## SETTING BASIC SECURITY _____________________________________________________
  63. # A. Unsets all global variables set from a superglobal array
  64. /**
  65. * @access private
  66. * @return void
  67. */
  68. function unregister_globals()
  69. {
  70. $args = func_get_args();
  71. foreach($args as $k => $v)
  72. if(array_key_exists($k, $GLOBALS)) unset($GLOBALS[$k]);
  73. }
  74. if(ini_get('register_globals'))
  75. {
  76. unregister_globals( '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER',
  77. '_ENV', '_FILES');
  78. ini_set('register_globals', 0);
  79. }
  80. # B. removing magic quotes
  81. /**
  82. * @access private
  83. * @param string $array
  84. * @return array
  85. */
  86. function remove_magic_quotes($array)
  87. {
  88. foreach ($array as $k => $v)
  89. $array[$k] = is_array($v) ? remove_magic_quotes($v) : stripslashes($v);
  90. return $array;
  91. }
  92. if (get_magic_quotes_gpc())
  93. {
  94. $_GET = remove_magic_quotes($_GET);
  95. $_POST = remove_magic_quotes($_POST);
  96. $_COOKIE = remove_magic_quotes($_COOKIE);
  97. ini_set('magic_quotes_gpc', 0);
  98. }
  99. if(get_magic_quotes_runtime()) set_magic_quotes_runtime(false);
  100. # C. Disable error display
  101. # by default, no error reporting; it will be switched on later in run().
  102. # ini_set('display_errors', 1); must be called explicitly in app file
  103. # if you want to show errors before running app
  104. ini_set('display_errors', 0);
  105. ## SETTING INTERNAL ROUTES _____________________________________________________
  106. dispatch(array("/_lim_css/*.css", array('_lim_css_filename')), 'render_limonade_css');
  107. /**
  108. * Internal controller that responds to route /_lim_css/*.css
  109. *
  110. * @access private
  111. * @return string
  112. */
  113. function render_limonade_css()
  114. {
  115. option('views_dir', file_path(option('limonade_public_dir'), 'css'));
  116. $fpath = file_path(params('_lim_css_filename').".css");
  117. return css($fpath, null); // with no layout
  118. }
  119. dispatch(array("/_lim_public/**", array('_lim_public_file')), 'render_limonade_file');
  120. /**
  121. * Internal controller that responds to route /_lim_public/**
  122. *
  123. * @access private
  124. * @return void
  125. */
  126. function render_limonade_file()
  127. {
  128. $fpath = file_path(option('limonade_public_dir'), params('_lim_public_file'));
  129. return render_file($fpath, true);
  130. }
  131. # # #
  132. # ============================================================================ #
  133. # 1. BASE #
  134. # ============================================================================ #
  135. ## ABSTRACTS ___________________________________________________________________
  136. # function configure(){}
  137. # function before(){}
  138. # function after(){}
  139. # function not_found(){}
  140. # function server_error(){}
  141. # function route_missing(){}
  142. # function before_exit(){}
  143. ## MAIN PUBLIC FUNCTIONS _______________________________________________________
  144. /**
  145. * Set and returns options values
  146. *
  147. * If multiple values are provided, set $name option with an array of those values.
  148. * If there is only one value, set $name option with the provided $values
  149. *
  150. * @param string $name
  151. * @param mixed $values,...
  152. * @return mixed option value for $name if $name argument is provided, else return all options
  153. */
  154. function option($name = null, $values = null)
  155. {
  156. static $options = array();
  157. $args = func_get_args();
  158. $name = array_shift($args);
  159. if(is_null($name)) return $options;
  160. if(!empty($args))
  161. {
  162. $options[$name] = count($args) > 1 ? $args : $args[0];
  163. }
  164. if(array_key_exists($name, $options)) return $options[$name];
  165. return;
  166. }
  167. /**
  168. * Set and returns params
  169. *
  170. * Depending on provided arguments:
  171. *
  172. * * Reset params if first argument is null
  173. *
  174. * * If first argument is an array, merge it with current params
  175. *
  176. * * If there is a second argument $value, set param $name (first argument) with $value
  177. * <code>
  178. * params('name', 'Doe') // set 'name' => 'Doe'
  179. * </code>
  180. * * If there is more than 2 arguments, set param $name (first argument) value with
  181. * an array of next arguments
  182. * <code>
  183. * params('months', 'jan', 'feb', 'mar') // set 'month' => array('months', 'jan', 'feb', 'mar')
  184. * </code>
  185. *
  186. * @param mixed $name_or_array_or_null could be null || array of params || name of a param (optional)
  187. * @param mixed $value,... for the $name param (optional)
  188. * @return mixed all params, or one if a first argument $name is provided
  189. */
  190. function params($name_or_array_or_null = null, $value = null)
  191. {
  192. static $params = array();
  193. $args = func_get_args();
  194. if(func_num_args() > 0)
  195. {
  196. $name = array_shift($args);
  197. if(is_null($name))
  198. {
  199. # Reset params
  200. $params = array();
  201. return $params;
  202. }
  203. if(is_array($name))
  204. {
  205. $params = array_merge($params, $name);
  206. return $params;
  207. }
  208. $nargs = count($args);
  209. if($nargs > 0)
  210. {
  211. $value = $nargs > 1 ? $args : $args[0];
  212. $params[$name] = $value;
  213. }
  214. return array_key_exists($name,$params) ? $params[$name] : null;
  215. }
  216. return $params;
  217. }
  218. /**
  219. * Set and returns template variables
  220. *
  221. * If multiple values are provided, set $name variable with an array of those values.
  222. * If there is only one value, set $name variable with the provided $values
  223. *
  224. * @param string $name
  225. * @param mixed $values,...
  226. * @return mixed variable value for $name if $name argument is provided, else return all variables
  227. */
  228. function set($name = null, $values = null)
  229. {
  230. static $vars = array();
  231. $args = func_get_args();
  232. $name = array_shift($args);
  233. if(is_null($name)) return $vars;
  234. if(!empty($args))
  235. {
  236. $vars[$name] = count($args) > 1 ? $args : $args[0];
  237. }
  238. if(array_key_exists($name, $vars)) return $vars[$name];
  239. return $vars;
  240. }
  241. /**
  242. * Sets a template variable with a value or a default value if value is empty
  243. *
  244. * @param string $name
  245. * @param string $value
  246. * @param string $default
  247. * @return mixed setted value
  248. */
  249. function set_or_default($name, $value, $default)
  250. {
  251. return set($name, value_or_default($value, $default));
  252. }
  253. /**
  254. * Running application
  255. *
  256. * @param string $env
  257. * @return void
  258. */
  259. function run($env = null)
  260. {
  261. if(is_null($env)) $env = env();
  262. # 0. Set default configuration
  263. $root_dir = dirname(app_file());
  264. $base_path = dirname(file_path($env['SERVER']['SCRIPT_NAME']));
  265. $base_file = basename($env['SERVER']['SCRIPT_NAME']);
  266. $base_uri = file_path($base_path, (($base_file == 'index.php') ? '?' : $base_file.'?'));
  267. $lim_dir = dirname(__FILE__);
  268. option('root_dir', $root_dir);
  269. option('base_path', $base_path);
  270. option('base_uri', $base_uri); // set it manually if you use url_rewriting
  271. option('limonade_dir', file_path($lim_dir));
  272. option('limonade_views_dir', file_path($lim_dir, 'limonade', 'views'));
  273. option('limonade_public_dir',file_path($lim_dir, 'limonade', 'public'));
  274. option('public_dir', file_path($root_dir, 'public'));
  275. option('views_dir', file_path($root_dir, 'views'));
  276. option('controllers_dir', file_path($root_dir, 'controllers'));
  277. option('lib_dir', file_path($root_dir, 'lib'));
  278. option('error_views_dir', option('limonade_views_dir'));
  279. option('env', ENV_PRODUCTION);
  280. option('debug', true);
  281. option('session', LIM_SESSION_NAME); // true, false or the name of your session
  282. option('encoding', 'utf-8');
  283. option('x-sendfile', 0); // 0: disabled,
  284. // X-SENDFILE: for Apache and Lighttpd v. >= 1.5,
  285. // X-LIGHTTPD-SEND-FILE: for Apache and Lighttpd v. < 1.5
  286. option('content-type', 'text/html');
  287. # 1. Set error handling
  288. ini_set('display_errors', 1);
  289. set_error_handler('error_handler_dispatcher', E_ALL ^ E_NOTICE);
  290. # 2. Set user configuration
  291. call_if_exists('configure');
  292. # 3. Loading libs
  293. require_once_dir(option('lib_dir'));
  294. # 4. Starting session
  295. if(!defined('SID') && option('session'))
  296. {
  297. if(!is_bool(option('session'))) session_name(option('session'));
  298. if(!session_start()) trigger_error("An error occured while trying to start the session", E_USER_WARNING);
  299. }
  300. # 5. Set some default methods if needed
  301. if(!function_exists('after'))
  302. {
  303. function after($output)
  304. {
  305. return $output;
  306. }
  307. }
  308. if(!function_exists('route_missing'))
  309. {
  310. function route_missing($request_method, $request_uri)
  311. {
  312. halt(NOT_FOUND, "($request_method) $request_uri");
  313. }
  314. }
  315. # 6. Check request
  316. if($rm = request_method())
  317. {
  318. if(request_is_head()) ob_start(); // then no output
  319. if(!request_method_is_allowed($rm))
  320. halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'$rm'</code> is not implemented");
  321. # 6.1 Check matching route
  322. if($route = route_find($rm, request_uri()))
  323. {
  324. params($route['params']);
  325. # 6.2 Load controllers dir
  326. require_once_dir(option('controllers_dir'));
  327. if(function_exists($route['function']))
  328. {
  329. # 6.3 Call before function
  330. call_if_exists('before');
  331. # 6.4 Call matching controller function and output result
  332. if($output = call_user_func($route['function']))
  333. {
  334. echo after(error_notices_render() . $output);
  335. }
  336. stop_and_exit();
  337. }
  338. else halt(SERVER_ERROR, "Routing error: undefined function '{$route['function']}'", $route);
  339. }
  340. else route_missing($rm, request_uri());
  341. }
  342. else halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'$rm'</code> is not implemented");
  343. }
  344. /**
  345. * Stop and exit limonade application
  346. *
  347. * @access private
  348. * @param boolean exit or not
  349. * @return void
  350. */
  351. function stop_and_exit($exit = true)
  352. {
  353. call_if_exists('before_exit');
  354. $flash_sweep = true;
  355. $headers = headers_list();
  356. foreach($headers as $header)
  357. {
  358. // If a Content-Type header exists, flash_sweep only if is text/html
  359. // Else if there's no Content-Type header, flash_sweep by default
  360. if(stripos($header, 'Content-Type:') === false)
  361. {
  362. $flash_sweep = stripos($header, 'Content-Type: text/html') === false;
  363. break;
  364. }
  365. }
  366. if($flash_sweep) flash_sweep();
  367. if(defined('SID')) session_write_close();
  368. if(request_is_head()) ob_end_clean();
  369. if($exit) exit;
  370. }
  371. /**
  372. * Returns limonade environment variables:
  373. *
  374. * 'SERVER', 'FILES', 'REQUEST', 'SESSION', 'ENV', 'COOKIE',
  375. * 'GET', 'POST', 'PUT', 'DELETE'
  376. *
  377. * If a null argument is passed, reset and rebuild environment
  378. *
  379. * @param null @reset reset and rebuild environment
  380. * @return array
  381. */
  382. function env($reset = null)
  383. {
  384. static $env = array();
  385. if(func_num_args() > 0)
  386. {
  387. $args = func_get_args();
  388. if(is_null($args[0])) $env = array();
  389. }
  390. if(empty($env))
  391. {
  392. if(empty($GLOBALS['_SERVER']))
  393. {
  394. // Fixing empty $GLOBALS['_SERVER'] bug
  395. // http://sofadesign.lighthouseapp.com/projects/29612-limonade/tickets/29-env-is-empty
  396. $GLOBALS['_SERVER'] =& $_SERVER;
  397. $GLOBALS['_FILES'] =& $_FILES;
  398. $GLOBALS['_REQUEST'] =& $_REQUEST;
  399. $GLOBALS['_SESSION'] =& $_SESSION;
  400. $GLOBALS['_ENV'] =& $_ENV;
  401. $GLOBALS['_COOKIE'] =& $_COOKIE;
  402. }
  403. $glo_names = array('SERVER', 'FILES', 'REQUEST', 'SESSION', 'ENV', 'COOKIE');
  404. $vars = array_merge($glo_names, request_methods());
  405. foreach($vars as $var)
  406. {
  407. $varname = "_$var";
  408. if(!array_key_exists($varname, $GLOBALS)) $GLOBALS[$varname] = array();
  409. $env[$var] =& $GLOBALS[$varname];
  410. }
  411. $method = request_method($env);
  412. if($method == 'PUT' || $method == 'DELETE')
  413. {
  414. $varname = "_$method";
  415. if(array_key_exists('_method', $_POST) && $_POST['_method'] == $method)
  416. {
  417. foreach($_POST as $k => $v)
  418. {
  419. if($k == "_method") continue;
  420. $GLOBALS[$varname][$k] = $v;
  421. }
  422. }
  423. else
  424. {
  425. parse_str(file_get_contents('php://input'), $GLOBALS[$varname]);
  426. }
  427. }
  428. }
  429. return $env;
  430. }
  431. /**
  432. * Returns application root file path
  433. *
  434. * @return string
  435. */
  436. function app_file()
  437. {
  438. static $file;
  439. if(empty($file))
  440. {
  441. $stacktrace = array_pop(debug_backtrace());
  442. $file = $stacktrace['file'];
  443. }
  444. return file_path($file);
  445. }
  446. # # #
  447. # ============================================================================ #
  448. # 2. ERROR #
  449. # ============================================================================ #
  450. /**
  451. * Associate a function with error code(s) and return all associations
  452. *
  453. * @param string $errno
  454. * @param string $function
  455. * @return array
  456. */
  457. function error($errno = null, $function = null)
  458. {
  459. static $errors = array();
  460. if(func_num_args() > 0)
  461. {
  462. $errors[] = array('errno'=>$errno, 'function'=> $function);
  463. }
  464. return $errors;
  465. }
  466. /**
  467. * Raise an error, passing a given error number and an optional message,
  468. * then exit.
  469. * Error number should be a HTTP status code or a php user error (E_USER...)
  470. * $errno and $msg arguments can be passsed in any order
  471. * If no arguments are passed, default $errno is SERVER_ERROR (500)
  472. *
  473. * @param int,string $errno Error number or message string
  474. * @param string,string $msg Message string or error number
  475. * @param mixed $debug_args extra data provided for debugging
  476. * @return void
  477. */
  478. function halt($errno = SERVER_ERROR, $msg = '', $debug_args = null)
  479. {
  480. $args = func_get_args();
  481. $error = array_shift($args);
  482. # switch $errno and $msg args
  483. # TODO cleanup / refactoring
  484. if(is_string($errno))
  485. {
  486. $msg = $errno;
  487. $oldmsg = array_shift($args);
  488. $errno = empty($oldmsg) ? SERVER_ERROR : $oldmsg;
  489. }
  490. else if(!empty($args)) $msg = array_shift($args);
  491. if(empty($msg) && $errno == NOT_FOUND) $msg = request_uri();
  492. if(empty($msg)) $msg = "";
  493. if(!empty($args)) $debug_args = $args;
  494. set('_lim_err_debug_args', $debug_args);
  495. error_handler_dispatcher($errno, $msg, null, null);
  496. }
  497. /**
  498. * Internal error handler dispatcher
  499. * Find and call matching error handler and exit
  500. * If no match found, call default error handler
  501. *
  502. * @access private
  503. * @param int $errno
  504. * @param string $errstr
  505. * @param string $errfile
  506. * @param string $errline
  507. * @return void
  508. */
  509. function error_handler_dispatcher($errno, $errstr, $errfile, $errline)
  510. {
  511. $back_trace = debug_backtrace();
  512. while($trace = array_shift($back_trace))
  513. {
  514. if($trace['function'] == 'halt')
  515. {
  516. $errfile = $trace['file'];
  517. $errline = $trace['line'];
  518. break;
  519. }
  520. }
  521. # Notices and warning won't halt execution
  522. if(error_wont_halt_app($errno))
  523. {
  524. error_notice($errno, $errstr, $errfile, $errline);
  525. return;
  526. }
  527. else
  528. {
  529. # Other errors will stop application
  530. $handlers = error();
  531. $is_http_err = http_response_status_is_valid($errno);
  532. foreach($handlers as $handler)
  533. {
  534. $e = is_array($handler['errno']) ? $handler['errno'] : array($handler['errno']);
  535. while($ee = array_shift($e))
  536. {
  537. if($ee == $errno || $ee == E_LIM_PHP || ($ee == E_LIM_HTTP && $is_http_err))
  538. {
  539. echo call_if_exists($handler['function'], $errno, $errstr, $errfile, $errline);
  540. exit;
  541. }
  542. }
  543. }
  544. echo error_default_handler($errno, $errstr, $errfile, $errline);
  545. stop_and_exit();
  546. }
  547. }
  548. /**
  549. * Default error handler
  550. *
  551. * @param string $errno
  552. * @param string $errstr
  553. * @param string $errfile
  554. * @param string $errline
  555. * @return string error output
  556. */
  557. function error_default_handler($errno, $errstr, $errfile, $errline)
  558. {
  559. $is_http_err = http_response_status_is_valid($errno);
  560. $http_error_code = $is_http_err ? $errno : SERVER_ERROR;
  561. status($http_error_code);
  562. return $http_error_code == NOT_FOUND ?
  563. error_not_found_output($errno, $errstr, $errfile, $errline) :
  564. error_server_error_output($errno, $errstr, $errfile, $errline);
  565. }
  566. /**
  567. * Returns not found error output
  568. *
  569. * @access private
  570. * @param string $msg
  571. * @return string
  572. */
  573. function error_not_found_output($errno, $errstr, $errfile, $errline)
  574. {
  575. if(!function_exists('not_found'))
  576. {
  577. /**
  578. * Default not found error output
  579. *
  580. * @param string $errno
  581. * @param string $errstr
  582. * @param string $errfile
  583. * @param string $errline
  584. * @return string
  585. */
  586. function not_found($errno, $errstr, $errfile=null, $errline=null)
  587. {
  588. option('views_dir', option('error_views_dir'));
  589. $msg = h(rawurldecode($errstr));
  590. return html("<h1>Page not found:</h1><p><code>{$msg}</code></p>", error_layout());
  591. }
  592. }
  593. return not_found($errno, $errstr, $errfile, $errline);
  594. }
  595. /**
  596. * Returns server error output
  597. *
  598. * @access private
  599. * @param int $errno
  600. * @param string $errstr
  601. * @param string $errfile
  602. * @param string $errline
  603. * @return string
  604. */
  605. function error_server_error_output($errno, $errstr, $errfile, $errline)
  606. {
  607. if(!function_exists('server_error'))
  608. {
  609. /**
  610. * Default server error output
  611. *
  612. * @param string $errno
  613. * @param string $errstr
  614. * @param string $errfile
  615. * @param string $errline
  616. * @return string
  617. */
  618. function server_error($errno, $errstr, $errfile=null, $errline=null)
  619. {
  620. $is_http_error = http_response_status_is_valid($errno);
  621. $args = compact('errno', 'errstr', 'errfile', 'errline', 'is_http_error');
  622. option('views_dir', option('limonade_views_dir'));
  623. $html = render('error.html.php', null, $args);
  624. option('views_dir', option('error_views_dir'));
  625. return html($html, error_layout(), $args);
  626. }
  627. }
  628. return server_error($errno, $errstr, $errfile, $errline);
  629. }
  630. /**
  631. * Set and returns error output layout
  632. *
  633. * @param string $layout
  634. * @return string
  635. */
  636. function error_layout($layout = false)
  637. {
  638. static $o_layout = 'default_layout.php';
  639. if($layout !== false)
  640. {
  641. option('error_views_dir', option('views_dir'));
  642. $o_layout = $layout;
  643. }
  644. return $o_layout;
  645. }
  646. /**
  647. * Set a notice if arguments are provided
  648. * Returns all stored notices.
  649. * If $errno argument is null, reset the notices array
  650. *
  651. * @access private
  652. * @param string, null $str
  653. * @return array
  654. */
  655. function error_notice($errno = false, $errstr = null, $errfile = null, $errline = null)
  656. {
  657. static $notices = array();
  658. if($errno) $notices[] = compact('errno', 'errstr', 'errfile', 'errline');
  659. else if(is_null($errno)) $notices = array();
  660. return $notices;
  661. }
  662. /**
  663. * Returns notices output rendering and reset notices
  664. *
  665. * @return string
  666. */
  667. function error_notices_render()
  668. {
  669. if(option('debug') && option('env') > ENV_PRODUCTION)
  670. {
  671. $notices = error_notice();
  672. error_notice(null); // reset notices
  673. $c_view_dir = option('views_dir'); // keep for restore after render
  674. option('views_dir', option('limonade_views_dir'));
  675. $o = render('_notices.html.php', null, array('notices' => $notices));
  676. option('views_dir', $c_view_dir); // restore current views dir
  677. return $o;
  678. }
  679. }
  680. /**
  681. * Checks if an error is will halt application execution.
  682. * Notices and warnings will not.
  683. *
  684. * @access private
  685. * @param string $num error code number
  686. * @return boolean
  687. */
  688. function error_wont_halt_app($num)
  689. {
  690. return $num == E_NOTICE ||
  691. $num == E_WARNING ||
  692. $num == E_CORE_WARNING ||
  693. $num == E_COMPILE_WARNING ||
  694. $num == E_USER_WARNING ||
  695. $num == E_USER_NOTICE ||
  696. $num == E_DEPRECATED ||
  697. $num == E_USER_DEPRECATED ||
  698. $num == E_LIM_DEPRECATED;
  699. }
  700. /**
  701. * return error code name for a given code num, or return all errors names
  702. *
  703. * @param string $num
  704. * @return mixed
  705. */
  706. function error_type($num = null)
  707. {
  708. $types = array (
  709. E_ERROR => 'ERROR',
  710. E_WARNING => 'WARNING',
  711. E_PARSE => 'PARSING ERROR',
  712. E_NOTICE => 'NOTICE',
  713. E_CORE_ERROR => 'CORE ERROR',
  714. E_CORE_WARNING => 'CORE WARNING',
  715. E_COMPILE_ERROR => 'COMPILE ERROR',
  716. E_COMPILE_WARNING => 'COMPILE WARNING',
  717. E_USER_ERROR => 'USER ERROR',
  718. E_USER_WARNING => 'USER WARNING',
  719. E_USER_NOTICE => 'USER NOTICE',
  720. E_STRICT => 'STRICT NOTICE',
  721. E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR',
  722. E_DEPRECATED => 'DEPRECATED WARNING',
  723. E_USER_DEPRECATED => 'USER DEPRECATED WARNING',
  724. E_LIM_DEPRECATED => 'LIMONADE DEPRECATED WARNING'
  725. );
  726. return is_null($num) ? $types : $types[$num];
  727. }
  728. /**
  729. * Returns http response status for a given error number
  730. *
  731. * @param string $errno
  732. * @return int
  733. */
  734. function error_http_status($errno)
  735. {
  736. $code = http_response_status_is_valid($errno) ? $errno : SERVER_ERROR;
  737. return http_response_status($code);
  738. }
  739. # # #
  740. # ============================================================================ #
  741. # 3. REQUEST #
  742. # ============================================================================ #
  743. /**
  744. * Returns current request method for a given environment or current one
  745. *
  746. * @param string $env
  747. * @return string
  748. */
  749. function request_method($env = null)
  750. {
  751. if(is_null($env)) $env = env();
  752. $m = array_key_exists('REQUEST_METHOD', $env['SERVER']) ? $env['SERVER']['REQUEST_METHOD'] : null;
  753. if($m == "POST" && array_key_exists('_method', $env['POST']))
  754. $m = strtoupper($env['POST']['_method']);
  755. if(!in_array(strtoupper($m), request_methods()))
  756. {
  757. trigger_error("'$m' request method is unkown or unavailable.", E_USER_WARNING);
  758. $m = false;
  759. }
  760. return $m;
  761. }
  762. /**
  763. * Checks if a request method or current one is allowed
  764. *
  765. * @param string $m
  766. * @return bool
  767. */
  768. function request_method_is_allowed($m = null)
  769. {
  770. if(is_null($m)) $m = request_method();
  771. return in_array(strtoupper($m), request_methods());
  772. }
  773. /**
  774. * Checks if request method is GET
  775. *
  776. * @param string $env
  777. * @return bool
  778. */
  779. function request_is_get($env = null)
  780. {
  781. return request_method($env) == "GET";
  782. }
  783. /**
  784. * Checks if request method is POST
  785. *
  786. * @param string $env
  787. * @return bool
  788. */
  789. function request_is_post($env = null)
  790. {
  791. return request_method($env) == "POST";
  792. }
  793. /**
  794. * Checks if request method is PUT
  795. *
  796. * @param string $env
  797. * @return bool
  798. */
  799. function request_is_put($env = null)
  800. {
  801. return request_method($env) == "PUT";
  802. }
  803. /**
  804. * Checks if request method is DELETE
  805. *
  806. * @param string $env
  807. * @return bool
  808. */
  809. function request_is_delete($env = null)
  810. {
  811. return request_method($env) == "DELETE";
  812. }
  813. /**
  814. * Checks if request method is HEAD
  815. *
  816. * @param string $env
  817. * @return bool
  818. */
  819. function request_is_head($env = null)
  820. {
  821. return request_method($env) == "HEAD";
  822. }
  823. /**
  824. * Returns allowed request methods
  825. *
  826. * @return array
  827. */
  828. function request_methods()
  829. {
  830. return array("GET","POST","PUT","DELETE", "HEAD");
  831. }
  832. /**
  833. * Returns current request uri (the path that will be compared with routes)
  834. *
  835. * (Inspired from codeigniter URI::_fetch_uri_string method)
  836. *
  837. * @return string
  838. */
  839. function request_uri($env = null)
  840. {
  841. static $uri = null;
  842. if(is_null($env))
  843. {
  844. if(!is_null($uri)) return $uri;
  845. $env = env();
  846. }
  847. if(array_key_exists('uri', $env['GET']))
  848. {
  849. $uri = $env['GET']['uri'];
  850. }
  851. else if(array_key_exists('u', $env['GET']))
  852. {
  853. $uri = $env['GET']['u'];
  854. }
  855. // bug: dot are converted to _... so we can't use it...
  856. // else if (count($env['GET']) == 1 && trim(key($env['GET']), '/') != '')
  857. // {
  858. // $uri = key($env['GET']);
  859. // }
  860. else
  861. {
  862. $app_file = app_file();
  863. $path_info = isset($env['SERVER']['PATH_INFO']) ? $env['SERVER']['PATH_INFO'] : @getenv('PATH_INFO');
  864. $query_string = isset($env['SERVER']['QUERY_STRING']) ? $env['SERVER']['QUERY_STRING'] : @getenv('QUERY_STRING');
  865. // Is there a PATH_INFO variable?
  866. // Note: some servers seem to have trouble with getenv() so we'll test it two ways
  867. if (trim($path_info, '/') != '' && $path_info != "/".$app_file)
  868. {
  869. $uri = $path_info;
  870. }
  871. // No PATH_INFO?... What about QUERY_STRING?
  872. elseif (trim($query_string, '/') != '')
  873. {
  874. $uri = $query_string;
  875. }
  876. elseif(array_key_exists('REQUEST_URI', $env['SERVER']) && !empty($env['SERVER']['REQUEST_URI']))
  877. {
  878. $request_uri = rtrim(rawurldecode($env['SERVER']['REQUEST_URI']), '?/').'/';
  879. $base_path = $env['SERVER']['SCRIPT_NAME'];
  880. if($request_uri."index.php" == $base_path) $request_uri .= "index.php";
  881. $uri = str_replace($base_path, '', $request_uri);
  882. }
  883. elseif($env['SERVER']['argc'] > 1 && trim($env['SERVER']['argv'][1], '/') != '')
  884. {
  885. $uri = $env['SERVER']['argv'][1];
  886. }
  887. }
  888. $uri = rtrim($uri, "/"); # removes ending /
  889. if(empty($uri))
  890. {
  891. $uri = '/';
  892. }
  893. else if($uri[0] != '/')
  894. {
  895. $uri = '/' . $uri; # add a leading slash
  896. }
  897. return $uri;
  898. }
  899. # # #
  900. # ============================================================================ #
  901. # 4. ROUTER #
  902. # ============================================================================ #
  903. /**
  904. * an alias of dispatch_get
  905. *
  906. * @return void
  907. */
  908. function dispatch($path_or_array, $function)
  909. {
  910. dispatch_get($path_or_array, $function);
  911. }
  912. /**
  913. * Add a GET route. Also automatically defines a HEAD route.
  914. *
  915. * @param string $path_or_array
  916. * @param string $function
  917. * @return void
  918. */
  919. function dispatch_get($path_or_array, $function)
  920. {
  921. route("GET", $path_or_array, $function);
  922. route("HEAD", $path_or_array, $function);
  923. }
  924. /**
  925. * Add a POST route
  926. *
  927. * @param string $path_or_array
  928. * @param string $function
  929. * @return void
  930. */
  931. function dispatch_post($path_or_array, $function)
  932. {
  933. route("POST", $path_or_array, $function);
  934. }
  935. /**
  936. * Add a PUT route
  937. *
  938. * @param string $path_or_array
  939. * @param string $function
  940. * @return void
  941. */
  942. function dispatch_put($path_or_array, $function)
  943. {
  944. route("PUT", $path_or_array, $function);
  945. }
  946. /**
  947. * Add a DELETE route
  948. *
  949. * @param string $path_or_array
  950. * @param string $function
  951. * @return void
  952. */
  953. function dispatch_delete($path_or_array, $function)
  954. {
  955. route("DELETE", $path_or_array, $function);
  956. }
  957. /**
  958. * Add route if required params are provided.
  959. * Delete all routes if null is passed as a unique argument
  960. * Return all routes
  961. *
  962. * @access private
  963. * @param string $method
  964. * @param string $path_or_array
  965. * @param string $func
  966. * @return array
  967. */
  968. function route()
  969. {
  970. static $routes = array();
  971. $nargs = func_num_args();
  972. if( $nargs > 0)
  973. {
  974. $args = func_get_args();
  975. if($nargs === 1 && is_null($args[0])) $routes = array();
  976. else if($nargs < 3) trigger_error("Missing arguments for route()", E_USER_ERROR);
  977. else
  978. {
  979. $method = $args[0];
  980. $path_or_array = $args[1];
  981. $func = $args[2];
  982. $routes[] = route_build($method, $path_or_array, $func);
  983. }
  984. }
  985. return $routes;
  986. }
  987. /**
  988. * An alias of route(null): reset all routes
  989. *
  990. * @access private
  991. * @return void
  992. */
  993. function route_reset()
  994. {
  995. route(null);
  996. }
  997. /**
  998. * Build a route and return it
  999. *
  1000. * @access private
  1001. * @param string $method
  1002. * @param string $path_or_array
  1003. * @param string $func
  1004. * @return array
  1005. */
  1006. function route_build($method, $path_or_array, $func)
  1007. {
  1008. $method = strtoupper($method);
  1009. if(!in_array($method, request_methods()))
  1010. trigger_error("'$method' request method is unkown or unavailable.", E_USER_WARNING);
  1011. if(is_array($path_or_array))
  1012. {
  1013. $path = array_shift($path_or_array);
  1014. $names = $path_or_array[0];
  1015. }
  1016. else
  1017. {
  1018. $path = $path_or_array;
  1019. $names = array();
  1020. }
  1021. $single_asterisk_subpattern = "(?:/([^\/]*))?";
  1022. $double_asterisk_subpattern = "(?:/(.*))?";
  1023. $optionnal_slash_subpattern = "(?:/*?)";
  1024. $no_slash_asterisk_subpattern = "(?:([^\/]*))?";
  1025. if($path[0] == "^")
  1026. {
  1027. if($path{strlen($path) - 1} != "$") $path .= "$";
  1028. $pattern = "#".$path."#i";
  1029. }
  1030. else if(empty($path) || $path == "/")
  1031. {
  1032. $pattern = "#^".$optionnal_slash_subpattern."$#";
  1033. }
  1034. else
  1035. {
  1036. $parsed = array();
  1037. $elts = explode('/', $path);
  1038. $parameters_count = 0;
  1039. foreach($elts as $elt)
  1040. {
  1041. if(empty($elt)) continue;
  1042. $name = null;
  1043. # extracting double asterisk **
  1044. if($elt == "**"):
  1045. $parsed[] = $double_asterisk_subpattern;
  1046. $name = $parameters_count;
  1047. # extracting single asterisk *
  1048. elseif($elt == "*"):
  1049. $parsed[] = $single_asterisk_subpattern;
  1050. $name = $parameters_count;
  1051. # extracting named parameters :my_param
  1052. elseif($elt[0] == ":"):
  1053. if(preg_match('/^:([^\:]+)$/', $elt, $matches))
  1054. {
  1055. $parsed[] = $single_asterisk_subpattern;
  1056. $name = $matches[1];
  1057. };
  1058. elseif(strpos($elt, '*') !== false):
  1059. $sub_elts = explode('*', $elt);
  1060. $parsed_sub = array();
  1061. foreach($sub_elts as $sub_elt)
  1062. {
  1063. $parsed_sub[] = preg_quote($sub_elt, "#");
  1064. $name = $parameters_count;
  1065. }
  1066. //
  1067. $parsed[] = "/".implode($no_slash_asterisk_subpattern, $parsed_sub);
  1068. else:
  1069. $parsed[] = "/".preg_quote($elt, "#");
  1070. endif;
  1071. /* set parameters names */
  1072. if(is_null($name)) continue;
  1073. if(!array_key_exists($parameters_count, $names) || is_null($names[$parameters_count]))
  1074. $names[$parameters_count] = $name;
  1075. $parameters_count++;
  1076. }
  1077. $pattern = "#^".implode('', $parsed).$optionnal_slash_subpattern."?$#i";
  1078. }
  1079. return array( "method" => $method,
  1080. "pattern" => $pattern,
  1081. "names" => $names,
  1082. "function" => $func );
  1083. }
  1084. /**
  1085. * Find a route and returns it.
  1086. * If not found, returns false.
  1087. * Routes are checked from first added to last added.
  1088. *
  1089. * @access private
  1090. * @param string $method
  1091. * @param string $path
  1092. * @return array,false
  1093. */
  1094. function route_find($method, $path)
  1095. {
  1096. $routes = route();
  1097. $method = strtoupper($method);
  1098. foreach($routes as $route)
  1099. {
  1100. if($method == $route["method"] && preg_match($route["pattern"], $path, $matches))
  1101. {
  1102. $params = array();
  1103. if(count($matches) > 1)
  1104. {
  1105. array_shift($matches);
  1106. $n_matches = count($matches);
  1107. $names = array_values($route["names"]);
  1108. $n_names = count($names);
  1109. if( $n_matches < $n_names )
  1110. {
  1111. $a = array_fill(0, $n_names - $n_matches, null);
  1112. $matches = array_merge($matches, $a);
  1113. }
  1114. else if( $n_matches > $n_names )
  1115. {
  1116. $names = range($n_names, $n_matches - 1);
  1117. }
  1118. $params = array_combine($names, $matches);
  1119. }
  1120. $route["params"] = $params;
  1121. return $route;
  1122. }
  1123. }
  1124. return false;
  1125. }
  1126. # ============================================================================ #
  1127. # OUTPUT AND RENDERING #
  1128. # ============================================================================ #
  1129. /**
  1130. * Returns a string to output
  1131. *
  1132. * It might use a a template file or function, a formatted string (like {@link sprintf()}).
  1133. * It could be embraced by a layout or not.
  1134. * Local vars can be passed in addition to variables made available with the {@link set()}
  1135. * function.
  1136. *
  1137. * @param string $content_or_func
  1138. * @param string $layout
  1139. * @param string $locals
  1140. * @return string
  1141. */
  1142. function render($content_or_func, $layout = '', $locals = array())
  1143. {
  1144. $args = func_get_args();
  1145. $content_or_func = array_shift($args);
  1146. $layout = count($args) > 0 ? array_shift($args) : layout();
  1147. $view_path = file_path(option('views_dir'),$content_or_func);
  1148. $vars = array_merge(set(), $locals);
  1149. $flash = flash_now();
  1150. if(array_key_exists('flash', $vars)) trigger_error('A $flash variable is already passed to view. Flash messages will only be accessible through flash_now()', E_USER_NOTICE);
  1151. else if(!empty($flash)) $vars['flash'] = $flash;
  1152. $infinite_loop = false;
  1153. # Avoid infinite loop: this function is in the backtrace ?
  1154. if(function_exists($content_or_func))
  1155. {
  1156. $back_trace = debug_backtrace();
  1157. while($trace = array_shift($back_trace))
  1158. {
  1159. if($trace['function'] == strtolower($content_or_func))
  1160. {
  1161. $infinite_loop = true;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. if(function_exists($content_or_func) && !$infinite_loop)
  1167. {
  1168. ob_start();
  1169. call_user_func($content_or_func, $vars);
  1170. $content = ob_get_clean();
  1171. }
  1172. elseif(file_exists($view_path))
  1173. {
  1174. ob_start();
  1175. extract($vars);
  1176. include $view_path;
  1177. $content = ob_get_clean();
  1178. }
  1179. else
  1180. {
  1181. if(substr_count($content_or_func, '%') !== count($vars)) $content = $content_or_func;
  1182. else $content = vsprintf($content_or_func, $vars);
  1183. }
  1184. if(empty($layout)) return $content;
  1185. return render($layout, null, array('content' => $content));
  1186. }
  1187. /**
  1188. * Returns html output with proper http headers
  1189. *
  1190. * @param string $content_or_func
  1191. * @param string $layout
  1192. * @param string $locals
  1193. * @return string
  1194. */
  1195. function html($content_or_func, $layout = '', $locals = array())
  1196. {
  1197. $content_type = option('content_type');
  1198. $content_type = empty($content_type) ? 'text/html' : $content_type;
  1199. if(!headers_sent()) header('Content-Type: '.$content_type.'; charset='.strtolower(option('encoding')));
  1200. $args = func_get_args();
  1201. return call_user_func_array('render', $args);
  1202. }
  1203. /**
  1204. * Set and return current layout
  1205. *
  1206. * @param string $function_or_file
  1207. * @return string
  1208. */
  1209. function layout($function_or_file = null)
  1210. {
  1211. static $layout = null;
  1212. if(func_num_args() > 0) $layout = $function_or_file;
  1213. return $layout;
  1214. }
  1215. /**
  1216. * Returns xml output with proper http headers
  1217. *
  1218. * @param string $content_or_func
  1219. * @param string $layout
  1220. * @param string $locals
  1221. * @return string
  1222. */
  1223. function xml($data)
  1224. {
  1225. if(!headers_sent()) header('Content-Type: text/xml; charset='.strtolower(option('encoding')));
  1226. $args = func_get_args();
  1227. return call_user_func_array('render', $args);
  1228. }
  1229. /**
  1230. * Returns css output with proper http headers
  1231. *
  1232. * @param string $content_or_func
  1233. * @param string $layout
  1234. * @param string $locals
  1235. * @return string
  1236. */
  1237. function css($content_or_func, $layout = '', $locals = array())
  1238. {
  1239. if(!headers_sent()) header('Content-Type: text/css; charset='.strtolower(option('encoding')));
  1240. $args = func_get_args();
  1241. return call_user_func_array('render', $args);
  1242. }
  1243. /**
  1244. * Returns txt output with proper http headers
  1245. *
  1246. * @param string $content_or_func
  1247. * @param string $layout
  1248. * @param string $locals
  1249. * @return string
  1250. */
  1251. function txt($content_or_func, $layout = '', $locals = array())
  1252. {
  1253. if(!headers_sent()) header('Content-Type: text/plain; charset='.strtolower(option('encoding')));
  1254. $args = func_get_args();
  1255. return call_user_func_array('render', $args);
  1256. }
  1257. /**
  1258. * Returns json representation of data with proper http headers
  1259. *
  1260. * @param string $data
  1261. * @param int $json_option
  1262. * @return string
  1263. */
  1264. function json($data, $json_option = 0)
  1265. {
  1266. if(!headers_sent()) header('Content-Type: application/x-javascript; charset='.strtolower(option('encoding')));
  1267. return version_compare(PHP_VERSION, '5.3.0', '>=') ? json_encode($data, $json_option) : json_encode($data);
  1268. }
  1269. /**
  1270. * undocumented function
  1271. *
  1272. * @param string $filename
  1273. * @param string $return
  1274. * @return mixed number of bytes delivered or file output if $return = true
  1275. */
  1276. function render_file($filename, $return = false)
  1277. {
  1278. # TODO implements X-SENDFILE headers
  1279. // if($x-sendfile = option('x-sendfile'))
  1280. // {
  1281. // // add a X-Sendfile header for apache and Lighttpd >= 1.5
  1282. // if($x-sendfile > X-SENDFILE) // add a X-LIGHTTPD-send-file header
  1283. //
  1284. // }
  1285. // else
  1286. // {
  1287. //
  1288. // }
  1289. if(file_exists($filename))
  1290. {
  1291. $content_type = mime_type(file_extension($filename));
  1292. $header = 'Content-type: '.$content_type;
  1293. if(file_is_text($filename)) $header .= '; charset='.strtolower(option('encoding'));
  1294. if(!headers_sent()) header($header);
  1295. return file_read($filename, $return);
  1296. }
  1297. else halt(NOT_FOUND, "unknown filename $filename");
  1298. }
  1299. # # #
  1300. # ============================================================================ #
  1301. # 5. HELPERS #
  1302. # ============================================================================ #
  1303. /**
  1304. * Returns an url composed of params joined with /
  1305. *
  1306. * @param string $params,...
  1307. * @return string
  1308. */
  1309. function url_for($params = null)
  1310. {
  1311. $paths = array();
  1312. $params = func_get_args();
  1313. $first = true;
  1314. foreach($params as $param)
  1315. {
  1316. if($first)
  1317. {
  1318. if(filter_var($param , FILTER_VALIDATE_URL))
  1319. {
  1320. $paths[] = $param;
  1321. continue;
  1322. }
  1323. }
  1324. $p = explode('/',$param);
  1325. foreach($p as $v)
  1326. {
  1327. if(!empty($v)) $paths[] = str_replace('%23', '#', rawurlencode($v));
  1328. }
  1329. }
  1330. $path = rtrim(implode('/', $paths), '/');
  1331. if(!filter_var($path , FILTER_VALIDATE_URL))
  1332. {
  1333. # it's a relative URL or an URL without a schema
  1334. $base_uri = option('base_uri');
  1335. $path = file_path($base_uri, $path);
  1336. }
  1337. if(DIRECTORY_SEPARATOR != '/') $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  1338. return $path;
  1339. }
  1340. /**
  1341. * An alias of {@link htmlspecialchars()}.
  1342. * If no $charset is provided, uses option('encoding') value
  1343. *
  1344. * @param string $str
  1345. * @param string $quote_style
  1346. * @param string $charset
  1347. * @return void
  1348. */
  1349. function h($str, $quote_style = ENT_NOQUOTES, $charset = null)
  1350. {
  1351. if(is_null($charset)) $charset = strtoupper(option('encoding'));
  1352. return htmlspecialchars($str, $quote_style, $charset);
  1353. }
  1354. /**
  1355. * Set and returns flash messages that will be available in the next action
  1356. * via the {@link flash_now()} function or the view variable <code>$flash</code>.
  1357. *
  1358. * If multiple values are provided, set <code>$name</code> variable with an array of those values.
  1359. * If there is only one value, set <code>$name</code> variable with the provided $values
  1360. * or if it's <code>$name</code> is an array, merge it with current messages.
  1361. *
  1362. * @param string, array $name
  1363. * @param mixed $values,...
  1364. * @return mixed variable value for $name if $name argument is provided, else return all variables
  1365. */
  1366. function flash($name = null, $value = null)
  1367. {
  1368. if(!defined('SID')) trigger_error("Flash messages can't be used because session isn't enabled", E_USER_WARNING);
  1369. static $messages = array();
  1370. $args = func_get_args();
  1371. $name = array_shift($args);
  1372. if(is_null($name)) return $messages;
  1373. if(is_array($name)) return $messages = array_merge($messages, $name);
  1374. if(!empty($args))
  1375. {
  1376. $messages[$name] = count($args) > 1 ? $args : $args[0];
  1377. }
  1378. if(array_key_exists($name, $messages)) return $messages[$name];
  1379. return $messages;
  1380. }
  1381. /**
  1382. * Set and returns flash messages available for the current action, included those
  1383. * defined in the previous action with {@link flash()}
  1384. * Those messages will also be passed to the views and made available in the
  1385. * <code>$flash</code> variable.
  1386. *
  1387. * If multiple values are provided, set <code>$name</code> variable with an array of those values.
  1388. * If there is only one value, set <code>$name</code> variable with the provided $values
  1389. * or if it's <code>$name</code> is an array, merge it with current messages.
  1390. *
  1391. * @param string, array $name
  1392. * @param mixed $values,...
  1393. * @return mixed variable value for $name if $name argument is provided, else return all variables
  1394. */
  1395. function flash_now($name = null, $value = null)
  1396. {
  1397. static $messages = null;
  1398. if(is_null($messages))
  1399. {
  1400. $fkey = LIM_SESSION_FLASH_KEY;
  1401. $messages = array();
  1402. if(defined('SID') && array_key_exists($fkey, $_SESSION)) $messages = $_SESSION[$fkey];
  1403. }
  1404. $args = func_get_args();
  1405. $name = array_shift($args);
  1406. if(is_null($name)) return $messages;
  1407. if(is_array($name)) return $messages = array_merge($messages, $name);
  1408. if(!empty($args))
  1409. {
  1410. $messages[$name] = count($args) > 1 ? $args : $args[0];
  1411. }
  1412. if(array_key_exists($name, $messages)) return $messages[$name];
  1413. return $messages;
  1414. }
  1415. /**
  1416. * Delete current flash messages in session, and set new ones stored with
  1417. * flash function.
  1418. * Called before application exit.
  1419. *
  1420. * @access private
  1421. * @return void
  1422. */
  1423. function flash_sweep()
  1424. {
  1425. if(defined('SID'))
  1426. {
  1427. $fkey = LIM_SESSION_FLASH_KEY;
  1428. $_SESSION[$fkey] = flash();
  1429. }
  1430. }
  1431. # # #
  1432. # ============================================================================ #
  1433. # 6. UTILS #
  1434. # ============================================================================ #
  1435. /**
  1436. * Calls a function if exists
  1437. *
  1438. * @param string $func the function name
  1439. * @param mixed $arg,.. (optional)
  1440. * @return mixed
  1441. */
  1442. function call_if_exists($func)
  1443. {
  1444. $args = func_get_args();
  1445. $func = array_shift($args);
  1446. if(function_exists($func)) return call_user_func_array($func, $args);
  1447. return;
  1448. }
  1449. /**
  1450. * Define a constant unless it already exists
  1451. *
  1452. * @param string $name
  1453. * @param string $value
  1454. * @return void
  1455. */
  1456. function define_unless_exists($name, $value)
  1457. {
  1458. if(!defined($name)) define($name, $value);
  1459. }
  1460. /**
  1461. * Return a default value if provided value is empty
  1462. *
  1463. * @param mixed $value
  1464. * @param mixed $default default value returned if $value is empty
  1465. * @return mixed
  1466. */
  1467. function value_or_default($value, $default)
  1468. {
  1469. return empty($value) ? $default : $value;
  1470. }
  1471. /**
  1472. * An alias of {@link value_or_default()}
  1473. *
  1474. *
  1475. * @param mixed $value
  1476. * @param mixed $default
  1477. * @return mixed
  1478. */
  1479. function v($value, $default)
  1480. {
  1481. return value_or_default($value, $default);
  1482. }
  1483. /**
  1484. * Load php files with require_once in a given dir
  1485. *
  1486. * @param string $path Path in which are the file to load
  1487. * @param string $pattern a regexp pattern that filter files to load
  1488. * @return array paths of loaded files
  1489. */
  1490. function require_once_dir($path, $pattern = "*.php")
  1491. {
  1492. if($path[strlen($path) - 1] != "/") $path .= "/";
  1493. $filenames = glob($path.$pattern);
  1494. if(!is_array($filenames)) $filenames = array();
  1495. foreach($filenames as $filename) require_once $filename;
  1496. return $filenames;
  1497. }
  1498. ## HTTP utils _________________________________________________________________
  1499. ### Constants: HTTP status codes
  1500. define( 'HTTP_CONTINUE', 100 );
  1501. define( 'HTTP_SWITCHING_PROTOCOLS', 101 );
  1502. define( 'HTTP_PROCESSING', 102 );
  1503. define( 'HTTP_OK', 200 );
  1504. define( 'HTTP_CREATED', 201 );
  1505. define( 'HTTP_ACCEPTED', 202 );
  1506. define( 'HTTP_NON_AUTHORITATIVE', 203 );
  1507. define( 'HTTP_NO_CONTENT', 204 );
  1508. define( 'HTTP_RESET_CONTENT', 205 );
  1509. define( 'HTTP_PARTIAL_CONTENT', 206 );
  1510. define( 'HTTP_MULTI_STATUS', 207 );
  1511. define( 'HTTP_MULTIPLE_CHOICES', 300 );
  1512. define( 'HTTP_MOVED_PERMANENTLY', 301 );
  1513. define( 'HTTP_MOVED_TEMPORARILY', 302 );
  1514. define( 'HTTP_SEE_OTHER', 303 );
  1515. define( 'HTTP_NOT_MODIFIED', 304 );
  1516. define( 'HTTP_USE_PROXY', 305 );
  1517. define( 'HTTP_TEMPORARY_REDIRECT', 307 );
  1518. define( 'HTTP_BAD_REQUEST', 400 );
  1519. define( 'HTTP_UNAUTHORIZED', 401 );
  1520. define( 'HTTP_PAYMENT_REQUIRED', 402 );
  1521. define( 'HTTP_FORBIDDEN', 403 );
  1522. define( 'HTTP_NOT_FOUND', 404 );
  1523. define( 'HTTP_METHOD_NOT_ALLOWED', 405 );
  1524. define( 'HTTP_NOT_ACCEPTABLE', 406 );
  1525. define( 'HTTP_PROXY_AUTHENTICATION_REQUIRED', 407 );
  1526. define( 'HTTP_REQUEST_TIME_OUT', 408 );
  1527. define( 'HTTP_CONFLICT', 409 );
  1528. define( 'HTTP_GONE', 410 );
  1529. define( 'HTTP_LENGTH_REQUIRED', 411 );
  1530. define( 'HTTP_PRECONDITION_FAILED', 412 );
  1531. define( 'HTTP_REQUEST_ENTITY_TOO_LARGE', 413 );
  1532. define( 'HTTP_REQUEST_URI_TOO_LARGE', 414 );
  1533. define( 'HTTP_UNSUPPORTED_MEDIA_TYPE', 415 );
  1534. define( 'HTTP_RANGE_NOT_SATISFIABLE', 416 );
  1535. define( 'HTTP_EXPECTATION_FAILED', 417 );
  1536. define( 'HTTP_UNPROCESSABLE_ENTITY', 422 );
  1537. define( 'HTTP_LOCKED', 423 );
  1538. define( 'HTTP_FAILED_DEPENDENCY', 424 );
  1539. define( 'HTTP_UPGRADE_REQUIRED', 426 );
  1540. define( 'HTTP_INTERNAL_SERVER_ERROR', 500 );
  1541. define( 'HTTP_NOT_IMPLEMENTED', 501 );
  1542. define( 'HTTP_BAD_GATEWAY', 502 );
  1543. define( 'HTTP_SERVICE_UNAVAILABLE', 503 );
  1544. define( 'HTTP_GATEWAY_TIME_OUT', 504 );
  1545. define( 'HTTP_VERSION_NOT_SUPPORTED', 505 );
  1546. define( 'HTTP_VARIANT_ALSO_VARIES', 506 );
  1547. define( 'HTTP_INSUFFICIENT_STORAGE', 507 );
  1548. define( 'HTTP_NOT_EXTENDED', 510 );
  1549. /**
  1550. * Output proper HTTP header for a given HTTP code
  1551. *
  1552. * @param string $code
  1553. * @return void
  1554. */
  1555. function status($code = 500)
  1556. {
  1557. if(!headers_sent())
  1558. {
  1559. $str = http_response_status_code($code);
  1560. header($str);
  1561. }
  1562. }
  1563. /**
  1564. * Http redirection
  1565. *
  1566. * @param string $params,...
  1567. * @return void
  1568. */
  1569. function redirect_to($params)
  1570. {
  1571. # [NOTE]: (from php.net) HTTP/1.1 requires an absolute URI as argument to » Location:
  1572. # including the scheme, hostname and absolute path, but some clients accept
  1573. # relative URIs. You can usually use $_SERVER['HTTP_HOST'],
  1574. # $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative
  1575. # one yourself.
  1576. # TODO make absolute uri
  1577. if(!headers_sent())
  1578. {
  1579. $params = func_get_args();
  1580. $uri = call_user_func_array('url_for', $params);
  1581. stop_and_exit(false);
  1582. header('Location: '.$uri);
  1583. exit;
  1584. }
  1585. }
  1586. /**
  1587. * Http redirection
  1588. *
  1589. * @deprecated deprecated since version 0.4. Please use {@link redirect_to()} instead.
  1590. * @param string $url
  1591. * @return void
  1592. */
  1593. function redirect($uri)
  1594. {
  1595. # halt('redirect() is deprecated. Please use redirect_to() instead.', E_LIM_DEPRECATED);
  1596. # halt not

Large files files are truncated, but you can click here to view the full file