Renderer.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. <?php
  2. namespace Drupal\Core\Render;
  3. use Drupal\Component\Render\MarkupInterface;
  4. use Drupal\Component\Utility\Html;
  5. use Drupal\Component\Utility\Xss;
  6. use Drupal\Core\Access\AccessResultInterface;
  7. use Drupal\Core\Cache\Cache;
  8. use Drupal\Core\Cache\CacheableMetadata;
  9. use Drupal\Core\Controller\ControllerResolverInterface;
  10. use Drupal\Core\Form\FormHelper;
  11. use Drupal\Core\Render\Element\RenderCallbackInterface;
  12. use Drupal\Core\Security\TrustedCallbackInterface;
  13. use Drupal\Core\Security\DoTrustedCallbackTrait;
  14. use Drupal\Core\Theme\ThemeManagerInterface;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. /**
  17. * Turns a render array into a HTML string.
  18. */
  19. class Renderer implements RendererInterface {
  20. use DoTrustedCallbackTrait;
  21. /**
  22. * The theme manager.
  23. *
  24. * @var \Drupal\Core\Theme\ThemeManagerInterface
  25. */
  26. protected $theme;
  27. /**
  28. * The controller resolver.
  29. *
  30. * @var \Drupal\Core\Controller\ControllerResolverInterface
  31. */
  32. protected $controllerResolver;
  33. /**
  34. * The element info.
  35. *
  36. * @var \Drupal\Core\Render\ElementInfoManagerInterface
  37. */
  38. protected $elementInfo;
  39. /**
  40. * The placeholder generator.
  41. *
  42. * @var \Drupal\Core\Render\PlaceholderGeneratorInterface
  43. */
  44. protected $placeholderGenerator;
  45. /**
  46. * The render cache service.
  47. *
  48. * @var \Drupal\Core\Render\RenderCacheInterface
  49. */
  50. protected $renderCache;
  51. /**
  52. * The renderer configuration array.
  53. *
  54. * @var array
  55. */
  56. protected $rendererConfig;
  57. /**
  58. * Whether we're currently in a ::renderRoot() call.
  59. *
  60. * @var bool
  61. */
  62. protected $isRenderingRoot = FALSE;
  63. /**
  64. * The request stack.
  65. *
  66. * @var \Symfony\Component\HttpFoundation\RequestStack
  67. */
  68. protected $requestStack;
  69. /**
  70. * The render context collection.
  71. *
  72. * An individual global render context is tied to the current request. We then
  73. * need to maintain a different context for each request to correctly handle
  74. * rendering in subrequests.
  75. *
  76. * This must be static as long as some controllers rebuild the container
  77. * during a request. This causes multiple renderer instances to co-exist
  78. * simultaneously, render state getting lost, and therefore causing pages to
  79. * fail to render correctly. As soon as it is guaranteed that during a request
  80. * the same container is used, it no longer needs to be static.
  81. *
  82. * @var \Drupal\Core\Render\RenderContext[]
  83. */
  84. protected static $contextCollection;
  85. /**
  86. * Constructs a new Renderer.
  87. *
  88. * @param \Drupal\Core\Controller\ControllerResolverInterface $controller_resolver
  89. * The controller resolver.
  90. * @param \Drupal\Core\Theme\ThemeManagerInterface $theme
  91. * The theme manager.
  92. * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
  93. * The element info.
  94. * @param \Drupal\Core\Render\PlaceholderGeneratorInterface $placeholder_generator
  95. * The placeholder generator.
  96. * @param \Drupal\Core\Render\RenderCacheInterface $render_cache
  97. * The render cache service.
  98. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  99. * The request stack.
  100. * @param array $renderer_config
  101. * The renderer configuration array.
  102. */
  103. public function __construct(ControllerResolverInterface $controller_resolver, ThemeManagerInterface $theme, ElementInfoManagerInterface $element_info, PlaceholderGeneratorInterface $placeholder_generator, RenderCacheInterface $render_cache, RequestStack $request_stack, array $renderer_config) {
  104. $this->controllerResolver = $controller_resolver;
  105. $this->theme = $theme;
  106. $this->elementInfo = $element_info;
  107. $this->placeholderGenerator = $placeholder_generator;
  108. $this->renderCache = $render_cache;
  109. $this->rendererConfig = $renderer_config;
  110. $this->requestStack = $request_stack;
  111. // Initialize the context collection if needed.
  112. if (!isset(static::$contextCollection)) {
  113. static::$contextCollection = new \SplObjectStorage();
  114. }
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. public function renderRoot(&$elements) {
  120. // Disallow calling ::renderRoot() from within another ::renderRoot() call.
  121. if ($this->isRenderingRoot) {
  122. $this->isRenderingRoot = FALSE;
  123. throw new \LogicException('A stray renderRoot() invocation is causing bubbling of attached assets to break.');
  124. }
  125. // Render in its own render context.
  126. $this->isRenderingRoot = TRUE;
  127. $output = $this->executeInRenderContext(new RenderContext(), function () use (&$elements) {
  128. return $this->render($elements, TRUE);
  129. });
  130. $this->isRenderingRoot = FALSE;
  131. return $output;
  132. }
  133. /**
  134. * {@inheritdoc}
  135. */
  136. public function renderPlain(&$elements) {
  137. return $this->executeInRenderContext(new RenderContext(), function () use (&$elements) {
  138. return $this->render($elements, TRUE);
  139. });
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function renderPlaceholder($placeholder, array $elements) {
  145. // Get the render array for the given placeholder
  146. $placeholder_elements = $elements['#attached']['placeholders'][$placeholder];
  147. // Prevent the render array from being auto-placeholdered again.
  148. $placeholder_elements['#create_placeholder'] = FALSE;
  149. // Render the placeholder into markup.
  150. $markup = $this->renderPlain($placeholder_elements);
  151. // Replace the placeholder with its rendered markup, and merge its
  152. // bubbleable metadata with the main elements'.
  153. $elements['#markup'] = Markup::create(str_replace($placeholder, $markup, $elements['#markup']));
  154. $elements = $this->mergeBubbleableMetadata($elements, $placeholder_elements);
  155. // Remove the placeholder that we've just rendered.
  156. unset($elements['#attached']['placeholders'][$placeholder]);
  157. return $elements;
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function render(&$elements, $is_root_call = FALSE) {
  163. // Since #pre_render, #post_render, #lazy_builder callbacks and theme
  164. // functions or templates may be used for generating a render array's
  165. // content, and we might be rendering the main content for the page, it is
  166. // possible that any of them throw an exception that will cause a different
  167. // page to be rendered (e.g. throwing
  168. // \Symfony\Component\HttpKernel\Exception\NotFoundHttpException will cause
  169. // the 404 page to be rendered). That page might also use
  170. // Renderer::renderRoot() but if exceptions aren't caught here, it will be
  171. // impossible to call Renderer::renderRoot() again.
  172. // Hence, catch all exceptions, reset the isRenderingRoot property and
  173. // re-throw exceptions.
  174. try {
  175. return $this->doRender($elements, $is_root_call);
  176. }
  177. catch (\Exception $e) {
  178. // Mark the ::rootRender() call finished due to this exception & re-throw.
  179. $this->isRenderingRoot = FALSE;
  180. throw $e;
  181. }
  182. }
  183. /**
  184. * See the docs for ::render().
  185. */
  186. protected function doRender(&$elements, $is_root_call = FALSE) {
  187. if (empty($elements)) {
  188. return '';
  189. }
  190. if (!isset($elements['#access']) && isset($elements['#access_callback'])) {
  191. $elements['#access'] = $this->doCallback('#access_callback', $elements['#access_callback'], [$elements]);
  192. }
  193. // Early-return nothing if user does not have access.
  194. if (isset($elements['#access'])) {
  195. // If #access is an AccessResultInterface object, we must apply its
  196. // cacheability metadata to the render array.
  197. if ($elements['#access'] instanceof AccessResultInterface) {
  198. $this->addCacheableDependency($elements, $elements['#access']);
  199. if (!$elements['#access']->isAllowed()) {
  200. return '';
  201. }
  202. }
  203. elseif ($elements['#access'] === FALSE) {
  204. return '';
  205. }
  206. }
  207. // Do not print elements twice.
  208. if (!empty($elements['#printed'])) {
  209. return '';
  210. }
  211. $context = $this->getCurrentRenderContext();
  212. if (!isset($context)) {
  213. throw new \LogicException("Render context is empty, because render() was called outside of a renderRoot() or renderPlain() call. Use renderPlain()/renderRoot() or #lazy_builder/#pre_render instead.");
  214. }
  215. $context->push(new BubbleableMetadata());
  216. // Set the bubbleable rendering metadata that has configurable defaults, if:
  217. // - this is the root call, to ensure that the final render array definitely
  218. // has these configurable defaults, even when no subtree is render cached.
  219. // - this is a render cacheable subtree, to ensure that the cached data has
  220. // the configurable defaults (which may affect the ID and invalidation).
  221. if ($is_root_call || isset($elements['#cache']['keys'])) {
  222. $required_cache_contexts = $this->rendererConfig['required_cache_contexts'];
  223. if (isset($elements['#cache']['contexts'])) {
  224. $elements['#cache']['contexts'] = Cache::mergeContexts($elements['#cache']['contexts'], $required_cache_contexts);
  225. }
  226. else {
  227. $elements['#cache']['contexts'] = $required_cache_contexts;
  228. }
  229. }
  230. // Try to fetch the prerendered element from cache, replace any placeholders
  231. // and return the final markup.
  232. if (isset($elements['#cache']['keys'])) {
  233. $cached_element = $this->renderCache->get($elements);
  234. if ($cached_element !== FALSE) {
  235. $elements = $cached_element;
  236. // Only when we're in a root (non-recursive) Renderer::render() call,
  237. // placeholders must be processed, to prevent breaking the render cache
  238. // in case of nested elements with #cache set.
  239. if ($is_root_call) {
  240. $this->replacePlaceholders($elements);
  241. }
  242. // Mark the element markup as safe if is it a string.
  243. if (is_string($elements['#markup'])) {
  244. $elements['#markup'] = Markup::create($elements['#markup']);
  245. }
  246. // The render cache item contains all the bubbleable rendering metadata
  247. // for the subtree.
  248. $context->update($elements);
  249. // Render cache hit, so rendering is finished, all necessary info
  250. // collected!
  251. $context->bubble();
  252. return $elements['#markup'];
  253. }
  254. }
  255. // Two-tier caching: track pre-bubbling elements' #cache, #lazy_builder and
  256. // #create_placeholder for later comparison.
  257. // @see \Drupal\Core\Render\RenderCacheInterface::get()
  258. // @see \Drupal\Core\Render\RenderCacheInterface::set()
  259. $pre_bubbling_elements = array_intersect_key($elements, [
  260. '#cache' => TRUE,
  261. '#lazy_builder' => TRUE,
  262. '#create_placeholder' => TRUE,
  263. ]);
  264. // If the default values for this element have not been loaded yet, populate
  265. // them.
  266. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  267. $elements += $this->elementInfo->getInfo($elements['#type']);
  268. }
  269. // First validate the usage of #lazy_builder; both of the next if-statements
  270. // use it if available.
  271. if (isset($elements['#lazy_builder'])) {
  272. // @todo Convert to assertions once https://www.drupal.org/node/2408013
  273. // lands.
  274. if (!is_array($elements['#lazy_builder'])) {
  275. throw new \DomainException('The #lazy_builder property must have an array as a value.');
  276. }
  277. if (count($elements['#lazy_builder']) !== 2) {
  278. throw new \DomainException('The #lazy_builder property must have an array as a value, containing two values: the callback, and the arguments for the callback.');
  279. }
  280. if (count($elements['#lazy_builder'][1]) !== count(array_filter($elements['#lazy_builder'][1], function ($v) {
  281. return is_null($v) || is_scalar($v);
  282. }))) {
  283. throw new \DomainException("A #lazy_builder callback's context may only contain scalar values or NULL.");
  284. }
  285. $children = Element::children($elements);
  286. if ($children) {
  287. throw new \DomainException(sprintf('When a #lazy_builder callback is specified, no children can exist; all children must be generated by the #lazy_builder callback. You specified the following children: %s.', implode(', ', $children)));
  288. }
  289. $supported_keys = [
  290. '#lazy_builder',
  291. '#cache',
  292. '#create_placeholder',
  293. // The keys below are not actually supported, but these are added
  294. // automatically by the Renderer. Adding them as though they are
  295. // supported allows us to avoid throwing an exception 100% of the time.
  296. '#weight',
  297. '#printed',
  298. ];
  299. $unsupported_keys = array_diff(array_keys($elements), $supported_keys);
  300. if (count($unsupported_keys)) {
  301. throw new \DomainException(sprintf('When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: %s.', implode(', ', $unsupported_keys)));
  302. }
  303. }
  304. // Determine whether to do auto-placeholdering.
  305. if ($this->placeholderGenerator->canCreatePlaceholder($elements) && $this->placeholderGenerator->shouldAutomaticallyPlaceholder($elements)) {
  306. $elements['#create_placeholder'] = TRUE;
  307. }
  308. // If instructed to create a placeholder, and a #lazy_builder callback is
  309. // present (without such a callback, it would be impossible to replace the
  310. // placeholder), replace the current element with a placeholder.
  311. // @todo remove the isMethodCacheable() check when
  312. // https://www.drupal.org/node/2367555 lands.
  313. if (isset($elements['#create_placeholder']) && $elements['#create_placeholder'] === TRUE && $this->requestStack->getCurrentRequest()->isMethodCacheable()) {
  314. if (!isset($elements['#lazy_builder'])) {
  315. throw new \LogicException('When #create_placeholder is set, a #lazy_builder callback must be present as well.');
  316. }
  317. $elements = $this->placeholderGenerator->createPlaceholder($elements);
  318. }
  319. // Build the element if it is still empty.
  320. if (isset($elements['#lazy_builder'])) {
  321. $new_elements = $this->doCallback('#lazy_builder', $elements['#lazy_builder'][0], $elements['#lazy_builder'][1]);
  322. // Retain the original cacheability metadata, plus cache keys.
  323. CacheableMetadata::createFromRenderArray($elements)
  324. ->merge(CacheableMetadata::createFromRenderArray($new_elements))
  325. ->applyTo($new_elements);
  326. if (isset($elements['#cache']['keys'])) {
  327. $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
  328. }
  329. $elements = $new_elements;
  330. $elements['#lazy_builder_built'] = TRUE;
  331. }
  332. // Make any final changes to the element before it is rendered. This means
  333. // that the $element or the children can be altered or corrected before the
  334. // element is rendered into the final text.
  335. if (isset($elements['#pre_render'])) {
  336. foreach ($elements['#pre_render'] as $callable) {
  337. $elements = $this->doCallback('#pre_render', $callable, [$elements]);
  338. }
  339. }
  340. // All render elements support #markup and #plain_text.
  341. if (isset($elements['#markup']) || isset($elements['#plain_text'])) {
  342. $elements = $this->ensureMarkupIsSafe($elements);
  343. }
  344. // Defaults for bubbleable rendering metadata.
  345. $elements['#cache']['tags'] = isset($elements['#cache']['tags']) ? $elements['#cache']['tags'] : [];
  346. $elements['#cache']['max-age'] = isset($elements['#cache']['max-age']) ? $elements['#cache']['max-age'] : Cache::PERMANENT;
  347. $elements['#attached'] = isset($elements['#attached']) ? $elements['#attached'] : [];
  348. // Allow #pre_render to abort rendering.
  349. if (!empty($elements['#printed'])) {
  350. // The #printed element contains all the bubbleable rendering metadata for
  351. // the subtree.
  352. $context->update($elements);
  353. // #printed, so rendering is finished, all necessary info collected!
  354. $context->bubble();
  355. return '';
  356. }
  357. // Add any JavaScript state information associated with the element.
  358. if (!empty($elements['#states'])) {
  359. FormHelper::processStates($elements);
  360. }
  361. // Get the children of the element, sorted by weight.
  362. $children = Element::children($elements, TRUE);
  363. // Initialize this element's #children, unless a #pre_render callback
  364. // already preset #children.
  365. if (!isset($elements['#children'])) {
  366. $elements['#children'] = '';
  367. }
  368. // Assume that if #theme is set it represents an implemented hook.
  369. $theme_is_implemented = isset($elements['#theme']);
  370. // Check the elements for insecure HTML and pass through sanitization.
  371. if (isset($elements)) {
  372. $markup_keys = [
  373. '#description',
  374. '#field_prefix',
  375. '#field_suffix',
  376. ];
  377. foreach ($markup_keys as $key) {
  378. if (!empty($elements[$key]) && is_scalar($elements[$key])) {
  379. $elements[$key] = $this->xssFilterAdminIfUnsafe($elements[$key]);
  380. }
  381. }
  382. }
  383. // Call the element's #theme function if it is set. Then any children of the
  384. // element have to be rendered there. If the internal #render_children
  385. // property is set, do not call the #theme function to prevent infinite
  386. // recursion.
  387. if ($theme_is_implemented && !isset($elements['#render_children'])) {
  388. $elements['#children'] = $this->theme->render($elements['#theme'], $elements);
  389. // If ThemeManagerInterface::render() returns FALSE this means that the
  390. // hook in #theme was not found in the registry and so we need to update
  391. // our flag accordingly. This is common for theme suggestions.
  392. $theme_is_implemented = ($elements['#children'] !== FALSE);
  393. }
  394. // If #theme is not implemented or #render_children is set and the element
  395. // has an empty #children attribute, render the children now. This is the
  396. // same process as Renderer::render() but is inlined for speed.
  397. if ((!$theme_is_implemented || isset($elements['#render_children'])) && empty($elements['#children'])) {
  398. foreach ($children as $key) {
  399. $elements['#children'] .= $this->doRender($elements[$key]);
  400. }
  401. $elements['#children'] = Markup::create($elements['#children']);
  402. }
  403. // If #theme is not implemented and the element has raw #markup as a
  404. // fallback, prepend the content in #markup to #children. In this case
  405. // #children will contain whatever is provided by #pre_render prepended to
  406. // what is rendered recursively above. If #theme is implemented then it is
  407. // the responsibility of that theme implementation to render #markup if
  408. // required. Eventually #theme_wrappers will expect both #markup and
  409. // #children to be a single string as #children.
  410. if (!$theme_is_implemented && isset($elements['#markup'])) {
  411. $elements['#children'] = Markup::create($elements['#markup'] . $elements['#children']);
  412. }
  413. // Let the theme functions in #theme_wrappers add markup around the rendered
  414. // children.
  415. // #states and #attached have to be processed before #theme_wrappers,
  416. // because the #type 'page' render array from drupal_prepare_page() would
  417. // render the $page and wrap it into the html.html.twig template without the
  418. // attached assets otherwise.
  419. // If the internal #render_children property is set, do not call the
  420. // #theme_wrappers function(s) to prevent infinite recursion.
  421. if (isset($elements['#theme_wrappers']) && !isset($elements['#render_children'])) {
  422. foreach ($elements['#theme_wrappers'] as $key => $value) {
  423. // If the value of a #theme_wrappers item is an array then the theme
  424. // hook is found in the key of the item and the value contains attribute
  425. // overrides. Attribute overrides replace key/value pairs in $elements
  426. // for only this ThemeManagerInterface::render() call. This allows
  427. // #theme hooks and #theme_wrappers hooks to share variable names
  428. // without conflict or ambiguity.
  429. $wrapper_elements = $elements;
  430. if (is_string($key)) {
  431. $wrapper_hook = $key;
  432. foreach ($value as $attribute => $override) {
  433. $wrapper_elements[$attribute] = $override;
  434. }
  435. }
  436. else {
  437. $wrapper_hook = $value;
  438. }
  439. $elements['#children'] = $this->theme->render($wrapper_hook, $wrapper_elements);
  440. }
  441. }
  442. // Filter the outputted content and make any last changes before the content
  443. // is sent to the browser. The changes are made on $content which allows the
  444. // outputted text to be filtered.
  445. if (isset($elements['#post_render'])) {
  446. foreach ($elements['#post_render'] as $callable) {
  447. $elements['#children'] = $this->doCallback('#post_render', $callable, [$elements['#children'], $elements]);
  448. }
  449. }
  450. // We store the resulting output in $elements['#markup'], to be consistent
  451. // with how render cached output gets stored. This ensures that placeholder
  452. // replacement logic gets the same data to work with, no matter if #cache is
  453. // disabled, #cache is enabled, there is a cache hit or miss. If
  454. // #render_children is set the #prefix and #suffix will have already been
  455. // added.
  456. if (isset($elements['#render_children'])) {
  457. $elements['#markup'] = Markup::create($elements['#children']);
  458. }
  459. else {
  460. $prefix = isset($elements['#prefix']) ? $this->xssFilterAdminIfUnsafe($elements['#prefix']) : '';
  461. $suffix = isset($elements['#suffix']) ? $this->xssFilterAdminIfUnsafe($elements['#suffix']) : '';
  462. $elements['#markup'] = Markup::create($prefix . $elements['#children'] . $suffix);
  463. }
  464. // We've rendered this element (and its subtree!), now update the context.
  465. $context->update($elements);
  466. // Cache the processed element if both $pre_bubbling_elements and $elements
  467. // have the metadata necessary to generate a cache ID.
  468. if (isset($pre_bubbling_elements['#cache']['keys']) && isset($elements['#cache']['keys'])) {
  469. if ($pre_bubbling_elements['#cache']['keys'] !== $elements['#cache']['keys']) {
  470. throw new \LogicException('Cache keys may not be changed after initial setup. Use the contexts property instead to bubble additional metadata.');
  471. }
  472. $this->renderCache->set($elements, $pre_bubbling_elements);
  473. // Update the render context; the render cache implementation may update
  474. // the element, and it may have different bubbleable metadata now.
  475. // @see \Drupal\Core\Render\PlaceholderingRenderCache::set()
  476. $context->pop();
  477. $context->push(new BubbleableMetadata());
  478. $context->update($elements);
  479. }
  480. // Only when we're in a root (non-recursive) Renderer::render() call,
  481. // placeholders must be processed, to prevent breaking the render cache in
  482. // case of nested elements with #cache set.
  483. //
  484. // By running them here, we ensure that:
  485. // - they run when #cache is disabled,
  486. // - they run when #cache is enabled and there is a cache miss.
  487. // Only the case of a cache hit when #cache is enabled, is not handled here,
  488. // that is handled earlier in Renderer::render().
  489. if ($is_root_call) {
  490. $this->replacePlaceholders($elements);
  491. // @todo remove as part of https://www.drupal.org/node/2511330.
  492. if ($context->count() !== 1) {
  493. throw new \LogicException('A stray drupal_render() invocation with $is_root_call = TRUE is causing bubbling of attached assets to break.');
  494. }
  495. }
  496. // Rendering is finished, all necessary info collected!
  497. $context->bubble();
  498. $elements['#printed'] = TRUE;
  499. return $elements['#markup'];
  500. }
  501. /**
  502. * {@inheritdoc}
  503. */
  504. public function hasRenderContext() {
  505. return (bool) $this->getCurrentRenderContext();
  506. }
  507. /**
  508. * {@inheritdoc}
  509. */
  510. public function executeInRenderContext(RenderContext $context, callable $callable) {
  511. // Store the current render context.
  512. $previous_context = $this->getCurrentRenderContext();
  513. // Set the provided context and call the callable, it will use that context.
  514. $this->setCurrentRenderContext($context);
  515. $result = $callable();
  516. // @todo Convert to an assertion in https://www.drupal.org/node/2408013
  517. if ($context->count() > 1) {
  518. throw new \LogicException('Bubbling failed.');
  519. }
  520. // Restore the original render context.
  521. $this->setCurrentRenderContext($previous_context);
  522. return $result;
  523. }
  524. /**
  525. * Returns the current render context.
  526. *
  527. * @return \Drupal\Core\Render\RenderContext
  528. * The current render context.
  529. */
  530. protected function getCurrentRenderContext() {
  531. $request = $this->requestStack->getCurrentRequest();
  532. return isset(static::$contextCollection[$request]) ? static::$contextCollection[$request] : NULL;
  533. }
  534. /**
  535. * Sets the current render context.
  536. *
  537. * @param \Drupal\Core\Render\RenderContext|null $context
  538. * The render context. This can be NULL for instance when restoring the
  539. * original render context, which is in fact NULL.
  540. *
  541. * @return $this
  542. */
  543. protected function setCurrentRenderContext(RenderContext $context = NULL) {
  544. $request = $this->requestStack->getCurrentRequest();
  545. static::$contextCollection[$request] = $context;
  546. return $this;
  547. }
  548. /**
  549. * Replaces placeholders.
  550. *
  551. * Placeholders may have:
  552. * - #lazy_builder callback, to build a render array to be rendered into
  553. * markup that can replace the placeholder
  554. * - #cache: to cache the result of the placeholder
  555. *
  556. * Also merges the bubbleable metadata resulting from the rendering of the
  557. * contents of the placeholders. Hence $elements will be contain the entirety
  558. * of bubbleable metadata.
  559. *
  560. * @param array &$elements
  561. * The structured array describing the data being rendered. Including the
  562. * bubbleable metadata associated with the markup that replaced the
  563. * placeholders.
  564. *
  565. * @returns bool
  566. * Whether placeholders were replaced.
  567. *
  568. * @see \Drupal\Core\Render\Renderer::renderPlaceholder()
  569. */
  570. protected function replacePlaceholders(array &$elements) {
  571. if (!isset($elements['#attached']['placeholders']) || empty($elements['#attached']['placeholders'])) {
  572. return FALSE;
  573. }
  574. // The 'status messages' placeholder needs to be special cased, because it
  575. // depends on global state that can be modified when other placeholders are
  576. // being rendered: any code can add messages to render.
  577. // This violates the principle that each lazy builder must be able to render
  578. // itself in isolation, and therefore in any order. However, we cannot
  579. // change the way \Drupal\Core\Messenger\Messenger works in the Drupal 8
  580. // cycle. So we have to accommodate its special needs.
  581. // Allowing placeholders to be rendered in a particular order (in this case:
  582. // last) would violate this isolation principle. Thus a monopoly is granted
  583. // to this one special case, with this hard-coded solution.
  584. // @see \Drupal\Core\Render\Element\StatusMessages
  585. // @see https://www.drupal.org/node/2712935#comment-11368923
  586. // First render all placeholders except 'status messages' placeholders.
  587. $message_placeholders = [];
  588. foreach ($elements['#attached']['placeholders'] as $placeholder => $placeholder_element) {
  589. if (isset($placeholder_element['#lazy_builder']) && $placeholder_element['#lazy_builder'][0] === 'Drupal\Core\Render\Element\StatusMessages::renderMessages') {
  590. $message_placeholders[] = $placeholder;
  591. }
  592. else {
  593. $elements = $this->renderPlaceholder($placeholder, $elements);
  594. }
  595. }
  596. // Then render 'status messages' placeholders.
  597. foreach ($message_placeholders as $message_placeholder) {
  598. $elements = $this->renderPlaceholder($message_placeholder, $elements);
  599. }
  600. return TRUE;
  601. }
  602. /**
  603. * {@inheritdoc}
  604. */
  605. public function mergeBubbleableMetadata(array $a, array $b) {
  606. $meta_a = BubbleableMetadata::createFromRenderArray($a);
  607. $meta_b = BubbleableMetadata::createFromRenderArray($b);
  608. $meta_a->merge($meta_b)->applyTo($a);
  609. return $a;
  610. }
  611. /**
  612. * {@inheritdoc}
  613. */
  614. public function addCacheableDependency(array &$elements, $dependency) {
  615. $meta_a = CacheableMetadata::createFromRenderArray($elements);
  616. $meta_b = CacheableMetadata::createFromObject($dependency);
  617. $meta_a->merge($meta_b)->applyTo($elements);
  618. }
  619. /**
  620. * Applies a very permissive XSS/HTML filter for admin-only use.
  621. *
  622. * Note: This method only filters if $string is not marked safe already. This
  623. * ensures that HTML intended for display is not filtered.
  624. *
  625. * @param string|\Drupal\Core\Render\Markup $string
  626. * A string.
  627. *
  628. * @return \Drupal\Core\Render\Markup
  629. * The escaped string wrapped in a Markup object. If the string is an
  630. * instance of \Drupal\Component\Render\MarkupInterface, it won't be escaped
  631. * again.
  632. */
  633. protected function xssFilterAdminIfUnsafe($string) {
  634. if (!($string instanceof MarkupInterface)) {
  635. $string = Xss::filterAdmin($string);
  636. }
  637. return Markup::create($string);
  638. }
  639. /**
  640. * Escapes #plain_text or filters #markup as required.
  641. *
  642. * Drupal uses Twig's auto-escape feature to improve security. This feature
  643. * automatically escapes any HTML that is not known to be safe. Due to this
  644. * the render system needs to ensure that all markup it generates is marked
  645. * safe so that Twig does not do any additional escaping.
  646. *
  647. * By default all #markup is filtered to protect against XSS using the admin
  648. * tag list. Render arrays can alter the list of tags allowed by the filter
  649. * using the #allowed_tags property. This value should be an array of tags
  650. * that Xss::filter() would accept. Render arrays can escape text instead
  651. * of XSS filtering by setting the #plain_text property instead of #markup. If
  652. * #plain_text is used #allowed_tags is ignored.
  653. *
  654. * @param array $elements
  655. * A render array with #markup set.
  656. *
  657. * @return \Drupal\Component\Render\MarkupInterface|string
  658. * The escaped markup wrapped in a Markup object. If $elements['#markup']
  659. * is an instance of \Drupal\Component\Render\MarkupInterface, it won't be
  660. * escaped or filtered again.
  661. *
  662. * @see \Drupal\Component\Utility\Html::escape()
  663. * @see \Drupal\Component\Utility\Xss::filter()
  664. * @see \Drupal\Component\Utility\Xss::filterAdmin()
  665. */
  666. protected function ensureMarkupIsSafe(array $elements) {
  667. if (isset($elements['#plain_text'])) {
  668. $elements['#markup'] = Markup::create(Html::escape($elements['#plain_text']));
  669. }
  670. elseif (!($elements['#markup'] instanceof MarkupInterface)) {
  671. // The default behavior is to XSS filter using the admin tag list.
  672. $tags = isset($elements['#allowed_tags']) ? $elements['#allowed_tags'] : Xss::getAdminTagList();
  673. $elements['#markup'] = Markup::create(Xss::filter($elements['#markup'], $tags));
  674. }
  675. return $elements;
  676. }
  677. /**
  678. * Performs a callback.
  679. *
  680. * @param string $callback_type
  681. * The type of the callback. For example, '#post_render'.
  682. * @param string|callable $callback
  683. * The callback to perform.
  684. * @param array $args
  685. * The arguments to pass to the callback.
  686. *
  687. * @return mixed
  688. * The callback's return value.
  689. *
  690. * @see \Drupal\Core\Security\TrustedCallbackInterface
  691. */
  692. protected function doCallback($callback_type, $callback, array $args) {
  693. if (is_string($callback)) {
  694. $double_colon = strpos($callback, '::');
  695. if ($double_colon === FALSE) {
  696. $callback = $this->controllerResolver->getControllerFromDefinition($callback);
  697. }
  698. elseif ($double_colon > 0) {
  699. $callback = explode('::', $callback, 2);
  700. }
  701. }
  702. $message = sprintf('Render %s callbacks must be methods of a class that implements \Drupal\Core\Security\TrustedCallbackInterface or be an anonymous function. The callback was %s. Support for this callback implementation is deprecated in 8.8.0 and will be removed in Drupal 9.0.0. See https://www.drupal.org/node/2966725', $callback_type, '%s');
  703. // Add \Drupal\Core\Render\Element\RenderCallbackInterface as an extra
  704. // trusted interface so that:
  705. // - All public methods on Render elements are considered trusted.
  706. // - Helper classes that contain only callback methods can implement this
  707. // instead of TrustedCallbackInterface.
  708. return $this->doTrustedCallback($callback, $args, $message, TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION, RenderCallbackInterface::class);
  709. }
  710. }