PageRenderTime 62ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/Slim/Slim.php

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