Grav.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. * Process a request
  158. */
  159. public function process()
  160. {
  161. if (isset($this->initialized['process'])) {
  162. return;
  163. }
  164. // Initialize Grav if needed.
  165. $this->setup();
  166. $this->initialized['process'] = true;
  167. $container = new Container(
  168. [
  169. 'configurationProcessor' => function () {
  170. return new ConfigurationProcessor($this);
  171. },
  172. 'loggerProcessor' => function () {
  173. return new LoggerProcessor($this);
  174. },
  175. 'errorsProcessor' => function () {
  176. return new ErrorsProcessor($this);
  177. },
  178. 'debuggerProcessor' => function () {
  179. return new DebuggerProcessor($this);
  180. },
  181. 'initializeProcessor' => function () {
  182. return new InitializeProcessor($this);
  183. },
  184. 'backupsProcessor' => function () {
  185. return new BackupsProcessor($this);
  186. },
  187. 'pluginsProcessor' => function () {
  188. return new PluginsProcessor($this);
  189. },
  190. 'themesProcessor' => function () {
  191. return new ThemesProcessor($this);
  192. },
  193. 'schedulerProcessor' => function () {
  194. return new SchedulerProcessor($this);
  195. },
  196. 'requestProcessor' => function () {
  197. return new RequestProcessor($this);
  198. },
  199. 'tasksProcessor' => function () {
  200. return new TasksProcessor($this);
  201. },
  202. 'assetsProcessor' => function () {
  203. return new AssetsProcessor($this);
  204. },
  205. 'twigProcessor' => function () {
  206. return new TwigProcessor($this);
  207. },
  208. 'pagesProcessor' => function () {
  209. return new PagesProcessor($this);
  210. },
  211. 'debuggerAssetsProcessor' => function () {
  212. return new DebuggerAssetsProcessor($this);
  213. },
  214. 'renderProcessor' => function () {
  215. return new RenderProcessor($this);
  216. },
  217. ]
  218. );
  219. $default = function (ServerRequestInterface $request) {
  220. return new Response(404);
  221. };
  222. /** @var Debugger $debugger */
  223. $debugger = $this['debugger'];
  224. $collection = new RequestHandler($this->middleware, $default, $container);
  225. $response = $collection->handle($this['request']);
  226. $body = $response->getBody();
  227. // Handle ETag and If-None-Match headers.
  228. if ($response->getHeaderLine('ETag') === '1') {
  229. $etag = md5($body);
  230. $response = $response->withHeader('ETag', $etag);
  231. if ($this['request']->getHeaderLine('If-None-Match') === $etag) {
  232. $response = $response->withStatus(304);
  233. $body = '';
  234. }
  235. }
  236. $this->header($response);
  237. echo $body;
  238. $debugger->render();
  239. register_shutdown_function([$this, 'shutdown']);
  240. }
  241. /**
  242. * Set the system locale based on the language and configuration
  243. */
  244. public function setLocale()
  245. {
  246. // Initialize Locale if set and configured.
  247. if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) {
  248. $language = $this['language']->getLanguage();
  249. setlocale(LC_ALL, \strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language);
  250. } elseif ($this['config']->get('system.default_locale')) {
  251. setlocale(LC_ALL, $this['config']->get('system.default_locale'));
  252. }
  253. }
  254. /**
  255. * Redirect browser to another location.
  256. *
  257. * @param string $route Internal route.
  258. * @param int $code Redirection code (30x)
  259. */
  260. public function redirect($route, $code = null)
  261. {
  262. /** @var Uri $uri */
  263. $uri = $this['uri'];
  264. //Check for code in route
  265. $regex = '/.*(\[(30[1-7])\])$/';
  266. preg_match($regex, $route, $matches);
  267. if ($matches) {
  268. $route = str_replace($matches[1], '', $matches[0]);
  269. $code = $matches[2];
  270. }
  271. if ($code === null) {
  272. $code = $this['config']->get('system.pages.redirect_default_code', 302);
  273. }
  274. if (isset($this['session'])) {
  275. $this['session']->close();
  276. }
  277. if ($uri->isExternal($route)) {
  278. $url = $route;
  279. } else {
  280. $url = rtrim($uri->rootUrl(), '/') . '/';
  281. if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
  282. $url .= trim($route, '/'); // Remove trailing slash
  283. } else {
  284. $url .= ltrim($route, '/'); // Support trailing slash default routes
  285. }
  286. }
  287. header("Location: {$url}", true, $code);
  288. exit();
  289. }
  290. /**
  291. * Redirect browser to another location taking language into account (preferred)
  292. *
  293. * @param string $route Internal route.
  294. * @param int $code Redirection code (30x)
  295. */
  296. public function redirectLangSafe($route, $code = null)
  297. {
  298. if (!$this['uri']->isExternal($route)) {
  299. $this->redirect($this['pages']->route($route), $code);
  300. } else {
  301. $this->redirect($route, $code);
  302. }
  303. }
  304. /**
  305. * Set response header.
  306. *
  307. * @param ResponseInterface|null $response
  308. */
  309. public function header(ResponseInterface $response = null)
  310. {
  311. if (null === $response) {
  312. /** @var PageInterface $page */
  313. $page = $this['page'];
  314. $response = new Response($page->httpResponseCode(), $page->httpHeaders(), '');
  315. }
  316. header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}");
  317. foreach ($response->getHeaders() as $key => $values) {
  318. foreach ($values as $i => $value) {
  319. header($key . ': ' . $value, $i === 0);
  320. }
  321. }
  322. }
  323. /**
  324. * Fires an event with optional parameters.
  325. *
  326. * @param string $eventName
  327. * @param Event $event
  328. *
  329. * @return Event
  330. */
  331. public function fireEvent($eventName, Event $event = null)
  332. {
  333. /** @var EventDispatcher $events */
  334. $events = $this['events'];
  335. return $events->dispatch($eventName, $event);
  336. }
  337. /**
  338. * Set the final content length for the page and flush the buffer
  339. *
  340. */
  341. public function shutdown()
  342. {
  343. // Prevent user abort allowing onShutdown event to run without interruptions.
  344. if (\function_exists('ignore_user_abort')) {
  345. @ignore_user_abort(true);
  346. }
  347. // Close the session allowing new requests to be handled.
  348. if (isset($this['session'])) {
  349. $this['session']->close();
  350. }
  351. if ($this['config']->get('system.debugger.shutdown.close_connection', true)) {
  352. // Flush the response and close the connection to allow time consuming tasks to be performed without leaving
  353. // the connection to the client open. This will make page loads to feel much faster.
  354. // FastCGI allows us to flush all response data to the client and finish the request.
  355. $success = \function_exists('fastcgi_finish_request') ? @fastcgi_finish_request() : false;
  356. if (!$success) {
  357. // Unfortunately without FastCGI there is no way to force close the connection.
  358. // We need to ask browser to close the connection for us.
  359. if ($this['config']->get('system.cache.gzip')) {
  360. // Flush gzhandler buffer if gzip setting was enabled.
  361. ob_end_flush();
  362. } else {
  363. // Without gzip we have no other choice than to prevent server from compressing the output.
  364. // This action turns off mod_deflate which would prevent us from closing the connection.
  365. if ($this['config']->get('system.cache.allow_webserver_gzip')) {
  366. header('Content-Encoding: identity');
  367. } else {
  368. header('Content-Encoding: none');
  369. }
  370. }
  371. // Get length and close the connection.
  372. header('Content-Length: ' . ob_get_length());
  373. header('Connection: close');
  374. ob_end_flush();
  375. @ob_flush();
  376. flush();
  377. }
  378. }
  379. // Run any time consuming tasks.
  380. $this->fireEvent('onShutdown');
  381. }
  382. /**
  383. * Magic Catch All Function
  384. *
  385. * Used to call closures.
  386. *
  387. * Source: http://stackoverflow.com/questions/419804/closures-as-class-members
  388. */
  389. public function __call($method, $args)
  390. {
  391. $closure = $this->{$method};
  392. \call_user_func_array($closure, $args);
  393. }
  394. /**
  395. * Measure how long it takes to do an action.
  396. *
  397. * @param string $timerId
  398. * @param string $timerTitle
  399. * @param callable $callback
  400. * @return mixed Returns value returned by the callable.
  401. */
  402. public function measureTime(string $timerId, string $timerTitle, callable $callback)
  403. {
  404. $debugger = $this['debugger'];
  405. $debugger->startTimer($timerId, $timerTitle);
  406. $result = $callback();
  407. $debugger->stopTimer($timerId);
  408. return $result;
  409. }
  410. /**
  411. * Initialize and return a Grav instance
  412. *
  413. * @param array $values
  414. *
  415. * @return static
  416. */
  417. protected static function load(array $values)
  418. {
  419. $container = new static($values);
  420. $container['debugger'] = new Debugger();
  421. $container['grav'] = function (Container $container) {
  422. user_error('Calling $grav[\'grav\'] or {{ grav.grav }} is deprecated since Grav 1.6, just use $grav or {{ grav }}', E_USER_DEPRECATED);
  423. return $container;
  424. };
  425. $container->measureTime('_services', 'Services', function () use ($container) {
  426. $container->registerServices();
  427. });
  428. return $container;
  429. }
  430. /**
  431. * Register all services
  432. * Services are defined in the diMap. They can either only the class
  433. * of a Service Provider or a pair of serviceKey => serviceClass that
  434. * gets directly mapped into the container.
  435. *
  436. * @return void
  437. */
  438. protected function registerServices()
  439. {
  440. foreach (self::$diMap as $serviceKey => $serviceClass) {
  441. if (\is_int($serviceKey)) {
  442. $this->register(new $serviceClass);
  443. } else {
  444. $this[$serviceKey] = function ($c) use ($serviceClass) {
  445. return new $serviceClass($c);
  446. };
  447. }
  448. }
  449. }
  450. /**
  451. * This attempts to find media, other files, and download them
  452. *
  453. * @param string $path
  454. */
  455. public function fallbackUrl($path)
  456. {
  457. $this->fireEvent('onPageFallBackUrl');
  458. /** @var Uri $uri */
  459. $uri = $this['uri'];
  460. /** @var Config $config */
  461. $config = $this['config'];
  462. $uri_extension = strtolower($uri->extension());
  463. $fallback_types = $config->get('system.media.allowed_fallback_types', null);
  464. $supported_types = $config->get('media.types');
  465. // Check whitelist first, then ensure extension is a valid media type
  466. if (!empty($fallback_types) && !\in_array($uri_extension, $fallback_types, true)) {
  467. return false;
  468. }
  469. if (!array_key_exists($uri_extension, $supported_types)) {
  470. return false;
  471. }
  472. $path_parts = pathinfo($path);
  473. /** @var PageInterface $page */
  474. $page = $this['pages']->dispatch($path_parts['dirname'], true);
  475. if ($page) {
  476. $media = $page->media()->all();
  477. $parsed_url = parse_url(rawurldecode($uri->basename()));
  478. $media_file = $parsed_url['path'];
  479. // if this is a media object, try actions first
  480. if (isset($media[$media_file])) {
  481. /** @var Medium $medium */
  482. $medium = $media[$media_file];
  483. foreach ($uri->query(null, true) as $action => $params) {
  484. if (\in_array($action, ImageMedium::$magic_actions, true)) {
  485. \call_user_func_array([&$medium, $action], explode(',', $params));
  486. }
  487. }
  488. Utils::download($medium->path(), false);
  489. }
  490. // unsupported media type, try to download it...
  491. if ($uri_extension) {
  492. $extension = $uri_extension;
  493. } else {
  494. if (isset($path_parts['extension'])) {
  495. $extension = $path_parts['extension'];
  496. } else {
  497. $extension = null;
  498. }
  499. }
  500. if ($extension) {
  501. $download = true;
  502. if (\in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
  503. $download = false;
  504. }
  505. Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);
  506. }
  507. // Nothing found
  508. return false;
  509. }
  510. return $page;
  511. }
  512. }