Blame view

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