PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Slim/Slim.php

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