Grav.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use Grav\Common\Config\Config;
  10. use Grav\Common\Config\Setup;
  11. use Grav\Common\Page\Interfaces\PageInterface;
  12. use Grav\Common\Page\Medium\ImageMedium;
  13. use Grav\Common\Page\Medium\Medium;
  14. use Grav\Common\Processors\AssetsProcessor;
  15. use Grav\Common\Processors\BackupsProcessor;
  16. use Grav\Common\Processors\ConfigurationProcessor;
  17. use Grav\Common\Processors\DebuggerAssetsProcessor;
  18. use Grav\Common\Processors\DebuggerProcessor;
  19. use Grav\Common\Processors\ErrorsProcessor;
  20. use Grav\Common\Processors\InitializeProcessor;
  21. use Grav\Common\Processors\LoggerProcessor;
  22. use Grav\Common\Processors\PagesProcessor;
  23. use Grav\Common\Processors\PluginsProcessor;
  24. use Grav\Common\Processors\RenderProcessor;
  25. use Grav\Common\Processors\RequestProcessor;
  26. use Grav\Common\Processors\SchedulerProcessor;
  27. use Grav\Common\Processors\TasksProcessor;
  28. use Grav\Common\Processors\ThemesProcessor;
  29. use Grav\Common\Processors\TwigProcessor;
  30. use Grav\Framework\DI\Container;
  31. use Grav\Framework\Psr7\Response;
  32. use Grav\Framework\RequestHandler\RequestHandler;
  33. use Psr\Http\Message\ResponseInterface;
  34. use Psr\Http\Message\ServerRequestInterface;
  35. use RocketTheme\Toolbox\Event\Event;
  36. use RocketTheme\Toolbox\Event\EventDispatcher;
  37. /**
  38. * Grav container is the heart of Grav.
  39. *
  40. * @package Grav\Common
  41. */
  42. class Grav extends Container
  43. {
  44. /**
  45. * @var string Processed output for the page.
  46. */
  47. public $output;
  48. /**
  49. * @var static The singleton instance
  50. */
  51. protected static $instance;
  52. /**
  53. * @var array Contains all Services and ServicesProviders that are mapped
  54. * to the dependency injection container.
  55. */
  56. protected static $diMap = [
  57. 'Grav\Common\Service\AccountsServiceProvider',
  58. 'Grav\Common\Service\AssetsServiceProvider',
  59. 'Grav\Common\Service\BackupsServiceProvider',
  60. 'Grav\Common\Service\ConfigServiceProvider',
  61. 'Grav\Common\Service\ErrorServiceProvider',
  62. 'Grav\Common\Service\FilesystemServiceProvider',
  63. 'Grav\Common\Service\InflectorServiceProvider',
  64. 'Grav\Common\Service\LoggerServiceProvider',
  65. 'Grav\Common\Service\OutputServiceProvider',
  66. 'Grav\Common\Service\PagesServiceProvider',
  67. 'Grav\Common\Service\RequestServiceProvider',
  68. 'Grav\Common\Service\SessionServiceProvider',
  69. 'Grav\Common\Service\StreamsServiceProvider',
  70. 'Grav\Common\Service\TaskServiceProvider',
  71. 'browser' => 'Grav\Common\Browser',
  72. 'cache' => 'Grav\Common\Cache',
  73. 'events' => 'RocketTheme\Toolbox\Event\EventDispatcher',
  74. 'exif' => 'Grav\Common\Helpers\Exif',
  75. 'plugins' => 'Grav\Common\Plugins',
  76. 'scheduler' => 'Grav\Common\Scheduler\Scheduler',
  77. 'taxonomy' => 'Grav\Common\Taxonomy',
  78. 'themes' => 'Grav\Common\Themes',
  79. 'twig' => 'Grav\Common\Twig\Twig',
  80. 'uri' => 'Grav\Common\Uri',
  81. ];
  82. /**
  83. * @var array All middleware processors that are processed in $this->process()
  84. */
  85. protected $middleware = [
  86. 'configurationProcessor',
  87. 'loggerProcessor',
  88. 'errorsProcessor',
  89. 'debuggerProcessor',
  90. 'initializeProcessor',
  91. 'pluginsProcessor',
  92. 'themesProcessor',
  93. 'requestProcessor',
  94. 'tasksProcessor',
  95. 'backupsProcessor',
  96. 'schedulerProcessor',
  97. 'assetsProcessor',
  98. 'twigProcessor',
  99. 'pagesProcessor',
  100. 'debuggerAssetsProcessor',
  101. 'renderProcessor',
  102. ];
  103. protected $initialized = [];
  104. /**
  105. * Reset the Grav instance.
  106. */
  107. public static function resetInstance()
  108. {
  109. if (self::$instance) {
  110. self::$instance = null;
  111. }
  112. }
  113. /**
  114. * Return the Grav instance. Create it if it's not already instanced
  115. *
  116. * @param array $values
  117. *
  118. * @return Grav
  119. */
  120. public static function instance(array $values = [])
  121. {
  122. if (!self::$instance) {
  123. self::$instance = static::load($values);
  124. } elseif ($values) {
  125. $instance = self::$instance;
  126. foreach ($values as $key => $value) {
  127. $instance->offsetSet($key, $value);
  128. }
  129. }
  130. return self::$instance;
  131. }
  132. /**
  133. * Setup Grav instance using specific environment.
  134. *
  135. * Initializes Grav streams by
  136. *
  137. * @param string|null $environment
  138. * @return $this
  139. */
  140. public function setup(string $environment = null)
  141. {
  142. if (isset($this->initialized['setup'])) {
  143. return $this;
  144. }
  145. $this->initialized['setup'] = true;
  146. $this->measureTime('_setup', 'Site Setup', function () use ($environment) {
  147. // Force environment if passed to the method.
  148. if ($environment) {
  149. Setup::$environment = $environment;
  150. }
  151. $this['setup'];
  152. $this['streams'];
  153. });
  154. return $this;
  155. }
  156. /**
  157. * Initialize CLI environment.
  158. *
  159. * Call after `$grav->setup($environment)`
  160. *
  161. * - Load configuration
  162. * - Disable debugger
  163. * - Set timezone, locale
  164. * - Load plugins
  165. * - Set Users type to be used in the site
  166. *
  167. * This method WILL NOT initialize assets, twig or pages.
  168. *
  169. * @param string|null $environment
  170. * @return $this
  171. */
  172. public function initializeCli()
  173. {
  174. InitializeProcessor::initializeCli($this);
  175. return $this;
  176. }
  177. /**
  178. * Process a request
  179. */
  180. public function process()
  181. {
  182. if (isset($this->initialized['process'])) {
  183. return;
  184. }
  185. // Initialize Grav if needed.
  186. $this->setup();
  187. $this->initialized['process'] = true;
  188. $container = new Container(
  189. [
  190. 'configurationProcessor' => function () {
  191. return new ConfigurationProcessor($this);
  192. },
  193. 'loggerProcessor' => function () {
  194. return new LoggerProcessor($this);
  195. },
  196. 'errorsProcessor' => function () {
  197. return new ErrorsProcessor($this);
  198. },
  199. 'debuggerProcessor' => function () {
  200. return new DebuggerProcessor($this);
  201. },
  202. 'initializeProcessor' => function () {
  203. return new InitializeProcessor($this);
  204. },
  205. 'backupsProcessor' => function () {
  206. return new BackupsProcessor($this);
  207. },
  208. 'pluginsProcessor' => function () {
  209. return new PluginsProcessor($this);
  210. },
  211. 'themesProcessor' => function () {
  212. return new ThemesProcessor($this);
  213. },
  214. 'schedulerProcessor' => function () {
  215. return new SchedulerProcessor($this);
  216. },
  217. 'requestProcessor' => function () {
  218. return new RequestProcessor($this);
  219. },
  220. 'tasksProcessor' => function () {
  221. return new TasksProcessor($this);
  222. },
  223. 'assetsProcessor' => function () {
  224. return new AssetsProcessor($this);
  225. },
  226. 'twigProcessor' => function () {
  227. return new TwigProcessor($this);
  228. },
  229. 'pagesProcessor' => function () {
  230. return new PagesProcessor($this);
  231. },
  232. 'debuggerAssetsProcessor' => function () {
  233. return new DebuggerAssetsProcessor($this);
  234. },
  235. 'renderProcessor' => function () {
  236. return new RenderProcessor($this);
  237. },
  238. ]
  239. );
  240. $default = function (ServerRequestInterface $request) {
  241. return new Response(404, ['Expires' => 0, 'Cache-Control' => 'no-cache, no-store, must-revalidate'], 'Not Found');
  242. };
  243. /** @var Debugger $debugger */
  244. $debugger = $this['debugger'];
  245. $collection = new RequestHandler($this->middleware, $default, $container);
  246. $response = $collection->handle($this['request']);
  247. $body = $response->getBody();
  248. // Handle ETag and If-None-Match headers.
  249. if ($response->getHeaderLine('ETag') === '1') {
  250. $etag = md5($body);
  251. $response = $response->withHeader('ETag', $etag);
  252. if ($this['request']->getHeaderLine('If-None-Match') === $etag) {
  253. $response = $response->withStatus(304);
  254. $body = '';
  255. }
  256. }
  257. $this->header($response);
  258. echo $body;
  259. $debugger->render();
  260. register_shutdown_function([$this, 'shutdown']);
  261. }
  262. /**
  263. * Set the system locale based on the language and configuration
  264. */
  265. public function setLocale()
  266. {
  267. // Initialize Locale if set and configured.
  268. if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) {
  269. $language = $this['language']->getLanguage();
  270. setlocale(LC_ALL, \strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language);
  271. } elseif ($this['config']->get('system.default_locale')) {
  272. setlocale(LC_ALL, $this['config']->get('system.default_locale'));
  273. }
  274. }
  275. /**
  276. * Redirect browser to another location.
  277. *
  278. * @param string $route Internal route.
  279. * @param int $code Redirection code (30x)
  280. */
  281. public function redirect($route, $code = null)
  282. {
  283. /** @var Uri $uri */
  284. $uri = $this['uri'];
  285. // Clean route for redirect
  286. $route = preg_replace("#^\/[\\\/]+\/#", '/', $route);
  287. // Check for code in route
  288. $regex = '/.*(\[(30[1-7])\])$/';
  289. preg_match($regex, $route, $matches);
  290. if ($matches) {
  291. $route = str_replace($matches[1], '', $matches[0]);
  292. $code = $matches[2];
  293. }
  294. if ($code === null) {
  295. $code = $this['config']->get('system.pages.redirect_default_code', 302);
  296. }
  297. if (isset($this['session'])) {
  298. $this['session']->close();
  299. }
  300. if ($uri->isExternal($route)) {
  301. $url = $route;
  302. } else {
  303. $url = rtrim($uri->rootUrl(), '/') . '/';
  304. if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
  305. $url .= trim($route, '/'); // Remove trailing slash
  306. } else {
  307. $url .= ltrim($route, '/'); // Support trailing slash default routes
  308. }
  309. }
  310. header("Location: {$url}", true, $code);
  311. exit();
  312. }
  313. /**
  314. * Redirect browser to another location taking language into account (preferred)
  315. *
  316. * @param string $route Internal route.
  317. * @param int $code Redirection code (30x)
  318. */
  319. public function redirectLangSafe($route, $code = null)
  320. {
  321. if (!$this['uri']->isExternal($route)) {
  322. $this->redirect($this['pages']->route($route), $code);
  323. } else {
  324. $this->redirect($route, $code);
  325. }
  326. }
  327. /**
  328. * Set response header.
  329. *
  330. * @param ResponseInterface|null $response
  331. */
  332. public function header(ResponseInterface $response = null)
  333. {
  334. if (null === $response) {
  335. /** @var PageInterface $page */
  336. $page = $this['page'];
  337. $response = new Response($page->httpResponseCode(), $page->httpHeaders(), '');
  338. }
  339. header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}");
  340. foreach ($response->getHeaders() as $key => $values) {
  341. foreach ($values as $i => $value) {
  342. header($key . ': ' . $value, $i === 0);
  343. }
  344. }
  345. }
  346. /**
  347. * Fires an event with optional parameters.
  348. *
  349. * @param string $eventName
  350. * @param Event $event
  351. *
  352. * @return Event
  353. */
  354. public function fireEvent($eventName, Event $event = null)
  355. {
  356. /** @var EventDispatcher $events */
  357. $events = $this['events'];
  358. return $events->dispatch($eventName, $event);
  359. }
  360. /**
  361. * Set the final content length for the page and flush the buffer
  362. *
  363. */
  364. public function shutdown()
  365. {
  366. // Prevent user abort allowing onShutdown event to run without interruptions.
  367. if (\function_exists('ignore_user_abort')) {
  368. @ignore_user_abort(true);
  369. }
  370. // Close the session allowing new requests to be handled.
  371. if (isset($this['session'])) {
  372. $this['session']->close();
  373. }
  374. if ($this['config']->get('system.debugger.shutdown.close_connection', true)) {
  375. // Flush the response and close the connection to allow time consuming tasks to be performed without leaving
  376. // the connection to the client open. This will make page loads to feel much faster.
  377. // FastCGI allows us to flush all response data to the client and finish the request.
  378. $success = \function_exists('fastcgi_finish_request') ? @fastcgi_finish_request() : false;
  379. if (!$success) {
  380. // Unfortunately without FastCGI there is no way to force close the connection.
  381. // We need to ask browser to close the connection for us.
  382. if ($this['config']->get('system.cache.gzip')) {
  383. // Flush gzhandler buffer if gzip setting was enabled.
  384. ob_end_flush();
  385. } else {
  386. // Without gzip we have no other choice than to prevent server from compressing the output.
  387. // This action turns off mod_deflate which would prevent us from closing the connection.
  388. if ($this['config']->get('system.cache.allow_webserver_gzip')) {
  389. header('Content-Encoding: identity');
  390. } else {
  391. header('Content-Encoding: none');
  392. }
  393. }
  394. // Get length and close the connection.
  395. header('Content-Length: ' . ob_get_length());
  396. header('Connection: close');
  397. ob_end_flush();
  398. @ob_flush();
  399. flush();
  400. }
  401. }
  402. // Run any time consuming tasks.
  403. $this->fireEvent('onShutdown');
  404. }
  405. /**
  406. * Magic Catch All Function
  407. *
  408. * Used to call closures.
  409. *
  410. * Source: http://stackoverflow.com/questions/419804/closures-as-class-members
  411. *
  412. * @param string $method
  413. * @param array $args
  414. * @return
  415. */
  416. public function __call($method, $args)
  417. {
  418. $closure = $this->{$method} ?? null;
  419. return is_callable($closure) ? $closure(...$args) : null;
  420. }
  421. /**
  422. * Measure how long it takes to do an action.
  423. *
  424. * @param string $timerId
  425. * @param string $timerTitle
  426. * @param callable $callback
  427. * @return mixed Returns value returned by the callable.
  428. */
  429. public function measureTime(string $timerId, string $timerTitle, callable $callback)
  430. {
  431. $debugger = $this['debugger'];
  432. $debugger->startTimer($timerId, $timerTitle);
  433. $result = $callback();
  434. $debugger->stopTimer($timerId);
  435. return $result;
  436. }
  437. /**
  438. * Initialize and return a Grav instance
  439. *
  440. * @param array $values
  441. *
  442. * @return static
  443. */
  444. protected static function load(array $values)
  445. {
  446. $container = new static($values);
  447. $container['debugger'] = new Debugger();
  448. $container['grav'] = function (Container $container) {
  449. user_error('Calling $grav[\'grav\'] or {{ grav.grav }} is deprecated since Grav 1.6, just use $grav or {{ grav }}', E_USER_DEPRECATED);
  450. return $container;
  451. };
  452. $container->measureTime('_services', 'Services', function () use ($container) {
  453. $container->registerServices();
  454. });
  455. return $container;
  456. }
  457. /**
  458. * Register all services
  459. * Services are defined in the diMap. They can either only the class
  460. * of a Service Provider or a pair of serviceKey => serviceClass that
  461. * gets directly mapped into the container.
  462. *
  463. * @return void
  464. */
  465. protected function registerServices()
  466. {
  467. foreach (self::$diMap as $serviceKey => $serviceClass) {
  468. if (\is_int($serviceKey)) {
  469. $this->register(new $serviceClass);
  470. } else {
  471. $this[$serviceKey] = function ($c) use ($serviceClass) {
  472. return new $serviceClass($c);
  473. };
  474. }
  475. }
  476. }
  477. /**
  478. * This attempts to find media, other files, and download them
  479. *
  480. * @param string $path
  481. */
  482. public function fallbackUrl($path)
  483. {
  484. $this->fireEvent('onPageFallBackUrl');
  485. /** @var Uri $uri */
  486. $uri = $this['uri'];
  487. /** @var Config $config */
  488. $config = $this['config'];
  489. $uri_extension = strtolower($uri->extension());
  490. $fallback_types = $config->get('system.media.allowed_fallback_types', null);
  491. $supported_types = $config->get('media.types');
  492. // Check whitelist first, then ensure extension is a valid media type
  493. if (!empty($fallback_types) && !\in_array($uri_extension, $fallback_types, true)) {
  494. return false;
  495. }
  496. if (!array_key_exists($uri_extension, $supported_types)) {
  497. return false;
  498. }
  499. $path_parts = pathinfo($path);
  500. /** @var PageInterface $page */
  501. $page = $this['pages']->dispatch($path_parts['dirname'], true);
  502. if ($page) {
  503. $media = $page->media()->all();
  504. $parsed_url = parse_url(rawurldecode($uri->basename()));
  505. $media_file = $parsed_url['path'];
  506. // if this is a media object, try actions first
  507. if (isset($media[$media_file])) {
  508. /** @var Medium $medium */
  509. $medium = $media[$media_file];
  510. foreach ($uri->query(null, true) as $action => $params) {
  511. if (\in_array($action, ImageMedium::$magic_actions, true)) {
  512. \call_user_func_array([&$medium, $action], explode(',', $params));
  513. }
  514. }
  515. Utils::download($medium->path(), false);
  516. }
  517. // unsupported media type, try to download it...
  518. if ($uri_extension) {
  519. $extension = $uri_extension;
  520. } else {
  521. if (isset($path_parts['extension'])) {
  522. $extension = $path_parts['extension'];
  523. } else {
  524. $extension = null;
  525. }
  526. }
  527. if ($extension) {
  528. $download = true;
  529. if (\in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
  530. $download = false;
  531. }
  532. Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);
  533. }
  534. // Nothing found
  535. return false;
  536. }
  537. return $page;
  538. }
  539. }