PageRenderTime 34ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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. * Return a default value if provided value is empty
  1602. *
  1603. * @param mixed $value
  1604. * @param mixed $default default value returned if $value is empty
  1605. * @return mixed
  1606. */
  1607. function value_or_default($value, $default)
  1608. {
  1609. return empty($value) ? $default : $value;
  1610. }
  1611. /**
  1612. * An alias of {@link value_or_default()}
  1613. *
  1614. *
  1615. * @param mixed $value
  1616. * @param mixed $default
  1617. * @return mixed
  1618. */
  1619. function v($value, $default)
  1620. {
  1621. return value_or_default($value, $default);
  1622. }
  1623. /**
  1624. * Load php files with require_once in a given dir
  1625. *
  1626. * @param string $path Path in which are the file to load
  1627. * @param string $pattern a regexp pattern that filter files to load
  1628. * @param bool $prevents_output security option that prevents output
  1629. * @return array paths of loaded files
  1630. */
  1631. function require_once_dir($path, $pattern = "*.php", $prevents_output = true)
  1632. {
  1633. if($path[strlen($path) - 1] != "/") $path .= "/";
  1634. $filenames = glob($path.$pattern);
  1635. if(!is_array($filenames)) $filenames = array();
  1636. if($prevents_output) ob_start();
  1637. foreach($filenames as $filename) require_once $filename;
  1638. if($prevents_output) ob_end_clean();
  1639. return $filenames;
  1640. }
  1641. ## HTTP utils _________________________________________________________________
  1642. ### Constants: HTTP status codes
  1643. define( 'HTTP_CONTINUE', 100 );
  1644. define( 'HTTP_SWITCHING_PROTOCOLS', 101 );
  1645. define( 'HTTP_PROCESSING', 102 );
  1646. define( 'HTTP_OK', 200 );
  1647. define( 'HTTP_CREATED', 201 );
  1648. define( 'HTTP_ACCEPTED', 202 );
  1649. define( 'HTTP_NON_AUTHORITATIVE', 203 );
  1650. define( 'HTTP_NO_CONTENT', 204 );
  1651. define( 'HTTP_RESET_CONTENT', 205 );
  1652. define( 'HTTP_PARTIAL_CONTENT', 206 );
  1653. define( 'HTTP_MULTI_STATUS', 207 );
  1654. define( 'HTTP_MULTIPLE_CHOICES', 300 );
  1655. define( 'HTTP_MOVED_PERMANENTLY', 301 );
  1656. define( 'HTTP_MOVED_TEMPORARILY', 302 );
  1657. define( 'HTTP_SEE_OTHER', 303 );
  1658. define( 'HTTP_NOT_MODIFIED', 304 );
  1659. define( 'HTTP_USE_PROXY', 305 );
  1660. define( 'HTTP_TEMPORARY_REDIRECT', 307 );
  1661. define( 'HTTP_BAD_REQUEST', 400 );
  1662. define( 'HTTP_UNAUTHORIZED', 401 );
  1663. define( 'HTTP_PAYMENT_REQUIRED', 402 );
  1664. define( 'HTTP_FORBIDDEN', 403 );
  1665. define( 'HTTP_NOT_FOUND', 404 );
  1666. define( 'HTTP_METHOD_NOT_ALLOWED', 405 );
  1667. define( 'HTTP_NOT_ACCEPTABLE', 406 );
  1668. define( 'HTTP_PROXY_AUTHENTICATION_REQUIRED', 407 );
  1669. define( 'HTTP_REQUEST_TIME_OUT', 408 );
  1670. define( 'HTTP_CONFLICT', 409 );
  1671. define( 'HTTP_GONE', 410 );
  1672. define( 'HTTP_LENGTH_REQUIRED', 411 );
  1673. define( 'HTTP_PRECONDITION_FAILED', 412 );
  1674. define( 'HTTP_REQUEST_ENTITY_TOO_LARGE', 413 );
  1675. define( 'HTTP_REQUEST_URI_TOO_LARGE', 414 );
  1676. define( 'HTTP_UNSUPPORTED_MEDIA_TYPE', 415 );
  1677. define( 'HTTP_RANGE_NOT_SATISFIABLE', 416 );
  1678. define( 'HTTP_EXPECTATION_FAILED', 417 );
  1679. define( 'HTTP_UNPROCESSABLE_ENTITY', 422 );
  1680. define( 'HTTP_LOCKED', 423 );
  1681. define( 'HTTP_FAILED_DEPENDENCY', 424 );
  1682. define( 'HTTP_UPGRADE_REQUIRED', 426 );
  1683. define( 'HTTP_INTERNAL_SERVER_ERROR', 500 );
  1684. define( 'HTTP_NOT_IMPLEMENTED', 501 );
  1685. define( 'HTTP_BAD_GATEWAY', 502 );
  1686. define( 'HTTP_SERVICE_UNAVAILABLE', 503 );
  1687. define( 'HTTP_GATEWAY_TIME_OUT', 504 );
  1688. define( 'HTTP_VERSION_NOT_SUPPORTED', 505 );
  1689. define( 'HTTP_VARIANT_ALSO_VARIES', 506 );
  1690. define( 'HTTP_INSUFFICIENT_STORAGE', 507 );
  1691. define( 'HTTP_NOT_EXTENDED', 510 );
  1692. /**
  1693. * Output proper HTTP header for a given HTTP code
  1694. *
  1695. * @param string $code
  1696. * @return void
  1697. */
  1698. function status($code = 500)
  1699. {
  1700. if(!headers_sent())
  1701. {
  1702. $str = http_response_status_code($code);
  1703. header($str);
  1704. }
  1705. }
  1706. /**
  1707. * Http redirection
  1708. *
  1709. * Same use as {@link url_for()}
  1710. * By default HTTP status code is 302, but a different code can be specified
  1711. * with a status key in array parameter.
  1712. *
  1713. * <code>
  1714. * redirecto('new','url'); # 302 HTTP_MOVED_TEMPORARILY by default
  1715. * redirecto('new','url', array('status' => HTTP_MOVED_PERMANENTLY));
  1716. * </code>
  1717. *
  1718. * @param string or array $param1, $param2...
  1719. * @return void
  1720. */
  1721. function redirect_to($params)
  1722. {
  1723. # [NOTE]: (from php.net) HTTP/1.1 requires an absolute URI as argument to » Location:
  1724. # including the scheme, hostname and absolute path, but some clients accept
  1725. # relative URIs. You can usually use $_SERVER['HTTP_HOST'],
  1726. # $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative
  1727. # one yourself.
  1728. # TODO make absolute uri
  1729. if(!headers_sent())
  1730. {
  1731. $status = HTTP_MOVED_TEMPORARILY; # default for a redirection in PHP
  1732. $params = func_get_args();
  1733. $n_params = array();
  1734. # extract status param if exists
  1735. foreach($params as $param)
  1736. {
  1737. if(is_array($param))
  1738. {
  1739. if(array_key_exists('status', $param))
  1740. {
  1741. $status = $param['status'];
  1742. unset($param['status']);
  1743. }
  1744. }
  1745. $n_params[] = $param;
  1746. }
  1747. $uri = call_user_func_array('url_for', $n_params);
  1748. stop_and_exit(false);
  1749. header('Location: '.$uri, true, $status);
  1750. exit;
  1751. }
  1752. }
  1753. /**
  1754. * Http redirection
  1755. *
  1756. * @deprecated deprecated since version 0.4. Please use {@link redirect_to()} instead.
  1757. * @param string $url
  1758. * @return void
  1759. */
  1760. function redirect($uri)
  1761. {
  1762. # halt('redirect() is deprecated. Please use redirect_to() instead.', E_LIM_DEPRECATED);
  1763. # halt not necesary... it won't be visible because of http redirection...
  1764. redirect_to($uri);
  1765. }
  1766. /**
  1767. * Returns HTTP response status for a given code.
  1768. * If no code provided, return an array of all status
  1769. *
  1770. * @param string $num
  1771. * @return string,array
  1772. */
  1773. function http_response_status($num = null)
  1774. {
  1775. $status = array(
  1776. 100 => 'Continue',
  1777. 101 => 'Switching Protocols',
  1778. 102 => 'Processing',
  1779. 200 => 'OK',
  1780. 201 => 'Created',
  1781. 202 => 'Accepted',
  1782. 203 => 'Non-Authoritative Information',
  1783. 204 => 'No Content',
  1784. 205 => 'Reset Content',
  1785. 206 => 'Partial Content',
  1786. 207 => 'Multi-Status',
  1787. 226 => 'IM Used',
  1788. 300 => 'Multiple Choices',
  1789. 301 => 'Moved Permanently',
  1790. 302 => 'Found',
  1791. 303 => 'See Other',
  1792. 304 => 'Not Modified',
  1793. 305 => 'Use Proxy',
  1794. 306 => 'Reserved',
  1795. 307 => 'Temporary Redirect',
  1796. 400 => 'Bad Request',
  1797. 401 => 'Unauthorized',
  1798. 402 => 'Payment Required',
  1799. 403 => 'Forbidden',
  1800. 404 => 'Not Found',
  1801. 405 => 'Method Not Allowed',
  1802. 406 => 'Not Acceptable',
  1803. 407 => 'Proxy Authentication Required',
  1804. 408 => 'Request Timeout',
  1805. 409 => 'Conflict',
  1806. 410 => 'Gone',
  1807. 411 => 'Length Required',
  1808. 412 => 'Precondition Failed',
  1809. 413 => 'Request Entity Too Large',
  1810. 414 => 'Request-URI Too Long',
  1811. 415 => 'Unsupported Media Type',
  1812. 416 => 'Requested Range Not Satisfiable',
  1813. 417 => 'Expectation Failed',
  1814. 422 => 'Unprocessable Entity',
  1815. 423 => 'Locked',
  1816. 424 => 'Failed Dependency',
  1817. 426 => 'Upgrade Required',
  1818. 500 => 'Internal Server Error',
  1819. 501 => 'Not Implemented',
  1820. 502 => 'Bad Gateway',
  1821. 503 => 'Service Unavailable',
  1822. 504 => 'Gateway Timeout',
  1823. 505 => 'HTTP Version Not Supported',
  1824. 506 => 'Variant Also Negotiates',
  1825. 507 => 'Insufficient Storage',
  1826. 510 => 'Not Extended'
  1827. );
  1828. if(is_null($num)) return $status;
  1829. return array_key_exists($num, $status) ? $status[$num] : '';
  1830. }
  1831. /**
  1832. * Checks if an HTTP response code is valid
  1833. *
  1834. * @param string $num
  1835. * @return bool
  1836. */
  1837. function http_response_status_is_valid($num)
  1838. {
  1839. $r = http_response_status($num);
  1840. return !empty($r);
  1841. }
  1842. /**
  1843. * Returns an HTTP response status string for a given code
  1844. *
  1845. * @param string $num
  1846. * @return string
  1847. */
  1848. function http_response_status_code($num)
  1849. {
  1850. if($str = http_response_status($num)) return "HTTP/1.1 $num $str";
  1851. }
  1852. ## FILE utils _________________________________________________________________
  1853. /**
  1854. * Returns mime type for a given extension or if no extension is provided,
  1855. * all mime types in an associative array, with extensions as keys.
  1856. * (extracted from Orbit source http://orbit.luaforge.net/)
  1857. *
  1858. * @param string $ext
  1859. * @return string, array
  1860. */
  1861. function mime_type($ext = null)
  1862. {
  1863. $types = array(
  1864. 'ai' => 'application/postscript',
  1865. 'aif' => 'audio/x-aiff',
  1866. 'aifc' => 'audio/x-aiff',
  1867. 'aiff' => 'audio/x-aiff',
  1868. 'asc' => 'text/plain',
  1869. 'atom' => 'application/atom+xml',
  1870. 'atom' => 'application/atom+xml',
  1871. 'au' => 'audio/basic',
  1872. 'avi' => 'video/x-msvideo',
  1873. 'bcpio' => 'application/x-bcpio',
  1874. 'bin' => 'application/octet-stream',
  1875. 'bmp' => 'image/bmp',
  1876. 'cdf' => 'application/x-netcdf',
  1877. 'cgm' => 'image/cgm',
  1878. 'class' => 'application/octet-stream',
  1879. 'cpio' => 'application/x-cpio',
  1880. 'cpt' => 'application/mac-compactpro',
  1881. 'csh' => 'application/x-csh',
  1882. 'css' => 'text/css',
  1883. 'csv' => 'text/csv',
  1884. 'dcr' => 'application/x-director',
  1885. 'dir' => 'application/x-director',
  1886. 'djv' => 'image/vnd.djvu',
  1887. 'djvu' => 'image/vnd.djvu',
  1888. 'dll' => 'application/octet-stream',
  1889. 'dmg' => 'application/octet-stream',
  1890. 'dms' => 'application/octet-stream',
  1891. 'doc' => 'application/msword',
  1892. 'dtd' => 'application/xml-dtd',
  1893. 'dvi' => 'application/x-dvi',
  1894. 'dxr' => 'application/x-director',
  1895. 'eps' => 'application/postscript',
  1896. 'etx' => 'text/x-setext',
  1897. 'exe' => 'application/octet-stream',
  1898. 'ez' => 'application/andrew-inset',
  1899. 'gif' => 'image/gif',
  1900. 'gram' => 'application/srgs',
  1901. 'grxml' => 'application/srgs+xml',
  1902. 'gtar' => 'application/x-gtar',
  1903. 'hdf' => 'application/x-hdf',
  1904. 'hqx' => 'application/mac-binhex40',
  1905. 'htm' => 'text/html',
  1906. 'html' => 'text/html',
  1907. 'ice' => 'x-conference/x-cooltalk',
  1908. 'ico' => 'image/x-icon',
  1909. 'ics' => 'text/calendar',
  1910. 'ief' => 'image/ief',
  1911. 'ifb' => 'text/calendar',
  1912. 'iges' => 'model/iges',
  1913. 'igs' => 'model/iges',
  1914. 'jpe' => 'image/jpeg',
  1915. 'jpeg' => 'image/jpeg',
  1916. 'jpg' => 'image/jpeg',
  1917. 'js' => 'application/x-javascript',
  1918. 'kar' => 'audio/midi',
  1919. 'latex' => 'application/x-latex',
  1920. 'lha' => 'application/octet-stream',
  1921. 'lzh' => 'application/octet-stream',
  1922. 'm3u' => 'audio/x-mpegurl',
  1923. 'man' => 'application/x-troff-man',
  1924. 'mathml' => 'application/mathml+xml',
  1925. 'me' => 'application/x-troff-me',
  1926. 'mesh' => 'model/mesh',
  1927. 'mid' => 'audio/midi',
  1928. 'midi' => 'audio/midi',
  1929. 'mif' => 'application/vnd.mif',
  1930. 'mov' => 'video/quicktime',
  1931. 'movie' => 'video/x-sgi-movie',
  1932. 'mp2' => 'audio/mpeg',
  1933. 'mp3' => 'audio/mpeg',
  1934. 'mpe' => 'video/mpeg',
  1935. 'mpeg' => 'video/mpeg',
  1936. 'mpg' => 'video/mpeg',
  1937. 'mpga' => 'audio/mpeg',
  1938. 'ms' => 'application/x-troff-ms',
  1939. 'msh' => 'model/mesh',
  1940. 'mxu' => 'video/vnd.mpegurl',
  1941. 'nc' => 'application/x-netcdf',
  1942. 'oda' => 'application/oda',
  1943. 'ogg' => 'application/ogg',
  1944. 'pbm' => 'image/x-portable-bitmap',
  1945. 'pdb' => 'chemical/x-pdb',
  1946. 'pdf' => 'application/pdf',
  1947. 'pgm' => 'image/x-portable-graymap',
  1948. 'pgn' => 'application/x-chess-pgn',
  1949. 'png' => 'image/png',
  1950. 'pnm' => 'image/x-portable-anymap',
  1951. 'ppm' => 'image/x-portable-pixmap',
  1952. 'ppt' => 'application/vnd.ms-powerpoint',
  1953. 'ps' => 'application/postscript',
  1954. 'qt' => 'video/quicktime',
  1955. 'ra' => 'audio/x-pn-realaudio',
  1956. 'ram' => 'audio/x-pn-realaudio',
  1957. 'ras' => 'image/x-cmu-raster',
  1958. 'rdf' => 'application/rdf+xml',
  1959. 'rgb' => 'image/x-rgb',
  1960. 'rm' => 'application/vnd.rn-realmedia',
  1961. 'roff' => 'application/x-troff',
  1962. 'rss' => 'application/rss+xml',
  1963. 'rtf' => 'text/rtf',
  1964. 'rtx' => 'text/richtext',
  1965. 'sgm' => 'text/sgml',
  1966. 'sgml' => 'text/sgml',
  1967. 'sh' => 'application/x-sh',
  1968. 'shar' => 'application/x-shar',
  1969. 'silo' => 'model/mesh',
  1970. 'sit' => 'application/x-stuffit',
  1971. 'skd' => 'application/x-koan',
  1972. 'skm' => 'application/x-koan',
  1973. 'skp' => 'application/x-koan',
  1974. 'skt' => 'application/x-koan',
  1975. 'smi' => 'application/smil',
  1976. 'smil' => 'application/smil',
  1977. 'snd' => 'audio/basic',
  1978. 'so' => 'application/octet-stream',
  1979. 'spl' => 'application/x-futuresplash',
  1980. 'src' => 'application/x-wais-source',
  1981. 'sv4cpio' => 'application/x-sv4cpio',
  1982. 'sv4crc' => 'application/x-sv4crc',
  1983. 'svg' => 'image/svg+xml',
  1984. 'svgz' => 'image/svg+xml',
  1985. 'swf' => 'application/x-shockwave-flash',
  1986. 't' => 'application/x-troff',
  1987. 'tar' => 'application/x-tar',
  1988. 'tcl' => 'application/x-tcl',
  1989. 'tex' => 'application/x-tex',
  1990. 'texi' => 'application/x-texinfo',
  1991. 'texinfo' => 'application/x-texinfo',
  1992. 'tif' => 'image/tiff',
  1993. 'tiff' => 'image/tiff',
  1994. 'tr' => 'application/x-troff',
  1995. 'tsv' => 'text/tab-separated-values',
  1996. 'txt' => 'text/plain',
  1997. 'ustar' => 'application/x-ustar',
  1998. 'vcd' => 'application/x-cdlink',
  1999. 'vrml' => 'model/vrml',
  2000. 'vxml' => 'application/voicexml+xml',
  2001. 'wav' => 'audio/x-wav',
  2002. 'wbmp' => 'image/vnd.wap.wbmp',
  2003. 'wbxml' => 'application/vnd.wap.wbxml',
  2004. 'wml' => 'text/vnd.wap.wml',
  2005. 'wmlc' => 'application/vnd.wap.wmlc',
  2006. 'wmls' => 'text/vnd.wap.wmlscript',
  2007. 'wmlsc' => 'application/vnd.wap.wmlscriptc',
  2008. 'wrl' => 'model/vrml',
  2009. 'xbm' => 'image/x-xbitmap',
  2010. 'xht' => 'application/xhtml+xml',
  2011. 'xhtml' => 'application/xhtml+xml',
  2012. 'xls' => 'application/vnd.ms-excel',
  2013. 'xml' => 'application/xml',
  2014. 'xpm' => 'image/x-xpixmap',
  2015. 'xsl' => 'application/xml',
  2016. 'xslt' => 'application/xslt+xml',
  2017. 'xul' => 'application/vnd.mozilla.xul+xml',
  2018. 'xwd' => 'image/x-xwindowdump',
  2019. 'xyz' => 'chemical/x-xyz',
  2020. 'zip' => 'application/zip'
  2021. );
  2022. return is_null($ext) ? $types : $types[strtolower($ext)];
  2023. }
  2024. /**
  2025. * Detect MIME Content-type for a file
  2026. *
  2027. * @param string $filename Path to the tested file.
  2028. * @return string
  2029. */
  2030. function file_mime_content_type($filename)
  2031. {
  2032. $ext = file_extension($filename); /* strtolower isn't necessary */
  2033. if($mime = mime_type($ext)) return $mime;
  2034. elseif (function_exists('finfo_open'))
  2035. {
  2036. $finfo = finfo_open(FILEINFO_MIME);
  2037. $mime = finfo_file($finfo, $filename);
  2038. finfo_close($finfo);
  2039. return $mime;
  2040. }
  2041. else return 'application/octet-stream';
  2042. }
  2043. /**
  2044. * Read and output file content and return filesize in bytes or status after
  2045. * closing file.
  2046. * This function is very efficient for outputing large files without timeout
  2047. * nor too expensive memory use
  2048. *
  2049. * @param string $filename
  2050. * @param string $retbytes
  2051. * @return bool, int
  2052. */
  2053. function file_read_chunked($filename, $retbytes = true)
  2054. {
  2055. $chunksize = 1*(1024*1024); // how many bytes per chunk
  2056. $buffer = '';
  2057. $cnt = 0;
  2058. $handle = fopen($filename, 'rb');
  2059. if ($handle === false) return false;
  2060. ob_start();
  2061. while (!feof($handle)) {
  2062. $buffer = fread($handle, $chunksize);
  2063. echo $buffer;
  2064. ob_flush();
  2065. flush();
  2066. if ($retbytes) $cnt += strlen($buffer);
  2067. set_time_limit(0);
  2068. }
  2069. ob_end_flush();
  2070. $status = fclose($handle);
  2071. if ($retbytes && $status) return $cnt; // return num. bytes delivered like readfile() does.
  2072. return $status;
  2073. }
  2074. /**
  2075. * Create a file path by concatenation of given arguments.
  2076. * Windows paths with backslash directory separators are normalized in *nix paths.
  2077. *
  2078. * @param string $path, ...
  2079. * @return string normalized path
  2080. */
  2081. function file_path($path)
  2082. {
  2083. $args = func_get_args();
  2084. $ds = '/';
  2085. $win_ds = '\\';
  2086. $n_path = count($args) > 1 ? implode($ds, $args) : $path;
  2087. if(strpos($n_path, $win_ds) !== false) $n_path = str_replace( $win_ds, $ds, $n_path );
  2088. $n_path = preg_replace( '/'.preg_quote($ds, $ds).'{2,}'.'/',
  2089. $ds,
  2090. $n_path);
  2091. return $n_path;
  2092. }
  2093. /**
  2094. * Returns file extension or false if none
  2095. *
  2096. * @param string $filename
  2097. * @return string, false
  2098. */
  2099. function file_extension($filename)
  2100. {
  2101. $pos = strrpos($filename, '.');
  2102. if($pos !== false) return substr($filename, $pos + 1);
  2103. return false;
  2104. }
  2105. /**
  2106. * Checks if $filename is a text file
  2107. *
  2108. * @param string $filename
  2109. * @return bool
  2110. */
  2111. function file_is_text($filename)
  2112. {
  2113. if($mime = file_mime_content_type($filename)) return substr($mime,0,5) == "text/";
  2114. return null;
  2115. }
  2116. /**
  2117. * Checks if $filename is a binary file
  2118. *
  2119. * @param string $filename
  2120. * @return void
  2121. */
  2122. function file_is_binary($filename)
  2123. {
  2124. $is_text = file_is_text($filename);
  2125. return is_null($is_text) ? null : !$is_text;
  2126. }
  2127. /**
  2128. * Return or output file content
  2129. *
  2130. * @return string, int
  2131. *
  2132. **/
  2133. function file_read($filename, $return = false)
  2134. {
  2135. if(!file_exists($filename)) trigger_error("$filename doesn't exists", E_USER_ERROR);
  2136. if($return) return file_get_contents($filename);
  2137. return file_read_chunked($filename);
  2138. }
  2139. /**
  2140. * Returns an array of files contained in a directory
  2141. *
  2142. * @param string $dir
  2143. * @return array
  2144. */
  2145. function file_list_dir($dir)
  2146. {
  2147. $files = array();
  2148. if ($handle = opendir($dir))
  2149. {
  2150. while (false !== ($file = readdir($handle)))
  2151. {
  2152. if ($file[0] != "." && $file != "..") $files[] = $file;
  2153. }
  2154. closedir($handle);
  2155. }
  2156. return $files;
  2157. }
  2158. ## Extra utils ________________________________________________________________
  2159. if(!function_exists('array_replace'))
  2160. {
  2161. /**
  2162. * For PHP 5 < 5.3.0 (backward compatibility)
  2163. * (from {@link http://www.php.net/manual/fr/function.array-replace.php#92549 this php doc. note})
  2164. *
  2165. * @see array_replace()
  2166. * @param string $array
  2167. * @param string $array1
  2168. * @return $array
  2169. */
  2170. function array_replace( array &$array, array &$array1 )
  2171. {
  2172. $args = func_get_args();
  2173. $count = func_num_args();
  2174. for ($i = 0; $i < $count; ++$i)
  2175. {
  2176. if(is_array($args[$i]))
  2177. {
  2178. foreach ($args[$i] as $key => $val) $array[$key] = $val;
  2179. }
  2180. else
  2181. {
  2182. trigger_error(
  2183. __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
  2184. E_USER_WARNING
  2185. );
  2186. return null;
  2187. }
  2188. }
  2189. return $array;
  2190. }
  2191. }
  2192. # ================================= END ================================== #