PageRenderTime 106ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/webapp/php/lib/limonade.php

https://bitbucket.org/co-me/isucon2
PHP | 2670 lines | 1483 code | 256 blank | 931 comment | 246 complexity | 5a799450c3c39e5acbdefb31809a7d17 MD5 | raw 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_NAME', 'Un grand cru qui sait se faire attendre');
  48. define('LIM_START_MICROTIME', (float)substr(microtime(), 0, 10));
  49. define('LIM_SESSION_NAME', 'LIMONADE'.str_replace('.','x',LIMONADE));
  50. define('LIM_SESSION_FLASH_KEY', '_lim_flash_messages');
  51. if(function_exists('memory_get_usage'))
  52. define('LIM_START_MEMORY', memory_get_usage());
  53. define('E_LIM_HTTP', 32768);
  54. define('E_LIM_PHP', 65536);
  55. define('E_LIM_DEPRECATED', 35000);
  56. define('NOT_FOUND', 404);
  57. define('SERVER_ERROR', 500);
  58. define('ENV_PRODUCTION', 10);
  59. define('ENV_DEVELOPMENT', 100);
  60. define('X-SENDFILE', 10);
  61. define('X-LIGHTTPD-SEND-FILE', 20);
  62. # for PHP 5.3.0 <
  63. if(!defined('E_DEPRECATED')) define('E_DEPRECATED', 8192);
  64. if(!defined('E_USER_DEPRECATED')) define('E_USER_DEPRECATED', 16384);
  65. # for PHP 5.2.0 <
  66. if (!defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
  67. ## SETTING BASIC SECURITY _____________________________________________________
  68. # A. Unsets all global variables set from a superglobal array
  69. /**
  70. * @access private
  71. * @return void
  72. */
  73. function unregister_globals()
  74. {
  75. $args = func_get_args();
  76. foreach($args as $k => $v)
  77. if(array_key_exists($k, $GLOBALS)) unset($GLOBALS[$k]);
  78. }
  79. if(ini_get('register_globals'))
  80. {
  81. unregister_globals( '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER',
  82. '_ENV', '_FILES');
  83. ini_set('register_globals', 0);
  84. }
  85. # B. removing magic quotes
  86. /**
  87. * @access private
  88. * @param string $array
  89. * @return array
  90. */
  91. function remove_magic_quotes($array)
  92. {
  93. foreach ($array as $k => $v)
  94. $array[$k] = is_array($v) ? remove_magic_quotes($v) : stripslashes($v);
  95. return $array;
  96. }
  97. if (get_magic_quotes_gpc())
  98. {
  99. $_GET = remove_magic_quotes($_GET);
  100. $_POST = remove_magic_quotes($_POST);
  101. $_COOKIE = remove_magic_quotes($_COOKIE);
  102. ini_set('magic_quotes_gpc', 0);
  103. }
  104. if(function_exists('set_magic_quotes_runtime') && get_magic_quotes_runtime()) set_magic_quotes_runtime(false);
  105. # C. Disable error display
  106. # by default, no error reporting; it will be switched on later in run().
  107. # ini_set('display_errors', 1); must be called explicitly in app file
  108. # if you want to show errors before running app
  109. ini_set('display_errors', 0);
  110. ## SETTING INTERNAL ROUTES _____________________________________________________
  111. dispatch(array("/_lim_css/*.css", array('_lim_css_filename')), 'render_limonade_css');
  112. /**
  113. * Internal controller that responds to route /_lim_css/*.css
  114. *
  115. * @access private
  116. * @return string
  117. */
  118. function render_limonade_css()
  119. {
  120. option('views_dir', file_path(option('limonade_public_dir'), 'css'));
  121. $fpath = file_path(params('_lim_css_filename').".css");
  122. return css($fpath, null); // with no layout
  123. }
  124. dispatch(array("/_lim_public/**", array('_lim_public_file')), 'render_limonade_file');
  125. /**
  126. * Internal controller that responds to route /_lim_public/**
  127. *
  128. * @access private
  129. * @return void
  130. */
  131. function render_limonade_file()
  132. {
  133. $fpath = file_path(option('limonade_public_dir'), params('_lim_public_file'));
  134. return render_file($fpath, true);
  135. }
  136. # # #
  137. # ============================================================================ #
  138. # 1. BASE #
  139. # ============================================================================ #
  140. ## ABSTRACTS ___________________________________________________________________
  141. # Abstract methods that might be redefined by user:
  142. #
  143. # - function configure(){}
  144. # - function initialize(){}
  145. # - function autoload_controller($callback){}
  146. # - function before($route){}
  147. # - function after($output, $route){}
  148. # - function not_found($errno, $errstr, $errfile=null, $errline=null){}
  149. # - function server_error($errno, $errstr, $errfile=null, $errline=null){}
  150. # - function route_missing($request_method, $request_uri){}
  151. # - function before_exit(){}
  152. # - function before_render($content_or_func, $layout, $locals, $view_path){}
  153. # - function autorender($route){}
  154. # - function before_sending_header($header){}
  155. #
  156. # See abstract.php for more details.
  157. ## MAIN PUBLIC FUNCTIONS _______________________________________________________
  158. /**
  159. * Set and returns options values
  160. *
  161. * If multiple values are provided, set $name option with an array of those values.
  162. * If there is only one value, set $name option with the provided $values
  163. *
  164. * @param string $name
  165. * @param mixed $values,...
  166. * @return mixed option value for $name if $name argument is provided, else return all options
  167. */
  168. function option($name = null, $values = null)
  169. {
  170. static $options = array();
  171. $args = func_get_args();
  172. $name = array_shift($args);
  173. if(is_null($name)) return $options;
  174. if(!empty($args))
  175. {
  176. $options[$name] = count($args) > 1 ? $args : $args[0];
  177. }
  178. if(array_key_exists($name, $options)) return $options[$name];
  179. return;
  180. }
  181. /**
  182. * Set and returns params
  183. *
  184. * Depending on provided arguments:
  185. *
  186. * * Reset params if first argument is null
  187. *
  188. * * If first argument is an array, merge it with current params
  189. *
  190. * * If there is a second argument $value, set param $name (first argument) with $value
  191. * <code>
  192. * params('name', 'Doe') // set 'name' => 'Doe'
  193. * </code>
  194. * * If there is more than 2 arguments, set param $name (first argument) value with
  195. * an array of next arguments
  196. * <code>
  197. * params('months', 'jan', 'feb', 'mar') // set 'month' => array('months', 'jan', 'feb', 'mar')
  198. * </code>
  199. *
  200. * @param mixed $name_or_array_or_null could be null || array of params || name of a param (optional)
  201. * @param mixed $value,... for the $name param (optional)
  202. * @return mixed all params, or one if a first argument $name is provided
  203. */
  204. function params($name_or_array_or_null = null, $value = null)
  205. {
  206. static $params = array();
  207. $args = func_get_args();
  208. if(func_num_args() > 0)
  209. {
  210. $name = array_shift($args);
  211. if(is_null($name))
  212. {
  213. # Reset params
  214. $params = array();
  215. return $params;
  216. }
  217. if(is_array($name))
  218. {
  219. $params = array_merge($params, $name);
  220. return $params;
  221. }
  222. $nargs = count($args);
  223. if($nargs > 0)
  224. {
  225. $value = $nargs > 1 ? $args : $args[0];
  226. $params[$name] = $value;
  227. }
  228. return array_key_exists($name,$params) ? $params[$name] : null;
  229. }
  230. return $params;
  231. }
  232. /**
  233. * Set and returns template variables
  234. *
  235. * If multiple values are provided, set $name variable with an array of those values.
  236. * If there is only one value, set $name variable with the provided $values
  237. *
  238. * @param string $name
  239. * @param mixed $values,...
  240. * @return mixed variable value for $name if $name argument is provided, else return all variables
  241. */
  242. function set($name = null, $values = null)
  243. {
  244. static $vars = array();
  245. $args = func_get_args();
  246. $name = array_shift($args);
  247. if(is_null($name)) return $vars;
  248. if(!empty($args))
  249. {
  250. $vars[$name] = count($args) > 1 ? $args : $args[0];
  251. }
  252. if(array_key_exists($name, $vars)) return $vars[$name];
  253. return $vars;
  254. }
  255. /**
  256. * Sets a template variable with a value or a default value if value is empty
  257. *
  258. * @param string $name
  259. * @param string $value
  260. * @param string $default
  261. * @return mixed setted value
  262. */
  263. function set_or_default($name, $value, $default)
  264. {
  265. return set($name, value_or_default($value, $default));
  266. }
  267. /**
  268. * Running application
  269. *
  270. * @param string $env
  271. * @return void
  272. */
  273. function run($env = null)
  274. {
  275. if(is_null($env)) $env = env();
  276. # 0. Set default configuration
  277. $root_dir = dirname(app_file());
  278. $lim_dir = dirname(__FILE__);
  279. $base_path = dirname(file_path($env['SERVER']['SCRIPT_NAME']));
  280. $base_file = basename($env['SERVER']['SCRIPT_NAME']);
  281. $base_uri = file_path($base_path, (($base_file == 'index.php') ? '?' : $base_file.'?'));
  282. option('root_dir', $root_dir);
  283. option('limonade_dir', file_path($lim_dir));
  284. option('limonade_views_dir', file_path($lim_dir, 'limonade', 'views'));
  285. option('limonade_public_dir',file_path($lim_dir, 'limonade', 'public'));
  286. option('public_dir', file_path($root_dir, 'public'));
  287. option('views_dir', file_path($root_dir, 'views'));
  288. option('controllers_dir', file_path($root_dir, 'controllers'));
  289. option('lib_dir', file_path($root_dir, 'lib'));
  290. option('error_views_dir', option('limonade_views_dir'));
  291. option('base_path', $base_path);
  292. option('base_uri', $base_uri); // set it manually if you use url_rewriting
  293. option('env', ENV_PRODUCTION);
  294. option('debug', true);
  295. option('session', LIM_SESSION_NAME); // true, false or the name of your session
  296. option('encoding', 'utf-8');
  297. option('signature', LIM_NAME); // X-Limonade header value or false to hide it
  298. option('gzip', false);
  299. option('x-sendfile', 0); // 0: disabled,
  300. // X-SENDFILE: for Apache and Lighttpd v. >= 1.5,
  301. // X-LIGHTTPD-SEND-FILE: for Apache and Lighttpd v. < 1.5
  302. # 1. Set handlers
  303. # 1.1 Set error handling
  304. ini_set('display_errors', 1);
  305. set_error_handler('error_handler_dispatcher', E_ALL ^ E_NOTICE);
  306. # 1.2 Register shutdown function
  307. register_shutdown_function('stop_and_exit');
  308. # 2. Set user configuration
  309. call_if_exists('configure');
  310. # 2.1 Set gzip compression if defined
  311. if(is_bool(option('gzip')) && option('gzip'))
  312. {
  313. ini_set('zlib.output_compression', '1');
  314. }
  315. # 2.2 Set X-Limonade header
  316. if($signature = option('signature')) send_header("X-Limonade: $signature");
  317. # 3. Loading libs
  318. require_once_dir(option('lib_dir'));
  319. fallbacks_for_not_implemented_functions();
  320. # 4. Starting session
  321. if(!defined('SID') && option('session'))
  322. {
  323. if(!is_bool(option('session'))) session_name(option('session'));
  324. if(!session_start()) trigger_error("An error occured while trying to start the session", E_USER_WARNING);
  325. }
  326. # 5. Set some default methods if needed
  327. if(!function_exists('after'))
  328. {
  329. function after($output)
  330. {
  331. return $output;
  332. }
  333. }
  334. if(!function_exists('route_missing'))
  335. {
  336. function route_missing($request_method, $request_uri)
  337. {
  338. halt(NOT_FOUND, "($request_method) $request_uri");
  339. }
  340. }
  341. call_if_exists('initialize');
  342. # 6. Check request
  343. if($rm = request_method($env))
  344. {
  345. if(request_is_head($env)) ob_start(); // then no output
  346. if(!request_method_is_allowed($rm))
  347. halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'$rm'</code> is not implemented");
  348. # 6.1 Check matching route
  349. if($route = route_find($rm, request_uri($env)))
  350. {
  351. params($route['params']);
  352. # 6.2 Load controllers dir
  353. if(!function_exists('autoload_controller'))
  354. {
  355. function autoload_controller($callback)
  356. {
  357. require_once_dir(option('controllers_dir'));
  358. }
  359. }
  360. autoload_controller($route['callback']);
  361. if(is_callable($route['callback']))
  362. {
  363. # 6.3 Call before function
  364. call_if_exists('before', $route);
  365. # 6.4 Call matching controller function and output result
  366. $output = call_user_func_array($route['callback'], array_values($route['params']));
  367. if(is_null($output)) $output = call_if_exists('autorender', $route);
  368. echo after(error_notices_render() . $output, $route);
  369. }
  370. else halt(SERVER_ERROR, "Routing error: undefined function '{$route['callback']}'", $route);
  371. }
  372. else route_missing($rm, request_uri($env));
  373. }
  374. else halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'$rm'</code> is not implemented");
  375. }
  376. /**
  377. * Stop and exit limonade application
  378. *
  379. * @access private
  380. * @param boolean exit or not
  381. * @return void
  382. */
  383. function stop_and_exit($exit = true)
  384. {
  385. call_if_exists('before_exit', $exit);
  386. $headers = headers_list();
  387. if(request_is_head())
  388. {
  389. ob_end_clean();
  390. } else {
  391. $flash_sweep = true;
  392. foreach($headers as $header)
  393. {
  394. // If a Content-Type header exists, flash_sweep only if is text/html
  395. // Else if there's no Content-Type header, flash_sweep by default
  396. if(stripos($header, 'Content-Type:') === 0)
  397. {
  398. $flash_sweep = stripos($header, 'Content-Type: text/html') === 0;
  399. break;
  400. }
  401. }
  402. if($flash_sweep) flash_sweep();
  403. }
  404. if(defined('SID')) session_write_close();
  405. if($exit) exit;
  406. }
  407. /**
  408. * Returns limonade environment variables:
  409. *
  410. * 'SERVER', 'FILES', 'REQUEST', 'SESSION', 'ENV', 'COOKIE',
  411. * 'GET', 'POST', 'PUT', 'DELETE'
  412. *
  413. * If a null argument is passed, reset and rebuild environment
  414. *
  415. * @param null @reset reset and rebuild environment
  416. * @return array
  417. */
  418. function env($reset = null)
  419. {
  420. static $env = array();
  421. if(func_num_args() > 0)
  422. {
  423. $args = func_get_args();
  424. if(is_null($args[0])) $env = array();
  425. }
  426. if(empty($env))
  427. {
  428. if(empty($GLOBALS['_SERVER']))
  429. {
  430. // Fixing empty $GLOBALS['_SERVER'] bug
  431. // http://sofadesign.lighthouseapp.com/projects/29612-limonade/tickets/29-env-is-empty
  432. $GLOBALS['_SERVER'] =& $_SERVER;
  433. $GLOBALS['_FILES'] =& $_FILES;
  434. $GLOBALS['_REQUEST'] =& $_REQUEST;
  435. $GLOBALS['_SESSION'] =& $_SESSION;
  436. $GLOBALS['_ENV'] =& $_ENV;
  437. $GLOBALS['_COOKIE'] =& $_COOKIE;
  438. }
  439. $glo_names = array('SERVER', 'FILES', 'REQUEST', 'SESSION', 'ENV', 'COOKIE');
  440. $vars = array_merge($glo_names, request_methods());
  441. foreach($vars as $var)
  442. {
  443. $varname = "_$var";
  444. if(!array_key_exists($varname, $GLOBALS)) $GLOBALS[$varname] = array();
  445. $env[$var] =& $GLOBALS[$varname];
  446. }
  447. $method = request_method($env);
  448. if($method == 'PUT' || $method == 'DELETE')
  449. {
  450. $varname = "_$method";
  451. if(array_key_exists('_method', $_POST) && $_POST['_method'] == $method)
  452. {
  453. foreach($_POST as $k => $v)
  454. {
  455. if($k == "_method") continue;
  456. $GLOBALS[$varname][$k] = $v;
  457. }
  458. }
  459. else
  460. {
  461. parse_str(file_get_contents('php://input'), $GLOBALS[$varname]);
  462. }
  463. }
  464. }
  465. return $env;
  466. }
  467. /**
  468. * Returns application root file path
  469. *
  470. * @return string
  471. */
  472. function app_file()
  473. {
  474. static $file;
  475. if(empty($file))
  476. {
  477. $debug_backtrace = debug_backtrace();
  478. $stacktrace = array_pop($debug_backtrace);
  479. $file = $stacktrace['file'];
  480. }
  481. return file_path($file);
  482. }
  483. # # #
  484. # ============================================================================ #
  485. # 2. ERROR #
  486. # ============================================================================ #
  487. /**
  488. * Associate a function with error code(s) and return all associations
  489. *
  490. * @param string $errno
  491. * @param string $function
  492. * @return array
  493. */
  494. function error($errno = null, $function = null)
  495. {
  496. static $errors = array();
  497. if(func_num_args() > 0)
  498. {
  499. $errors[] = array('errno'=>$errno, 'function'=> $function);
  500. }
  501. return $errors;
  502. }
  503. /**
  504. * Raise an error, passing a given error number and an optional message,
  505. * then exit.
  506. * Error number should be a HTTP status code or a php user error (E_USER...)
  507. * $errno and $msg arguments can be passsed in any order
  508. * If no arguments are passed, default $errno is SERVER_ERROR (500)
  509. *
  510. * @param int,string $errno Error number or message string
  511. * @param string,string $msg Message string or error number
  512. * @param mixed $debug_args extra data provided for debugging
  513. * @return void
  514. */
  515. function halt($errno = SERVER_ERROR, $msg = '', $debug_args = null)
  516. {
  517. $args = func_get_args();
  518. $error = array_shift($args);
  519. # switch $errno and $msg args
  520. # TODO cleanup / refactoring
  521. if(is_string($errno))
  522. {
  523. $msg = $errno;
  524. $oldmsg = array_shift($args);
  525. $errno = empty($oldmsg) ? SERVER_ERROR : $oldmsg;
  526. }
  527. else if(!empty($args)) $msg = array_shift($args);
  528. if(empty($msg) && $errno == NOT_FOUND) $msg = request_uri();
  529. if(empty($msg)) $msg = "";
  530. if(!empty($args)) $debug_args = $args;
  531. set('_lim_err_debug_args', $debug_args);
  532. error_handler_dispatcher($errno, $msg, null, null);
  533. }
  534. /**
  535. * Internal error handler dispatcher
  536. * Find and call matching error handler and exit
  537. * If no match found, call default error handler
  538. *
  539. * @access private
  540. * @param int $errno
  541. * @param string $errstr
  542. * @param string $errfile
  543. * @param string $errline
  544. * @return void
  545. */
  546. function error_handler_dispatcher($errno, $errstr, $errfile, $errline)
  547. {
  548. $back_trace = debug_backtrace();
  549. while($trace = array_shift($back_trace))
  550. {
  551. if($trace['function'] == 'halt')
  552. {
  553. $errfile = $trace['file'];
  554. $errline = $trace['line'];
  555. break;
  556. }
  557. }
  558. # Notices and warning won't halt execution
  559. if(error_wont_halt_app($errno))
  560. {
  561. error_notice($errno, $errstr, $errfile, $errline);
  562. return;
  563. }
  564. else
  565. {
  566. # Other errors will stop application
  567. static $handlers = array();
  568. if(empty($handlers))
  569. {
  570. error(E_LIM_PHP, 'error_default_handler');
  571. $handlers = error();
  572. }
  573. $is_http_err = http_response_status_is_valid($errno);
  574. while($handler = array_shift($handlers))
  575. {
  576. $e = is_array($handler['errno']) ? $handler['errno'] : array($handler['errno']);
  577. while($ee = array_shift($e))
  578. {
  579. if($ee == $errno || $ee == E_LIM_PHP || ($ee == E_LIM_HTTP && $is_http_err))
  580. {
  581. echo call_if_exists($handler['function'], $errno, $errstr, $errfile, $errline);
  582. exit;
  583. }
  584. }
  585. }
  586. }
  587. }
  588. /**
  589. * Default error handler
  590. *
  591. * @param string $errno
  592. * @param string $errstr
  593. * @param string $errfile
  594. * @param string $errline
  595. * @return string error output
  596. */
  597. function error_default_handler($errno, $errstr, $errfile, $errline)
  598. {
  599. $is_http_err = http_response_status_is_valid($errno);
  600. $http_error_code = $is_http_err ? $errno : SERVER_ERROR;
  601. status($http_error_code);
  602. return $http_error_code == NOT_FOUND ?
  603. error_not_found_output($errno, $errstr, $errfile, $errline) :
  604. error_server_error_output($errno, $errstr, $errfile, $errline);
  605. }
  606. /**
  607. * Returns not found error output
  608. *
  609. * @access private
  610. * @param string $msg
  611. * @return string
  612. */
  613. function error_not_found_output($errno, $errstr, $errfile, $errline)
  614. {
  615. if(!function_exists('not_found'))
  616. {
  617. /**
  618. * Default not found error output
  619. *
  620. * @param string $errno
  621. * @param string $errstr
  622. * @param string $errfile
  623. * @param string $errline
  624. * @return string
  625. */
  626. function not_found($errno, $errstr, $errfile=null, $errline=null)
  627. {
  628. option('views_dir', option('error_views_dir'));
  629. $msg = h(rawurldecode($errstr));
  630. return html("<h1>Page not found:</h1><p><code>{$msg}</code></p>", error_layout());
  631. }
  632. }
  633. return not_found($errno, $errstr, $errfile, $errline);
  634. }
  635. /**
  636. * Returns server error output
  637. *
  638. * @access private
  639. * @param int $errno
  640. * @param string $errstr
  641. * @param string $errfile
  642. * @param string $errline
  643. * @return string
  644. */
  645. function error_server_error_output($errno, $errstr, $errfile, $errline)
  646. {
  647. if(!function_exists('server_error'))
  648. {
  649. /**
  650. * Default server error output
  651. *
  652. * @param string $errno
  653. * @param string $errstr
  654. * @param string $errfile
  655. * @param string $errline
  656. * @return string
  657. */
  658. function server_error($errno, $errstr, $errfile=null, $errline=null)
  659. {
  660. $is_http_error = http_response_status_is_valid($errno);
  661. $args = compact('errno', 'errstr', 'errfile', 'errline', 'is_http_error');
  662. option('views_dir', option('limonade_views_dir'));
  663. $html = render('error.html.php', null, $args);
  664. option('views_dir', option('error_views_dir'));
  665. return html($html, error_layout(), $args);
  666. }
  667. }
  668. return server_error($errno, $errstr, $errfile, $errline);
  669. }
  670. /**
  671. * Set and returns error output layout
  672. *
  673. * @param string $layout
  674. * @return string
  675. */
  676. function error_layout($layout = false)
  677. {
  678. static $o_layout = 'default_layout.php';
  679. if($layout !== false)
  680. {
  681. option('error_views_dir', option('views_dir'));
  682. $o_layout = $layout;
  683. }
  684. return $o_layout;
  685. }
  686. /**
  687. * Set a notice if arguments are provided
  688. * Returns all stored notices.
  689. * If $errno argument is null, reset the notices array
  690. *
  691. * @access private
  692. * @param string, null $str
  693. * @return array
  694. */
  695. function error_notice($errno = false, $errstr = null, $errfile = null, $errline = null)
  696. {
  697. static $notices = array();
  698. if($errno) $notices[] = compact('errno', 'errstr', 'errfile', 'errline');
  699. else if(is_null($errno)) $notices = array();
  700. return $notices;
  701. }
  702. /**
  703. * Returns notices output rendering and reset notices
  704. *
  705. * @return string
  706. */
  707. function error_notices_render()
  708. {
  709. if(option('debug') && option('env') > ENV_PRODUCTION)
  710. {
  711. $notices = error_notice();
  712. error_notice(null); // reset notices
  713. $c_view_dir = option('views_dir'); // keep for restore after render
  714. option('views_dir', option('limonade_views_dir'));
  715. $o = render('_notices.html.php', null, array('notices' => $notices));
  716. option('views_dir', $c_view_dir); // restore current views dir
  717. return $o;
  718. }
  719. }
  720. /**
  721. * Checks if an error is will halt application execution.
  722. * Notices and warnings will not.
  723. *
  724. * @access private
  725. * @param string $num error code number
  726. * @return boolean
  727. */
  728. function error_wont_halt_app($num)
  729. {
  730. return $num == E_NOTICE ||
  731. $num == E_WARNING ||
  732. $num == E_CORE_WARNING ||
  733. $num == E_COMPILE_WARNING ||
  734. $num == E_USER_WARNING ||
  735. $num == E_USER_NOTICE ||
  736. $num == E_DEPRECATED ||
  737. $num == E_USER_DEPRECATED ||
  738. $num == E_LIM_DEPRECATED;
  739. }
  740. /**
  741. * return error code name for a given code num, or return all errors names
  742. *
  743. * @param string $num
  744. * @return mixed
  745. */
  746. function error_type($num = null)
  747. {
  748. $types = array (
  749. E_ERROR => 'ERROR',
  750. E_WARNING => 'WARNING',
  751. E_PARSE => 'PARSING ERROR',
  752. E_NOTICE => 'NOTICE',
  753. E_CORE_ERROR => 'CORE ERROR',
  754. E_CORE_WARNING => 'CORE WARNING',
  755. E_COMPILE_ERROR => 'COMPILE ERROR',
  756. E_COMPILE_WARNING => 'COMPILE WARNING',
  757. E_USER_ERROR => 'USER ERROR',
  758. E_USER_WARNING => 'USER WARNING',
  759. E_USER_NOTICE => 'USER NOTICE',
  760. E_STRICT => 'STRICT NOTICE',
  761. E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR',
  762. E_DEPRECATED => 'DEPRECATED WARNING',
  763. E_USER_DEPRECATED => 'USER DEPRECATED WARNING',
  764. E_LIM_DEPRECATED => 'LIMONADE DEPRECATED WARNING'
  765. );
  766. return is_null($num) ? $types : $types[$num];
  767. }
  768. /**
  769. * Returns http response status for a given error number
  770. *
  771. * @param string $errno
  772. * @return int
  773. */
  774. function error_http_status($errno)
  775. {
  776. $code = http_response_status_is_valid($errno) ? $errno : SERVER_ERROR;
  777. return http_response_status($code);
  778. }
  779. # # #
  780. # ============================================================================ #
  781. # 3. REQUEST #
  782. # ============================================================================ #
  783. /**
  784. * Returns current request method for a given environment or current one
  785. *
  786. * @param string $env
  787. * @return string
  788. */
  789. function request_method($env = null)
  790. {
  791. if(is_null($env)) $env = env();
  792. $m = array_key_exists('REQUEST_METHOD', $env['SERVER']) ? $env['SERVER']['REQUEST_METHOD'] : null;
  793. if($m == "POST" && array_key_exists('_method', $env['POST']))
  794. $m = strtoupper($env['POST']['_method']);
  795. if(!in_array(strtoupper($m), request_methods()))
  796. {
  797. trigger_error("'$m' request method is unknown or unavailable.", E_USER_WARNING);
  798. $m = false;
  799. }
  800. return $m;
  801. }
  802. /**
  803. * Checks if a request method or current one is allowed
  804. *
  805. * @param string $m
  806. * @return bool
  807. */
  808. function request_method_is_allowed($m = null)
  809. {
  810. if(is_null($m)) $m = request_method();
  811. return in_array(strtoupper($m), request_methods());
  812. }
  813. /**
  814. * Checks if request method is GET
  815. *
  816. * @param string $env
  817. * @return bool
  818. */
  819. function request_is_get($env = null)
  820. {
  821. return request_method($env) == "GET";
  822. }
  823. /**
  824. * Checks if request method is POST
  825. *
  826. * @param string $env
  827. * @return bool
  828. */
  829. function request_is_post($env = null)
  830. {
  831. return request_method($env) == "POST";
  832. }
  833. /**
  834. * Checks if request method is PUT
  835. *
  836. * @param string $env
  837. * @return bool
  838. */
  839. function request_is_put($env = null)
  840. {
  841. return request_method($env) == "PUT";
  842. }
  843. /**
  844. * Checks if request method is DELETE
  845. *
  846. * @param string $env
  847. * @return bool
  848. */
  849. function request_is_delete($env = null)
  850. {
  851. return request_method($env) == "DELETE";
  852. }
  853. /**
  854. * Checks if request method is HEAD
  855. *
  856. * @param string $env
  857. * @return bool
  858. */
  859. function request_is_head($env = null)
  860. {
  861. return request_method($env) == "HEAD";
  862. }
  863. /**
  864. * Returns allowed request methods
  865. *
  866. * @return array
  867. */
  868. function request_methods()
  869. {
  870. return array("GET","POST","PUT","DELETE", "HEAD");
  871. }
  872. /**
  873. * Returns current request uri (the path that will be compared with routes)
  874. *
  875. * (Inspired from codeigniter URI::_fetch_uri_string method)
  876. *
  877. * @return string
  878. */
  879. function request_uri($env = null)
  880. {
  881. static $uri = null;
  882. if(is_null($env))
  883. {
  884. if(!is_null($uri)) return $uri;
  885. $env = env();
  886. }
  887. if(array_key_exists('uri', $env['GET']))
  888. {
  889. $uri = $env['GET']['uri'];
  890. }
  891. else if(array_key_exists('u', $env['GET']))
  892. {
  893. $uri = $env['GET']['u'];
  894. }
  895. // bug: dot are converted to _... so we can't use it...
  896. // else if (count($env['GET']) == 1 && trim(key($env['GET']), '/') != '')
  897. // {
  898. // $uri = key($env['GET']);
  899. // }
  900. else
  901. {
  902. $app_file = app_file();
  903. $path_info = isset($env['SERVER']['PATH_INFO']) ? $env['SERVER']['PATH_INFO'] : @getenv('PATH_INFO');
  904. $query_string = isset($env['SERVER']['QUERY_STRING']) ? $env['SERVER']['QUERY_STRING'] : @getenv('QUERY_STRING');
  905. // Is there a PATH_INFO variable?
  906. // Note: some servers seem to have trouble with getenv() so we'll test it two ways
  907. if (trim($path_info, '/') != '' && $path_info != "/".$app_file)
  908. {
  909. if(strpos($path_info, '&') !== 0)
  910. {
  911. # exclude GET params
  912. $params = explode('&', $path_info);
  913. $path_info = array_shift($params);
  914. # populate $_GET
  915. foreach($params as $param)
  916. {
  917. if(strpos($param, '=') > 0)
  918. {
  919. list($k, $v) = explode('=', $param);
  920. $env['GET'][$k] = $v;
  921. }
  922. }
  923. }
  924. $uri = $path_info;
  925. }
  926. // No PATH_INFO?... What about QUERY_STRING?
  927. elseif (trim($query_string, '/') != '' && $query_string[0] == '/')
  928. {
  929. $uri = $query_string;
  930. $get = $env['GET'];
  931. if(count($get) > 0)
  932. {
  933. # exclude GET params
  934. $keys = array_keys($get);
  935. $first = array_shift($keys);
  936. if(strpos($query_string, $first) === 0) $uri = $first;
  937. }
  938. }
  939. elseif(array_key_exists('REQUEST_URI', $env['SERVER']) && !empty($env['SERVER']['REQUEST_URI']))
  940. {
  941. $request_uri = rtrim($env['SERVER']['REQUEST_URI'], '?/').'/';
  942. $base_path = $env['SERVER']['SCRIPT_NAME'];
  943. if($request_uri."index.php" == $base_path) $request_uri .= "index.php";
  944. $uri = str_replace($base_path, '', $request_uri);
  945. if(option('base_uri') && strpos($uri, option('base_uri')) === 0) {
  946. $uri = substr($uri, strlen(option('base_uri')));
  947. }
  948. if(strpos($uri, '?') !== false) {
  949. $uri = substr($uri, 0, strpos($uri, '?')) . '/';
  950. }
  951. }
  952. elseif($env['SERVER']['argc'] > 1 && trim($env['SERVER']['argv'][1], '/') != '')
  953. {
  954. $uri = $env['SERVER']['argv'][1];
  955. }
  956. }
  957. $uri = rtrim($uri, "/"); # removes ending /
  958. if(empty($uri))
  959. {
  960. $uri = '/';
  961. }
  962. else if($uri[0] != '/')
  963. {
  964. $uri = '/' . $uri; # add a leading slash
  965. }
  966. return rawurldecode($uri);
  967. }
  968. # # #
  969. # ============================================================================ #
  970. # 4. ROUTER #
  971. # ============================================================================ #
  972. /**
  973. * An alias of {@link dispatch_get()}
  974. *
  975. * @return void
  976. */
  977. function dispatch($path_or_array, $callback, $options = array())
  978. {
  979. dispatch_get($path_or_array, $callback, $options);
  980. }
  981. /**
  982. * Add a GET route. Also automatically defines a HEAD route.
  983. *
  984. * @param string $path_or_array
  985. * @param string $callback
  986. * @param array $options (optional). See {@link route()} for available options.
  987. * @return void
  988. */
  989. function dispatch_get($path_or_array, $callback, $options = array())
  990. {
  991. route("GET", $path_or_array, $callback, $options);
  992. route("HEAD", $path_or_array, $callback, $options);
  993. }
  994. /**
  995. * Add a POST route
  996. *
  997. * @param string $path_or_array
  998. * @param string $callback
  999. * @param array $options (optional). See {@link route()} for available options.
  1000. * @return void
  1001. */
  1002. function dispatch_post($path_or_array, $callback, $options = array())
  1003. {
  1004. route("POST", $path_or_array, $callback, $options);
  1005. }
  1006. /**
  1007. * Add a PUT route
  1008. *
  1009. * @param string $path_or_array
  1010. * @param string $callback
  1011. * @param array $options (optional). See {@link route()} for available options.
  1012. * @return void
  1013. */
  1014. function dispatch_put($path_or_array, $callback, $options = array())
  1015. {
  1016. route("PUT", $path_or_array, $callback, $options);
  1017. }
  1018. /**
  1019. * Add a DELETE route
  1020. *
  1021. * @param string $path_or_array
  1022. * @param string $callback
  1023. * @param array $options (optional). See {@link route()} for available options.
  1024. * @return void
  1025. */
  1026. function dispatch_delete($path_or_array, $callback, $options = array())
  1027. {
  1028. route("DELETE", $path_or_array, $callback, $options);
  1029. }
  1030. /**
  1031. * Add route if required params are provided.
  1032. * Delete all routes if null is passed as a unique argument
  1033. * Return all routes
  1034. *
  1035. * @see route_build()
  1036. * @access private
  1037. * @param string $method
  1038. * @param string|array $path_or_array
  1039. * @param callback $func
  1040. * @param array $options (optional). Available options:
  1041. * - 'params' key with an array of parameters: for parametrized routes.
  1042. * those parameters will be merged with routes parameters.
  1043. * @return array
  1044. */
  1045. function route()
  1046. {
  1047. static $routes = array();
  1048. $nargs = func_num_args();
  1049. if( $nargs > 0)
  1050. {
  1051. $args = func_get_args();
  1052. if($nargs === 1 && is_null($args[0])) $routes = array();
  1053. else if($nargs < 3) trigger_error("Missing arguments for route()", E_USER_ERROR);
  1054. else
  1055. {
  1056. $method = $args[0];
  1057. $path_or_array = $args[1];
  1058. $func = $args[2];
  1059. $options = $nargs > 3 ? $args[3] : array();
  1060. $routes[] = route_build($method, $path_or_array, $func, $options);
  1061. }
  1062. }
  1063. return $routes;
  1064. }
  1065. /**
  1066. * An alias of route(null): reset all routes
  1067. *
  1068. * @access private
  1069. * @return void
  1070. */
  1071. function route_reset()
  1072. {
  1073. route(null);
  1074. }
  1075. /**
  1076. * Build a route and return it
  1077. *
  1078. * @access private
  1079. * @param string $method allowed http method (one of those returned by {@link request_methods()})
  1080. * @param string|array $path_or_array
  1081. * @param callback $callback callback called when route is found. It can be
  1082. * a function, an object method, a static method or a closure.
  1083. * See {@link http://php.net/manual/en/language.pseudo-types.php#language.types.callback php documentation}
  1084. * to learn more about callbacks.
  1085. * @param array $options (optional). Available options:
  1086. * - 'params' key with an array of parameters: for parametrized routes.
  1087. * those parameters will be merged with routes parameters.
  1088. * @return array array with keys "method", "pattern", "names", "callback", "options"
  1089. */
  1090. function route_build($method, $path_or_array, $callback, $options = array())
  1091. {
  1092. $method = strtoupper($method);
  1093. if(!in_array($method, request_methods()))
  1094. trigger_error("'$method' request method is unkown or unavailable.", E_USER_WARNING);
  1095. if(is_array($path_or_array))
  1096. {
  1097. $path = array_shift($path_or_array);
  1098. $names = $path_or_array[0];
  1099. }
  1100. else
  1101. {
  1102. $path = $path_or_array;
  1103. $names = array();
  1104. }
  1105. $single_asterisk_subpattern = "(?:/([^\/]*))?";
  1106. $double_asterisk_subpattern = "(?:/(.*))?";
  1107. $optionnal_slash_subpattern = "(?:/*?)";
  1108. $no_slash_asterisk_subpattern = "(?:([^\/]*))?";
  1109. if($path[0] == "^")
  1110. {
  1111. if($path{strlen($path) - 1} != "$") $path .= "$";
  1112. $pattern = "#".$path."#i";
  1113. }
  1114. else if(empty($path) || $path == "/")
  1115. {
  1116. $pattern = "#^".$optionnal_slash_subpattern."$#";
  1117. }
  1118. else
  1119. {
  1120. $parsed = array();
  1121. $elts = explode('/', $path);
  1122. $parameters_count = 0;
  1123. foreach($elts as $elt)
  1124. {
  1125. if(empty($elt)) continue;
  1126. $name = null;
  1127. # extracting double asterisk **
  1128. if($elt == "**"):
  1129. $parsed[] = $double_asterisk_subpattern;
  1130. $name = $parameters_count;
  1131. # extracting single asterisk *
  1132. elseif($elt == "*"):
  1133. $parsed[] = $single_asterisk_subpattern;
  1134. $name = $parameters_count;
  1135. # extracting named parameters :my_param
  1136. elseif($elt[0] == ":"):
  1137. if(preg_match('/^:([^\:]+)$/', $elt, $matches))
  1138. {
  1139. $parsed[] = $single_asterisk_subpattern;
  1140. $name = $matches[1];
  1141. };
  1142. elseif(strpos($elt, '*') !== false):
  1143. $sub_elts = explode('*', $elt);
  1144. $parsed_sub = array();
  1145. foreach($sub_elts as $sub_elt)
  1146. {
  1147. $parsed_sub[] = preg_quote($sub_elt, "#");
  1148. $name = $parameters_count;
  1149. }
  1150. //
  1151. $parsed[] = "/".implode($no_slash_asterisk_subpattern, $parsed_sub);
  1152. else:
  1153. $parsed[] = "/".preg_quote($elt, "#");
  1154. endif;
  1155. /* set parameters names */
  1156. if(is_null($name)) continue;
  1157. if(!array_key_exists($parameters_count, $names) || is_null($names[$parameters_count]))
  1158. $names[$parameters_count] = $name;
  1159. $parameters_count++;
  1160. }
  1161. $pattern = "#^".implode('', $parsed).$optionnal_slash_subpattern."?$#i";
  1162. }
  1163. return array( "method" => $method,
  1164. "pattern" => $pattern,
  1165. "names" => $names,
  1166. "callback" => $callback,
  1167. "options" => $options );
  1168. }
  1169. /**
  1170. * Find a route and returns it.
  1171. * Parameters values extracted from the path are added and merged
  1172. * with the default 'params' option of the route
  1173. * If not found, returns false.
  1174. * Routes are checked from first added to last added.
  1175. *
  1176. * @access private
  1177. * @param string $method
  1178. * @param string $path
  1179. * @return array,false route array has same keys as route returned by
  1180. * {@link route_build()} ("method", "pattern", "names", "callback", "options")
  1181. * + the processed "params" key
  1182. */
  1183. function route_find($method, $path)
  1184. {
  1185. $routes = route();
  1186. $method = strtoupper($method);
  1187. foreach($routes as $route)
  1188. {
  1189. if($method == $route["method"] && preg_match($route["pattern"], $path, $matches))
  1190. {
  1191. $options = $route["options"];
  1192. $params = array_key_exists('params', $options) ? $options["params"] : array();
  1193. if(count($matches) > 1)
  1194. {
  1195. array_shift($matches);
  1196. $n_matches = count($matches);
  1197. $names = array_values($route["names"]);
  1198. $n_names = count($names);
  1199. if( $n_matches < $n_names )
  1200. {
  1201. $a = array_fill(0, $n_names - $n_matches, null);
  1202. $matches = array_merge($matches, $a);
  1203. }
  1204. else if( $n_matches > $n_names )
  1205. {
  1206. $names = range($n_names, $n_matches - 1);
  1207. }
  1208. $arr_comb = array_combine($names, $matches);
  1209. $params = array_replace($params, $arr_comb);
  1210. }
  1211. $route["params"] = $params;
  1212. return $route;
  1213. }
  1214. }
  1215. return false;
  1216. }
  1217. # ============================================================================ #
  1218. # 5. OUTPUT AND RENDERING #
  1219. # ============================================================================ #
  1220. /**
  1221. * Returns a string to output
  1222. *
  1223. * It might use a template file, a function, or a formatted string (like {@link sprintf()}).
  1224. * It could be embraced by a layout or not.
  1225. * Local vars can be passed in addition to variables made available with the {@link set()}
  1226. * function.
  1227. *
  1228. * @param string $content_or_func
  1229. * @param string $layout
  1230. * @param string $locals
  1231. * @return string
  1232. */
  1233. function render($content_or_func, $layout = '', $locals = array())
  1234. {
  1235. $args = func_get_args();
  1236. $content_or_func = array_shift($args);
  1237. $layout = count($args) > 0 ? array_shift($args) : layout();
  1238. $view_path = file_path(option('views_dir'),$content_or_func);
  1239. if(function_exists('before_render'))
  1240. list($content_or_func, $layout, $locals, $view_path) = before_render($content_or_func, $layout, $locals, $view_path);
  1241. $vars = array_merge(set(), $locals);
  1242. $flash = flash_now();
  1243. 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);
  1244. else if(!empty($flash)) $vars['flash'] = $flash;
  1245. $infinite_loop = false;
  1246. # Avoid infinite loop: this function is in the backtrace ?
  1247. if(function_exists($content_or_func))
  1248. {
  1249. $back_trace = debug_backtrace();
  1250. while($trace = array_shift($back_trace))
  1251. {
  1252. if($trace['function'] == strtolower($content_or_func))
  1253. {
  1254. $infinite_loop = true;
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. if(function_exists($content_or_func) && !$infinite_loop)
  1260. {
  1261. ob_start();
  1262. call_user_func($content_or_func, $vars);
  1263. $content = ob_get_clean();
  1264. }
  1265. elseif(file_exists($view_path))
  1266. {
  1267. ob_start();
  1268. extract($vars);
  1269. include $view_path;
  1270. $content = ob_get_clean();
  1271. }
  1272. else
  1273. {
  1274. if(substr_count($content_or_func, '%') !== count($vars)) $content = $content_or_func;
  1275. else $content = vsprintf($content_or_func, $vars);
  1276. }
  1277. if(empty($layout)) return $content;
  1278. return render($layout, null, array('content' => $content));
  1279. }
  1280. /**
  1281. * Returns a string to output
  1282. *
  1283. * Shortcut to render with no layout.
  1284. *
  1285. * @param string $content_or_func
  1286. * @param string $locals
  1287. * @return string
  1288. */
  1289. function partial($content_or_func, $locals = array())
  1290. {
  1291. return render($content_or_func, null, $locals);
  1292. }
  1293. /**
  1294. * Returns html output with proper http headers
  1295. *
  1296. * @param string $content_or_func
  1297. * @param string $layout
  1298. * @param string $locals
  1299. * @return string
  1300. */
  1301. function html($content_or_func, $layout = '', $locals = array())
  1302. {
  1303. send_header('Content-Type: text/html; charset='.strtolower(option('encoding')));
  1304. $args = func_get_args();
  1305. return call_user_func_array('render', $args);
  1306. }
  1307. /**
  1308. * Set and return current layout
  1309. *
  1310. * @param string $function_or_file
  1311. * @return string
  1312. */
  1313. function layout($function_or_file = null)
  1314. {
  1315. static $layout = null;
  1316. if(func_num_args() > 0) $layout = $function_or_file;
  1317. return $layout;
  1318. }
  1319. /**
  1320. * Returns xml output with proper http headers
  1321. *
  1322. * @param string $content_or_func
  1323. * @param string $layout
  1324. * @param string $locals
  1325. * @return string
  1326. */
  1327. function xml($data)
  1328. {
  1329. send_header('Content-Type: text/xml; charset='.strtolower(option('encoding')));
  1330. $args = func_get_args();
  1331. return call_user_func_array('render', $args);
  1332. }
  1333. /**
  1334. * Returns css output with proper http headers
  1335. *
  1336. * @param string $content_or_func
  1337. * @param string $layout
  1338. * @param string $locals
  1339. * @return string
  1340. */
  1341. function css($content_or_func, $layout = '', $locals = array())
  1342. {
  1343. send_header('Content-Type: text/css; charset='.strtolower(option('encoding')));
  1344. $args = func_get_args();
  1345. return call_user_func_array('render', $args);
  1346. }
  1347. /**
  1348. * Returns javacript output with proper http headers
  1349. *
  1350. * @param string $content_or_func
  1351. * @param string $layout
  1352. * @param string $locals
  1353. * @return string
  1354. */
  1355. function js($content_or_func, $layout = '', $locals = array())
  1356. {
  1357. send_header('Content-Type: application/javascript; charset='.strtolower(option('encoding')));
  1358. $args = func_get_args();
  1359. return call_user_func_array('render', $args);
  1360. }
  1361. /**
  1362. * Returns txt output with proper http headers
  1363. *
  1364. * @param string $content_or_func
  1365. * @param string $layout
  1366. * @param string $locals
  1367. * @return string
  1368. */
  1369. function txt($content_or_func, $layout = '', $locals = array())
  1370. {
  1371. send_header('Content-Type: text/plain; charset='.strtolower(option('encoding')));
  1372. $args = func_get_args();
  1373. return call_user_func_array('render', $args);
  1374. }
  1375. /**
  1376. * Returns json representation of data with proper http headers.
  1377. * On PHP 5 < PHP 5.2.0, you must provide your own implementation of the
  1378. * <code>json_encode()</code> function beore using <code>json()</code>.
  1379. *
  1380. * @param string $data
  1381. * @param int $json_option
  1382. * @return string
  1383. */
  1384. function json($data, $json_option = 0)
  1385. {
  1386. send_header('Content-Type: application/json; charset='.strtolower(option('encoding')));
  1387. return version_compare(PHP_VERSION, '5.3.0', '>=') ? json_encode($data, $json_option) : json_encode($data);
  1388. }
  1389. /**
  1390. * undocumented function
  1391. *
  1392. * @param string $filename
  1393. * @param string $return
  1394. * @return mixed number of bytes delivered or file output if $return = true
  1395. */
  1396. function render_file($filename, $return = false)
  1397. {
  1398. # TODO implements X-SENDFILE headers
  1399. // if($x-sendfile = option('x-sendfile'))
  1400. // {
  1401. // // add a X-Sendfile header for apache and Lighttpd >= 1.5
  1402. // if($x-sendfile > X-SENDFILE) // add a X-LIGHTTPD-send-file header
  1403. //
  1404. // }
  1405. // else
  1406. // {
  1407. //
  1408. // }
  1409. $filename = str_replace('../', '', $filename);
  1410. if(file_exists($filename))
  1411. {
  1412. $content_type = mime_type(file_extension($filename));
  1413. $header = 'Content-type: '.$content_type;
  1414. if(file_is_text($filename)) $header .= '; charset='.strtolower(option('encoding'));
  1415. send_header($header);
  1416. return file_read($filename, $return);
  1417. }
  1418. else halt(NOT_FOUND, "unknown filename $filename");
  1419. }
  1420. /**
  1421. * Call before_sending_header() if it exists, then send headers
  1422. *
  1423. * @param string $header
  1424. * @return void
  1425. */
  1426. function send_header($header = null, $replace = true, $code = false)
  1427. {
  1428. if(!headers_sent())
  1429. {
  1430. call_if_exists('before_sending_header', $header);
  1431. header($header, $replace, $code);
  1432. }
  1433. }
  1434. # # #
  1435. # ============================================================================ #
  1436. # 6. HELPERS #
  1437. # ============================================================================ #
  1438. /**
  1439. * Returns an url composed of params joined with /
  1440. * A param can be a string or an array.
  1441. * If param is an array, its members will be added at the end of the return url
  1442. * as GET parameters "&key=value".
  1443. *
  1444. * @param string or array $param1, $param2 ...
  1445. * @return string
  1446. */
  1447. function url_for($params = null)
  1448. {
  1449. $paths = array();
  1450. $params = func_get_args();
  1451. $GET_params = array();
  1452. foreach($params as $param)
  1453. {
  1454. if(is_array($param))
  1455. {
  1456. $GET_params = array_merge($GET_params, $param);
  1457. continue;
  1458. }
  1459. if(filter_var_url($param))
  1460. {
  1461. $paths[] = $param;
  1462. continue;
  1463. }
  1464. $p = explode('/',$param);
  1465. foreach($p as $v)
  1466. {
  1467. if($v != "") $paths[] = str_replace('%23', '#', rawurlencode($v));
  1468. }
  1469. }
  1470. $path = rtrim(implode('/', $paths), '/');
  1471. if(!filter_var_url($path))
  1472. {
  1473. # it's a relative URL or an URL without a schema
  1474. $base_uri = option('base_uri');
  1475. $path = file_path($base_uri, $path);
  1476. }
  1477. if(!empty($GET_params))
  1478. {
  1479. $is_first_qs_param = true;
  1480. $path_as_no_question_mark = strpos($path, '?') === false;
  1481. foreach($GET_params as $k => $v)
  1482. {
  1483. $qs_separator = $is_first_qs_param && $path_as_no_question_mark ?
  1484. '?' : '&amp;';
  1485. $path .= $qs_separator . rawurlencode($k) . '=' . rawurlencode($v);
  1486. $is_first_qs_param = false;
  1487. }
  1488. }
  1489. if(DIRECTORY_SEPARATOR != '/') $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  1490. return $path;
  1491. }
  1492. /**
  1493. * An alias of {@link htmlspecialchars()}.
  1494. * If no $charset is provided, uses option('encoding') value
  1495. *
  1496. * @param string $str
  1497. * @param string $quote_style
  1498. * @param string $charset
  1499. * @return void
  1500. */
  1501. function h($str, $quote_style = ENT_NOQUOTES, $charset = null)
  1502. {
  1503. if(is_null($charset)) $charset = strtoupper(option('encoding'));
  1504. return htmlspecialchars($str, $quote_style, $charset);
  1505. }
  1506. /**
  1507. * Set and returns flash messages that will be available in the next action
  1508. * via the {@link flash_now()} function or the view variable <code>$flash</code>.
  1509. *
  1510. * If multiple values are provided, set <code>$name</code> variable with an array of those values.
  1511. * If there is only one value, set <code>$name</code> variable with the provided $values
  1512. * or if it's <code>$name</code> is an array, merge it with current messages.
  1513. *
  1514. * @param string, array $name
  1515. * @param mixed $values,...
  1516. * @return mixed variable value for $name if $name argument is provided, else return all variables
  1517. */
  1518. function flash($name = null, $value = null)
  1519. {
  1520. if(!defined('SID')) trigger_error("Flash messages can't be used because session isn't enabled", E_USER_WARNING);
  1521. static $messages = array();
  1522. $args = func_get_args();
  1523. $name = array_shift($args);
  1524. if(is_null($name)) return $messages;
  1525. if(is_array($name)) return $messages = array_merge($messages, $name);
  1526. if(!empty($args))
  1527. {
  1528. $messages[$name] = count($args) > 1 ? $args : $args[0];
  1529. }
  1530. if(!array_key_exists($name, $messages)) return null;
  1531. else return $messages[$name];
  1532. return $messages;
  1533. }
  1534. /**
  1535. * Set and returns flash messages available for the current action, included those
  1536. * defined in the previous action with {@link flash()}
  1537. * Those messages will also be passed to the views and made available in the
  1538. * <code>$flash</code> variable.
  1539. *
  1540. * If multiple values are provided, set <code>$name</code> variable with an array of those values.
  1541. * If there is only one value, set <code>$name</code> variable with the provided $values
  1542. * or if it's <code>$name</code> is an array, merge it with current messages.
  1543. *
  1544. * @param string, array $name
  1545. * @param mixed $values,...
  1546. * @return mixed variable value for $name if $name argument is provided, else return all variables
  1547. */
  1548. function flash_now($name = null, $value = null)
  1549. {
  1550. static $messages = null;
  1551. if(is_null($messages))
  1552. {
  1553. $fkey = LIM_SESSION_FLASH_KEY;
  1554. $messages = array();
  1555. if(defined('SID') && array_key_exists($fkey, $_SESSION)) $messages = $_SESSION[$fkey];
  1556. }
  1557. $args = func_get_args();
  1558. $name = array_shift($args);
  1559. if(is_null($name)) return $messages;
  1560. if(is_array($name)) return $messages = array_merge($messages, $name);
  1561. if(!empty($args))
  1562. {
  1563. $messages[$name] = count($args) > 1 ? $args : $args[0];
  1564. }
  1565. if(!array_key_exists($name, $messages)) return null;
  1566. else return $messages[$name];
  1567. return $messages;
  1568. }
  1569. /**
  1570. * Delete current flash messages in session, and set new ones stored with
  1571. * flash function.
  1572. * Called before application exit.
  1573. *
  1574. * @access private
  1575. * @return void
  1576. */
  1577. function flash_sweep()
  1578. {
  1579. if(defined('SID'))
  1580. {
  1581. $fkey = LIM_SESSION_FLASH_KEY;
  1582. $_SESSION[$fkey] = flash();
  1583. }
  1584. }
  1585. /**
  1586. * Starts capturing block of text
  1587. *
  1588. * Calling without params stops capturing (same as end_content_for()).
  1589. * After capturing the captured block is put into a variable
  1590. * named $name for later use in layouts. If second parameter
  1591. * is supplied, its content will be used instead of capturing
  1592. * a block of text.
  1593. *
  1594. * @param string $name
  1595. * @param string $content
  1596. * @return void
  1597. */
  1598. function content_for($name = null, $content = null)
  1599. {
  1600. static $_name = null;
  1601. if(is_null($name) && !is_null($_name))
  1602. {
  1603. set($_name, ob_get_clean());
  1604. $_name = null;
  1605. }
  1606. elseif(!is_null($name) && !isset($content))
  1607. {
  1608. $_name = $name;
  1609. ob_start();
  1610. }
  1611. elseif(isset($name, $content))
  1612. {
  1613. set($name, $content);
  1614. }
  1615. }
  1616. /**
  1617. * Stops capturing block of text
  1618. *
  1619. * @return void
  1620. */
  1621. function end_content_for()
  1622. {
  1623. content_for();
  1624. }
  1625. /**
  1626. * Shows current memory and execution time of the application.
  1627. * Returns only execution time if <code>memory_get_usage()</code>
  1628. * isn't available.
  1629. * ( That's the case before PHP5.2.1 if PHP isn't compiled with option
  1630. * <code>--enable-memory-limit</code>. )
  1631. *
  1632. * @access public
  1633. * @return array
  1634. */
  1635. function benchmark()
  1636. {
  1637. $res = array( 'execution_time' => (microtime() - LIM_START_MICROTIME) );
  1638. if(defined('LIM_START_MEMORY'))
  1639. {
  1640. $current_mem_usage = memory_get_usage();
  1641. $res['current_memory'] = $current_mem_usage;
  1642. $res['start_memory'] = LIM_START_MEMORY;
  1643. $res['average_memory'] = (LIM_START_MEMORY + $current_mem_usage) / 2;
  1644. }
  1645. return $res;
  1646. }
  1647. # # #
  1648. # ============================================================================ #
  1649. # 7. UTILS #
  1650. # ============================================================================ #
  1651. /**
  1652. * Calls a function if exists
  1653. *
  1654. * @param callback $callback a function stored in a string variable,
  1655. * or an object and the name of a method within the object
  1656. * See {@link http://php.net/manual/en/language.pseudo-types.php#language.types.callback php documentation}
  1657. * to learn more about callbacks.
  1658. * @param mixed $arg,.. (optional)
  1659. * @return mixed
  1660. */
  1661. function call_if_exists($callback)
  1662. {
  1663. $args = func_get_args();
  1664. $callback = array_shift($args);
  1665. if(is_callable($callback)) return call_user_func_array($callback, $args);
  1666. return;
  1667. }
  1668. /**
  1669. * Define a constant unless it already exists
  1670. *
  1671. * @param string $name
  1672. * @param string $value
  1673. * @return void
  1674. */
  1675. function define_unless_exists($name, $value)
  1676. {
  1677. if(!defined($name)) define($name, $value);
  1678. }
  1679. /**
  1680. * Return a default value if provided value is empty
  1681. *
  1682. * @param mixed $value
  1683. * @param mixed $default default value returned if $value is empty
  1684. * @return mixed
  1685. */
  1686. function value_or_default($value, $default)
  1687. {
  1688. return empty($value) ? $default : $value;
  1689. }
  1690. /**
  1691. * An alias of {@link value_or_default()}
  1692. *
  1693. *
  1694. * @param mixed $value
  1695. * @param mixed $default
  1696. * @return mixed
  1697. */
  1698. function v($value, $default)
  1699. {
  1700. return value_or_default($value, $default);
  1701. }
  1702. /**
  1703. * Load php files with require_once in a given dir
  1704. *
  1705. * @param string $path Path in which are the file to load
  1706. * @param string $pattern a regexp pattern that filter files to load
  1707. * @param bool $prevents_output security option that prevents output
  1708. * @return array paths of loaded files
  1709. */
  1710. function require_once_dir($path, $pattern = "*.php", $prevents_output = true)
  1711. {
  1712. if($path[strlen($path) - 1] != "/") $path .= "/";
  1713. $filenames = glob($path.$pattern);
  1714. if(!is_array($filenames)) $filenames = array();
  1715. if($prevents_output) ob_start();
  1716. foreach($filenames as $filename) require_once $filename;
  1717. if($prevents_output) ob_end_clean();
  1718. return $filenames;
  1719. }
  1720. /**
  1721. * Dumps a variable into inspectable format
  1722. *
  1723. * @param anything $var the variable to debug
  1724. * @param bool $output_as_html sets whether to wrap output in <pre> tags. default: true
  1725. * @return string the variable with output
  1726. */
  1727. function debug($var, $output_as_html = true)
  1728. {
  1729. if ( is_null($var) ) { return '<span class="null-value">[NULL]</span>'; };
  1730. $out = '';
  1731. switch ($var)
  1732. {
  1733. case empty($var):
  1734. $out = '[empty value]';
  1735. break;
  1736. case is_array($var):
  1737. $out = var_export($var, true);
  1738. break;
  1739. case is_object($var):
  1740. $out = var_export($var, true);
  1741. break;
  1742. case is_string($var):
  1743. $out = $var;
  1744. break;
  1745. default:
  1746. $out = var_export($var, true);
  1747. break;
  1748. }
  1749. if ($output_as_html) { $out = "<pre>\n" . h($out) ."</pre>"; }
  1750. return $out;
  1751. }
  1752. ## HTTP utils _________________________________________________________________
  1753. ### Constants: HTTP status codes
  1754. define( 'HTTP_CONTINUE', 100 );
  1755. define( 'HTTP_SWITCHING_PROTOCOLS', 101 );
  1756. define( 'HTTP_PROCESSING', 102 );
  1757. define( 'HTTP_OK', 200 );
  1758. define( 'HTTP_CREATED', 201 );
  1759. define( 'HTTP_ACCEPTED', 202 );
  1760. define( 'HTTP_NON_AUTHORITATIVE', 203 );
  1761. define( 'HTTP_NO_CONTENT', 204 );
  1762. define( 'HTTP_RESET_CONTENT', 205 );
  1763. define( 'HTTP_PARTIAL_CONTENT', 206 );
  1764. define( 'HTTP_MULTI_STATUS', 207 );
  1765. define( 'HTTP_MULTIPLE_CHOICES', 300 );
  1766. define( 'HTTP_MOVED_PERMANENTLY', 301 );
  1767. define( 'HTTP_MOVED_TEMPORARILY', 302 );
  1768. define( 'HTTP_SEE_OTHER', 303 );
  1769. define( 'HTTP_NOT_MODIFIED', 304 );
  1770. define( 'HTTP_USE_PROXY', 305 );
  1771. define( 'HTTP_TEMPORARY_REDIRECT', 307 );
  1772. define( 'HTTP_BAD_REQUEST', 400 );
  1773. define( 'HTTP_UNAUTHORIZED', 401 );
  1774. define( 'HTTP_PAYMENT_REQUIRED', 402 );
  1775. define( 'HTTP_FORBIDDEN', 403 );
  1776. define( 'HTTP_NOT_FOUND', 404 );
  1777. define( 'HTTP_METHOD_NOT_ALLOWED', 405 );
  1778. define( 'HTTP_NOT_ACCEPTABLE', 406 );
  1779. define( 'HTTP_PROXY_AUTHENTICATION_REQUIRED', 407 );
  1780. define( 'HTTP_REQUEST_TIME_OUT', 408 );
  1781. define( 'HTTP_CONFLICT', 409 );
  1782. define( 'HTTP_GONE', 410 );
  1783. define( 'HTTP_LENGTH_REQUIRED', 411 );
  1784. define( 'HTTP_PRECONDITION_FAILED', 412 );
  1785. define( 'HTTP_REQUEST_ENTITY_TOO_LARGE', 413 );
  1786. define( 'HTTP_REQUEST_URI_TOO_LARGE', 414 );
  1787. define( 'HTTP_UNSUPPORTED_MEDIA_TYPE', 415 );
  1788. define( 'HTTP_RANGE_NOT_SATISFIABLE', 416 );
  1789. define( 'HTTP_EXPECTATION_FAILED', 417 );
  1790. define( 'HTTP_UNPROCESSABLE_ENTITY', 422 );
  1791. define( 'HTTP_LOCKED', 423 );
  1792. define( 'HTTP_FAILED_DEPENDENCY', 424 );
  1793. define( 'HTTP_UPGRADE_REQUIRED', 426 );
  1794. define( 'HTTP_INTERNAL_SERVER_ERROR', 500 );
  1795. define( 'HTTP_NOT_IMPLEMENTED', 501 );
  1796. define( 'HTTP_BAD_GATEWAY', 502 );
  1797. define( 'HTTP_SERVICE_UNAVAILABLE', 503 );
  1798. define( 'HTTP_GATEWAY_TIME_OUT', 504 );
  1799. define( 'HTTP_VERSION_NOT_SUPPORTED', 505 );
  1800. define( 'HTTP_VARIANT_ALSO_VARIES', 506 );
  1801. define( 'HTTP_INSUFFICIENT_STORAGE', 507 );
  1802. define( 'HTTP_NOT_EXTENDED', 510 );
  1803. /**
  1804. * Output proper HTTP header for a given HTTP code
  1805. *
  1806. * @param string $code
  1807. * @return void
  1808. */
  1809. function status($code = 500)
  1810. {
  1811. if(!headers_sent())
  1812. {
  1813. $str = http_response_status_code($code);
  1814. send_header($str);
  1815. }
  1816. }
  1817. /**
  1818. * Http redirection
  1819. *
  1820. * Same use as {@link url_for()}
  1821. * By default HTTP status code is 302, but a different code can be specified
  1822. * with a status key in array parameter.
  1823. *
  1824. * <code>
  1825. * redirecto('new','url'); # 302 HTTP_MOVED_TEMPORARILY by default
  1826. * redirecto('new','url', array('status' => HTTP_MOVED_PERMANENTLY));
  1827. * </code>
  1828. *
  1829. * @param string or array $param1, $param2...
  1830. * @return void
  1831. */
  1832. function redirect_to($params)
  1833. {
  1834. # [NOTE]: (from php.net) HTTP/1.1 requires an absolute URI as argument to Âť Location:
  1835. # including the scheme, hostname and absolute path, but some clients accept
  1836. # relative URIs. You can usually use $_SERVER['HTTP_HOST'],
  1837. # $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative
  1838. # one yourself.
  1839. # TODO make absolute uri
  1840. if(!headers_sent())
  1841. {
  1842. $status = HTTP_MOVED_TEMPORARILY; # default for a redirection in PHP
  1843. $params = func_get_args();
  1844. $n_params = array();
  1845. # extract status param if exists
  1846. foreach($params as $param)
  1847. {
  1848. if(is_array($param))
  1849. {
  1850. if(array_key_exists('status', $param))
  1851. {
  1852. $status = $param['status'];
  1853. unset($param['status']);
  1854. }
  1855. }
  1856. $n_params[] = $param;
  1857. }
  1858. $uri = call_user_func_array('url_for', $n_params);
  1859. $uri = htmlspecialchars_decode($uri, ENT_NOQUOTES);
  1860. stop_and_exit(false);
  1861. send_header('Location: '.$uri, true, $status);
  1862. exit;
  1863. }
  1864. }
  1865. /**
  1866. * Http redirection
  1867. *
  1868. * @deprecated deprecated since version 0.4. Please use {@link redirect_to()} instead.
  1869. * @param string $url
  1870. * @return void
  1871. */
  1872. function redirect($uri)
  1873. {
  1874. # halt('redirect() is deprecated. Please use redirect_to() instead.', E_LIM_DEPRECATED);
  1875. # halt not necesary... it won't be visible because of http redirection...
  1876. redirect_to($uri);
  1877. }
  1878. /**
  1879. * Returns HTTP response status for a given code.
  1880. * If no code provided, return an array of all status
  1881. *
  1882. * @param string $num
  1883. * @return string,array
  1884. */
  1885. function http_response_status($num = null)
  1886. {
  1887. $status = array(
  1888. 100 => 'Continue',
  1889. 101 => 'Switching Protocols',
  1890. 102 => 'Processing',
  1891. 200 => 'OK',
  1892. 201 => 'Created',
  1893. 202 => 'Accepted',
  1894. 203 => 'Non-Authoritative Information',
  1895. 204 => 'No Content',
  1896. 205 => 'Reset Content',
  1897. 206 => 'Partial Content',
  1898. 207 => 'Multi-Status',
  1899. 226 => 'IM Used',
  1900. 300 => 'Multiple Choices',
  1901. 301 => 'Moved Permanently',
  1902. 302 => 'Found',
  1903. 303 => 'See Other',
  1904. 304 => 'Not Modified',
  1905. 305 => 'Use Proxy',
  1906. 306 => 'Reserved',
  1907. 307 => 'Temporary Redirect',
  1908. 400 => 'Bad Request',
  1909. 401 => 'Unauthorized',
  1910. 402 => 'Payment Required',
  1911. 403 => 'Forbidden',
  1912. 404 => 'Not Found',
  1913. 405 => 'Method Not Allowed',
  1914. 406 => 'Not Acceptable',
  1915. 407 => 'Proxy Authentication Required',
  1916. 408 => 'Request Timeout',
  1917. 409 => 'Conflict',
  1918. 410 => 'Gone',
  1919. 411 => 'Length Required',
  1920. 412 => 'Precondition Failed',
  1921. 413 => 'Request Entity Too Large',
  1922. 414 => 'Request-URI Too Long',
  1923. 415 => 'Unsupported Media Type',
  1924. 416 => 'Requested Range Not Satisfiable',
  1925. 417 => 'Expectation Failed',
  1926. 422 => 'Unprocessable Entity',
  1927. 423 => 'Locked',
  1928. 424 => 'Failed Dependency',
  1929. 426 => 'Upgrade Required',
  1930. 500 => 'Internal Server Error',
  1931. 501 => 'Not Implemented',
  1932. 502 => 'Bad Gateway',
  1933. 503 => 'Service Unavailable',
  1934. 504 => 'Gateway Timeout',
  1935. 505 => 'HTTP Version Not Supported',
  1936. 506 => 'Variant Also Negotiates',
  1937. 507 => 'Insufficient Storage',
  1938. 510 => 'Not Extended'
  1939. );
  1940. if(is_null($num)) return $status;
  1941. return array_key_exists($num, $status) ? $status[$num] : '';
  1942. }
  1943. /**
  1944. * Checks if an HTTP response code is valid
  1945. *
  1946. * @param string $num
  1947. * @return bool
  1948. */
  1949. function http_response_status_is_valid($num)
  1950. {
  1951. $r = http_response_status($num);
  1952. return !empty($r);
  1953. }
  1954. /**
  1955. * Returns an HTTP response status string for a given code
  1956. *
  1957. * @param string $num
  1958. * @return string
  1959. */
  1960. function http_response_status_code($num)
  1961. {
  1962. $protocole = empty($_SERVER["SERVER_PROTOCOL"]) ? "HTTP/1.1" : $_SERVER["SERVER_PROTOCOL"];
  1963. if($str = http_response_status($num)) return "$protocole $num $str";
  1964. }
  1965. /**
  1966. * Check if the _Accept_ header is present, and includes the given `type`.
  1967. *
  1968. * When the _Accept_ header is not present `true` is returned. Otherwise
  1969. * the given `type` is matched by an exact match, and then subtypes. You
  1970. * may pass the subtype such as "html" which is then converted internally
  1971. * to "text/html" using the mime lookup table.
  1972. *
  1973. * @param string $type
  1974. * @param string $env
  1975. * @return bool
  1976. */
  1977. function http_ua_accepts($type, $env = null)
  1978. {
  1979. if(is_null($env)) $env = env();
  1980. $accept = array_key_exists('HTTP_ACCEPT', $env['SERVER']) ? $env['SERVER']['HTTP_ACCEPT'] : null;
  1981. if(!$accept || $accept === '*/*') return true;
  1982. if($type)
  1983. {
  1984. // Allow "html" vs "text/html" etc
  1985. if(!strpos($type, '/')) $type = mime_type($type);
  1986. // Check if we have a direct match
  1987. if(strpos($accept, $type) > -1) return true;
  1988. // Check if we have type/*
  1989. $type_parts = explode('/', $type);
  1990. $type = $type_parts[0].'/*';
  1991. return (strpos($accept, $type) > -1);
  1992. }
  1993. return false;
  1994. }
  1995. ## FILE utils _________________________________________________________________
  1996. /**
  1997. * Returns mime type for a given extension or if no extension is provided,
  1998. * all mime types in an associative array, with extensions as keys.
  1999. * (extracted from Orbit source http://orbit.luaforge.net/)
  2000. *
  2001. * @param string $ext
  2002. * @return string, array
  2003. */
  2004. function mime_type($ext = null)
  2005. {
  2006. $types = array(
  2007. 'ai' => 'application/postscript',
  2008. 'aif' => 'audio/x-aiff',
  2009. 'aifc' => 'audio/x-aiff',
  2010. 'aiff' => 'audio/x-aiff',
  2011. 'asc' => 'text/plain',
  2012. 'atom' => 'application/atom+xml',
  2013. 'atom' => 'application/atom+xml',
  2014. 'au' => 'audio/basic',
  2015. 'avi' => 'video/x-msvideo',
  2016. 'bcpio' => 'application/x-bcpio',
  2017. 'bin' => 'application/octet-stream',
  2018. 'bmp' => 'image/bmp',
  2019. 'cdf' => 'application/x-netcdf',
  2020. 'cgm' => 'image/cgm',
  2021. 'class' => 'application/octet-stream',
  2022. 'cpio' => 'application/x-cpio',
  2023. 'cpt' => 'application/mac-compactpro',
  2024. 'csh' => 'application/x-csh',
  2025. 'css' => 'text/css',
  2026. 'csv' => 'text/csv',
  2027. 'dcr' => 'application/x-director',
  2028. 'dir' => 'application/x-director',
  2029. 'djv' => 'image/vnd.djvu',
  2030. 'djvu' => 'image/vnd.djvu',
  2031. 'dll' => 'application/octet-stream',
  2032. 'dmg' => 'application/octet-stream',
  2033. 'dms' => 'application/octet-stream',
  2034. 'doc' => 'application/msword',
  2035. 'dtd' => 'application/xml-dtd',
  2036. 'dvi' => 'application/x-dvi',
  2037. 'dxr' => 'application/x-director',
  2038. 'eps' => 'application/postscript',
  2039. 'etx' => 'text/x-setext',
  2040. 'exe' => 'application/octet-stream',
  2041. 'ez' => 'application/andrew-inset',
  2042. 'gif' => 'image/gif',
  2043. 'gram' => 'application/srgs',
  2044. 'grxml' => 'application/srgs+xml',
  2045. 'gtar' => 'application/x-gtar',
  2046. 'hdf' => 'application/x-hdf',
  2047. 'hqx' => 'application/mac-binhex40',
  2048. 'htm' => 'text/html',
  2049. 'html' => 'text/html',
  2050. 'ice' => 'x-conference/x-cooltalk',
  2051. 'ico' => 'image/x-icon',
  2052. 'ics' => 'text/calendar',
  2053. 'ief' => 'image/ief',
  2054. 'ifb' => 'text/calendar',
  2055. 'iges' => 'model/iges',
  2056. 'igs' => 'model/iges',
  2057. 'jpe' => 'image/jpeg',
  2058. 'jpeg' => 'image/jpeg',
  2059. 'jpg' => 'image/jpeg',
  2060. 'js' => 'application/x-javascript',
  2061. 'json' => 'application/json',
  2062. 'kar' => 'audio/midi',
  2063. 'latex' => 'application/x-latex',
  2064. 'lha' => 'application/octet-stream',
  2065. 'lzh' => 'application/octet-stream',
  2066. 'm3u' => 'audio/x-mpegurl',
  2067. 'man' => 'application/x-troff-man',
  2068. 'mathml' => 'application/mathml+xml',
  2069. 'me' => 'application/x-troff-me',
  2070. 'mesh' => 'model/mesh',
  2071. 'mid' => 'audio/midi',
  2072. 'midi' => 'audio/midi',
  2073. 'mif' => 'application/vnd.mif',
  2074. 'mov' => 'video/quicktime',
  2075. 'movie' => 'video/x-sgi-movie',
  2076. 'mp2' => 'audio/mpeg',
  2077. 'mp3' => 'audio/mpeg',
  2078. 'mpe' => 'video/mpeg',
  2079. 'mpeg' => 'video/mpeg',
  2080. 'mpg' => 'video/mpeg',
  2081. 'mpga' => 'audio/mpeg',
  2082. 'ms' => 'application/x-troff-ms',
  2083. 'msh' => 'model/mesh',
  2084. 'mxu' => 'video/vnd.mpegurl',
  2085. 'nc' => 'application/x-netcdf',
  2086. 'oda' => 'application/oda',
  2087. 'ogg' => 'application/ogg',
  2088. 'pbm' => 'image/x-portable-bitmap',
  2089. 'pdb' => 'chemical/x-pdb',
  2090. 'pdf' => 'application/pdf',
  2091. 'pgm' => 'image/x-portable-graymap',
  2092. 'pgn' => 'application/x-chess-pgn',
  2093. 'png' => 'image/png',
  2094. 'pnm' => 'image/x-portable-anymap',
  2095. 'ppm' => 'image/x-portable-pixmap',
  2096. 'ppt' => 'application/vnd.ms-powerpoint',
  2097. 'ps' => 'application/postscript',
  2098. 'qt' => 'video/quicktime',
  2099. 'ra' => 'audio/x-pn-realaudio',
  2100. 'ram' => 'audio/x-pn-realaudio',
  2101. 'ras' => 'image/x-cmu-raster',
  2102. 'rdf' => 'application/rdf+xml',
  2103. 'rgb' => 'image/x-rgb',
  2104. 'rm' => 'application/vnd.rn-realmedia',
  2105. 'roff' => 'application/x-troff',
  2106. 'rss' => 'application/rss+xml',
  2107. 'rtf' => 'text/rtf',
  2108. 'rtx' => 'text/richtext',
  2109. 'sgm' => 'text/sgml',
  2110. 'sgml' => 'text/sgml',
  2111. 'sh' => 'application/x-sh',
  2112. 'shar' => 'application/x-shar',
  2113. 'silo' => 'model/mesh',
  2114. 'sit' => 'application/x-stuffit',
  2115. 'skd' => 'application/x-koan',
  2116. 'skm' => 'application/x-koan',
  2117. 'skp' => 'application/x-koan',
  2118. 'skt' => 'application/x-koan',
  2119. 'smi' => 'application/smil',
  2120. 'smil' => 'application/smil',
  2121. 'snd' => 'audio/basic',
  2122. 'so' => 'application/octet-stream',
  2123. 'spl' => 'application/x-futuresplash',
  2124. 'src' => 'application/x-wais-source',
  2125. 'sv4cpio' => 'application/x-sv4cpio',
  2126. 'sv4crc' => 'application/x-sv4crc',
  2127. 'svg' => 'image/svg+xml',
  2128. 'svgz' => 'image/svg+xml',
  2129. 'swf' => 'application/x-shockwave-flash',
  2130. 't' => 'application/x-troff',
  2131. 'tar' => 'application/x-tar',
  2132. 'tcl' => 'application/x-tcl',
  2133. 'tex' => 'application/x-tex',
  2134. 'texi' => 'application/x-texinfo',
  2135. 'texinfo' => 'application/x-texinfo',
  2136. 'tif' => 'image/tiff',
  2137. 'tiff' => 'image/tiff',
  2138. 'tr' => 'application/x-troff',
  2139. 'tsv' => 'text/tab-separated-values',
  2140. 'txt' => 'text/plain',
  2141. 'ustar' => 'application/x-ustar',
  2142. 'vcd' => 'application/x-cdlink',
  2143. 'vrml' => 'model/vrml',
  2144. 'vxml' => 'application/voicexml+xml',
  2145. 'wav' => 'audio/x-wav',
  2146. 'wbmp' => 'image/vnd.wap.wbmp',
  2147. 'wbxml' => 'application/vnd.wap.wbxml',
  2148. 'wml' => 'text/vnd.wap.wml',
  2149. 'wmlc' => 'application/vnd.wap.wmlc',
  2150. 'wmls' => 'text/vnd.wap.wmlscript',
  2151. 'wmlsc' => 'application/vnd.wap.wmlscriptc',
  2152. 'wrl' => 'model/vrml',
  2153. 'xbm' => 'image/x-xbitmap',
  2154. 'xht' => 'application/xhtml+xml',
  2155. 'xhtml' => 'application/xhtml+xml',
  2156. 'xls' => 'application/vnd.ms-excel',
  2157. 'xml' => 'application/xml',
  2158. 'xpm' => 'image/x-xpixmap',
  2159. 'xsl' => 'application/xml',
  2160. 'xslt' => 'application/xslt+xml',
  2161. 'xul' => 'application/vnd.mozilla.xul+xml',
  2162. 'xwd' => 'image/x-xwindowdump',
  2163. 'xyz' => 'chemical/x-xyz',
  2164. 'zip' => 'application/zip'
  2165. );
  2166. return is_null($ext) ? $types : $types[strtolower($ext)];
  2167. }
  2168. /**
  2169. * Detect MIME Content-type for a file
  2170. *
  2171. * @param string $filename Path to the tested file.
  2172. * @return string
  2173. */
  2174. function file_mime_content_type($filename)
  2175. {
  2176. $ext = file_extension($filename); /* strtolower isn't necessary */
  2177. if($mime = mime_type($ext)) return $mime;
  2178. elseif (function_exists('finfo_open'))
  2179. {
  2180. if($finfo = finfo_open(FILEINFO_MIME))
  2181. {
  2182. if($mime = finfo_file($finfo, $filename))
  2183. {
  2184. finfo_close($finfo);
  2185. return $mime;
  2186. }
  2187. }
  2188. }
  2189. return 'application/octet-stream';
  2190. }
  2191. /**
  2192. * Read and output file content and return filesize in bytes or status after
  2193. * closing file.
  2194. * This function is very efficient for outputing large files without timeout
  2195. * nor too expensive memory use
  2196. *
  2197. * @param string $filename
  2198. * @param string $retbytes
  2199. * @return bool, int
  2200. */
  2201. function file_read_chunked($filename, $retbytes = true)
  2202. {
  2203. $chunksize = 1*(1024*1024); // how many bytes per chunk
  2204. $buffer = '';
  2205. $cnt = 0;
  2206. $handle = fopen($filename, 'rb');
  2207. if ($handle === false) return false;
  2208. ob_start();
  2209. while (!feof($handle)) {
  2210. $buffer = fread($handle, $chunksize);
  2211. echo $buffer;
  2212. ob_flush();
  2213. flush();
  2214. if ($retbytes) $cnt += strlen($buffer);
  2215. set_time_limit(0);
  2216. }
  2217. ob_end_flush();
  2218. $status = fclose($handle);
  2219. if ($retbytes && $status) return $cnt; // return num. bytes delivered like readfile() does.
  2220. return $status;
  2221. }
  2222. /**
  2223. * Create a file path by concatenation of given arguments.
  2224. * Windows paths with backslash directory separators are normalized in *nix paths.
  2225. *
  2226. * @param string $path, ...
  2227. * @return string normalized path
  2228. */
  2229. function file_path($path)
  2230. {
  2231. $args = func_get_args();
  2232. $ds = '/';
  2233. $win_ds = '\\';
  2234. $n_path = count($args) > 1 ? implode($ds, $args) : $path;
  2235. if(strpos($n_path, $win_ds) !== false) $n_path = str_replace( $win_ds, $ds, $n_path );
  2236. $n_path = preg_replace( "#$ds+#", $ds, $n_path);
  2237. return $n_path;
  2238. }
  2239. /**
  2240. * Returns file extension or false if none
  2241. *
  2242. * @param string $filename
  2243. * @return string, false
  2244. */
  2245. function file_extension($filename)
  2246. {
  2247. $pos = strrpos($filename, '.');
  2248. if($pos !== false) return substr($filename, $pos + 1);
  2249. return false;
  2250. }
  2251. /**
  2252. * Checks if $filename is a text file
  2253. *
  2254. * @param string $filename
  2255. * @return bool
  2256. */
  2257. function file_is_text($filename)
  2258. {
  2259. if($mime = file_mime_content_type($filename)) return substr($mime,0,5) == "text/";
  2260. return null;
  2261. }
  2262. /**
  2263. * Checks if $filename is a binary file
  2264. *
  2265. * @param string $filename
  2266. * @return void
  2267. */
  2268. function file_is_binary($filename)
  2269. {
  2270. $is_text = file_is_text($filename);
  2271. return is_null($is_text) ? null : !$is_text;
  2272. }
  2273. /**
  2274. * Return or output file content
  2275. *
  2276. * @return string, int
  2277. *
  2278. **/
  2279. function file_read($filename, $return = false)
  2280. {
  2281. if(!file_exists($filename)) trigger_error("$filename doesn't exists", E_USER_ERROR);
  2282. if($return) return file_get_contents($filename);
  2283. return file_read_chunked($filename);
  2284. }
  2285. /**
  2286. * Returns an array of files contained in a directory
  2287. *
  2288. * @param string $dir
  2289. * @return array
  2290. */
  2291. function file_list_dir($dir)
  2292. {
  2293. $files = array();
  2294. if ($handle = opendir($dir))
  2295. {
  2296. while (false !== ($file = readdir($handle)))
  2297. {
  2298. if ($file[0] != "." && $file != "..") $files[] = $file;
  2299. }
  2300. closedir($handle);
  2301. }
  2302. return $files;
  2303. }
  2304. ## Extra utils ________________________________________________________________
  2305. if(!function_exists('array_replace'))
  2306. {
  2307. /**
  2308. * For PHP 5 < 5.3.0 (backward compatibility)
  2309. * (from {@link http://www.php.net/manual/fr/function.array-replace.php#92549 this php doc. note})
  2310. *
  2311. * @see array_replace()
  2312. * @param string $array
  2313. * @param string $array1
  2314. * @return $array
  2315. */
  2316. function array_replace( array &$array, array &$array1 )
  2317. {
  2318. $args = func_get_args();
  2319. $count = func_num_args();
  2320. for ($i = 0; $i < $count; ++$i)
  2321. {
  2322. if(is_array($args[$i]))
  2323. {
  2324. foreach ($args[$i] as $key => $val) $array[$key] = $val;
  2325. }
  2326. else
  2327. {
  2328. trigger_error(
  2329. __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
  2330. E_USER_WARNING
  2331. );
  2332. return null;
  2333. }
  2334. }
  2335. return $array;
  2336. }
  2337. }
  2338. /**
  2339. * Check if a string is an url
  2340. *
  2341. * This implementation no longer requires
  2342. * {@link http://www.php.net/manual/en/book.filter.php the filter extenstion},
  2343. * so it will improve compatibility with older PHP versions.
  2344. *
  2345. * @param string $str
  2346. * @return false, str the string if true, false instead
  2347. */
  2348. function filter_var_url($str)
  2349. {
  2350. $regexp = '@^https?://([-[:alnum:]]+\.)+[a-zA-Z]{2,6}(:[0-9]+)?(.*)?$@';
  2351. $options = array( "options" => array("regexp" => $regexp ));
  2352. return preg_match($regexp, $str) ? $str : false;
  2353. }
  2354. /**
  2355. * For PHP 5 < 5.1.0 (backward compatibility)
  2356. * (from {@link http://www.php.net/manual/en/function.htmlspecialchars-decode.php#82133})
  2357. *
  2358. * @param string $string
  2359. * @param string $quote_style, one of: ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES
  2360. * @return the decoded string
  2361. */
  2362. function limonade_htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
  2363. {
  2364. $table = array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style));
  2365. if($quote_style === ENT_QUOTES)
  2366. $table['&#039;'] = $table['&#39;'] = '\'';
  2367. return strtr($string, $table);
  2368. }
  2369. if(!function_exists('htmlspecialchars_decode'))
  2370. {
  2371. function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
  2372. {
  2373. return limonade_htmlspecialchars_decode($string, $quote_style);
  2374. }
  2375. }
  2376. /**
  2377. * Called just after loading libs, it provides fallback for some
  2378. * functions if they don't exists.
  2379. *
  2380. */
  2381. function fallbacks_for_not_implemented_functions()
  2382. {
  2383. if(!function_exists('json_encode'))
  2384. {
  2385. /**
  2386. * for PHP 5 < PHP 5.2.0
  2387. *
  2388. */
  2389. function json_encode()
  2390. {
  2391. trigger_error(
  2392. __FUNCTION__ . '(): no JSON functions available. Please provide your own implementation of ' . __FUNCTION__ . '() in order to use it.', E_USER_WARNING
  2393. );
  2394. }
  2395. }
  2396. }
  2397. # ================================= END ================================== #