1a3392ba42eded0adce40a32f0ef10f74cb4c04a
[yaffs-website] / web / core / modules / filter / src / Element / ProcessedText.php
1 <?php
2
3 namespace Drupal\filter\Element;
4
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;
12
13 /**
14  * Provides a processed text render element.
15  *
16  * @RenderElement("processed_text")
17  */
18 class ProcessedText extends RenderElement {
19
20   /**
21    * {@inheritdoc}
22    */
23   public function getInfo() {
24     $class = get_class($this);
25     return [
26       '#text' => '',
27       '#format' => NULL,
28       '#filter_types_to_skip' => [],
29       '#langcode' => '',
30       '#pre_render' => [
31         [$class, 'preRenderText'],
32       ],
33     ];
34   }
35
36   /**
37    * Pre-render callback: Renders a processed text element into #markup.
38    *
39    * Runs all the enabled filters on a piece of text.
40    *
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.
46    *
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
59    *     cannot be skipped.
60    *
61    * @return array
62    *   The passed-in element with the filtered text in '#markup'.
63    *
64    * @ingroup sanitization
65    */
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'];
71
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)
78         ->applyTo($element);
79     }
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'] = '';
88       return $element;
89     }
90
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;
97     };
98
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);
102
103     // Get a complete list of filters, ordered properly.
104     /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
105     $filters = $format->filters();
106
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);
111       }
112     }
113
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();
121       }
122     }
123
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);
130
131     // Set the updated bubbleable rendering metadata and the text format's
132     // cache tag.
133     $metadata->applyTo($element);
134     $element['#cache']['tags'] = Cache::mergeTags($element['#cache']['tags'], $format->getCacheTags());
135
136     return $element;
137   }
138
139   /**
140    * Wraps a logger channel.
141    *
142    * @param string $channel
143    *   The name of the channel.
144    *
145    * @return \Psr\Log\LoggerInterface
146    *   The logger for this channel.
147    */
148   protected static function logger($channel) {
149     return \Drupal::logger($channel);
150   }
151
152   /**
153    * Wraps the config factory.
154    *
155    * @return \Drupal\Core\Config\ConfigFactoryInterface
156    */
157   protected static function configFactory() {
158     return \Drupal::configFactory();
159   }
160
161 }