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