PageRenderTime 67ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Slim/Slim.php

https://bitbucket.org/jlaso/m4us
PHP | 1183 lines | 471 code | 92 blank | 620 comment | 75 complexity | 75633a06689846d54611f2190fe6f249 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Slim - a micro PHP 5 framework
  4. *
  5. * @author Josh Lockhart <info@joshlockhart.com>
  6. * @copyright 2011 Josh Lockhart
  7. * @link http://www.slimframework.com
  8. * @license http://www.slimframework.com/license
  9. * @version 1.5.0
  10. *
  11. * MIT LICENSE
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining
  14. * a copy of this software and associated documentation files (the
  15. * "Software"), to deal in the Software without restriction, including
  16. * without limitation the rights to use, copy, modify, merge, publish,
  17. * distribute, sublicense, and/or sell copies of the Software, and to
  18. * permit persons to whom the Software is furnished to do so, subject to
  19. * the following conditions:
  20. *
  21. * The above copyright notice and this permission notice shall be
  22. * included in all copies or substantial portions of the Software.
  23. *
  24. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. */
  32. //Ensure PHP session IDs only use the characters [a-z0-9]
  33. ini_set('session.hash_bits_per_character', 4);
  34. ini_set('session.hash_function', 0);
  35. //Slim's Encryted Cookies rely on libmcyrpt and these two constants.
  36. //If libmycrpt is unavailable, we ensure the expected constants
  37. //are available to avoid errors.
  38. if ( !defined('MCRYPT_RIJNDAEL_256') ) {
  39. define('MCRYPT_RIJNDAEL_256', 0);
  40. }
  41. if ( !defined('MCRYPT_MODE_CBC') ) {
  42. define('MCRYPT_MODE_CBC', 0);
  43. }
  44. //This determines which errors are reported by PHP. By default, all
  45. //errors (including E_STRICT) are reported.
  46. error_reporting(E_ALL | E_STRICT);
  47. //This tells PHP to auto-load classes using Slim's autoloader; this will
  48. //only auto-load a class file located in the same directory as Slim.php
  49. //whose file name (excluding the final dot and extension) is the same
  50. //as its class name (case-sensitive). For example, "View.php" will be
  51. //loaded when Slim uses the "View" class for the first time.
  52. spl_autoload_register(array('Slim', 'autoload'));
  53. //PHP 5.3 will complain if you don't set a timezone. If you do not
  54. //specify your own timezone before requiring Slim, this tells PHP to use UTC.
  55. if ( @date_default_timezone_set(date_default_timezone_get()) === false ) {
  56. date_default_timezone_set('UTC');
  57. }
  58. /**
  59. * Slim
  60. *
  61. * @package Slim
  62. * @author Josh Lockhart <info@joshlockhart.com>
  63. * @since Version 1.0
  64. */
  65. class Slim {
  66. /**
  67. * @var array[Slim]
  68. */
  69. protected static $apps = array();
  70. /**
  71. * @var string
  72. */
  73. protected $name;
  74. /**
  75. * @var Slim_Http_Request
  76. */
  77. protected $request;
  78. /**
  79. * @var Slim_Http_Response
  80. */
  81. protected $response;
  82. /**
  83. * @var Slim_Router
  84. */
  85. protected $router;
  86. /**
  87. * @var Slim_View
  88. */
  89. protected $view;
  90. /**
  91. * @var Slim_Log
  92. */
  93. protected $log;
  94. /**
  95. * @var array Key-value array of application settings
  96. */
  97. protected $settings;
  98. /**
  99. * @var string The application mode
  100. */
  101. protected $mode;
  102. /**
  103. * @var array Plugin hooks
  104. */
  105. protected $hooks = array(
  106. 'slim.before' => array(array()),
  107. 'slim.before.router' => array(array()),
  108. 'slim.before.dispatch' => array(array()),
  109. 'slim.after.dispatch' => array(array()),
  110. 'slim.after.router' => array(array()),
  111. 'slim.after' => array(array())
  112. );
  113. /**
  114. * Slim auto-loader
  115. *
  116. * This method lazy-loads class files when a given class if first used.
  117. * Class files must exist in the same directory as this file and be named
  118. * the same as its class definition (excluding the dot and extension).
  119. *
  120. * @return void
  121. */
  122. public static function autoload( $class ) {
  123. if ( strpos($class, 'Slim') !== 0 ) {
  124. return;
  125. }
  126. $file = dirname(__FILE__) . '/' . str_replace('_', DIRECTORY_SEPARATOR, substr($class,5)) . '.php';
  127. if ( file_exists($file) ) {
  128. require $file;
  129. }
  130. }
  131. /***** INITIALIZATION *****/
  132. /**
  133. * Constructor
  134. * @param array $userSettings
  135. * @return void
  136. */
  137. public function __construct( $userSettings = array() ) {
  138. //Merge application settings
  139. $this->settings = array_merge(array(
  140. //Mode
  141. 'mode' => 'development',
  142. //Logging
  143. 'log.enable' => false,
  144. 'log.logger' => null,
  145. 'log.path' => './logs',
  146. 'log.level' => 4,
  147. //Debugging
  148. 'debug' => true,
  149. //View
  150. 'templates.path' => './templates',
  151. 'view' => 'Slim_View',
  152. //Settings for all cookies
  153. 'cookies.lifetime' => '20 minutes',
  154. 'cookies.path' => '/',
  155. 'cookies.domain' => '',
  156. 'cookies.secure' => false,
  157. 'cookies.httponly' => false,
  158. //Settings for encrypted cookies
  159. 'cookies.secret_key' => 'CHANGE_ME',
  160. 'cookies.cipher' => MCRYPT_RIJNDAEL_256,
  161. 'cookies.cipher_mode' => MCRYPT_MODE_CBC,
  162. 'cookies.encrypt' => true,
  163. 'cookies.user_id' => 'DEFAULT',
  164. //Session handler
  165. 'session.handler' => new Slim_Session_Handler_Cookies(),
  166. 'session.flash_key' => 'flash',
  167. //HTTP
  168. 'http.version' => null
  169. ), $userSettings);
  170. //Determine application mode
  171. $this->getMode();
  172. //Setup HTTP request and response handling
  173. $this->request = new Slim_Http_Request();
  174. $this->response = new Slim_Http_Response($this->request);
  175. $this->response->setCookieJar(new Slim_Http_CookieJar($this->settings['cookies.secret_key'], array(
  176. 'high_confidentiality' => $this->settings['cookies.encrypt'],
  177. 'mcrypt_algorithm' => $this->settings['cookies.cipher'],
  178. 'mcrypt_mode' => $this->settings['cookies.cipher_mode'],
  179. 'enable_ssl' => $this->settings['cookies.secure']
  180. )));
  181. $this->response->httpVersion($this->settings['http.version']);
  182. $this->router = new Slim_Router($this->request);
  183. //Start session if not already started
  184. if ( session_id() === '' ) {
  185. $sessionHandler = $this->config('session.handler');
  186. if ( $sessionHandler instanceof Slim_Session_Handler ) {
  187. $sessionHandler->register($this);
  188. }
  189. session_cache_limiter(false);
  190. session_start();
  191. }
  192. //Setup view with flash messaging
  193. $this->view($this->config('view'))->setData('flash', new Slim_Session_Flash($this->config('session.flash_key')));
  194. //Set app name
  195. if ( !isset(self::$apps['default']) ) {
  196. $this->setName('default');
  197. }
  198. //Set global Error handler after Slim app instantiated
  199. set_error_handler(array('Slim', 'handleErrors'));
  200. }
  201. /**
  202. * Get application mode
  203. * @return string
  204. */
  205. public function getMode() {
  206. if ( !isset($this->mode) ) {
  207. if ( isset($_ENV['SLIM_MODE']) ) {
  208. $this->mode = (string)$_ENV['SLIM_MODE'];
  209. } else {
  210. $envMode = getenv('SLIM_MODE');
  211. if ( $envMode !== false ) {
  212. $this->mode = $envMode;
  213. } else {
  214. $this->mode = (string)$this->config('mode');
  215. }
  216. }
  217. }
  218. return $this->mode;
  219. }
  220. /***** NAMING *****/
  221. /**
  222. * Get Slim application with name
  223. * @param string $name The name of the Slim application to fetch
  224. * @return Slim|null
  225. */
  226. public static function getInstance( $name = 'default' ) {
  227. return isset(self::$apps[(string)$name]) ? self::$apps[(string)$name] : null;
  228. }
  229. /**
  230. * Set Slim application name
  231. * @param string $name The name of this Slim application
  232. * @return void
  233. */
  234. public function setName( $name ) {
  235. $this->name = $name;
  236. self::$apps[$name] = $this;
  237. }
  238. /**
  239. * Get Slim application name
  240. * @return string|null
  241. */
  242. public function getName() {
  243. return $this->name;
  244. }
  245. /***** LOGGING *****/
  246. /**
  247. * Get application Log (lazy-loaded)
  248. * @return Slim_Log
  249. */
  250. public function getLog() {
  251. if ( !isset($this->log) ) {
  252. $this->log = new Slim_Log();
  253. $this->log->setEnabled($this->config('log.enable'));
  254. $logger = $this->config('log.logger');
  255. if ( $logger ) {
  256. $this->log->setLogger($logger);
  257. } else {
  258. $this->log->setLogger(new Slim_Logger($this->config('log.path'), $this->config('log.level')));
  259. }
  260. }
  261. return $this->log;
  262. }
  263. /***** CONFIGURATION *****/
  264. /**
  265. * Configure Slim for a given mode
  266. *
  267. * This method will immediately invoke the callable if
  268. * the specified mode matches the current application mode.
  269. * Otherwise, the callable is ignored. This should be called
  270. * only _after_ you initialize your Slim app.
  271. *
  272. * @param string $mode
  273. * @param mixed $callable
  274. * @return void
  275. */
  276. public function configureMode( $mode, $callable ) {
  277. if ( $mode === $this->getMode() && is_callable($callable) ) {
  278. call_user_func($callable);
  279. }
  280. }
  281. /**
  282. * Configure Slim Settings
  283. *
  284. * This method defines application settings and acts as a setter and a getter.
  285. *
  286. * If only one argument is specified and that argument is a string, the value
  287. * of the setting identified by the first argument will be returned, or NULL if
  288. * that setting does not exist.
  289. *
  290. * If only one argument is specified and that argument is an associative array,
  291. * the array will be merged into the existing application settings.
  292. *
  293. * If two arguments are provided, the first argument is the name of the setting
  294. * to be created or updated, and the second argument is the setting value.
  295. *
  296. * @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values
  297. * @param mixed $value If name is a string, the value of the setting identified by $name
  298. * @return mixed The value of a setting if only one argument is a string
  299. */
  300. public function config( $name, $value = null ) {
  301. if ( func_num_args() === 1 ) {
  302. if ( is_array($name) ) {
  303. $this->settings = array_merge($this->settings, $name);
  304. } else {
  305. return in_array($name, array_keys($this->settings)) ? $this->settings[$name] : null;
  306. }
  307. } else {
  308. $this->settings[$name] = $value;
  309. }
  310. }
  311. /***** ROUTING *****/
  312. /**
  313. * Add GET|POST|PUT|DELETE route
  314. *
  315. * Adds a new route to the router with associated callable. This
  316. * route will only be invoked when the HTTP request's method matches
  317. * this route's method.
  318. *
  319. * ARGUMENTS:
  320. *
  321. * First: string The URL pattern (REQUIRED)
  322. * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL)
  323. * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED)
  324. *
  325. * The first argument is required and must always be the
  326. * route pattern (ie. '/books/:id').
  327. *
  328. * The last argument is required and must always be the callable object
  329. * to be invoked when the route matches an HTTP request.
  330. *
  331. * You may also provide an unlimited number of in-between arguments;
  332. * each interior argument must be callable and will be invoked in the
  333. * order specified before the route's callable is invoked.
  334. *
  335. * USAGE:
  336. *
  337. * Slim::get('/foo'[, middleware, middleware, ...], callable);
  338. *
  339. * @param array (See notes above)
  340. * @return Slim_Route
  341. */
  342. protected function mapRoute($args) {
  343. $pattern = array_shift($args);
  344. $callable = array_pop($args);
  345. $route = $this->router->map($pattern, $callable);
  346. if ( count($args) > 0 ) {
  347. $route->setMiddleware($args);
  348. }
  349. return $route;
  350. }
  351. /**
  352. * Add generic route without associated HTTP method
  353. * @see Slim::mapRoute
  354. * @return Slim_Route
  355. */
  356. public function map() {
  357. $args = func_get_args();
  358. return $this->mapRoute($args);
  359. }
  360. /**
  361. * Add GET route
  362. * @see Slim::mapRoute
  363. * @return Slim_Route
  364. */
  365. public function get() {
  366. $args = func_get_args();
  367. return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_GET, Slim_Http_Request::METHOD_HEAD);
  368. }
  369. /**
  370. * Add POST route
  371. * @see Slim::mapRoute
  372. * @return Slim_Route
  373. */
  374. public function post() {
  375. $args = func_get_args();
  376. return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_POST);
  377. }
  378. /**
  379. * Add PUT route
  380. * @see Slim::mapRoute
  381. * @return Slim_Route
  382. */
  383. public function put() {
  384. $args = func_get_args();
  385. return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_PUT);
  386. }
  387. /**
  388. * Add DELETE route
  389. * @see Slim::mapRoute
  390. * @return Slim_Route
  391. */
  392. public function delete() {
  393. $args = func_get_args();
  394. return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_DELETE);
  395. }
  396. /**
  397. * Add OPTIONS route
  398. * @see Slim::mapRoute
  399. * @return Slim_Route
  400. */
  401. public function options() {
  402. $args = func_get_args();
  403. return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_OPTIONS);
  404. }
  405. /**
  406. * Not Found Handler
  407. *
  408. * This method defines or invokes the application-wide Not Found handler.
  409. * There are two contexts in which this method may be invoked:
  410. *
  411. * 1. When declaring the handler:
  412. *
  413. * If the $callable parameter is not null and is callable, this
  414. * method will register the callable to be invoked when no
  415. * routes match the current HTTP request. It WILL NOT invoke the callable.
  416. *
  417. * 2. When invoking the handler:
  418. *
  419. * If the $callable parameter is null, Slim assumes you want
  420. * to invoke an already-registered handler. If the handler has been
  421. * registered and is callable, it is invoked and sends a 404 HTTP Response
  422. * whose body is the output of the Not Found handler.
  423. *
  424. * @param mixed $callable Anything that returns true for is_callable()
  425. * @return void
  426. */
  427. public function notFound( $callable = null ) {
  428. if ( !is_null($callable) ) {
  429. $this->router->notFound($callable);
  430. } else {
  431. ob_start();
  432. $customNotFoundHandler = $this->router->notFound();
  433. if ( is_callable($customNotFoundHandler) ) {
  434. call_user_func($customNotFoundHandler);
  435. } else {
  436. call_user_func(array($this, 'defaultNotFound'));
  437. }
  438. $this->halt(404, ob_get_clean());
  439. }
  440. }
  441. /**
  442. * Error Handler
  443. *
  444. * This method defines or invokes the application-wide Error handler.
  445. * There are two contexts in which this method may be invoked:
  446. *
  447. * 1. When declaring the handler:
  448. *
  449. * If the $argument parameter is callable, this
  450. * method will register the callable to be invoked when an uncaught
  451. * Exception is detected, or when otherwise explicitly invoked.
  452. * The handler WILL NOT be invoked in this context.
  453. *
  454. * 2. When invoking the handler:
  455. *
  456. * If the $argument parameter is not callable, Slim assumes you want
  457. * to invoke an already-registered handler. If the handler has been
  458. * registered and is callable, it is invoked and passed the caught Exception
  459. * as its one and only argument. The error handler's output is captured
  460. * into an output buffer and sent as the body of a 500 HTTP Response.
  461. *
  462. * @param mixed $argument Callable|Exception
  463. * @return void
  464. */
  465. public function error( $argument = null ) {
  466. if ( is_callable($argument) ) {
  467. //Register error handler
  468. $this->router->error($argument);
  469. } else {
  470. //Invoke error handler
  471. ob_start();
  472. $customErrorHandler = $this->router->error();
  473. if ( is_callable($customErrorHandler) ) {
  474. call_user_func_array($customErrorHandler, array($argument));
  475. } else {
  476. call_user_func_array(array($this, 'defaultError'), array($argument));
  477. }
  478. $this->halt(500, ob_get_clean());
  479. }
  480. }
  481. /***** ACCESSORS *****/
  482. /**
  483. * Get the Request object
  484. * @return Slim_Http_Request
  485. */
  486. public function request() {
  487. return $this->request;
  488. }
  489. /**
  490. * Get the Response object
  491. * @return Slim_Http_Response
  492. */
  493. public function response() {
  494. return $this->response;
  495. }
  496. /**
  497. * Get the Router object
  498. * @return Slim_Router
  499. */
  500. public function router() {
  501. return $this->router;
  502. }
  503. /**
  504. * Get and/or set the View
  505. *
  506. * This method declares the View to be used by the Slim application.
  507. * If the argument is a string, Slim will instantiate a new object
  508. * of the same class. If the argument is an instance of View or a subclass
  509. * of View, Slim will use the argument as the View.
  510. *
  511. * If a View already exists and this method is called to create a
  512. * new View, data already set in the existing View will be
  513. * transferred to the new View.
  514. *
  515. * @param string|Slim_View $viewClass The name of a Slim_View class;
  516. * An instance of Slim_View;
  517. * @return Slim_View
  518. */
  519. public function view( $viewClass = null ) {
  520. if ( !is_null($viewClass) ) {
  521. $existingData = is_null($this->view) ? array() : $this->view->getData();
  522. if ( $viewClass instanceOf Slim_View ) {
  523. $this->view = $viewClass;
  524. } else {
  525. $this->view = new $viewClass();
  526. }
  527. $this->view->appendData($existingData);
  528. }
  529. return $this->view;
  530. }
  531. /***** RENDERING *****/
  532. /**
  533. * Render a template
  534. *
  535. * Call this method within a GET, POST, PUT, DELETE, NOT FOUND, or ERROR
  536. * callable to render a template whose output is appended to the
  537. * current HTTP response body. How the template is rendered is
  538. * delegated to the current View.
  539. *
  540. * @param string $template The name of the template passed into the View::render method
  541. * @param array $data Associative array of data made available to the View
  542. * @param int $status The HTTP response status code to use (Optional)
  543. * @return void
  544. */
  545. public function render( $template, $data = array(), $status = null ) {
  546. $templatesPath = $this->config('templates.path');
  547. //Legacy support
  548. if ( is_null($templatesPath) ) {
  549. $templatesPath = $this->config('templates_dir');
  550. }
  551. $this->view->setTemplatesDirectory($templatesPath);
  552. if ( !is_null($status) ) {
  553. $this->response->status($status);
  554. }
  555. $this->view->appendData($data);
  556. $this->view->display($template);
  557. }
  558. /***** HTTP CACHING *****/
  559. /**
  560. * Set Last-Modified HTTP Response Header
  561. *
  562. * Set the HTTP 'Last-Modified' header and stop if a conditional
  563. * GET request's `If-Modified-Since` header matches the last modified time
  564. * of the resource. The `time` argument is a UNIX timestamp integer value.
  565. * When the current request includes an 'If-Modified-Since' header that
  566. * matches the specified last modified time, the application will stop
  567. * and send a '304 Not Modified' response to the client.
  568. *
  569. * @param int $time The last modified UNIX timestamp
  570. * @throws SlimException Returns HTTP 304 Not Modified response if resource last modified time matches `If-Modified-Since` header
  571. * @throws InvalidArgumentException If provided timestamp is not an integer
  572. * @return void
  573. */
  574. public function lastModified( $time ) {
  575. if ( is_integer($time) ) {
  576. $this->response->header('Last-Modified', date(DATE_RFC1123, $time));
  577. if ( $time === strtotime($this->request->headers('IF_MODIFIED_SINCE')) ) $this->halt(304);
  578. } else {
  579. throw new InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
  580. }
  581. }
  582. /**
  583. * Set ETag HTTP Response Header
  584. *
  585. * Set the etag header and stop if the conditional GET request matches.
  586. * The `value` argument is a unique identifier for the current resource.
  587. * The `type` argument indicates whether the etag should be used as a strong or
  588. * weak cache validator.
  589. *
  590. * When the current request includes an 'If-None-Match' header with
  591. * a matching etag, execution is immediately stopped. If the request
  592. * method is GET or HEAD, a '304 Not Modified' response is sent.
  593. *
  594. * @param string $value The etag value
  595. * @param string $type The type of etag to create; either "strong" or "weak"
  596. * @throws InvalidArgumentException If provided type is invalid
  597. * @return void
  598. */
  599. public function etag( $value, $type = 'strong' ) {
  600. //Ensure type is correct
  601. if ( !in_array($type, array('strong', 'weak')) ) {
  602. throw new InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
  603. }
  604. //Set etag value
  605. $value = '"' . $value . '"';
  606. if ( $type === 'weak' ) $value = 'W/'.$value;
  607. $this->response->header('ETag', $value);
  608. //Check conditional GET
  609. if ( $etagsHeader = $this->request->headers('IF_NONE_MATCH')) {
  610. $etags = preg_split('@\s*,\s*@', $etagsHeader);
  611. if ( in_array($value, $etags) || in_array('*', $etags) ) $this->halt(304);
  612. }
  613. }
  614. /***** COOKIES *****/
  615. /**
  616. * Set a normal, unencrypted Cookie
  617. *
  618. * @param string $name The cookie name
  619. * @param mixed $value The cookie value
  620. * @param mixed $time The duration of the cookie;
  621. * If integer, should be UNIX timestamp;
  622. * If string, converted to UNIX timestamp with `strtotime`;
  623. * @param string $path The path on the server in which the cookie will be available on
  624. * @param string $domain The domain that the cookie is available to
  625. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  626. * HTTPS connection to/from the client
  627. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  628. * @return void
  629. */
  630. public function setCookie( $name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null ) {
  631. $time = is_null($time) ? $this->config('cookies.lifetime') : $time;
  632. $path = is_null($path) ? $this->config('cookies.path') : $path;
  633. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  634. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  635. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  636. $this->response->getCookieJar()->setClassicCookie($name, $value, $time, $path, $domain, $secure, $httponly);
  637. }
  638. /**
  639. * Get the value of a Cookie from the current HTTP Request
  640. *
  641. * Return the value of a cookie from the current HTTP request,
  642. * or return NULL if cookie does not exist. Cookies created during
  643. * the current request will not be available until the next request.
  644. *
  645. * @param string $name
  646. * @return string|null
  647. */
  648. public function getCookie( $name ) {
  649. return $this->request->cookies($name);
  650. }
  651. /**
  652. * Set an encrypted Cookie
  653. *
  654. * @param string $name The cookie name
  655. * @param mixed $value The cookie value
  656. * @param mixed $time The duration of the cookie;
  657. * If integer, should be UNIX timestamp;
  658. * If string, converted to UNIX timestamp with `strtotime`;
  659. * @param string $path The path on the server in which the cookie will be available on
  660. * @param string $domain The domain that the cookie is available to
  661. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  662. * HTTPS connection from the client
  663. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  664. * @return void
  665. */
  666. public function setEncryptedCookie( $name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null ) {
  667. $time = is_null($time) ? $this->config('cookies.lifetime') : $time;
  668. $path = is_null($path) ? $this->config('cookies.path') : $path;
  669. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  670. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  671. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  672. $userId = $this->config('cookies.user_id');
  673. $this->response->getCookieJar()->setCookie($name, $value, $userId, $time, $path, $domain, $secure, $httponly);
  674. }
  675. /**
  676. * Get the value of an encrypted Cookie from the current HTTP request
  677. *
  678. * Return the value of an encrypted cookie from the current HTTP request,
  679. * or return NULL if cookie does not exist. Encrypted cookies created during
  680. * the current request will not be available until the next request.
  681. *
  682. * @param string $name
  683. * @return string|null
  684. */
  685. public function getEncryptedCookie( $name ) {
  686. $value = $this->response->getCookieJar()->getCookieValue($name);
  687. return ($value === false) ? null : $value;
  688. }
  689. /**
  690. * Delete a Cookie (for both normal or encrypted Cookies)
  691. *
  692. * Remove a Cookie from the client. This method will overwrite an existing Cookie
  693. * with a new, empty, auto-expiring Cookie. This method's arguments must match
  694. * the original Cookie's respective arguments for the original Cookie to be
  695. * removed. If any of this method's arguments are omitted or set to NULL, the
  696. * default Cookie setting values (set during Slim::init) will be used instead.
  697. *
  698. * @param string $name The cookie name
  699. * @param string $path The path on the server in which the cookie will be available on
  700. * @param string $domain The domain that the cookie is available to
  701. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  702. * HTTPS connection from the client
  703. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  704. * @return void
  705. */
  706. public function deleteCookie( $name, $path = null, $domain = null, $secure = null, $httponly = null ) {
  707. $path = is_null($path) ? $this->config('cookies.path') : $path;
  708. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  709. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  710. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  711. $this->response->getCookieJar()->deleteCookie( $name, $path, $domain, $secure, $httponly );
  712. }
  713. /***** HELPERS *****/
  714. /**
  715. * Get the Slim application's absolute directory path
  716. *
  717. * This method returns the absolute path to the Slim application's
  718. * directory. If the Slim application is installed in a public-accessible
  719. * sub-directory, the sub-directory path will be included. This method
  720. * will always return an absolute path WITH a trailing slash.
  721. *
  722. * @return string
  723. */
  724. public function root() {
  725. return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
  726. }
  727. /**
  728. * Stop
  729. *
  730. * Send the current Response as is and stop executing the Slim
  731. * application. The thrown exception will be caught by the Slim
  732. * custom exception handler which exits this script.
  733. *
  734. * @throws Slim_Exception_Stop
  735. * @return void
  736. */
  737. public function stop() {
  738. $flash = $this->view->getData('flash');
  739. if ( $flash ) {
  740. $flash->save();
  741. }
  742. session_write_close();
  743. $this->response->send();
  744. throw new Slim_Exception_Stop();
  745. }
  746. /**
  747. * Halt
  748. *
  749. * Halt the application and immediately send an HTTP response with a
  750. * specific status code and body. This may be used to send any type of
  751. * response: info, success, redirect, client error, or server error.
  752. * If you need to render a template AND customize the response status,
  753. * you should use Slim::render() instead.
  754. *
  755. * @param int $status The HTTP response status
  756. * @param string $message The HTTP response body
  757. * @return void
  758. */
  759. public function halt( $status, $message = '') {
  760. if ( ob_get_level() !== 0 ) {
  761. ob_clean();
  762. }
  763. $this->response->status($status);
  764. $this->response->body($message);
  765. $this->stop();
  766. }
  767. /**
  768. * Pass
  769. *
  770. * This method will cause the Router::dispatch method to ignore
  771. * the current route and continue to the next matching route in the
  772. * dispatch loop. If no subsequent mathing routes are found,
  773. * a 404 Not Found response will be sent to the client.
  774. *
  775. * @throws Slim_Exception_Pass
  776. * @return void
  777. */
  778. public function pass() {
  779. if ( ob_get_level() !== 0 ) {
  780. ob_clean();
  781. }
  782. throw new Slim_Exception_Pass();
  783. }
  784. /**
  785. * Set the HTTP response Content-Type
  786. * @param string $type The Content-Type for the Response (ie. text/html)
  787. * @return void
  788. */
  789. public function contentType( $type ) {
  790. $this->response->header('Content-Type', $type);
  791. }
  792. /**
  793. * Set the HTTP response status code
  794. * @param int $status The HTTP response status code
  795. * @return void
  796. */
  797. public function status( $code ) {
  798. $this->response->status($code);
  799. }
  800. /**
  801. * Get the URL for a named Route
  802. * @param string $name The route name
  803. * @param array $params Key-value array of URL parameters
  804. * @throws RuntimeException If named route does not exist
  805. * @return string
  806. */
  807. public function urlFor( $name, $params = array() ) {
  808. return $this->router->urlFor($name, $params);
  809. }
  810. /**
  811. * Redirect
  812. *
  813. * This method immediately redirects to a new URL. By default,
  814. * this issues a 302 Found response; this is considered the default
  815. * generic redirect response. You may also specify another valid
  816. * 3xx status code if you want. This method will automatically set the
  817. * HTTP Location header for you using the URL parameter and place the
  818. * destination URL into the response body.
  819. *
  820. * @param string $url The destination URL
  821. * @param int $status The HTTP redirect status code (Optional)
  822. * @throws InvalidArgumentException If status parameter is not a valid 3xx status code
  823. * @return void
  824. */
  825. public function redirect( $url, $status = 302 ) {
  826. if ( $status >= 300 && $status <= 307 ) {
  827. $this->response->header('Location', (string)$url);
  828. $this->halt($status, (string)$url);
  829. } else {
  830. throw new InvalidArgumentException('Slim::redirect only accepts HTTP 300-307 status codes.');
  831. }
  832. }
  833. /***** FLASH *****/
  834. /**
  835. * Set flash message for subsequent request
  836. * @param string $key
  837. * @param mixed $value
  838. * @return void
  839. */
  840. public function flash( $key, $value ) {
  841. $this->view->getData('flash')->set($key, $value);
  842. }
  843. /**
  844. * Set flash message for current request
  845. * @param string $key
  846. * @param mixed $value
  847. * @return void
  848. */
  849. public function flashNow( $key, $value ) {
  850. $this->view->getData('flash')->now($key, $value);
  851. }
  852. /**
  853. * Keep flash messages from previous request for subsequent request
  854. * @return void
  855. */
  856. public function flashKeep() {
  857. $this->view->getData('flash')->keep();
  858. }
  859. /***** HOOKS *****/
  860. /**
  861. * Assign hook
  862. * @param string $name The hook name
  863. * @param mixed $callable A callable object
  864. * @param int $priority The hook priority; 0 = high, 10 = low
  865. * @return void
  866. */
  867. public function hook( $name, $callable, $priority = 10 ) {
  868. if ( !isset($this->hooks[$name]) ) {
  869. $this->hooks[$name] = array(array());
  870. }
  871. if ( is_callable($callable) ) {
  872. $this->hooks[$name][(int)$priority][] = $callable;
  873. }
  874. }
  875. /**
  876. * Invoke hook
  877. * @param string $name The hook name
  878. * @param mixed $hookArgs (Optional) Argument for hooked functions
  879. * @return mixed
  880. */
  881. public function applyHook( $name, $hookArg = null ) {
  882. if ( !isset($this->hooks[$name]) ) {
  883. $this->hooks[$name] = array(array());
  884. }
  885. if( !empty($this->hooks[$name]) ) {
  886. // Sort by priority, low to high, if there's more than one priority
  887. if ( count($this->hooks[$name]) > 1 ) {
  888. ksort($this->hooks[$name]);
  889. }
  890. foreach( $this->hooks[$name] as $priority ) {
  891. if( !empty($priority) ) {
  892. foreach($priority as $callable) {
  893. $hookArg = call_user_func($callable, $hookArg);
  894. }
  895. }
  896. }
  897. return $hookArg;
  898. }
  899. }
  900. /**
  901. * Get hook listeners
  902. *
  903. * Return an array of registered hooks. If `$name` is a valid
  904. * hook name, only the listeners attached to that hook are returned.
  905. * Else, all listeners are returned as an associative array whose
  906. * keys are hook names and whose values are arrays of listeners.
  907. *
  908. * @param string $name A hook name (Optional)
  909. * @return array|null
  910. */
  911. public function getHooks( $name = null ) {
  912. if ( !is_null($name) ) {
  913. return isset($this->hooks[(string)$name]) ? $this->hooks[(string)$name] : null;
  914. } else {
  915. return $this->hooks;
  916. }
  917. }
  918. /**
  919. * Clear hook listeners
  920. *
  921. * Clear all listeners for all hooks. If `$name` is
  922. * a valid hook name, only the listeners attached
  923. * to that hook will be cleared.
  924. *
  925. * @param string $name A hook name (Optional)
  926. * @return void
  927. */
  928. public function clearHooks( $name = null ) {
  929. if ( !is_null($name) && isset($this->hooks[(string)$name]) ) {
  930. $this->hooks[(string)$name] = array(array());
  931. } else {
  932. foreach( $this->hooks as $key => $value ) {
  933. $this->hooks[$key] = array(array());
  934. }
  935. }
  936. }
  937. /***** RUN SLIM *****/
  938. /**
  939. * Run the Slim application
  940. *
  941. * This method is the "meat and potatoes" of Slim and should be the last
  942. * method called. This fires up Slim, invokes the Route that matches
  943. * the current request, and returns the response to the client.
  944. *
  945. * This method will invoke the Not Found handler if no matching
  946. * routes are found.
  947. *
  948. * This method will also catch any unexpected Exceptions thrown by this
  949. * application; the Exceptions will be logged to this application's log
  950. * and rethrown to the global Exception handler.
  951. *
  952. * @return void
  953. */
  954. public function run() {
  955. try {
  956. try {
  957. $this->applyHook('slim.before');
  958. ob_start();
  959. $this->applyHook('slim.before.router');
  960. $dispatched = false;
  961. $httpMethod = $this->request()->getMethod();
  962. $httpMethodsAllowed = array();
  963. foreach ( $this->router as $route ) {
  964. if ( $route->supportsHttpMethod($httpMethod) ) {
  965. try {
  966. $this->applyHook('slim.before.dispatch');
  967. $dispatched = $route->dispatch();
  968. $this->applyHook('slim.after.dispatch');
  969. if ( $dispatched ) {
  970. break;
  971. }
  972. } catch ( Slim_Exception_Pass $e ) {
  973. continue;
  974. }
  975. } else {
  976. $httpMethodsAllowed = array_merge($httpMethodsAllowed, $route->getHttpMethods());
  977. }
  978. }
  979. if ( !$dispatched ) {
  980. if ( $httpMethodsAllowed ) {
  981. $this->response()->header('Allow', implode(' ', $httpMethodsAllowed));
  982. $this->halt(405);
  983. } else {
  984. $this->notFound();
  985. }
  986. }
  987. $this->response()->write(ob_get_clean());
  988. $this->applyHook('slim.after.router');
  989. $this->view->getData('flash')->save();
  990. session_write_close();
  991. $this->response->send();
  992. $this->applyHook('slim.after');
  993. } catch ( Slim_Exception_RequestSlash $e ) {
  994. $this->redirect($this->request->getRootUri() . $this->request->getResourceUri() . '/', 301);
  995. } catch ( Exception $e ) {
  996. if ( $e instanceof Slim_Exception_Stop ) throw $e;
  997. $this->getLog()->error($e);
  998. if ( $this->config('debug') === true ) {
  999. $this->halt(500, self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
  1000. } else {
  1001. $this->error($e);
  1002. }
  1003. }
  1004. } catch ( Slim_Exception_Stop $e ) {
  1005. //Exit application context
  1006. }
  1007. }
  1008. /***** EXCEPTION AND ERROR HANDLING *****/
  1009. /**
  1010. * Handle errors
  1011. *
  1012. * This is the global Error handler that will catch reportable Errors
  1013. * and convert them into ErrorExceptions that are caught and handled
  1014. * by each Slim application.
  1015. *
  1016. * @param int $errno The numeric type of the Error
  1017. * @param string $errstr The error message
  1018. * @param string $errfile The absolute path to the affected file
  1019. * @param int $errline The line number of the error in the affected file
  1020. * @return true
  1021. * @throws ErrorException
  1022. */
  1023. public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) {
  1024. if ( error_reporting() & $errno ) {
  1025. throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
  1026. }
  1027. return true;
  1028. }
  1029. /**
  1030. * Generate markup for error message
  1031. *
  1032. * This method accepts details about an error or exception and
  1033. * generates HTML markup for the 500 response body that will
  1034. * be sent to the client.
  1035. *
  1036. * @param string $message The error message
  1037. * @param string $file The absolute file path to the affected file
  1038. * @param int $line The line number in the affected file
  1039. * @param string $trace A stack trace of the error
  1040. * @return string
  1041. */
  1042. protected static function generateErrorMarkup( $message, $file = '', $line = '', $trace = '' ) {
  1043. $body = '<p>The application could not run because of the following error:</p>';
  1044. $body .= "<h2>Details:</h2><strong>Message:</strong> $message<br/>";
  1045. if ( $file !== '' ) $body .= "<strong>File:</strong> $file<br/>";
  1046. if ( $line !== '' ) $body .= "<strong>Line:</strong> $line<br/>";
  1047. if ( $trace !== '' ) $body .= '<h2>Stack Trace:</h2>' . nl2br($trace);
  1048. // Added for log sql errors
  1049. if(class_exists("FirePHP")){
  1050. $firephp = FirePHP::getInstance(true);
  1051. $firephp->log(ORM::get_last_query(), 'ORM-last-query');
  1052. $firephp->log(ORM::get_query_log(), 'ORM-query-log');
  1053. }else{
  1054. $body .= "<br/><hr/>Offending sql sentence:<br/>".print_r(ORM::get_last_query(),true);
  1055. }
  1056. // -----
  1057. return self::generateTemplateMarkup('Slim Application Error', $body);
  1058. }
  1059. /**
  1060. * Generate default template markup
  1061. *
  1062. * This method accepts a title and body content to generate
  1063. * an HTML page. This is primarily used to generate the layout markup
  1064. * for Error handlers and Not Found handlers.
  1065. *
  1066. * @param string $title The title of the HTML template
  1067. * @param string $body The body content of the HTML template
  1068. * @return string
  1069. */
  1070. protected static function generateTemplateMarkup( $title, $body ) {
  1071. $html = "<html><head><title>$title</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>";
  1072. $html .= "<h1>$title</h1>";
  1073. $html .= $body;
  1074. $html .= '</body></html>';
  1075. return $html;
  1076. }
  1077. /**
  1078. * Default Not Found handler
  1079. * @return void
  1080. */
  1081. protected function defaultNotFound() {
  1082. echo self::generateTemplateMarkup('404 Page Not Found', '<p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p><a href="' . $this->request->getRootUri() . '">Visit the Home Page</a>');
  1083. }
  1084. /**
  1085. * Default Error handler
  1086. * @return void
  1087. */
  1088. protected function defaultError() {
  1089. echo self::generateTemplateMarkup('Error', '<p>A website error has occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.</p>');
  1090. }
  1091. }