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

/Slim/Slim.php

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