PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/limonade.php

https://github.com/artisonian/limonade-mongo-starter
PHP | 2448 lines | 1360 code | 240 blank | 848 comment | 226 complexity | a922754f516701a1b4fa1b2bfee9f5ea MD5 | raw file

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

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