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