5c7a21234ecc716173b0bb691c8ed289fc0d475f
[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\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;
11
12 /**
13  * Provides a processed text render element.
14  *
15  * @RenderElement("processed_text")
16  */
17 class ProcessedText extends RenderElement {
18
19   /**
20    * {@inheritdoc}
21    */
22   public function getInfo() {
23     $class = get_class($this);
24     return [
25       '#text' => '',
26       '#format' => NULL,
27       '#filter_types_to_skip' => [],
28       '#langcode' => '',
29       '#pre_render' => [
30         [$class, 'preRenderText'],
31       ],
32     ];
33   }
34
35   /**
36    * Pre-render callback: Renders a processed text element into #markup.
37    *
38    * Runs all the enabled filters on a piece of text.
39    *
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.
45    *
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
58    *     cannot be skipped.
59    *
60    * @return array
61    *   The passed-in element with the filtered text in '#markup'.
62    *
63    * @ingroup sanitization
64    */
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'];
70
71     if (!isset($format_id)) {
72       $format_id = static::configFactory()->get('filter.settings')->get('fallback_format');
73     }
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'] = '';
82       return $element;
83     }
84
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;
91     };
92
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);
96
97     // Get a complete list of filters, ordered properly.
98     /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
99     $filters = $format->filters();
100
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);
105       }
106     }
107
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();
115       }
116     }
117
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);
124
125     // Set the updated bubbleable rendering metadata and the text format's
126     // cache tag.
127     $metadata->applyTo($element);
128     $element['#cache']['tags'] = Cache::mergeTags($element['#cache']['tags'], $format->getCacheTags());
129
130     return $element;
131   }
132
133   /**
134    * Wraps a logger channel.
135    *
136    * @param string $channel
137    *   The name of the channel.
138    *
139    * @return \Psr\Log\LoggerInterface
140    *   The logger for this channel.
141    */
142   protected static function logger($channel) {
143     return \Drupal::logger($channel);
144   }
145
146   /**
147    * Wraps the config factory.
148    *
149    * @return \Drupal\Core\Config\ConfigFactoryInterface
150    */
151   protected static function configFactory() {
152     return \Drupal::configFactory();
153   }
154
155 }