PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Slim/Slim.php

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