3 namespace Drupal\filter\Element;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Render\BubbleableMetadata;
8 use Drupal\Core\Render\Element\RenderElement;
9 use Drupal\filter\Entity\FilterFormat;
10 use Drupal\filter\Plugin\FilterInterface;
11 use Drupal\filter\Render\FilteredMarkup;
14 * Provides a processed text render element.
16 * @RenderElement("processed_text")
18 class ProcessedText extends RenderElement {
23 public function getInfo() {
24 $class = get_class($this);
28 '#filter_types_to_skip' => [],
31 [$class, 'preRenderText'],
37 * Pre-render callback: Renders a processed text element into #markup.
39 * Runs all the enabled filters on a piece of text.
41 * Note: Because filters can inject JavaScript or execute PHP code, security
42 * is vital here. When a user supplies a text format, you should validate it
43 * using $format->access() before accepting/using it. This is normally done in
44 * the validation stage of the Form API. You should for example never make a
45 * preview of content in a disallowed format.
47 * @param array $element
48 * A structured array with the following key-value pairs:
49 * - #text: containing the text to be filtered
50 * - #format: containing the machine name of the filter format to be used to
51 * filter the text. Defaults to the fallback format.
52 * - #langcode: the language code of the text to be filtered, e.g. 'en' for
53 * English. This allows filters to be language-aware so language-specific
54 * text replacement can be implemented. Defaults to an empty string.
55 * - #filter_types_to_skip: an array of filter types to skip, or an empty
56 * array (default) to skip no filter types. All of the format's filters
57 * will be applied, except for filters of the types that are marked to be
58 * skipped. FilterInterface::TYPE_HTML_RESTRICTOR is the only type that
62 * The passed-in element with the filtered text in '#markup'.
64 * @ingroup sanitization
66 public static function preRenderText($element) {
67 $format_id = $element['#format'];
68 $filter_types_to_skip = $element['#filter_types_to_skip'];
69 $text = $element['#text'];
70 $langcode = $element['#langcode'];
72 if (!isset($format_id)) {
73 $filter_settings = static::configFactory()->get('filter.settings');
74 $format_id = $filter_settings->get('fallback_format');
75 // Ensure 'filter.settings' config's cacheability is respected.
76 CacheableMetadata::createFromRenderArray($element)
77 ->addCacheableDependency($filter_settings)
80 /** @var \Drupal\filter\Entity\FilterFormat $format **/
81 $format = FilterFormat::load($format_id);
82 // If the requested text format doesn't exist or its disabled, the text
83 // cannot be filtered.
84 if (!$format || !$format->status()) {
85 $message = !$format ? 'Missing text format: %format.' : 'Disabled text format: %format.';
86 static::logger('filter')->alert($message, ['%format' => $format_id]);
87 $element['#markup'] = '';
91 $filter_must_be_applied = function (FilterInterface $filter) use ($filter_types_to_skip) {
92 $enabled = $filter->status === TRUE;
93 $type = $filter->getType();
94 // Prevent FilterInterface::TYPE_HTML_RESTRICTOR from being skipped.
95 $filter_type_must_be_applied = $type == FilterInterface::TYPE_HTML_RESTRICTOR || !in_array($type, $filter_types_to_skip);
96 return $enabled && $filter_type_must_be_applied;
99 // Convert all Windows and Mac newlines to a single newline, so filters only
100 // need to deal with one possibility.
101 $text = str_replace(["\r\n", "\r"], "\n", $text);
103 // Get a complete list of filters, ordered properly.
104 /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
105 $filters = $format->filters();
107 // Give filters a chance to escape HTML-like data such as code or formulas.
108 foreach ($filters as $filter) {
109 if ($filter_must_be_applied($filter)) {
110 $text = $filter->prepare($text, $langcode);
114 // Perform filtering.
115 $metadata = BubbleableMetadata::createFromRenderArray($element);
116 foreach ($filters as $filter) {
117 if ($filter_must_be_applied($filter)) {
118 $result = $filter->process($text, $langcode);
119 $metadata = $metadata->merge($result);
120 $text = $result->getProcessedText();
124 // Filtering and sanitizing have been done in
125 // \Drupal\filter\Plugin\FilterInterface. $text is not guaranteed to be
126 // safe, but it has been passed through the filter system and checked with
127 // a text format, so it must be printed as is. (See the note about security
128 // in the method documentation above.)
129 $element['#markup'] = FilteredMarkup::create($text);
131 // Set the updated bubbleable rendering metadata and the text format's
133 $metadata->applyTo($element);
134 $element['#cache']['tags'] = Cache::mergeTags($element['#cache']['tags'], $format->getCacheTags());
140 * Wraps a logger channel.
142 * @param string $channel
143 * The name of the channel.
145 * @return \Psr\Log\LoggerInterface
146 * The logger for this channel.
148 protected static function logger($channel) {
149 return \Drupal::logger($channel);
153 * Wraps the config factory.
155 * @return \Drupal\Core\Config\ConfigFactoryInterface
157 protected static function configFactory() {
158 return \Drupal::configFactory();