PageRenderTime 70ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/limonade.php

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