Grav.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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);
  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. //Check for code in route
  286. $regex = '/.*(\[(30[1-7])\])$/';
  287. preg_match($regex, $route, $matches);
  288. if ($matches) {
  289. $route = str_replace($matches[1], '', $matches[0]);
  290. $code = $matches[2];
  291. }
  292. if ($code === null) {
  293. $code = $this['config']->get('system.pages.redirect_default_code', 302);
  294. }
  295. if (isset($this['session'])) {
  296. $this['session']->close();
  297. }
  298. if ($uri->isExternal($route)) {
  299. $url = $route;
  300. } else {
  301. $url = rtrim($uri->rootUrl(), '/') . '/';
  302. if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
  303. $url .= trim($route, '/'); // Remove trailing slash
  304. } else {
  305. $url .= ltrim($route, '/'); // Support trailing slash default routes
  306. }
  307. }
  308. header("Location: {$url}", true, $code);
  309. exit();
  310. }
  311. /**
  312. * Redirect browser to another location taking language into account (preferred)
  313. *
  314. * @param string $route Internal route.
  315. * @param int $code Redirection code (30x)
  316. */
  317. public function redirectLangSafe($route, $code = null)
  318. {
  319. if (!$this['uri']->isExternal($route)) {
  320. $this->redirect($this['pages']->route($route), $code);
  321. } else {
  322. $this->redirect($route, $code);
  323. }
  324. }
  325. /**
  326. * Set response header.
  327. *
  328. * @param ResponseInterface|null $response
  329. */
  330. public function header(ResponseInterface $response = null)
  331. {
  332. if (null === $response) {
  333. /** @var PageInterface $page */
  334. $page = $this['page'];
  335. $response = new Response($page->httpResponseCode(), $page->httpHeaders(), '');
  336. }
  337. header("HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}");
  338. foreach ($response->getHeaders() as $key => $values) {
  339. foreach ($values as $i => $value) {
  340. header($key . ': ' . $value, $i === 0);
  341. }
  342. }
  343. }
  344. /**
  345. * Fires an event with optional parameters.
  346. *
  347. * @param string $eventName
  348. * @param Event $event
  349. *
  350. * @return Event
  351. */
  352. public function fireEvent($eventName, Event $event = null)
  353. {
  354. /** @var EventDispatcher $events */
  355. $events = $this['events'];
  356. return $events->dispatch($eventName, $event);
  357. }
  358. /**
  359. * Set the final content length for the page and flush the buffer
  360. *
  361. */
  362. public function shutdown()
  363. {
  364. // Prevent user abort allowing onShutdown event to run without interruptions.
  365. if (\function_exists('ignore_user_abort')) {
  366. @ignore_user_abort(true);
  367. }
  368. // Close the session allowing new requests to be handled.
  369. if (isset($this['session'])) {
  370. $this['session']->close();
  371. }
  372. if ($this['config']->get('system.debugger.shutdown.close_connection', true)) {
  373. // Flush the response and close the connection to allow time consuming tasks to be performed without leaving
  374. // the connection to the client open. This will make page loads to feel much faster.
  375. // FastCGI allows us to flush all response data to the client and finish the request.
  376. $success = \function_exists('fastcgi_finish_request') ? @fastcgi_finish_request() : false;
  377. if (!$success) {
  378. // Unfortunately without FastCGI there is no way to force close the connection.
  379. // We need to ask browser to close the connection for us.
  380. if ($this['config']->get('system.cache.gzip')) {
  381. // Flush gzhandler buffer if gzip setting was enabled.
  382. ob_end_flush();
  383. } else {
  384. // Without gzip we have no other choice than to prevent server from compressing the output.
  385. // This action turns off mod_deflate which would prevent us from closing the connection.
  386. if ($this['config']->get('system.cache.allow_webserver_gzip')) {
  387. header('Content-Encoding: identity');
  388. } else {
  389. header('Content-Encoding: none');
  390. }
  391. }
  392. // Get length and close the connection.
  393. header('Content-Length: ' . ob_get_length());
  394. header('Connection: close');
  395. ob_end_flush();
  396. @ob_flush();
  397. flush();
  398. }
  399. }
  400. // Run any time consuming tasks.
  401. $this->fireEvent('onShutdown');
  402. }
  403. /**
  404. * Magic Catch All Function
  405. *
  406. * Used to call closures.
  407. *
  408. * Source: http://stackoverflow.com/questions/419804/closures-as-class-members
  409. *
  410. * @param string $method
  411. * @param array $args
  412. * @return
  413. */
  414. public function __call($method, $args)
  415. {
  416. $closure = $this->{$method} ?? null;
  417. return is_callable($closure) ? $closure(...$args) : null;
  418. }
  419. /**
  420. * Measure how long it takes to do an action.
  421. *
  422. * @param string $timerId
  423. * @param string $timerTitle
  424. * @param callable $callback
  425. * @return mixed Returns value returned by the callable.
  426. */
  427. public function measureTime(string $timerId, string $timerTitle, callable $callback)
  428. {
  429. $debugger = $this['debugger'];
  430. $debugger->startTimer($timerId, $timerTitle);
  431. $result = $callback();
  432. $debugger->stopTimer($timerId);
  433. return $result;
  434. }
  435. /**
  436. * Initialize and return a Grav instance
  437. *
  438. * @param array $values
  439. *
  440. * @return static
  441. */
  442. protected static function load(array $values)
  443. {
  444. $container = new static($values);
  445. $container['debugger'] = new Debugger();
  446. $container['grav'] = function (Container $container) {
  447. user_error('Calling $grav[\'grav\'] or {{ grav.grav }} is deprecated since Grav 1.6, just use $grav or {{ grav }}', E_USER_DEPRECATED);
  448. return $container;
  449. };
  450. $container->measureTime('_services', 'Services', function () use ($container) {
  451. $container->registerServices();
  452. });
  453. return $container;
  454. }
  455. /**
  456. * Register all services
  457. * Services are defined in the diMap. They can either only the class
  458. * of a Service Provider or a pair of serviceKey => serviceClass that
  459. * gets directly mapped into the container.
  460. *
  461. * @return void
  462. */
  463. protected function registerServices()
  464. {
  465. foreach (self::$diMap as $serviceKey => $serviceClass) {
  466. if (\is_int($serviceKey)) {
  467. $this->register(new $serviceClass);
  468. } else {
  469. $this[$serviceKey] = function ($c) use ($serviceClass) {
  470. return new $serviceClass($c);
  471. };
  472. }
  473. }
  474. }
  475. /**
  476. * This attempts to find media, other files, and download them
  477. *
  478. * @param string $path
  479. */
  480. public function fallbackUrl($path)
  481. {
  482. $this->fireEvent('onPageFallBackUrl');
  483. /** @var Uri $uri */
  484. $uri = $this['uri'];
  485. /** @var Config $config */
  486. $config = $this['config'];
  487. $uri_extension = strtolower($uri->extension());
  488. $fallback_types = $config->get('system.media.allowed_fallback_types', null);
  489. $supported_types = $config->get('media.types');
  490. // Check whitelist first, then ensure extension is a valid media type
  491. if (!empty($fallback_types) && !\in_array($uri_extension, $fallback_types, true)) {
  492. return false;
  493. }
  494. if (!array_key_exists($uri_extension, $supported_types)) {
  495. return false;
  496. }
  497. $path_parts = pathinfo($path);
  498. /** @var PageInterface $page */
  499. $page = $this['pages']->dispatch($path_parts['dirname'], true);
  500. if ($page) {
  501. $media = $page->media()->all();
  502. $parsed_url = parse_url(rawurldecode($uri->basename()));
  503. $media_file = $parsed_url['path'];
  504. // if this is a media object, try actions first
  505. if (isset($media[$media_file])) {
  506. /** @var Medium $medium */
  507. $medium = $media[$media_file];
  508. foreach ($uri->query(null, true) as $action => $params) {
  509. if (\in_array($action, ImageMedium::$magic_actions, true)) {
  510. \call_user_func_array([&$medium, $action], explode(',', $params));
  511. }
  512. }
  513. Utils::download($medium->path(), false);
  514. }
  515. // unsupported media type, try to download it...
  516. if ($uri_extension) {
  517. $extension = $uri_extension;
  518. } else {
  519. if (isset($path_parts['extension'])) {
  520. $extension = $path_parts['extension'];
  521. } else {
  522. $extension = null;
  523. }
  524. }
  525. if ($extension) {
  526. $download = true;
  527. if (\in_array(ltrim($extension, '.'), $config->get('system.media.unsupported_inline_types', []), true)) {
  528. $download = false;
  529. }
  530. Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);
  531. }
  532. // Nothing found
  533. return false;
  534. }
  535. return $page;
  536. }
  537. }