PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/Slim/Slim.php

https://bitbucket.org/AgentCodeMonkey/tutorialslimapi
PHP | 1412 lines | 609 code | 131 blank | 672 comment | 66 complexity | 76e59d9a2515a4880eeecb80f876f1fd MD5 | raw file
  1. <?php
  2. /**
  3. * Slim - a micro PHP 5 framework
  4. *
  5. * @author Josh Lockhart <info@slimframework.com>
  6. * @copyright 2011 Josh Lockhart
  7. * @link http://www.slimframework.com
  8. * @license http://www.slimframework.com/license
  9. * @version 2.4.2
  10. * @package Slim
  11. *
  12. * MIT LICENSE
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining
  15. * a copy of this software and associated documentation files (the
  16. * "Software"), to deal in the Software without restriction, including
  17. * without limitation the rights to use, copy, modify, merge, publish,
  18. * distribute, sublicense, and/or sell copies of the Software, and to
  19. * permit persons to whom the Software is furnished to do so, subject to
  20. * the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be
  23. * included in all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. namespace Slim;
  34. // Ensure mcrypt constants are defined even if mcrypt extension is not loaded
  35. if (!extension_loaded('mcrypt')) {
  36. define('MCRYPT_MODE_CBC', 0);
  37. define('MCRYPT_RIJNDAEL_256', 0);
  38. }
  39. /**
  40. * Slim
  41. * @package Slim
  42. * @author Josh Lockhart
  43. * @since 1.0.0
  44. *
  45. * @property \Slim\Environment $environment
  46. * @property \Slim\Http\Response $response
  47. * @property \Slim\Http\Request $request
  48. * @property \Slim\Router $router
  49. */
  50. class Slim
  51. {
  52. /**
  53. * @const string
  54. */
  55. const VERSION = '2.4.2';
  56. /**
  57. * @var \Slim\Helper\Set
  58. */
  59. public $container;
  60. /**
  61. * @var array[\Slim]
  62. */
  63. protected static $apps = array();
  64. /**
  65. * @var string
  66. */
  67. protected $name;
  68. /**
  69. * @var array
  70. */
  71. protected $middleware;
  72. /**
  73. * @var mixed Callable to be invoked if application error
  74. */
  75. protected $error;
  76. /**
  77. * @var mixed Callable to be invoked if no matching routes are found
  78. */
  79. protected $notFound;
  80. /**
  81. * @var array
  82. */
  83. protected $hooks = array(
  84. 'slim.before' => array(array()),
  85. 'slim.before.router' => array(array()),
  86. 'slim.before.dispatch' => array(array()),
  87. 'slim.after.dispatch' => array(array()),
  88. 'slim.after.router' => array(array()),
  89. 'slim.after' => array(array())
  90. );
  91. /********************************************************************************
  92. * PSR-0 Autoloader
  93. *
  94. * Do not use if you are using Composer to autoload dependencies.
  95. *******************************************************************************/
  96. /**
  97. * Slim PSR-0 autoloader
  98. */
  99. public static function autoload($className)
  100. {
  101. $thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
  102. $baseDir = __DIR__;
  103. if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
  104. $baseDir = substr($baseDir, 0, -strlen($thisClass));
  105. }
  106. $className = ltrim($className, '\\');
  107. $fileName = $baseDir;
  108. $namespace = '';
  109. if ($lastNsPos = strripos($className, '\\')) {
  110. $namespace = substr($className, 0, $lastNsPos);
  111. $className = substr($className, $lastNsPos + 1);
  112. $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
  113. }
  114. $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
  115. if (file_exists($fileName)) {
  116. require $fileName;
  117. }
  118. }
  119. /**
  120. * Register Slim's PSR-0 autoloader
  121. */
  122. public static function registerAutoloader()
  123. {
  124. spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload");
  125. }
  126. /********************************************************************************
  127. * Instantiation and Configuration
  128. *******************************************************************************/
  129. /**
  130. * Constructor
  131. * @param array $userSettings Associative array of application settings
  132. */
  133. public function __construct(array $userSettings = array())
  134. {
  135. // Setup IoC container
  136. $this->container = new \Slim\Helper\Set();
  137. $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings);
  138. // Default environment
  139. $this->container->singleton('environment', function ($c) {
  140. return \Slim\Environment::getInstance();
  141. });
  142. // Default request
  143. $this->container->singleton('request', function ($c) {
  144. return new \Slim\Http\Request($c['environment']);
  145. });
  146. // Default response
  147. $this->container->singleton('response', function ($c) {
  148. return new \Slim\Http\Response();
  149. });
  150. // Default router
  151. $this->container->singleton('router', function ($c) {
  152. return new \Slim\Router();
  153. });
  154. // Default view
  155. $this->container->singleton('view', function ($c) {
  156. $viewClass = $c['settings']['view'];
  157. $templatesPath = $c['settings']['templates.path'];
  158. $view = ($viewClass instanceOf \Slim\View) ? $viewClass : new $viewClass;
  159. $view->setTemplatesDirectory($templatesPath);
  160. return $view;
  161. });
  162. // Default log writer
  163. $this->container->singleton('logWriter', function ($c) {
  164. $logWriter = $c['settings']['log.writer'];
  165. return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']);
  166. });
  167. // Default log
  168. $this->container->singleton('log', function ($c) {
  169. $log = new \Slim\Log($c['logWriter']);
  170. $log->setEnabled($c['settings']['log.enabled']);
  171. $log->setLevel($c['settings']['log.level']);
  172. $env = $c['environment'];
  173. $env['slim.log'] = $log;
  174. return $log;
  175. });
  176. // Default mode
  177. $this->container['mode'] = function ($c) {
  178. $mode = $c['settings']['mode'];
  179. if (isset($_ENV['SLIM_MODE'])) {
  180. $mode = $_ENV['SLIM_MODE'];
  181. } else {
  182. $envMode = getenv('SLIM_MODE');
  183. if ($envMode !== false) {
  184. $mode = $envMode;
  185. }
  186. }
  187. return $mode;
  188. };
  189. // Define default middleware stack
  190. $this->middleware = array($this);
  191. $this->add(new \Slim\Middleware\Flash());
  192. $this->add(new \Slim\Middleware\MethodOverride());
  193. // Make default if first instance
  194. if (is_null(static::getInstance())) {
  195. $this->setName('default');
  196. }
  197. }
  198. public function __get($name)
  199. {
  200. return $this->container[$name];
  201. }
  202. public function __set($name, $value)
  203. {
  204. $this->container[$name] = $value;
  205. }
  206. public function __isset($name)
  207. {
  208. return isset($this->container[$name]);
  209. }
  210. public function __unset($name)
  211. {
  212. unset($this->container[$name]);
  213. }
  214. /**
  215. * Get application instance by name
  216. * @param string $name The name of the Slim application
  217. * @return \Slim\Slim|null
  218. */
  219. public static function getInstance($name = 'default')
  220. {
  221. return isset(static::$apps[$name]) ? static::$apps[$name] : null;
  222. }
  223. /**
  224. * Set Slim application name
  225. * @param string $name The name of this Slim application
  226. */
  227. public function setName($name)
  228. {
  229. $this->name = $name;
  230. static::$apps[$name] = $this;
  231. }
  232. /**
  233. * Get Slim application name
  234. * @return string|null
  235. */
  236. public function getName()
  237. {
  238. return $this->name;
  239. }
  240. /**
  241. * Get default application settings
  242. * @return array
  243. */
  244. public static function getDefaultSettings()
  245. {
  246. return array(
  247. // Application
  248. 'mode' => 'development',
  249. // Debugging
  250. 'debug' => true,
  251. // Logging
  252. 'log.writer' => null,
  253. 'log.level' => \Slim\Log::DEBUG,
  254. 'log.enabled' => true,
  255. // View
  256. 'templates.path' => './templates',
  257. 'view' => '\Slim\View',
  258. // Cookies
  259. 'cookies.encrypt' => false,
  260. 'cookies.lifetime' => '20 minutes',
  261. 'cookies.path' => '/',
  262. 'cookies.domain' => null,
  263. 'cookies.secure' => false,
  264. 'cookies.httponly' => false,
  265. // Encryption
  266. 'cookies.secret_key' => 'CHANGE_ME',
  267. 'cookies.cipher' => MCRYPT_RIJNDAEL_256,
  268. 'cookies.cipher_mode' => MCRYPT_MODE_CBC,
  269. // HTTP
  270. 'http.version' => '1.1',
  271. // Routing
  272. 'routes.case_sensitive' => true
  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. {
  296. $c = $this->container;
  297. if (is_array($name)) {
  298. if (true === $value) {
  299. $c['settings'] = array_merge_recursive($c['settings'], $name);
  300. } else {
  301. $c['settings'] = array_merge($c['settings'], $name);
  302. }
  303. } elseif (func_num_args() === 1) {
  304. return isset($c['settings'][$name]) ? $c['settings'][$name] : null;
  305. } else {
  306. $settings = $c['settings'];
  307. $settings[$name] = $value;
  308. $c['settings'] = $settings;
  309. }
  310. }
  311. /********************************************************************************
  312. * Application Modes
  313. *******************************************************************************/
  314. /**
  315. * Get application mode
  316. *
  317. * This method determines the application mode. It first inspects the $_ENV
  318. * superglobal for key `SLIM_MODE`. If that is not found, it queries
  319. * the `getenv` function. Else, it uses the application `mode` setting.
  320. *
  321. * @return string
  322. */
  323. public function getMode()
  324. {
  325. return $this->mode;
  326. }
  327. /**
  328. * Configure Slim for a given mode
  329. *
  330. * This method will immediately invoke the callable if
  331. * the specified mode matches the current application mode.
  332. * Otherwise, the callable is ignored. This should be called
  333. * only _after_ you initialize your Slim app.
  334. *
  335. * @param string $mode
  336. * @param mixed $callable
  337. * @return void
  338. */
  339. public function configureMode($mode, $callable)
  340. {
  341. if ($mode === $this->getMode() && is_callable($callable)) {
  342. call_user_func($callable);
  343. }
  344. }
  345. /********************************************************************************
  346. * Logging
  347. *******************************************************************************/
  348. /**
  349. * Get application log
  350. * @return \Slim\Log
  351. */
  352. public function getLog()
  353. {
  354. return $this->log;
  355. }
  356. /********************************************************************************
  357. * Routing
  358. *******************************************************************************/
  359. /**
  360. * Add GET|POST|PUT|PATCH|DELETE route
  361. *
  362. * Adds a new route to the router with associated callable. This
  363. * route will only be invoked when the HTTP request's method matches
  364. * this route's method.
  365. *
  366. * ARGUMENTS:
  367. *
  368. * First: string The URL pattern (REQUIRED)
  369. * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL)
  370. * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED)
  371. *
  372. * The first argument is required and must always be the
  373. * route pattern (ie. '/books/:id').
  374. *
  375. * The last argument is required and must always be the callable object
  376. * to be invoked when the route matches an HTTP request.
  377. *
  378. * You may also provide an unlimited number of in-between arguments;
  379. * each interior argument must be callable and will be invoked in the
  380. * order specified before the route's callable is invoked.
  381. *
  382. * USAGE:
  383. *
  384. * Slim::get('/foo'[, middleware, middleware, ...], callable);
  385. *
  386. * @param array (See notes above)
  387. * @return \Slim\Route
  388. */
  389. protected function mapRoute($args)
  390. {
  391. $pattern = array_shift($args);
  392. $callable = array_pop($args);
  393. $route = new \Slim\Route($pattern, $callable, $this->settings['routes.case_sensitive']);
  394. $this->router->map($route);
  395. if (count($args) > 0) {
  396. $route->setMiddleware($args);
  397. }
  398. return $route;
  399. }
  400. /**
  401. * Add generic route without associated HTTP method
  402. * @see mapRoute()
  403. * @return \Slim\Route
  404. */
  405. public function map()
  406. {
  407. $args = func_get_args();
  408. return $this->mapRoute($args);
  409. }
  410. /**
  411. * Add GET route
  412. * @see mapRoute()
  413. * @return \Slim\Route
  414. */
  415. public function get()
  416. {
  417. $args = func_get_args();
  418. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD);
  419. }
  420. /**
  421. * Add POST route
  422. * @see mapRoute()
  423. * @return \Slim\Route
  424. */
  425. public function post()
  426. {
  427. $args = func_get_args();
  428. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST);
  429. }
  430. /**
  431. * Add PUT route
  432. * @see mapRoute()
  433. * @return \Slim\Route
  434. */
  435. public function put()
  436. {
  437. $args = func_get_args();
  438. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT);
  439. }
  440. /**
  441. * Add PATCH route
  442. * @see mapRoute()
  443. * @return \Slim\Route
  444. */
  445. public function patch()
  446. {
  447. $args = func_get_args();
  448. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH);
  449. }
  450. /**
  451. * Add DELETE route
  452. * @see mapRoute()
  453. * @return \Slim\Route
  454. */
  455. public function delete()
  456. {
  457. $args = func_get_args();
  458. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE);
  459. }
  460. /**
  461. * Add OPTIONS route
  462. * @see mapRoute()
  463. * @return \Slim\Route
  464. */
  465. public function options()
  466. {
  467. $args = func_get_args();
  468. return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS);
  469. }
  470. /**
  471. * Route Groups
  472. *
  473. * This method accepts a route pattern and a callback all Route
  474. * declarations in the callback will be prepended by the group(s)
  475. * that it is in
  476. *
  477. * Accepts the same parameters as a standard route so:
  478. * (pattern, middleware1, middleware2, ..., $callback)
  479. */
  480. public function group()
  481. {
  482. $args = func_get_args();
  483. $pattern = array_shift($args);
  484. $callable = array_pop($args);
  485. $this->router->pushGroup($pattern, $args);
  486. if (is_callable($callable)) {
  487. call_user_func($callable);
  488. }
  489. $this->router->popGroup();
  490. }
  491. /*
  492. * Add route for any HTTP method
  493. * @see mapRoute()
  494. * @return \Slim\Route
  495. */
  496. public function any()
  497. {
  498. $args = func_get_args();
  499. return $this->mapRoute($args)->via("ANY");
  500. }
  501. /**
  502. * Not Found Handler
  503. *
  504. * This method defines or invokes the application-wide Not Found handler.
  505. * There are two contexts in which this method may be invoked:
  506. *
  507. * 1. When declaring the handler:
  508. *
  509. * If the $callable parameter is not null and is callable, this
  510. * method will register the callable to be invoked when no
  511. * routes match the current HTTP request. It WILL NOT invoke the callable.
  512. *
  513. * 2. When invoking the handler:
  514. *
  515. * If the $callable parameter is null, Slim assumes you want
  516. * to invoke an already-registered handler. If the handler has been
  517. * registered and is callable, it is invoked and sends a 404 HTTP Response
  518. * whose body is the output of the Not Found handler.
  519. *
  520. * @param mixed $callable Anything that returns true for is_callable()
  521. */
  522. public function notFound ($callable = null)
  523. {
  524. if (is_callable($callable)) {
  525. $this->notFound = $callable;
  526. } else {
  527. ob_start();
  528. if (is_callable($this->notFound)) {
  529. call_user_func($this->notFound);
  530. } else {
  531. call_user_func(array($this, 'defaultNotFound'));
  532. }
  533. $this->halt(404, ob_get_clean());
  534. }
  535. }
  536. /**
  537. * Error Handler
  538. *
  539. * This method defines or invokes the application-wide Error handler.
  540. * There are two contexts in which this method may be invoked:
  541. *
  542. * 1. When declaring the handler:
  543. *
  544. * If the $argument parameter is callable, this
  545. * method will register the callable to be invoked when an uncaught
  546. * Exception is detected, or when otherwise explicitly invoked.
  547. * The handler WILL NOT be invoked in this context.
  548. *
  549. * 2. When invoking the handler:
  550. *
  551. * If the $argument parameter is not callable, Slim assumes you want
  552. * to invoke an already-registered handler. If the handler has been
  553. * registered and is callable, it is invoked and passed the caught Exception
  554. * as its one and only argument. The error handler's output is captured
  555. * into an output buffer and sent as the body of a 500 HTTP Response.
  556. *
  557. * @param mixed $argument Callable|\Exception
  558. */
  559. public function error($argument = null)
  560. {
  561. if (is_callable($argument)) {
  562. //Register error handler
  563. $this->error = $argument;
  564. } else {
  565. //Invoke error handler
  566. $this->response->status(500);
  567. $this->response->body('');
  568. $this->response->write($this->callErrorHandler($argument));
  569. $this->stop();
  570. }
  571. }
  572. /**
  573. * Call error handler
  574. *
  575. * This will invoke the custom or default error handler
  576. * and RETURN its output.
  577. *
  578. * @param \Exception|null $argument
  579. * @return string
  580. */
  581. protected function callErrorHandler($argument = null)
  582. {
  583. ob_start();
  584. if (is_callable($this->error)) {
  585. call_user_func_array($this->error, array($argument));
  586. } else {
  587. call_user_func_array(array($this, 'defaultError'), array($argument));
  588. }
  589. return ob_get_clean();
  590. }
  591. /********************************************************************************
  592. * Application Accessors
  593. *******************************************************************************/
  594. /**
  595. * Get a reference to the Environment object
  596. * @return \Slim\Environment
  597. */
  598. public function environment()
  599. {
  600. return $this->environment;
  601. }
  602. /**
  603. * Get the Request object
  604. * @return \Slim\Http\Request
  605. */
  606. public function request()
  607. {
  608. return $this->request;
  609. }
  610. /**
  611. * Get the Response object
  612. * @return \Slim\Http\Response
  613. */
  614. public function response()
  615. {
  616. return $this->response;
  617. }
  618. /**
  619. * Get the Router object
  620. * @return \Slim\Router
  621. */
  622. public function router()
  623. {
  624. return $this->router;
  625. }
  626. /**
  627. * Get and/or set the View
  628. *
  629. * This method declares the View to be used by the Slim application.
  630. * If the argument is a string, Slim will instantiate a new object
  631. * of the same class. If the argument is an instance of View or a subclass
  632. * of View, Slim will use the argument as the View.
  633. *
  634. * If a View already exists and this method is called to create a
  635. * new View, data already set in the existing View will be
  636. * transferred to the new View.
  637. *
  638. * @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass
  639. * @return \Slim\View
  640. */
  641. public function view($viewClass = null)
  642. {
  643. if (!is_null($viewClass)) {
  644. $existingData = is_null($this->view) ? array() : $this->view->getData();
  645. if ($viewClass instanceOf \Slim\View) {
  646. $this->view = $viewClass;
  647. } else {
  648. $this->view = new $viewClass();
  649. }
  650. $this->view->appendData($existingData);
  651. $this->view->setTemplatesDirectory($this->config('templates.path'));
  652. }
  653. return $this->view;
  654. }
  655. /********************************************************************************
  656. * Rendering
  657. *******************************************************************************/
  658. /**
  659. * Render a template
  660. *
  661. * Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR
  662. * callable to render a template whose output is appended to the
  663. * current HTTP response body. How the template is rendered is
  664. * delegated to the current View.
  665. *
  666. * @param string $template The name of the template passed into the view's render() method
  667. * @param array $data Associative array of data made available to the view
  668. * @param int $status The HTTP response status code to use (optional)
  669. */
  670. public function render($template, $data = array(), $status = null)
  671. {
  672. if (!is_null($status)) {
  673. $this->response->status($status);
  674. }
  675. $this->view->appendData($data);
  676. $this->view->display($template);
  677. }
  678. /********************************************************************************
  679. * HTTP Caching
  680. *******************************************************************************/
  681. /**
  682. * Set Last-Modified HTTP Response Header
  683. *
  684. * Set the HTTP 'Last-Modified' header and stop if a conditional
  685. * GET request's `If-Modified-Since` header matches the last modified time
  686. * of the resource. The `time` argument is a UNIX timestamp integer value.
  687. * When the current request includes an 'If-Modified-Since' header that
  688. * matches the specified last modified time, the application will stop
  689. * and send a '304 Not Modified' response to the client.
  690. *
  691. * @param int $time The last modified UNIX timestamp
  692. * @throws \InvalidArgumentException If provided timestamp is not an integer
  693. */
  694. public function lastModified($time)
  695. {
  696. if (is_integer($time)) {
  697. $this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time));
  698. if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) {
  699. $this->halt(304);
  700. }
  701. } else {
  702. throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
  703. }
  704. }
  705. /**
  706. * Set ETag HTTP Response Header
  707. *
  708. * Set the etag header and stop if the conditional GET request matches.
  709. * The `value` argument is a unique identifier for the current resource.
  710. * The `type` argument indicates whether the etag should be used as a strong or
  711. * weak cache validator.
  712. *
  713. * When the current request includes an 'If-None-Match' header with
  714. * a matching etag, execution is immediately stopped. If the request
  715. * method is GET or HEAD, a '304 Not Modified' response is sent.
  716. *
  717. * @param string $value The etag value
  718. * @param string $type The type of etag to create; either "strong" or "weak"
  719. * @throws \InvalidArgumentException If provided type is invalid
  720. */
  721. public function etag($value, $type = 'strong')
  722. {
  723. //Ensure type is correct
  724. if (!in_array($type, array('strong', 'weak'))) {
  725. throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
  726. }
  727. //Set etag value
  728. $value = '"' . $value . '"';
  729. if ($type === 'weak') {
  730. $value = 'W/'.$value;
  731. }
  732. $this->response['ETag'] = $value;
  733. //Check conditional GET
  734. if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) {
  735. $etags = preg_split('@\s*,\s*@', $etagsHeader);
  736. if (in_array($value, $etags) || in_array('*', $etags)) {
  737. $this->halt(304);
  738. }
  739. }
  740. }
  741. /**
  742. * Set Expires HTTP response header
  743. *
  744. * The `Expires` header tells the HTTP client the time at which
  745. * the current resource should be considered stale. At that time the HTTP
  746. * client will send a conditional GET request to the server; the server
  747. * may return a 200 OK if the resource has changed, else a 304 Not Modified
  748. * if the resource has not changed. The `Expires` header should be used in
  749. * conjunction with the `etag()` or `lastModified()` methods above.
  750. *
  751. * @param string|int $time If string, a time to be parsed by `strtotime()`;
  752. * If int, a UNIX timestamp;
  753. */
  754. public function expires($time)
  755. {
  756. if (is_string($time)) {
  757. $time = strtotime($time);
  758. }
  759. $this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time));
  760. }
  761. /********************************************************************************
  762. * HTTP Cookies
  763. *******************************************************************************/
  764. /**
  765. * Set HTTP cookie to be sent with the HTTP response
  766. *
  767. * @param string $name The cookie name
  768. * @param string $value The cookie value
  769. * @param int|string $time The duration of the cookie;
  770. * If integer, should be UNIX timestamp;
  771. * If string, converted to UNIX timestamp with `strtotime`;
  772. * @param string $path The path on the server in which the cookie will be available on
  773. * @param string $domain The domain that the cookie is available to
  774. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  775. * HTTPS connection to/from the client
  776. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  777. */
  778. public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null)
  779. {
  780. $settings = array(
  781. 'value' => $value,
  782. 'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time,
  783. 'path' => is_null($path) ? $this->config('cookies.path') : $path,
  784. 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
  785. 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
  786. 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
  787. );
  788. $this->response->cookies->set($name, $settings);
  789. }
  790. /**
  791. * Get value of HTTP cookie from the current HTTP request
  792. *
  793. * Return the value of a cookie from the current HTTP request,
  794. * or return NULL if cookie does not exist. Cookies created during
  795. * the current request will not be available until the next request.
  796. *
  797. * @param string $name
  798. * @param bool $deleteIfInvalid
  799. * @return string|null
  800. */
  801. public function getCookie($name, $deleteIfInvalid = true)
  802. {
  803. // Get cookie value
  804. $value = $this->request->cookies->get($name);
  805. // Decode if encrypted
  806. if ($this->config('cookies.encrypt')) {
  807. $value = \Slim\Http\Util::decodeSecureCookie(
  808. $value,
  809. $this->config('cookies.secret_key'),
  810. $this->config('cookies.cipher'),
  811. $this->config('cookies.cipher_mode')
  812. );
  813. if ($value === false && $deleteIfInvalid) {
  814. $this->deleteCookie($name);
  815. }
  816. }
  817. return $value;
  818. }
  819. /**
  820. * DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`.
  821. *
  822. * Set encrypted HTTP cookie
  823. *
  824. * @param string $name The cookie name
  825. * @param mixed $value The cookie value
  826. * @param mixed $expires The duration of the cookie;
  827. * If integer, should be UNIX timestamp;
  828. * If string, converted to UNIX timestamp with `strtotime`;
  829. * @param string $path The path on the server in which the cookie will be available on
  830. * @param string $domain The domain that the cookie is available to
  831. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  832. * HTTPS connection from the client
  833. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  834. */
  835. public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false)
  836. {
  837. $this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly);
  838. }
  839. /**
  840. * DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`.
  841. *
  842. * Get value of encrypted HTTP cookie
  843. *
  844. * Return the value of an encrypted cookie from the current HTTP request,
  845. * or return NULL if cookie does not exist. Encrypted cookies created during
  846. * the current request will not be available until the next request.
  847. *
  848. * @param string $name
  849. * @param bool $deleteIfInvalid
  850. * @return string|bool
  851. */
  852. public function getEncryptedCookie($name, $deleteIfInvalid = true)
  853. {
  854. return $this->getCookie($name, $deleteIfInvalid);
  855. }
  856. /**
  857. * Delete HTTP cookie (encrypted or unencrypted)
  858. *
  859. * Remove a Cookie from the client. This method will overwrite an existing Cookie
  860. * with a new, empty, auto-expiring Cookie. This method's arguments must match
  861. * the original Cookie's respective arguments for the original Cookie to be
  862. * removed. If any of this method's arguments are omitted or set to NULL, the
  863. * default Cookie setting values (set during Slim::init) will be used instead.
  864. *
  865. * @param string $name The cookie name
  866. * @param string $path The path on the server in which the cookie will be available on
  867. * @param string $domain The domain that the cookie is available to
  868. * @param bool $secure Indicates that the cookie should only be transmitted over a secure
  869. * HTTPS connection from the client
  870. * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
  871. */
  872. public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null)
  873. {
  874. $settings = array(
  875. 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
  876. 'path' => is_null($path) ? $this->config('cookies.path') : $path,
  877. 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
  878. 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
  879. );
  880. $this->response->cookies->remove($name, $settings);
  881. }
  882. /********************************************************************************
  883. * Helper Methods
  884. *******************************************************************************/
  885. /**
  886. * Get the absolute path to this Slim application's root directory
  887. *
  888. * This method returns the absolute path to the Slim application's
  889. * directory. If the Slim application is installed in a public-accessible
  890. * sub-directory, the sub-directory path will be included. This method
  891. * will always return an absolute path WITH a trailing slash.
  892. *
  893. * @return string
  894. */
  895. public function root()
  896. {
  897. return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
  898. }
  899. /**
  900. * Clean current output buffer
  901. */
  902. protected function cleanBuffer()
  903. {
  904. if (ob_get_level() !== 0) {
  905. ob_clean();
  906. }
  907. }
  908. /**
  909. * Stop
  910. *
  911. * The thrown exception will be caught in application's `call()` method
  912. * and the response will be sent as is to the HTTP client.
  913. *
  914. * @throws \Slim\Exception\Stop
  915. */
  916. public function stop()
  917. {
  918. throw new \Slim\Exception\Stop();
  919. }
  920. /**
  921. * Halt
  922. *
  923. * Stop the application and immediately send the response with a
  924. * specific status and body to the HTTP client. This may send any
  925. * type of response: info, success, redirect, client error, or server error.
  926. * If you need to render a template AND customize the response status,
  927. * use the application's `render()` method instead.
  928. *
  929. * @param int $status The HTTP response status
  930. * @param string $message The HTTP response body
  931. */
  932. public function halt($status, $message = '')
  933. {
  934. $this->cleanBuffer();
  935. $this->response->status($status);
  936. $this->response->body($message);
  937. $this->stop();
  938. }
  939. /**
  940. * Pass
  941. *
  942. * The thrown exception is caught in the application's `call()` method causing
  943. * the router's current iteration to stop and continue to the subsequent route if available.
  944. * If no subsequent matching routes are found, a 404 response will be sent to the client.
  945. *
  946. * @throws \Slim\Exception\Pass
  947. */
  948. public function pass()
  949. {
  950. $this->cleanBuffer();
  951. throw new \Slim\Exception\Pass();
  952. }
  953. /**
  954. * Set the HTTP response Content-Type
  955. * @param string $type The Content-Type for the Response (ie. text/html)
  956. */
  957. public function contentType($type)
  958. {
  959. $this->response->headers->set('Content-Type', $type);
  960. }
  961. /**
  962. * Set the HTTP response status code
  963. * @param int $code The HTTP response status code
  964. */
  965. public function status($code)
  966. {
  967. $this->response->setStatus($code);
  968. }
  969. /**
  970. * Get the URL for a named route
  971. * @param string $name The route name
  972. * @param array $params Associative array of URL parameters and replacement values
  973. * @throws \RuntimeException If named route does not exist
  974. * @return string
  975. */
  976. public function urlFor($name, $params = array())
  977. {
  978. return $this->request->getRootUri() . $this->router->urlFor($name, $params);
  979. }
  980. /**
  981. * Redirect
  982. *
  983. * This method immediately redirects to a new URL. By default,
  984. * this issues a 302 Found response; this is considered the default
  985. * generic redirect response. You may also specify another valid
  986. * 3xx status code if you want. This method will automatically set the
  987. * HTTP Location header for you using the URL parameter.
  988. *
  989. * @param string $url The destination URL
  990. * @param int $status The HTTP redirect status code (optional)
  991. */
  992. public function redirect($url, $status = 302)
  993. {
  994. $this->response->redirect($url, $status);
  995. $this->halt($status);
  996. }
  997. /********************************************************************************
  998. * Flash Messages
  999. *******************************************************************************/
  1000. /**
  1001. * Set flash message for subsequent request
  1002. * @param string $key
  1003. * @param mixed $value
  1004. */
  1005. public function flash($key, $value)
  1006. {
  1007. if (isset($this->environment['slim.flash'])) {
  1008. $this->environment['slim.flash']->set($key, $value);
  1009. }
  1010. }
  1011. /**
  1012. * Set flash message for current request
  1013. * @param string $key
  1014. * @param mixed $value
  1015. */
  1016. public function flashNow($key, $value)
  1017. {
  1018. if (isset($this->environment['slim.flash'])) {
  1019. $this->environment['slim.flash']->now($key, $value);
  1020. }
  1021. }
  1022. /**
  1023. * Keep flash messages from previous request for subsequent request
  1024. */
  1025. public function flashKeep()
  1026. {
  1027. if (isset($this->environment['slim.flash'])) {
  1028. $this->environment['slim.flash']->keep();
  1029. }
  1030. }
  1031. /********************************************************************************
  1032. * Hooks
  1033. *******************************************************************************/
  1034. /**
  1035. * Assign hook
  1036. * @param string $name The hook name
  1037. * @param mixed $callable A callable object
  1038. * @param int $priority The hook priority; 0 = high, 10 = low
  1039. */
  1040. public function hook($name, $callable, $priority = 10)
  1041. {
  1042. if (!isset($this->hooks[$name])) {
  1043. $this->hooks[$name] = array(array());
  1044. }
  1045. if (is_callable($callable)) {
  1046. $this->hooks[$name][(int) $priority][] = $callable;
  1047. }
  1048. }
  1049. /**
  1050. * Invoke hook
  1051. * @param string $name The hook name
  1052. * @param mixed $hookArg (Optional) Argument for hooked functions
  1053. */
  1054. public function applyHook($name, $hookArg = null)
  1055. {
  1056. if (!isset($this->hooks[$name])) {
  1057. $this->hooks[$name] = array(array());
  1058. }
  1059. if (!empty($this->hooks[$name])) {
  1060. // Sort by priority, low to high, if there's more than one priority
  1061. if (count($this->hooks[$name]) > 1) {
  1062. ksort($this->hooks[$name]);
  1063. }
  1064. foreach ($this->hooks[$name] as $priority) {
  1065. if (!empty($priority)) {
  1066. foreach ($priority as $callable) {
  1067. call_user_func($callable, $hookArg);
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. /**
  1074. * Get hook listeners
  1075. *
  1076. * Return an array of registered hooks. If `$name` is a valid
  1077. * hook name, only the listeners attached to that hook are returned.
  1078. * Else, all listeners are returned as an associative array whose
  1079. * keys are hook names and whose values are arrays of listeners.
  1080. *
  1081. * @param string $name A hook name (Optional)
  1082. * @return array|null
  1083. */
  1084. public function getHooks($name = null)
  1085. {
  1086. if (!is_null($name)) {
  1087. return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null;
  1088. } else {
  1089. return $this->hooks;
  1090. }
  1091. }
  1092. /**
  1093. * Clear hook listeners
  1094. *
  1095. * Clear all listeners for all hooks. If `$name` is
  1096. * a valid hook name, only the listeners attached
  1097. * to that hook will be cleared.
  1098. *
  1099. * @param string $name A hook name (Optional)
  1100. */
  1101. public function clearHooks($name = null)
  1102. {
  1103. if (!is_null($name) && isset($this->hooks[(string) $name])) {
  1104. $this->hooks[(string) $name] = array(array());
  1105. } else {
  1106. foreach ($this->hooks as $key => $value) {
  1107. $this->hooks[$key] = array(array());
  1108. }
  1109. }
  1110. }
  1111. /********************************************************************************
  1112. * Middleware
  1113. *******************************************************************************/
  1114. /**
  1115. * Add middleware
  1116. *
  1117. * This method prepends new middleware to the application middleware stack.
  1118. * The argument must be an instance that subclasses Slim_Middleware.
  1119. *
  1120. * @param \Slim\Middleware
  1121. */
  1122. public function add(\Slim\Middleware $newMiddleware)
  1123. {
  1124. if(in_array($newMiddleware, $this->middleware)) {
  1125. $middleware_class = get_class($newMiddleware);
  1126. throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middleware instance ({$middleware_class}) twice.");
  1127. }
  1128. $newMiddleware->setApplication($this);
  1129. $newMiddleware->setNextMiddleware($this->middleware[0]);
  1130. array_unshift($this->middleware, $newMiddleware);
  1131. }
  1132. /********************************************************************************
  1133. * Runner
  1134. *******************************************************************************/
  1135. /**
  1136. * Run
  1137. *
  1138. * This method invokes the middleware stack, including the core Slim application;
  1139. * the result is an array of HTTP status, header, and body. These three items
  1140. * are returned to the HTTP client.
  1141. */
  1142. public function run()
  1143. {
  1144. set_error_handler(array('\Slim\Slim', 'handleErrors'));
  1145. //Apply final outer middleware layers
  1146. if ($this->config('debug')) {
  1147. //Apply pretty exceptions only in debug to avoid accidental information leakage in production
  1148. $this->add(new \Slim\Middleware\PrettyExceptions());
  1149. }
  1150. //Invoke middleware and application stack
  1151. $this->middleware[0]->call();
  1152. //Fetch status, header, and body
  1153. list($status, $headers, $body) = $this->response->finalize();
  1154. // Serialize cookies (with optional encryption)
  1155. \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings);
  1156. //Send headers
  1157. if (headers_sent() === false) {
  1158. //Send status
  1159. if (strpos(PHP_SAPI, 'cgi') === 0) {
  1160. header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status)));
  1161. } else {
  1162. header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status)));
  1163. }
  1164. //Send headers
  1165. foreach ($headers as $name => $value) {
  1166. $hValues = explode("\n", $value);
  1167. foreach ($hValues as $hVal) {
  1168. header("$name: $hVal", false);
  1169. }
  1170. }
  1171. }
  1172. //Send body, but only if it isn't a HEAD request
  1173. if (!$this->request->isHead()) {
  1174. echo $body;
  1175. }
  1176. $this->applyHook('slim.after');
  1177. restore_error_handler();
  1178. }
  1179. /**
  1180. * Call
  1181. *
  1182. * This method finds and iterates all route objects that match the current request URI.
  1183. */
  1184. public function call()
  1185. {
  1186. try {
  1187. if (isset($this->environment['slim.flash'])) {
  1188. $this->view()->setData('flash', $this->environment['slim.flash']);
  1189. }
  1190. $this->applyHook('slim.before');
  1191. ob_start();
  1192. $this->applyHook('slim.before.router');
  1193. $dispatched = false;
  1194. $matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri());
  1195. foreach ($matchedRoutes as $route) {
  1196. try {
  1197. $this->applyHook('slim.before.dispatch');
  1198. $dispatched = $route->dispatch();
  1199. $this->applyHook('slim.after.dispatch');
  1200. if ($dispatched) {
  1201. break;
  1202. }
  1203. } catch (\Slim\Exception\Pass $e) {
  1204. continue;
  1205. }
  1206. }
  1207. if (!$dispatched) {
  1208. $this->notFound();
  1209. }
  1210. $this->applyHook('slim.after.router');
  1211. $this->stop();
  1212. } catch (\Slim\Exception\Stop $e) {
  1213. $this->response()->write(ob_get_clean());
  1214. } catch (\Exception $e) {
  1215. if ($this->config('debug')) {
  1216. throw $e;
  1217. } else {
  1218. try {
  1219. $this->error($e);
  1220. } catch (\Slim\Exception\Stop $e) {
  1221. // Do nothing
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /********************************************************************************
  1227. * Error Handling and Debugging
  1228. *******************************************************************************/
  1229. /**
  1230. * Convert errors into ErrorException objects
  1231. *
  1232. * This method catches PHP errors and converts them into \ErrorException objects;
  1233. * these \ErrorException objects are then thrown and caught by Slim's
  1234. * built-in or custom error handlers.
  1235. *
  1236. * @param int $errno The numeric type of the Error
  1237. * @param string $errstr The error message
  1238. * @param string $errfile The absolute path to the affected file
  1239. * @param int $errline The line number of the error in the affected file
  1240. * @return bool
  1241. * @throws \ErrorException
  1242. */
  1243. public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '')
  1244. {
  1245. if (!($errno & error_reporting())) {
  1246. return;
  1247. }
  1248. throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
  1249. }
  1250. /**
  1251. * Generate diagnostic template markup
  1252. *
  1253. * This method accepts a title and body content to generate an HTML document layout.
  1254. *
  1255. * @param string $title The title of the HTML template
  1256. * @param string $body The body content of the HTML template
  1257. * @return string
  1258. */
  1259. protected static function generateTemplateMarkup($title, $body)
  1260. {
  1261. return sprintf("<html><head><title>%s</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><h1>%s</h1>%s</body></html>", $title, $title, $body);
  1262. }
  1263. /**
  1264. * Default Not Found handler
  1265. */
  1266. protected function defaultNotFound()
  1267. {
  1268. echo static::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>');
  1269. }
  1270. /**
  1271. * Default Error handler
  1272. */
  1273. protected function defaultError($e)
  1274. {
  1275. $this->getLog()->error($e);
  1276. echo self::generateTemplateMarkup('Error', '<p>A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.</p>');
  1277. }
  1278. }