paulgoughbooks_old
This repository has no backups
This repository's network speed is throttled to 100KB/sec
Upgrade your account to fix these warnings, or use backups.vc for automated backups
@ 2
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 |
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2019 British Columbia Institute of Technology * Copyright (c) 2019-2020 CodeIgniter Foundation * * 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. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright 2019-2020 CodeIgniter Foundation * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 4.0.0 * @filesource */ namespace CodeIgniter; use Closure; use CodeIgniter\Debug\Timer; use CodeIgniter\Events\Events; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\Request; use CodeIgniter\HTTP\Response; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\URI; use CodeIgniter\Router\Exceptions\RedirectException; use CodeIgniter\Router\RouteCollectionInterface; use Config\Cache; use Config\Services; use Exception; /** * This class is the core of the framework, and will analyse the * request, route it to a controller, and send back the response. * Of course, there are variations to that flow, but this is the brains. */ class CodeIgniter { /** * The current version of CodeIgniter Framework */ const CI_VERSION = '4.0.4'; /** * App startup time. * * @var mixed */ protected $startTime; /** * Total app execution time * * @var float */ protected $totalTime; /** * Main application configuration * * @var \Config\App */ protected $config; /** * Timer instance. * * @var Timer */ protected $benchmark; /** * Current request. * * @var HTTP\Request|HTTP\IncomingRequest|CLIRequest */ protected $request; /** * Current response. * * @var HTTP\ResponseInterface */ protected $response; /** * Router to use. * * @var Router\Router */ protected $router; /** * Controller to use. * * @var string|\Closure */ protected $controller; /** * Controller method to invoke. * * @var string */ protected $method; /** * Output handler to use. * * @var string */ protected $output; /** * Cache expiration time * * @var integer */ protected static $cacheTTL = 0; /** * Request path to use. * * @var string */ protected $path; /** * Should the Response instance "pretend" * to keep from setting headers/cookies/etc * * @var boolean */ protected $useSafeOutput = false; //-------------------------------------------------------------------- /** * Constructor. * * @param type $config */ public function __construct($config) { $this->startTime = microtime(true); $this->config = $config; } //-------------------------------------------------------------------- /** * Handles some basic app and environment setup. */ public function initialize() { // Set default locale on the server locale_set_default($this->config->defaultLocale ?? 'en'); // Set default timezone on the server date_default_timezone_set($this->config->appTimezone ?? 'UTC'); // Define environment variables $this->detectEnvironment(); $this->bootstrapEnvironment(); // Setup Exception Handling Services::exceptions() ->initialize(); $this->initializeKint(); if (! CI_DEBUG) { // @codeCoverageIgnoreStart \Kint::$enabled_mode = false; // @codeCoverageIgnoreEnd } } //-------------------------------------------------------------------- /** * Initializes Kint */ protected function initializeKint() { // If we have KINT_DIR it means it's already loaded via composer if (! defined('KINT_DIR')) { spl_autoload_register(function ($class) { $class = explode('\\', $class); if ('Kint' !== array_shift($class)) { return; } $file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php'; file_exists($file) && require_once $file; }); require_once SYSTEMPATH . 'ThirdParty/Kint/init.php'; } /** * Config\Kint */ $config = config('Config\Kint'); \Kint::$max_depth = $config->maxDepth; \Kint::$display_called_from = $config->displayCalledFrom; \Kint::$expanded = $config->expanded; if (! empty($config->plugins) && is_array($config->plugins)) { \Kint::$plugins = $config->plugins; } \Kint\Renderer\RichRenderer::$theme = $config->richTheme; \Kint\Renderer\RichRenderer::$folder = $config->richFolder; \Kint\Renderer\RichRenderer::$sort = $config->richSort; if (! empty($config->richObjectPlugins) && is_array($config->richObjectPlugins)) { \Kint\Renderer\RichRenderer::$object_plugins = $config->richObjectPlugins; } if (! empty($config->richTabPlugins) && is_array($config->richTabPlugins)) { \Kint\Renderer\RichRenderer::$tab_plugins = $config->richTabPlugins; } \Kint\Renderer\CliRenderer::$cli_colors = $config->cliColors; \Kint\Renderer\CliRenderer::$force_utf8 = $config->cliForceUTF8; \Kint\Renderer\CliRenderer::$detect_width = $config->cliDetectWidth; \Kint\Renderer\CliRenderer::$min_terminal_width = $config->cliMinWidth; } //-------------------------------------------------------------------- /** * Launch the application! * * This is "the loop" if you will. The main entry point into the script * that gets the required class instances, fires off the filters, * tries to route the response, loads the controller and generally * makes all of the pieces work together. * * @param \CodeIgniter\Router\RouteCollectionInterface $routes * @param boolean $returnResponse * * @return boolean|\CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed * @throws \CodeIgniter\Router\Exceptions\RedirectException * @throws \Exception */ public function run(RouteCollectionInterface $routes = null, bool $returnResponse = false) { $this->startBenchmark(); $this->getRequestObject(); $this->getResponseObject(); $this->forceSecureAccess(); $this->spoofRequestMethod(); Events::trigger('pre_system'); // Check for a cached page. Execution will stop // if the page has been cached. $cacheConfig = new Cache(); $response = $this->displayCache($cacheConfig); if ($response instanceof ResponseInterface) { if ($returnResponse) { return $response; } $this->response->pretend($this->useSafeOutput)->send(); $this->callExit(EXIT_SUCCESS); } try { return $this->handleRequest($routes, $cacheConfig, $returnResponse); } catch (RedirectException $e) { $logger = Services::logger(); $logger->info('REDIRECTED ROUTE at ' . $e->getMessage()); // If the route is a 'redirect' route, it throws // the exception with the $to as the message $this->response->redirect(base_url($e->getMessage()), 'auto', $e->getCode()); $this->sendResponse(); $this->callExit(EXIT_SUCCESS); } catch (PageNotFoundException $e) { $this->display404errors($e); } } //-------------------------------------------------------------------- /** * Set our Response instance to "pretend" mode so that things like * cookies and headers are not actually sent, allowing PHP 7.2+ to * not complain when ini_set() function is used. * * @param boolean $safe * * @return $this */ public function useSafeOutput(bool $safe = true) { $this->useSafeOutput = $safe; return $this; } //-------------------------------------------------------------------- /** * Handles the main request logic and fires the controller. * * @param \CodeIgniter\Router\RouteCollectionInterface $routes * @param $cacheConfig * @param boolean $returnResponse * * @return \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed * @throws \CodeIgniter\Router\Exceptions\RedirectException */ protected function handleRequest(RouteCollectionInterface $routes = null, $cacheConfig, bool $returnResponse = false) { $routeFilter = $this->tryToRouteIt($routes); // Run "before" filters $filters = Services::filters(); // If any filters were specified within the routes file, // we need to ensure it's active for the current request if (! is_null($routeFilter)) { $filters->enableFilter($routeFilter, 'before'); $filters->enableFilter($routeFilter, 'after'); } $uri = $this->request instanceof CLIRequest ? $this->request->getPath() : $this->request->uri->getPath(); // Never run filters when running through Spark cli if (! defined('SPARKED')) { $possibleRedirect = $filters->run($uri, 'before'); if ($possibleRedirect instanceof RedirectResponse) { return $possibleRedirect->send(); } // If a Response instance is returned, the Response will be sent back to the client and script execution will stop if ($possibleRedirect instanceof ResponseInterface) { return $possibleRedirect->send(); } } $returned = $this->startController(); // Closure controller has run in startController(). if (! is_callable($this->controller)) { $controller = $this->createController(); // Is there a "post_controller_constructor" event? Events::trigger('post_controller_constructor'); $returned = $this->runController($controller); } else { $this->benchmark->stop('controller_constructor'); $this->benchmark->stop('controller'); } // If $returned is a string, then the controller output something, // probably a view, instead of echoing it directly. Send it along // so it can be used with the output. $this->gatherOutput($cacheConfig, $returned); // Never run filters when running through Spark cli if (! defined('SPARKED')) { $filters->setResponse($this->response); // Run "after" filters $response = $filters->run($uri, 'after'); } else { $response = $this->response; // Set response code for CLI command failures if (is_numeric($returned) || $returned === false) { $response->setStatusCode(400); } } if ($response instanceof Response) { $this->response = $response; } // Save our current URI as the previous URI in the session // for safer, more accurate use with `previous_url()` helper function. $this->storePreviousURL((string)current_url(true)); unset($uri); if (! $returnResponse) { $this->sendResponse(); } //-------------------------------------------------------------------- // Is there a post-system event? //-------------------------------------------------------------------- Events::trigger('post_system'); return $this->response; } //-------------------------------------------------------------------- /** * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production */ protected function detectEnvironment() { // Make sure ENVIRONMENT isn't already set by other means. if (! defined('ENVIRONMENT')) { // running under Continuous Integration server? if (getenv('CI') !== false) { define('ENVIRONMENT', 'testing'); } else { define('ENVIRONMENT', $_SERVER['CI_ENVIRONMENT'] ?? 'production'); } } } //-------------------------------------------------------------------- /** * Load any custom boot files based upon the current environment. * * If no boot file exists, we shouldn't continue because something * is wrong. At the very least, they should have error reporting setup. */ protected function bootstrapEnvironment() { if (is_file(APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php')) { require_once APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php'; } else { // @codeCoverageIgnoreStart header('HTTP/1.1 503 Service Unavailable.', true, 503); echo 'The application environment is not set correctly.'; exit(1); // EXIT_ERROR // @codeCoverageIgnoreEnd } } //-------------------------------------------------------------------- /** * Start the Benchmark * * The timer is used to display total script execution both in the * debug toolbar, and potentially on the displayed page. */ protected function startBenchmark() { $this->startTime = microtime(true); $this->benchmark = Services::timer(); $this->benchmark->start('total_execution', $this->startTime); $this->benchmark->start('bootstrap'); } //-------------------------------------------------------------------- /** * Sets a Request object to be used for this request. * Used when running certain tests. * * @param \CodeIgniter\HTTP\Request $request * * @return \CodeIgniter\CodeIgniter */ public function setRequest(Request $request) { $this->request = $request; return $this; } //-------------------------------------------------------------------- /** * Get our Request object, (either IncomingRequest or CLIRequest) * and set the server protocol based on the information provided * by the server. */ protected function getRequestObject() { if ($this->request instanceof Request) { return; } if (is_cli() && ENVIRONMENT !== 'testing') { // @codeCoverageIgnoreStart $this->request = Services::clirequest($this->config); // @codeCoverageIgnoreEnd } else { $this->request = Services::request($this->config); // guess at protocol if needed $this->request->setProtocolVersion($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'); } } //-------------------------------------------------------------------- /** * Get our Response object, and set some default values, including * the HTTP protocol version and a default successful response. */ protected function getResponseObject() { $this->response = Services::response($this->config); if (! is_cli() || ENVIRONMENT === 'testing') { $this->response->setProtocolVersion($this->request->getProtocolVersion()); } // Assume success until proven otherwise. $this->response->setStatusCode(200); } //-------------------------------------------------------------------- /** * Force Secure Site Access? If the config value 'forceGlobalSecureRequests' * is true, will enforce that all requests to this site are made through * HTTPS. Will redirect the user to the current page with HTTPS, as well * as set the HTTP Strict Transport Security header for those browsers * that support it. * * @param integer $duration How long the Strict Transport Security * should be enforced for this URL. */ protected function forceSecureAccess($duration = 31536000) { if ($this->config->forceGlobalSecureRequests !== true) { return; } force_https($duration, $this->request, $this->response); } //-------------------------------------------------------------------- /** * Determines if a response has been cached for the given URI. * * @param \Config\Cache $config * * @throws \Exception * * @return boolean|\CodeIgniter\HTTP\ResponseInterface */ public function displayCache($config) { if ($cachedResponse = cache()->get($this->generateCacheName($config))) { $cachedResponse = unserialize($cachedResponse); if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) { throw new Exception('Error unserializing page cache'); } $headers = $cachedResponse['headers']; $output = $cachedResponse['output']; // Clear all default headers foreach ($this->response->getHeaders() as $key => $val) { $this->response->removeHeader($key); } // Set cached headers foreach ($headers as $name => $value) { $this->response->setHeader($name, $value); } $output = $this->displayPerformanceMetrics($output); $this->response->setBody($output); return $this->response; } return false; } //-------------------------------------------------------------------- /** * Tells the app that the final output should be cached. * * @param integer $time * * @return void */ public static function cache(int $time) { static::$cacheTTL = $time; } //-------------------------------------------------------------------- /** * Caches the full response from the current request. Used for * full-page caching for very high performance. * * @param \Config\Cache $config * * @return mixed */ public function cachePage(Cache $config) { $headers = []; foreach ($this->response->getHeaders() as $header) { $headers[$header->getName()] = $header->getValueLine(); } return cache()->save( $this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL ); } //-------------------------------------------------------------------- /** * Returns an array with our basic performance stats collected. * * @return array */ public function getPerformanceStats(): array { return [ 'startTime' => $this->startTime, 'totalTime' => $this->totalTime, ]; } //-------------------------------------------------------------------- /** * Generates the cache name to use for our full-page caching. * * @param $config * * @return string */ protected function generateCacheName($config): string { if (get_class($this->request) === CLIRequest::class) { return md5($this->request->getPath()); } $uri = $this->request->uri; if ($config->cacheQueryString) { $name = URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery() ); } else { $name = URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath() ); } return md5($name); } //-------------------------------------------------------------------- /** * Replaces the memory_usage and elapsed_time tags. * * @param string $output * * @return string */ public function displayPerformanceMetrics(string $output): string { $this->totalTime = $this->benchmark->getElapsedTime('total_execution'); return str_replace('{elapsed_time}', $this->totalTime, $output); } //-------------------------------------------------------------------- /** * Try to Route It - As it sounds like, works with the router to * match a route against the current URI. If the route is a * "redirect route", will also handle the redirect. * * @param RouteCollectionInterface $routes An collection interface to use in place * of the config file. * * @return string * @throws \CodeIgniter\Router\Exceptions\RedirectException */ protected function tryToRouteIt(RouteCollectionInterface $routes = null) { if (empty($routes) || ! $routes instanceof RouteCollectionInterface) { require APPPATH . 'Config/Routes.php'; } // $routes is defined in Config/Routes.php $this->router = Services::router($routes, $this->request); $path = $this->determinePath(); $this->benchmark->stop('bootstrap'); $this->benchmark->start('routing'); ob_start(); $this->controller = $this->router->handle($path); $this->method = $this->router->methodName(); // If a {locale} segment was matched in the final route, // then we need to set the correct locale on our Request. if ($this->router->hasLocale()) { $this->request->setLocale($this->router->getLocale()); } $this->benchmark->stop('routing'); return $this->router->getFilter(); } //-------------------------------------------------------------------- /** * Determines the path to use for us to try to route to, based * on user input (setPath), or the CLI/IncomingRequest path. */ protected function determinePath() { if (! empty($this->path)) { return $this->path; } return (is_cli() && ! (ENVIRONMENT === 'testing')) ? $this->request->getPath() : $this->request->uri->getPath(); } //-------------------------------------------------------------------- /** * Allows the request path to be set from outside the class, * instead of relying on CLIRequest or IncomingRequest for the path. * * This is primarily used by the Console. * * @param string $path * * @return $this */ public function setPath(string $path) { $this->path = $path; return $this; } //-------------------------------------------------------------------- /** * Now that everything has been setup, this method attempts to run the * controller method and make the script go. If it's not able to, will * show the appropriate Page Not Found error. */ protected function startController() { $this->benchmark->start('controller'); $this->benchmark->start('controller_constructor'); // Is it routed to a Closure? if (is_object($this->controller) && (get_class($this->controller) === 'Closure')) { $controller = $this->controller; return $controller(...$this->router->params()); } // No controller specified - we don't know what to do now. if (empty($this->controller)) { throw PageNotFoundException::forEmptyController(); } // Try to autoload the class if (! class_exists($this->controller, true) || $this->method[0] === '_') { throw PageNotFoundException::forControllerNotFound($this->controller, $this->method); } else if (! method_exists($this->controller, '_remap') && ! is_callable([$this->controller, $this->method], false) ) { throw PageNotFoundException::forMethodNotFound($this->method); } } //-------------------------------------------------------------------- /** * Instantiates the controller class. * * @return mixed */ protected function createController() { $class = new $this->controller(); $class->initController($this->request, $this->response, Services::logger()); $this->benchmark->stop('controller_constructor'); return $class; } //-------------------------------------------------------------------- /** * Runs the controller, allowing for _remap methods to function. * * @param mixed $class * * @return mixed */ protected function runController($class) { // If this is a console request then use the input segments as parameters $params = defined('SPARKED') ? $this->request->getSegments() : $this->router->params(); if (method_exists($class, '_remap')) { $output = $class->_remap($this->method, ...$params); } else { $output = $class->{$this->method}(...$params); } $this->benchmark->stop('controller'); return $output; } //-------------------------------------------------------------------- /** * Displays a 404 Page Not Found error. If set, will try to * call the 404Override controller/method that was set in routing config. * * @param PageNotFoundException $e */ protected function display404errors(PageNotFoundException $e) { // Is there a 404 Override available? if ($override = $this->router->get404Override()) { if ($override instanceof Closure) { echo $override($e->getMessage()); } else if (is_array($override)) { $this->benchmark->start('controller'); $this->benchmark->start('controller_constructor'); $this->controller = $override[0]; $this->method = $override[1]; unset($override); $controller = $this->createController(); $this->runController($controller); } $cacheConfig = new Cache(); $this->gatherOutput($cacheConfig); $this->sendResponse(); return; } // Display 404 Errors $this->response->setStatusCode($e->getCode()); if (ENVIRONMENT !== 'testing') { // @codeCoverageIgnoreStart if (ob_get_level() > 0) { ob_end_flush(); } // @codeCoverageIgnoreEnd } else { // When testing, one is for phpunit, another is for test case. if (ob_get_level() > 2) { ob_end_flush(); } } throw PageNotFoundException::forPageNotFound(ENVIRONMENT !== 'production' || is_cli() ? $e->getMessage() : ''); } //-------------------------------------------------------------------- /** * Gathers the script output from the buffer, replaces some execution * time tag in the output and displays the debug toolbar, if required. * * @param null $cacheConfig * @param null $returned */ protected function gatherOutput($cacheConfig = null, $returned = null) { $this->output = ob_get_contents(); // If buffering is not null. // Clean (erase) the output buffer and turn off output buffering if (ob_get_length()) { ob_end_clean(); } if ($returned instanceof DownloadResponse) { $this->response = $returned; return; } // If the controller returned a response object, // we need to grab the body from it so it can // be added to anything else that might have been // echoed already. // We also need to save the instance locally // so that any status code changes, etc, take place. if ($returned instanceof Response) { $this->response = $returned; $returned = $returned->getBody(); } if (is_string($returned)) { $this->output .= $returned; } // Cache it without the performance metrics replaced // so that we can have live speed updates along the way. if (static::$cacheTTL > 0) { $this->cachePage($cacheConfig); } $this->output = $this->displayPerformanceMetrics($this->output); $this->response->setBody($this->output); } //-------------------------------------------------------------------- /** * If we have a session object to use, store the current URI * as the previous URI. This is called just prior to sending the * response to the client, and will make it available next request. * * This helps provider safer, more reliable previous_url() detection. * * @param \CodeIgniter\HTTP\URI $uri */ public function storePreviousURL($uri) { // Ignore CLI requests if (is_cli()) { return; } // Ignore AJAX requests if (method_exists($this->request, 'isAJAX') && $this->request->isAJAX()) { return; } // This is mainly needed during testing... if (is_string($uri)) { $uri = new URI($uri); } if (isset($_SESSION)) { $_SESSION['_ci_previous_url'] = (string) $uri; } } //-------------------------------------------------------------------- /** * Modifies the Request Object to use a different method if a POST * variable called _method is found. */ public function spoofRequestMethod() { // Only works with POSTED forms if ($this->request->getMethod() !== 'post') { return; } $method = $this->request->getPost('_method'); if (empty($method)) { return; } $this->request = $this->request->setMethod($method); } /** * Sends the output of this request back to the client. * This is what they've been waiting for! */ protected function sendResponse() { $this->response->pretend($this->useSafeOutput)->send(); } //-------------------------------------------------------------------- /** * Exits the application, setting the exit code for CLI-based applications * that might be watching. * * Made into a separate method so that it can be mocked during testing * without actually stopping script execution. * * @param $code */ protected function callExit($code) { // @codeCoverageIgnoreStart exit($code); // @codeCoverageIgnoreEnd } //-------------------------------------------------------------------- } |
Commits for paulgoughbooks_old/trunk/system/CodeIgniter.php
Revision | Author | Commited | Message |
---|---|---|---|
2 | tporter | Tue 03 Nov, 2020 08:50:21 +0000 | Migration of Paul Goughs Books site to Codeignitor 4 |