Twig.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. <?php
  2. /**
  3. * @package Grav\Common\Twig
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig;
  9. use Grav\Common\Debugger;
  10. use Grav\Common\Grav;
  11. use Grav\Common\Config\Config;
  12. use Grav\Common\Language\Language;
  13. use Grav\Common\Language\LanguageCodes;
  14. use Grav\Common\Page\Interfaces\PageInterface;
  15. use Grav\Common\Page\Pages;
  16. use Grav\Common\Twig\Exception\TwigException;
  17. use Grav\Common\Twig\Extension\FilesystemExtension;
  18. use Grav\Common\Twig\Extension\GravExtension;
  19. use Grav\Common\Utils;
  20. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  21. use RocketTheme\Toolbox\Event\Event;
  22. use RuntimeException;
  23. use Twig\Cache\FilesystemCache;
  24. use Twig\DeferredExtension\DeferredExtension;
  25. use Twig\Environment;
  26. use Twig\Error\LoaderError;
  27. use Twig\Error\RuntimeError;
  28. use Twig\Extension\CoreExtension;
  29. use Twig\Extension\DebugExtension;
  30. use Twig\Extension\StringLoaderExtension;
  31. use Twig\Loader\ArrayLoader;
  32. use Twig\Loader\ChainLoader;
  33. use Twig\Loader\ExistsLoaderInterface;
  34. use Twig\Loader\FilesystemLoader;
  35. use Twig\Profiler\Profile;
  36. use Twig\TwigFilter;
  37. use Twig\TwigFunction;
  38. use function function_exists;
  39. use function in_array;
  40. use function is_array;
  41. /**
  42. * Class Twig
  43. * @package Grav\Common\Twig
  44. */
  45. class Twig
  46. {
  47. /** @var Environment */
  48. public $twig;
  49. /** @var array */
  50. public $twig_vars = [];
  51. /** @var array */
  52. public $twig_paths;
  53. /** @var string */
  54. public $template;
  55. /** @var Grav */
  56. protected $grav;
  57. /** @var FilesystemLoader */
  58. protected $loader;
  59. /** @var ArrayLoader */
  60. protected $loaderArray;
  61. /** @var bool */
  62. protected $autoescape;
  63. /** @var Profile */
  64. protected $profile;
  65. /**
  66. * Constructor
  67. *
  68. * @param Grav $grav
  69. */
  70. public function __construct(Grav $grav)
  71. {
  72. $this->grav = $grav;
  73. $this->twig_paths = [];
  74. }
  75. /**
  76. * Twig initialization that sets the twig loader chain, then the environment, then extensions
  77. * and also the base set of twig vars
  78. *
  79. * @return $this
  80. */
  81. public function init()
  82. {
  83. if (null === $this->twig) {
  84. /** @var Config $config */
  85. $config = $this->grav['config'];
  86. /** @var UniformResourceLocator $locator */
  87. $locator = $this->grav['locator'];
  88. /** @var Language $language */
  89. $language = $this->grav['language'];
  90. $active_language = $language->getActive();
  91. // handle language templates if available
  92. if ($language->enabled()) {
  93. $lang_templates = $locator->findResource('theme://templates/' . ($active_language ?: $language->getDefault()));
  94. if ($lang_templates) {
  95. $this->twig_paths[] = $lang_templates;
  96. }
  97. }
  98. $this->twig_paths = array_merge($this->twig_paths, $locator->findResources('theme://templates'));
  99. $this->grav->fireEvent('onTwigTemplatePaths');
  100. // Add Grav core templates location
  101. $core_templates = array_merge($locator->findResources('system://templates'), $locator->findResources('system://templates/testing'));
  102. $this->twig_paths = array_merge($this->twig_paths, $core_templates);
  103. $this->loader = new FilesystemLoader($this->twig_paths);
  104. // Register all other prefixes as namespaces in twig
  105. foreach ($locator->getPaths('theme') as $prefix => $_) {
  106. if ($prefix === '') {
  107. continue;
  108. }
  109. $twig_paths = [];
  110. // handle language templates if available
  111. if ($language->enabled()) {
  112. $lang_templates = $locator->findResource('theme://'.$prefix.'templates/' . ($active_language ?: $language->getDefault()));
  113. if ($lang_templates) {
  114. $twig_paths[] = $lang_templates;
  115. }
  116. }
  117. $twig_paths = array_merge($twig_paths, $locator->findResources('theme://'.$prefix.'templates'));
  118. $namespace = trim($prefix, '/');
  119. $this->loader->setPaths($twig_paths, $namespace);
  120. }
  121. $this->grav->fireEvent('onTwigLoader');
  122. $this->loaderArray = new ArrayLoader([]);
  123. $loader_chain = new ChainLoader([$this->loaderArray, $this->loader]);
  124. $params = $config->get('system.twig');
  125. if (!empty($params['cache'])) {
  126. $cachePath = $locator->findResource('cache://twig', true, true);
  127. $params['cache'] = new FilesystemCache($cachePath, FilesystemCache::FORCE_BYTECODE_INVALIDATION);
  128. }
  129. if (!$config->get('system.strict_mode.twig_compat', false)) {
  130. // Force autoescape on for all files if in strict mode.
  131. $params['autoescape'] = 'html';
  132. } elseif (!empty($this->autoescape)) {
  133. $params['autoescape'] = $this->autoescape ? 'html' : false;
  134. }
  135. if (empty($params['autoescape'])) {
  136. user_error('Grav 2.0 will have Twig auto-escaping forced on (can be emulated by turning off \'system.strict_mode.twig_compat\' setting in your configuration)', E_USER_DEPRECATED);
  137. }
  138. $this->twig = new TwigEnvironment($loader_chain, $params);
  139. $this->twig->registerUndefinedFunctionCallback(function (string $name) use ($config) {
  140. $allowed = $config->get('system.twig.safe_functions');
  141. if (is_array($allowed) && in_array($name, $allowed, true) && function_exists($name)) {
  142. return new TwigFunction($name, $name);
  143. }
  144. if ($config->get('system.twig.undefined_functions')) {
  145. if (function_exists($name)) {
  146. if (!Utils::isDangerousFunction($name)) {
  147. user_error("PHP function {$name}() was used as Twig function. This is deprecated in Grav 1.7. Please add it to system configuration: `system.twig.safe_functions`", E_USER_DEPRECATED);
  148. return new TwigFunction($name, $name);
  149. }
  150. /** @var Debugger $debugger */
  151. $debugger = $this->grav['debugger'];
  152. $debugger->addException(new RuntimeException("Blocked potentially dangerous PHP function {$name}() being used as Twig function. If you really want to use it, please add it to system configuration: `system.twig.safe_functions`"));
  153. }
  154. return new TwigFunction($name, static function () {});
  155. }
  156. return false;
  157. });
  158. $this->twig->registerUndefinedFilterCallback(function (string $name) use ($config) {
  159. $allowed = $config->get('system.twig.safe_filters');
  160. if (is_array($allowed) && in_array($name, $allowed, true) && function_exists($name)) {
  161. return new TwigFilter($name, $name);
  162. }
  163. if ($config->get('system.twig.undefined_filters')) {
  164. if (function_exists($name)) {
  165. if (!Utils::isDangerousFunction($name)) {
  166. user_error("PHP function {$name}() used as Twig filter. This is deprecated in Grav 1.7. Please add it to system configuration: `system.twig.safe_filters`", E_USER_DEPRECATED);
  167. return new TwigFilter($name, $name);
  168. }
  169. /** @var Debugger $debugger */
  170. $debugger = $this->grav['debugger'];
  171. $debugger->addException(new RuntimeException("Blocked potentially dangerous PHP function {$name}() being used as Twig filter. If you really want to use it, please add it to system configuration: `system.twig.safe_filters`"));
  172. }
  173. return new TwigFilter($name, static function () {});
  174. }
  175. return false;
  176. });
  177. $this->grav->fireEvent('onTwigInitialized');
  178. // set default date format if set in config
  179. if ($config->get('system.pages.dateformat.long')) {
  180. /** @var CoreExtension $extension */
  181. $extension = $this->twig->getExtension(CoreExtension::class);
  182. $extension->setDateFormat($config->get('system.pages.dateformat.long'));
  183. }
  184. // enable the debug extension if required
  185. if ($config->get('system.twig.debug')) {
  186. $this->twig->addExtension(new DebugExtension());
  187. }
  188. $this->twig->addExtension(new GravExtension());
  189. $this->twig->addExtension(new FilesystemExtension());
  190. $this->twig->addExtension(new DeferredExtension());
  191. $this->twig->addExtension(new StringLoaderExtension());
  192. /** @var Debugger $debugger */
  193. $debugger = $this->grav['debugger'];
  194. $debugger->addTwigProfiler($this->twig);
  195. $this->grav->fireEvent('onTwigExtensions');
  196. /** @var Pages $pages */
  197. $pages = $this->grav['pages'];
  198. // Set some standard variables for twig
  199. $this->twig_vars += [
  200. 'config' => $config,
  201. 'system' => $config->get('system'),
  202. 'theme' => $config->get('theme'),
  203. 'site' => $config->get('site'),
  204. 'uri' => $this->grav['uri'],
  205. 'assets' => $this->grav['assets'],
  206. 'taxonomy' => $this->grav['taxonomy'],
  207. 'browser' => $this->grav['browser'],
  208. 'base_dir' => GRAV_ROOT,
  209. 'home_url' => $pages->homeUrl($active_language),
  210. 'base_url' => $pages->baseUrl($active_language),
  211. 'base_url_absolute' => $pages->baseUrl($active_language, true),
  212. 'base_url_relative' => $pages->baseUrl($active_language, false),
  213. 'base_url_simple' => $this->grav['base_url'],
  214. 'theme_dir' => $locator->findResource('theme://'),
  215. 'theme_url' => $this->grav['base_url'] . '/' . $locator->findResource('theme://', false),
  216. 'html_lang' => $this->grav['language']->getActive() ?: $config->get('site.default_lang', 'en'),
  217. 'language_codes' => new LanguageCodes,
  218. ];
  219. }
  220. return $this;
  221. }
  222. /**
  223. * @return Environment
  224. */
  225. public function twig()
  226. {
  227. return $this->twig;
  228. }
  229. /**
  230. * @return FilesystemLoader
  231. */
  232. public function loader()
  233. {
  234. return $this->loader;
  235. }
  236. /**
  237. * @return Profile
  238. */
  239. public function profile()
  240. {
  241. return $this->profile;
  242. }
  243. /**
  244. * Adds or overrides a template.
  245. *
  246. * @param string $name The template name
  247. * @param string $template The template source
  248. */
  249. public function setTemplate($name, $template)
  250. {
  251. $this->loaderArray->setTemplate($name, $template);
  252. }
  253. /**
  254. * Twig process that renders a page item. It supports two variations:
  255. * 1) Handles modular pages by rendering a specific page based on its modular twig template
  256. * 2) Renders individual page items for twig processing before the site rendering
  257. *
  258. * @param PageInterface $item The page item to render
  259. * @param string|null $content Optional content override
  260. *
  261. * @return string The rendered output
  262. */
  263. public function processPage(PageInterface $item, $content = null)
  264. {
  265. $content = $content ?? $item->content();
  266. // override the twig header vars for local resolution
  267. $this->grav->fireEvent('onTwigPageVariables', new Event(['page' => $item]));
  268. $twig_vars = $this->twig_vars;
  269. $twig_vars['page'] = $item;
  270. $twig_vars['media'] = $item->media();
  271. $twig_vars['header'] = $item->header();
  272. $local_twig = clone $this->twig;
  273. $output = '';
  274. try {
  275. if ($item->isModule()) {
  276. $twig_vars['content'] = $content;
  277. $template = $this->getPageTwigTemplate($item);
  278. $output = $content = $local_twig->render($template, $twig_vars);
  279. }
  280. // Process in-page Twig
  281. if ($item->shouldProcess('twig')) {
  282. $name = '@Page:' . $item->path();
  283. $this->setTemplate($name, $content);
  284. $output = $local_twig->render($name, $twig_vars);
  285. }
  286. } catch (LoaderError $e) {
  287. throw new RuntimeException($e->getRawMessage(), 400, $e);
  288. }
  289. return $output;
  290. }
  291. /**
  292. * Process a Twig template directly by using a template name
  293. * and optional array of variables
  294. *
  295. * @param string $template template to render with
  296. * @param array $vars Optional variables
  297. *
  298. * @return string
  299. */
  300. public function processTemplate($template, $vars = [])
  301. {
  302. // override the twig header vars for local resolution
  303. $this->grav->fireEvent('onTwigTemplateVariables');
  304. $vars += $this->twig_vars;
  305. try {
  306. $output = $this->twig->render($template, $vars);
  307. } catch (LoaderError $e) {
  308. throw new RuntimeException($e->getRawMessage(), 404, $e);
  309. }
  310. return $output;
  311. }
  312. /**
  313. * Process a Twig template directly by using a Twig string
  314. * and optional array of variables
  315. *
  316. * @param string $string string to render.
  317. * @param array $vars Optional variables
  318. *
  319. * @return string
  320. */
  321. public function processString($string, array $vars = [])
  322. {
  323. // override the twig header vars for local resolution
  324. $this->grav->fireEvent('onTwigStringVariables');
  325. $vars += $this->twig_vars;
  326. $name = '@Var:' . $string;
  327. $this->setTemplate($name, $string);
  328. try {
  329. $output = $this->twig->render($name, $vars);
  330. } catch (LoaderError $e) {
  331. throw new RuntimeException($e->getRawMessage(), 404, $e);
  332. }
  333. return $output;
  334. }
  335. /**
  336. * Twig process that renders the site layout. This is the main twig process that renders the overall
  337. * page and handles all the layout for the site display.
  338. *
  339. * @param string|null $format Output format (defaults to HTML).
  340. * @param array $vars
  341. * @return string the rendered output
  342. * @throws RuntimeException
  343. */
  344. public function processSite($format = null, array $vars = [])
  345. {
  346. try {
  347. $grav = $this->grav;
  348. // set the page now its been processed
  349. $grav->fireEvent('onTwigSiteVariables');
  350. /** @var Pages $pages */
  351. $pages = $grav['pages'];
  352. /** @var PageInterface $page */
  353. $page = $grav['page'];
  354. $twig_vars = $this->twig_vars;
  355. $twig_vars['theme'] = $grav['config']->get('theme');
  356. $twig_vars['pages'] = $pages->root();
  357. $twig_vars['page'] = $page;
  358. $twig_vars['header'] = $page->header();
  359. $twig_vars['media'] = $page->media();
  360. $twig_vars['content'] = $page->content();
  361. // determine if params are set, if so disable twig cache
  362. $params = $grav['uri']->params(null, true);
  363. if (!empty($params)) {
  364. $this->twig->setCache(false);
  365. }
  366. // Get Twig template layout
  367. $template = $this->getPageTwigTemplate($page, $format);
  368. $page->templateFormat($format);
  369. $output = $this->twig->render($template, $vars + $twig_vars);
  370. } catch (LoaderError $e) {
  371. throw new RuntimeException($e->getMessage(), 400, $e);
  372. } catch (RuntimeError $e) {
  373. $prev = $e->getPrevious();
  374. if ($prev instanceof TwigException) {
  375. $code = $prev->getCode() ?: 500;
  376. // Fire onPageNotFound event.
  377. $event = new Event([
  378. 'page' => $page,
  379. 'code' => $code,
  380. 'message' => $prev->getMessage(),
  381. 'exception' => $prev,
  382. 'route' => $grav['route'],
  383. 'request' => $grav['request']
  384. ]);
  385. $event = $grav->fireEvent("onDisplayErrorPage.{$code}", $event);
  386. $newPage = $event['page'];
  387. if ($newPage && $newPage !== $page) {
  388. unset($grav['page']);
  389. $grav['page'] = $newPage;
  390. return $this->processSite($newPage->templateFormat(), $vars);
  391. }
  392. }
  393. throw $e;
  394. }
  395. return $output;
  396. }
  397. /**
  398. * Wraps the FilesystemLoader addPath method (should be used only in `onTwigLoader()` event
  399. * @param string $template_path
  400. * @param string $namespace
  401. * @throws LoaderError
  402. */
  403. public function addPath($template_path, $namespace = '__main__')
  404. {
  405. $this->loader->addPath($template_path, $namespace);
  406. }
  407. /**
  408. * Wraps the FilesystemLoader prependPath method (should be used only in `onTwigLoader()` event
  409. * @param string $template_path
  410. * @param string $namespace
  411. * @throws LoaderError
  412. */
  413. public function prependPath($template_path, $namespace = '__main__')
  414. {
  415. $this->loader->prependPath($template_path, $namespace);
  416. }
  417. /**
  418. * Simple helper method to get the twig template if it has already been set, else return
  419. * the one being passed in
  420. *
  421. * @param string $template the template name
  422. * @return string the template name
  423. */
  424. public function template($template)
  425. {
  426. return $this->template ?? $template;
  427. }
  428. /**
  429. * @param PageInterface $page
  430. * @param string|null $format
  431. * @return string
  432. */
  433. public function getPageTwigTemplate($page, &$format = null)
  434. {
  435. $template = $page->template();
  436. $default = $page->isModule() ? 'modular/default' : 'default';
  437. $extension = $format ?: $page->templateFormat();
  438. $twig_extension = $extension ? '.'. $extension .TWIG_EXT : TEMPLATE_EXT;
  439. $template_file = $this->template($page->template() . $twig_extension);
  440. // TODO: no longer needed in Twig 3.
  441. /** @var ExistsLoaderInterface $loader */
  442. $loader = $this->twig->getLoader();
  443. if ($loader->exists($template_file)) {
  444. // template.xxx.twig
  445. $page_template = $template_file;
  446. } elseif ($twig_extension !== TEMPLATE_EXT && $loader->exists($template . TEMPLATE_EXT)) {
  447. // template.html.twig
  448. $page_template = $template . TEMPLATE_EXT;
  449. $format = 'html';
  450. } elseif ($loader->exists($default . $twig_extension)) {
  451. // default.xxx.twig
  452. $page_template = $default . $twig_extension;
  453. } else {
  454. // default.html.twig
  455. $page_template = $default . TEMPLATE_EXT;
  456. $format = 'html';
  457. }
  458. return $page_template;
  459. }
  460. /**
  461. * Overrides the autoescape setting
  462. *
  463. * @param bool $state
  464. * @return void
  465. * @deprecated 1.5 Auto-escape should always be turned on to protect against XSS issues (can be disabled per template file).
  466. */
  467. public function setAutoescape($state)
  468. {
  469. if (!$state) {
  470. user_error(__CLASS__ . '::' . __FUNCTION__ . '(false) is deprecated since Grav 1.5', E_USER_DEPRECATED);
  471. }
  472. $this->autoescape = (bool) $state;
  473. }
  474. }