PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/app/Slim/Slim.php

https://bitbucket.org/Sulla/fish-for-sites
PHP | 1136 lines | 440 code | 90 blank | 606 comment | 68 complexity | 2bedd0876e7f067394ab2672a66f81a6 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause
  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. ), $userSettings);
  168. //Determine application mode
  169. $this->getMode();
  170. //Setup HTTP request and response handling
  171. $this->request = new Slim_Http_Request();
  172. $this->response = new Slim_Http_Response($this->request);
  173. $this->response->setCookieJar(new Slim_Http_CookieJar($this->settings['cookies.secret_key'], array(
  174. 'high_confidentiality' => $this->settings['cookies.encrypt'],
  175. 'mcrypt_algorithm' => $this->settings['cookies.cipher'],
  176. 'mcrypt_mode' => $this->settings['cookies.cipher_mode'],
  177. 'enable_ssl' => $this->settings['cookies.secure']
  178. )));
  179. $this->router = new Slim_Router($this->request);
  180. //Start session if not already started
  181. if ( session_id() === '' ) {
  182. $sessionHandler = $this->config('session.handler');
  183. if ( $sessionHandler instanceof Slim_Session_Handler ) {
  184. $sessionHandler->register($this);
  185. }
  186. session_start();
  187. }
  188. //Setup view with flash messaging
  189. $this->view($this->config('view'))->setData('flash', new Slim_Session_Flash($this->config('session.flash_key')));
  190. //Set app name
  191. if ( !isset(self::$apps['default']) ) {
  192. $this->setName('default');
  193. }
  194. //Set global Error handler after Slim app instantiated
  195. set_error_handler(array('Slim', 'handleErrors'));
  196. }
  197. /**
  198. * Get application mode
  199. * @return string
  200. */
  201. public function getMode() {
  202. if ( !isset($this->mode) ) {
  203. if ( isset($_ENV['SLIM_MODE']) ) {
  204. $this->mode = (string)$_ENV['SLIM_MODE'];
  205. } else {
  206. $this->mode = (string)$this->config('mode');
  207. }
  208. }
  209. return $this->mode;
  210. }
  211. /***** NAMING *****/
  212. /**
  213. * Get Slim application with name
  214. * @param string $name The name of the Slim application to fetch
  215. * @return Slim|null
  216. */
  217. public static function getInstance( $name = 'default' ) {
  218. return isset(self::$apps[(string)$name]) ? self::$apps[(string)$name] : null;
  219. }
  220. /**
  221. * Set Slim application name
  222. * @param string $name The name of this Slim application
  223. * @return void
  224. */
  225. public function setName( $name ) {
  226. $this->name = $name;
  227. self::$apps[$name] = $this;
  228. }
  229. /**
  230. * Get Slim application name
  231. * @return string|null
  232. */
  233. public function getName() {
  234. return $this->name;
  235. }
  236. /***** LOGGING *****/
  237. /**
  238. * Get application Log (lazy-loaded)
  239. * @return Slim_Log
  240. */
  241. public function getLog() {
  242. if ( !isset($this->log) ) {
  243. $this->log = new Slim_Log();
  244. $this->log->setEnabled($this->config('log.enable'));
  245. $logger = $this->config('log.logger');
  246. if ( $logger ) {
  247. $this->log->setLogger($logger);
  248. } else {
  249. $this->log->setLogger(new Slim_Logger($this->config('log.path'), $this->config('log.level')));
  250. }
  251. }
  252. return $this->log;
  253. }
  254. /***** CONFIGURATION *****/
  255. /**
  256. * Configure Slim for a given mode
  257. *
  258. * This method will immediately invoke the callable if
  259. * the specified mode matches the current application mode.
  260. * Otherwise, the callable is ignored. This should be called
  261. * only _after_ you initialize your Slim app.
  262. *
  263. * @param string $mode
  264. * @param mixed $callable
  265. * @return void
  266. */
  267. public function configureMode( $mode, $callable ) {
  268. if ( $mode === $this->getMode() && is_callable($callable) ) {
  269. call_user_func($callable);
  270. }
  271. }
  272. /**
  273. * Configure Slim Settings
  274. *
  275. * This method defines application settings and acts as a setter and a getter.
  276. *
  277. * If only one argument is specified and that argument is a string, the value
  278. * of the setting identified by the first argument will be returned, or NULL if
  279. * that setting does not exist.
  280. *
  281. * If only one argument is specified and that argument is an associative array,
  282. * the array will be merged into the existing application settings.
  283. *
  284. * If two arguments are provided, the first argument is the name of the setting
  285. * to be created or updated, and the second argument is the setting value.
  286. *
  287. * @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
  288. * @param mixed $value If name is a string, the value of the setting identified by $name
  289. * @return mixed The value of a setting if only one argument is a string
  290. */
  291. public function config( $name, $value = null ) {
  292. if ( func_num_args() === 1 ) {
  293. if ( is_array($name) ) {
  294. $this->settings = array_merge($this->settings, $name);
  295. } else {
  296. return in_array($name, array_keys($this->settings)) ? $this->settings[$name] : null;
  297. }
  298. } else {
  299. $this->settings[$name] = $value;
  300. }
  301. }
  302. /***** ROUTING *****/
  303. /**
  304. * Add GET|POST|PUT|DELETE route
  305. *
  306. * Adds a new route to the router with associated callable. This
  307. * route will only be invoked when the HTTP request's method matches
  308. * this route's method.
  309. *
  310. * ARGUMENTS:
  311. *
  312. * First: string The URL pattern (REQUIRED)
  313. * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL)
  314. * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED)
  315. *
  316. * The first argument is required and must always be the
  317. * route pattern (ie. '/books/:id').
  318. *
  319. * The last argument is required and must always be the callable object
  320. * to be invoked when the route matches an HTTP request.
  321. *
  322. * You may also provide an unlimited number of in-between arguments;
  323. * each interior argument must be callable and will be invoked in the
  324. * order specified before the route's callable is invoked.
  325. *
  326. * USAGE:
  327. *
  328. * Slim::get('/foo'[, middleware, middleware, ...], callable);
  329. *
  330. * @param string The HTTP method (ie. GET, POST, PUT, DELETE)
  331. * @param array See notes above
  332. * @return Slim_Route
  333. */
  334. protected function mapRoute($type, $args) {
  335. $pattern = array_shift($args);
  336. $callable = array_pop($args);
  337. $route = $this->router->map($pattern, $callable, $type);
  338. if ( count($args) > 0 ) {
  339. $route->setMiddleware($args);
  340. }
  341. return $route;
  342. }
  343. /**
  344. * Add GET route
  345. * @see Slim::mapRoute
  346. * @return Slim_Route
  347. */
  348. public function get() {
  349. $args = func_get_args();
  350. return $this->mapRoute(Slim_Http_Request::METHOD_GET, $args);
  351. }
  352. /**
  353. * Add POST route
  354. * @see Slim::mapRoute
  355. * @return Slim_Route
  356. */
  357. public function post() {
  358. $args = func_get_args();
  359. return $this->mapRoute(Slim_Http_Request::METHOD_POST, $args);
  360. }
  361. /**
  362. * Add PUT route
  363. * @see Slim::mapRoute
  364. * @return Slim_Route
  365. */
  366. public function put() {
  367. $args = func_get_args();
  368. return $this->mapRoute(Slim_Http_Request::METHOD_PUT, $args);
  369. }
  370. /**
  371. * Add DELETE route
  372. * @see Slim::mapRoute
  373. * @return Slim_Route
  374. */
  375. public function delete() {
  376. $args = func_get_args();
  377. return $this->mapRoute(Slim_Http_Request::METHOD_DELETE, $args);
  378. }
  379. /**
  380. * Not Found Handler
  381. *
  382. * This method defines or invokes the application-wide Not Found handler.
  383. * There are two contexts in which this method may be invoked:
  384. *
  385. * 1. When declaring the handler:
  386. *
  387. * If the $callable parameter is not null and is callable, this
  388. * method will register the callable to be invoked when no
  389. * routes match the current HTTP request. It WILL NOT invoke the callable.
  390. *
  391. * 2. When invoking the handler:
  392. *
  393. * If the $callable parameter is null, Slim assumes you want
  394. * to invoke an already-registered handler. If the handler has been
  395. * registered and is callable, it is invoked and sends a 404 HTTP Response
  396. * whose body is the output of the Not Found handler.
  397. *
  398. * @param mixed $callable Anything that returns true for is_callable()
  399. * @return void
  400. */
  401. public function notFound( $callable = null ) {
  402. if ( !is_null($callable) ) {
  403. $this->router->notFound($callable);
  404. } else {
  405. ob_start();
  406. $customNotFoundHandler = $this->router->notFound();
  407. if ( is_callable($customNotFoundHandler) ) {
  408. call_user_func($customNotFoundHandler);
  409. } else {
  410. call_user_func(array($this, 'defaultNotFound'));
  411. }
  412. $this->halt(404, ob_get_clean());
  413. }
  414. }
  415. /**
  416. * Error Handler
  417. *
  418. * This method defines or invokes the application-wide Error handler.
  419. * There are two contexts in which this method may be invoked:
  420. *
  421. * 1. When declaring the handler:
  422. *
  423. * If the $callable parameter is not null and is callable, this
  424. * method will register the callable to be invoked when an uncaught
  425. * Exception or Error is detected. It WILL NOT invoke the handler.
  426. *
  427. * 2. When invoking the handler:
  428. *
  429. * If the $callable parameter is null, Slim assumes you want
  430. * to invoke an already-registered handler. If the handler has been
  431. * registered and is callable, it is invoked and sends a 500 HTTP Response
  432. * whose body is the output of the Error handler.
  433. *
  434. * @param mixed $callable Anything that returns true for is_callable()
  435. * @return void
  436. */
  437. public function error( $callable = null ) {
  438. if ( !is_null($callable) && $callable instanceof Exception === false ) {
  439. $this->router->error($callable);
  440. } else {
  441. ob_start();
  442. $customErrorHandler = $this->router->error();
  443. if ( is_callable($customErrorHandler) ) {
  444. call_user_func_array($customErrorHandler, array($callable));
  445. } else {
  446. call_user_func_array(array($this, 'defaultError'), array($callable));
  447. }
  448. $this->halt(500, ob_get_clean());
  449. }
  450. }
  451. /***** ACCESSORS *****/
  452. /**
  453. * Get the Request object
  454. * @return Slim_Http_Request
  455. */
  456. public function request() {
  457. return $this->request;
  458. }
  459. /**
  460. * Get the Response object
  461. * @return Slim_Http_Response
  462. */
  463. public function response() {
  464. return $this->response;
  465. }
  466. /**
  467. * Get the Router object
  468. * @return Slim_Router
  469. */
  470. public function router() {
  471. return $this->router;
  472. }
  473. /**
  474. * Get and/or set the View
  475. *
  476. * This method declares the View to be used by the Slim application.
  477. * If the argument is a string, Slim will instantiate a new object
  478. * of the same class. If the argument is an instance of View or a subclass
  479. * of View, Slim will use the argument as the View.
  480. *
  481. * If a View already exists and this method is called to create a
  482. * new View, data already set in the existing View will be
  483. * transferred to the new View.
  484. *
  485. * @param string|Slim_View $viewClass The name of a Slim_View class;
  486. * An instance of Slim_View;
  487. * @return Slim_View
  488. */
  489. public function view( $viewClass = null ) {
  490. if ( !is_null($viewClass) ) {
  491. $existingData = is_null($this->view) ? array() : $this->view->getData();
  492. if ( $viewClass instanceOf Slim_View ) {
  493. $this->view = $viewClass;
  494. } else {
  495. $this->view = new $viewClass();
  496. }
  497. $this->view->appendData($existingData);
  498. }
  499. return $this->view;
  500. }
  501. /***** RENDERING *****/
  502. /**
  503. * Render a template
  504. *
  505. * Call this method within a GET, POST, PUT, DELETE, NOT FOUND, or ERROR
  506. * callable to render a template whose output is appended to the
  507. * current HTTP response body. How the template is rendered is
  508. * delegated to the current View.
  509. *
  510. * @param string $template The name of the template passed into the View::render method
  511. * @param array $data Associative array of data made available to the View
  512. * @param int $status The HTTP response status code to use (Optional)
  513. * @return void
  514. */
  515. public function render( $template, $data = array(), $status = null ) {
  516. $templatesPath = $this->config('templates.path');
  517. //Legacy support
  518. if ( is_null($templatesPath) ) {
  519. $templatesPath = $this->config('templates_dir');
  520. }
  521. $this->view->setTemplatesDirectory($templatesPath);
  522. if ( !is_null($status) ) {
  523. $this->response->status($status);
  524. }
  525. $this->view->appendData($data);
  526. $this->view->display($template);
  527. }
  528. /***** HTTP CACHING *****/
  529. /**
  530. * Set Last-Modified HTTP Response Header
  531. *
  532. * Set the HTTP 'Last-Modified' header and stop if a conditional
  533. * GET request's `If-Modified-Since` header matches the last modified time
  534. * of the resource. The `time` argument is a UNIX timestamp integer value.
  535. * When the current request includes an 'If-Modified-Since' header that
  536. * matches the specified last modified time, the application will stop
  537. * and send a '304 Not Modified' response to the client.
  538. *
  539. * @param int $time The last modified UNIX timestamp
  540. * @throws SlimException Returns HTTP 304 Not Modified response if resource last modified time matches `If-Modified-Since` header
  541. * @throws InvalidArgumentException If provided timestamp is not an integer
  542. * @return void
  543. */
  544. public function lastModified( $time ) {
  545. if ( is_integer($time) ) {
  546. $this->response->header('Last-Modified', date(DATE_RFC1123, $time));
  547. if ( $time === strtotime($this->request->headers('IF_MODIFIED_SINCE')) ) $this->halt(304);
  548. } else {
  549. throw new InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
  550. }
  551. }
  552. /**
  553. * Set ETag HTTP Response Header
  554. *
  555. * Set the etag header and stop if the conditional GET request matches.
  556. * The `value` argument is a unique identifier for the current resource.
  557. * The `type` argument indicates whether the etag should be used as a strong or
  558. * weak cache validator.
  559. *
  560. * When the current request includes an 'If-None-Match' header with
  561. * a matching etag, execution is immediately stopped. If the request
  562. * method is GET or HEAD, a '304 Not Modified' response is sent.
  563. *
  564. * @param string $value The etag value
  565. * @param string $type The type of etag to create; either "strong" or "weak"
  566. * @throws InvalidArgumentException If provided type is invalid
  567. * @return void
  568. */
  569. public function etag( $value, $type = 'strong' ) {
  570. //Ensure type is correct
  571. if ( !in_array($type, array('strong', 'weak')) ) {
  572. throw new InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
  573. }
  574. //Set etag value
  575. $value = '"' . $value . '"';
  576. if ( $type === 'weak' ) $value = 'W/'.$value;
  577. $this->response->header('ETag', $value);
  578. //Check conditional GET
  579. if ( $etagsHeader = $this->request->headers('IF_NONE_MATCH')) {
  580. $etags = preg_split('@\s*,\s*@', $etagsHeader);
  581. if ( in_array($value, $etags) || in_array('*', $etags) ) $this->halt(304);
  582. }
  583. }
  584. /***** COOKIES *****/
  585. /**
  586. * Set a normal, unencrypted Cookie
  587. *
  588. * @param string $name The cookie name
  589. * @param mixed $value The cookie value
  590. * @param mixed $time The duration of the cookie;
  591. * If integer, should be UNIX timestamp;
  592. * If string, converted to UNIX timestamp with `strtotime`;
  593. * @param string $path The path on the server in which the cookie will be available on
  594. * @param string $domain The domain that the cookie is available to
  595. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  596. * HTTPS connection to/from the client
  597. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  598. * @return void
  599. */
  600. public function setCookie( $name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null ) {
  601. $time = is_null($time) ? $this->config('cookies.lifetime') : $time;
  602. $path = is_null($path) ? $this->config('cookies.path') : $path;
  603. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  604. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  605. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  606. $this->response->getCookieJar()->setClassicCookie($name, $value, $time, $path, $domain, $secure, $httponly);
  607. }
  608. /**
  609. * Get the value of a Cookie from the current HTTP Request
  610. *
  611. * Return the value of a cookie from the current HTTP request,
  612. * or return NULL if cookie does not exist. Cookies created during
  613. * the current request will not be available until the next request.
  614. *
  615. * @param string $name
  616. * @return string|null
  617. */
  618. public function getCookie( $name ) {
  619. return $this->request->cookies($name);
  620. }
  621. /**
  622. * Set an encrypted Cookie
  623. *
  624. * @param string $name The cookie name
  625. * @param mixed $value The cookie value
  626. * @param mixed $time The duration of the cookie;
  627. * If integer, should be UNIX timestamp;
  628. * If string, converted to UNIX timestamp with `strtotime`;
  629. * @param string $path The path on the server in which the cookie will be available on
  630. * @param string $domain The domain that the cookie is available to
  631. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  632. * HTTPS connection from the client
  633. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  634. * @return void
  635. */
  636. public function setEncryptedCookie( $name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null ) {
  637. $time = is_null($time) ? $this->config('cookies.lifetime') : $time;
  638. $path = is_null($path) ? $this->config('cookies.path') : $path;
  639. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  640. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  641. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  642. $userId = $this->config('cookies.user_id');
  643. $this->response->getCookieJar()->setCookie($name, $value, $userId, $time, $path, $domain, $secure, $httponly);
  644. }
  645. /**
  646. * Get the value of an encrypted Cookie from the current HTTP request
  647. *
  648. * Return the value of an encrypted cookie from the current HTTP request,
  649. * or return NULL if cookie does not exist. Encrypted cookies created during
  650. * the current request will not be available until the next request.
  651. *
  652. * @param string $name
  653. * @return string|null
  654. */
  655. public function getEncryptedCookie( $name ) {
  656. $value = $this->response->getCookieJar()->getCookieValue($name);
  657. return ($value === false) ? null : $value;
  658. }
  659. /**
  660. * Delete a Cookie (for both normal or encrypted Cookies)
  661. *
  662. * Remove a Cookie from the client. This method will overwrite an existing Cookie
  663. * with a new, empty, auto-expiring Cookie. This method's arguments must match
  664. * the original Cookie's respective arguments for the original Cookie to be
  665. * removed. If any of this method's arguments are omitted or set to NULL, the
  666. * default Cookie setting values (set during Slim::init) will be used instead.
  667. *
  668. * @param string $name The cookie name
  669. * @param string $path The path on the server in which the cookie will be available on
  670. * @param string $domain The domain that the cookie is available to
  671. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  672. * HTTPS connection from the client
  673. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  674. * @return void
  675. */
  676. public function deleteCookie( $name, $path = null, $domain = null, $secure = null, $httponly = null ) {
  677. $path = is_null($path) ? $this->config('cookies.path') : $path;
  678. $domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
  679. $secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
  680. $httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
  681. $this->response->getCookieJar()->deleteCookie( $name, $path, $domain, $secure, $httponly );
  682. }
  683. /***** HELPERS *****/
  684. /**
  685. * Get the Slim application's absolute directory path
  686. *
  687. * This method returns the absolute path to the Slim application's
  688. * directory. If the Slim application is installed in a public-accessible
  689. * sub-directory, the sub-directory path will be included. This method
  690. * will always return an absolute path WITH a trailing slash.
  691. *
  692. * @return string
  693. */
  694. public function root() {
  695. return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
  696. }
  697. /**
  698. * Stop
  699. *
  700. * Send the current Response as is and stop executing the Slim
  701. * application. The thrown exception will be caught by the Slim
  702. * custom exception handler which exits this script.
  703. *
  704. * @throws Slim_Exception_Stop
  705. * @return void
  706. */
  707. public function stop() {
  708. $flash = $this->view->getData('flash');
  709. if ( $flash ) {
  710. $flash->save();
  711. }
  712. session_write_close();
  713. $this->response->send();
  714. throw new Slim_Exception_Stop();
  715. }
  716. /**
  717. * Halt
  718. *
  719. * Halt the application and immediately send an HTTP response with a
  720. * specific status code and body. This may be used to send any type of
  721. * response: info, success, redirect, client error, or server error.
  722. * If you need to render a template AND customize the response status,
  723. * you should use Slim::render() instead.
  724. *
  725. * @param int $status The HTTP response status
  726. * @param string $message The HTTP response body
  727. * @return void
  728. */
  729. public function halt( $status, $message = '') {
  730. if ( ob_get_level() !== 0 ) {
  731. ob_clean();
  732. }
  733. $this->response->status($status);
  734. $this->response->body($message);
  735. $this->stop();
  736. }
  737. /**
  738. * Pass
  739. *
  740. * This method will cause the Router::dispatch method to ignore
  741. * the current route and continue to the next matching route in the
  742. * dispatch loop. If no subsequent mathing routes are found,
  743. * a 404 Not Found response will be sent to the client.
  744. *
  745. * @throws Slim_Exception_Pass
  746. * @return void
  747. */
  748. public function pass() {
  749. if ( ob_get_level() !== 0 ) {
  750. ob_clean();
  751. }
  752. throw new Slim_Exception_Pass();
  753. }
  754. /**
  755. * Set the HTTP response Content-Type
  756. * @param string $type The Content-Type for the Response (ie. text/html)
  757. * @return void
  758. */
  759. public function contentType( $type ) {
  760. $this->response->header('Content-Type', $type);
  761. }
  762. /**
  763. * Set the HTTP response status code
  764. * @param int $status The HTTP response status code
  765. * @return void
  766. */
  767. public function status( $code ) {
  768. $this->response->status($code);
  769. }
  770. /**
  771. * Get the URL for a named Route
  772. * @param string $name The route name
  773. * @param array $params Key-value array of URL parameters
  774. * @throws RuntimeException If named route does not exist
  775. * @return string
  776. */
  777. public function urlFor( $name, $params = array() ) {
  778. return $this->router->urlFor($name, $params);
  779. }
  780. /**
  781. * Redirect
  782. *
  783. * This method immediately redirects to a new URL. By default,
  784. * this issues a 302 Found response; this is considered the default
  785. * generic redirect response. You may also specify another valid
  786. * 3xx status code if you want. This method will automatically set the
  787. * HTTP Location header for you using the URL parameter and place the
  788. * destination URL into the response body.
  789. *
  790. * @param string $url The destination URL
  791. * @param int $status The HTTP redirect status code (Optional)
  792. * @throws InvalidArgumentException If status parameter is not a valid 3xx status code
  793. * @return void
  794. */
  795. public function redirect( $url, $status = 302 ) {
  796. if ( $status >= 300 && $status <= 307 ) {
  797. $this->response->header('Location', (string)$url);
  798. $this->halt($status, (string)$url);
  799. } else {
  800. throw new InvalidArgumentException('Slim::redirect only accepts HTTP 300-307 status codes.');
  801. }
  802. }
  803. /***** FLASH *****/
  804. /**
  805. * Set flash message for subsequent request
  806. * @param string $key
  807. * @param mixed $value
  808. * @return void
  809. */
  810. public function flash( $key, $value ) {
  811. $this->view->getData('flash')->set($key, $value);
  812. }
  813. /**
  814. * Set flash message for current request
  815. * @param string $key
  816. * @param mixed $value
  817. * @return void
  818. */
  819. public function flashNow( $key, $value ) {
  820. $this->view->getData('flash')->now($key, $value);
  821. }
  822. /**
  823. * Keep flash messages from previous request for subsequent request
  824. * @return void
  825. */
  826. public function flashKeep() {
  827. $this->view->getData('flash')->keep();
  828. }
  829. /***** HOOKS *****/
  830. /**
  831. * Assign hook
  832. * @param string $name The hook name
  833. * @param mixed $callable A callable object
  834. * @param int $priority The hook priority; 0 = high, 10 = low
  835. * @return void
  836. */
  837. public function hook( $name, $callable, $priority = 10 ) {
  838. if ( !isset($this->hooks[$name]) ) {
  839. $this->hooks[$name] = array(array());
  840. }
  841. if ( is_callable($callable) ) {
  842. $this->hooks[$name][(int)$priority][] = $callable;
  843. }
  844. }
  845. /**
  846. * Invoke hook
  847. * @param string $name The hook name
  848. * @param mixed $hookArgs (Optional) Argument for hooked functions
  849. * @return mixed
  850. */
  851. public function applyHook( $name, $hookArg = null ) {
  852. if ( !isset($this->hooks[$name]) ) {
  853. $this->hooks[$name] = array(array());
  854. }
  855. if( !empty($this->hooks[$name]) ) {
  856. // Sort by priority, low to high, if there's more than one priority
  857. if ( count($this->hooks[$name]) > 1 ) {
  858. ksort($this->hooks[$name]);
  859. }
  860. foreach( $this->hooks[$name] as $priority ) {
  861. if( !empty($priority) ) {
  862. foreach($priority as $callable) {
  863. $hookArg = call_user_func($callable, $hookArg);
  864. }
  865. }
  866. }
  867. return $hookArg;
  868. }
  869. }
  870. /**
  871. * Get hook listeners
  872. *
  873. * Return an array of registered hooks. If `$name` is a valid
  874. * hook name, only the listeners attached to that hook are returned.
  875. * Else, all listeners are returned as an associative array whose
  876. * keys are hook names and whose values are arrays of listeners.
  877. *
  878. * @param string $name A hook name (Optional)
  879. * @return array|null
  880. */
  881. public function getHooks( $name = null ) {
  882. if ( !is_null($name) ) {
  883. return isset($this->hooks[(string)$name]) ? $this->hooks[(string)$name] : null;
  884. } else {
  885. return $this->hooks;
  886. }
  887. }
  888. /**
  889. * Clear hook listeners
  890. *
  891. * Clear all listeners for all hooks. If `$name` is
  892. * a valid hook name, only the listeners attached
  893. * to that hook will be cleared.
  894. *
  895. * @param string $name A hook name (Optional)
  896. * @return void
  897. */
  898. public function clearHooks( $name = null ) {
  899. if ( !is_null($name) && isset($this->hooks[(string)$name]) ) {
  900. $this->hooks[(string)$name] = array(array());
  901. } else {
  902. foreach( $this->hooks as $key => $value ) {
  903. $this->hooks[$key] = array(array());
  904. }
  905. }
  906. }
  907. /***** RUN SLIM *****/
  908. /**
  909. * Run the Slim application
  910. *
  911. * This method is the "meat and potatoes" of Slim and should be the last
  912. * method called. This fires up Slim, invokes the Route that matches
  913. * the current request, and returns the response to the client.
  914. *
  915. * This method will invoke the Not Found handler if no matching
  916. * routes are found.
  917. *
  918. * This method will also catch any unexpected Exceptions thrown by this
  919. * application; the Exceptions will be logged to this application's log
  920. * and rethrown to the global Exception handler.
  921. *
  922. * @return void
  923. */
  924. public function run() {
  925. try {
  926. $this->applyHook('slim.before');
  927. ob_start();
  928. $this->applyHook('slim.before.router');
  929. $dispatched = false;
  930. foreach( $this->router->getMatchedRoutes() as $route ) {
  931. try {
  932. $this->applyHook('slim.before.dispatch');
  933. $dispatched = $route->dispatch();
  934. $this->applyHook('slim.after.dispatch');
  935. if ( $dispatched ) {
  936. break;
  937. }
  938. } catch ( Slim_Exception_Pass $e ) {
  939. continue;
  940. }
  941. }
  942. if ( !$dispatched ) {
  943. $this->notFound();
  944. }
  945. $this->response()->write(ob_get_clean());
  946. $this->applyHook('slim.after.router');
  947. $this->view->getData('flash')->save();
  948. session_write_close();
  949. $this->response->send();
  950. $this->applyHook('slim.after');
  951. } catch ( Slim_Exception_RequestSlash $e ) {
  952. try {
  953. $this->redirect($this->request->getRootUri() . $this->request->getResourceUri() . '/', 301);
  954. } catch ( Slim_Exception_Stop $e2 ) {
  955. //Ignore Slim_Exception_Stop and exit application context
  956. }
  957. } catch ( Slim_Exception_Stop $e ) {
  958. //Exit application context
  959. } catch ( Exception $e ) {
  960. $this->getLog()->error($e);
  961. try {
  962. if ( $this->config('debug') === true ) {
  963. $this->halt(500, self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
  964. } else {
  965. $this->error($e);
  966. }
  967. } catch ( Slim_Exception_Stop $e2 ) {
  968. //Ignore Slim_Exception_Stop and exit application context
  969. }
  970. }
  971. }
  972. /***** EXCEPTION AND ERROR HANDLING *****/
  973. /**
  974. * Handle errors
  975. *
  976. * This is the global Error handler that will catch reportable Errors
  977. * and convert them into ErrorExceptions that are caught and handled
  978. * by each Slim application.
  979. *
  980. * @param int $errno The numeric type of the Error
  981. * @param string $errstr The error message
  982. * @param string $errfile The absolute path to the affected file
  983. * @param int $errline The line number of the error in the affected file
  984. * @return true
  985. * @throws ErrorException
  986. */
  987. public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) {
  988. if ( error_reporting() & $errno ) {
  989. throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
  990. }
  991. return true;
  992. }
  993. /**
  994. * Generate markup for error message
  995. *
  996. * This method accepts details about an error or exception and
  997. * generates HTML markup for the 500 response body that will
  998. * be sent to the client.
  999. *
  1000. * @param string $message The error message
  1001. * @param string $file The absolute file path to the affected file
  1002. * @param int $line The line number in the affected file
  1003. * @param string $trace A stack trace of the error
  1004. * @return string
  1005. */
  1006. protected static function generateErrorMarkup( $message, $file = '', $line = '', $trace = '' ) {
  1007. $body = '<p>The application could not run because of the following error:</p>';
  1008. $body .= "<h2>Details:</h2><strong>Message:</strong> $message<br/>";
  1009. if ( $file !== '' ) $body .= "<strong>File:</strong> $file<br/>";
  1010. if ( $line !== '' ) $body .= "<strong>Line:</strong> $line<br/>";
  1011. if ( $trace !== '' ) $body .= '<h2>Stack Trace:</h2>' . nl2br($trace);
  1012. return self::generateTemplateMarkup('Slim Application Error', $body);
  1013. }
  1014. /**
  1015. * Generate default template markup
  1016. *
  1017. * This method accepts a title and body content to generate
  1018. * an HTML page. This is primarily used to generate the layout markup
  1019. * for Error handlers and Not Found handlers.
  1020. *
  1021. * @param string $title The title of the HTML template
  1022. * @param string $body The body content of the HTML template
  1023. * @return string
  1024. */
  1025. protected static function generateTemplateMarkup( $title, $body ) {
  1026. $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>";
  1027. $html .= "<h1>$title</h1>";
  1028. $html .= $body;
  1029. $html .= '</body></html>';
  1030. return $html;
  1031. }
  1032. /**
  1033. * Default Not Found handler
  1034. * @return void
  1035. */
  1036. protected function defaultNotFound() {
  1037. 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>');
  1038. }
  1039. /**
  1040. * Default Error handler
  1041. * @return void
  1042. */
  1043. protected function defaultError() {
  1044. 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>');
  1045. }
  1046. }