Grav.php 18 KB

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