Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / filter / filter.module
1 <?php
2
3 /**
4  * @file
5  * Framework for handling the filtering of content.
6  */
7
8 use Drupal\Component\Utility\Html;
9 use Drupal\Component\Utility\Unicode;
10 use Drupal\Core\Cache\Cache;
11 use Drupal\Core\Routing\RouteMatchInterface;
12 use Drupal\Core\Session\AccountInterface;
13 use Drupal\Core\Template\Attribute;
14 use Drupal\filter\FilterFormatInterface;
15
16 /**
17  * Implements hook_help().
18  */
19 function filter_help($route_name, RouteMatchInterface $route_match) {
20   switch ($route_name) {
21     case 'help.page.filter':
22       $output = '';
23       $output .= '<h3>' . t('About') . '</h3>';
24       $output .= '<p>' . t('The Filter module allows administrators to configure text formats. Text formats change how HTML tags and other text will be <em>processed and displayed</em> in the site. They are used to transform text, and also help to defend your web site against potentially damaging input from malicious users. Visual text editors can be associated with text formats by using the <a href=":editor_help">Text Editor module</a>. For more information, see the <a href=":filter_do">online documentation for the Filter module</a>.', [':filter_do' => 'https://www.drupal.org/documentation/modules/filter/', ':editor_help' => (\Drupal::moduleHandler()->moduleExists('editor')) ? \Drupal::url('help.page', ['name' => 'editor']) : '#']) . '</p>';
25       $output .= '<h3>' . t('Uses') . '</h3>';
26       $output .= '<dl>';
27       $output .= '<dt>' . t('Managing text formats') . '</dt>';
28       $output .= '<dd>' . t('You can create and edit text formats on the <a href=":formats">Text formats page</a> (if the Text Editor module is enabled, this page is named Text formats and editors). One text format is included by default: Plain text (which removes all HTML tags). Additional text formats may be created during installation. You can create a text format by clicking "<a href=":add_format">Add text format</a>".', [':formats' => \Drupal::url('filter.admin_overview'), ':add_format' => \Drupal::url('filter.format_add')]) . '</dd>';
29       $output .= '<dt>' . t('Assigning roles to text formats') . '</dt>';
30       $output .= '<dd>' . t('You can define which users will be able to use each text format by selecting roles. To ensure security, anonymous and untrusted users should only have access to text formats that restrict them to either plain text or a safe set of HTML tags. This is because HTML tags can allow embedding malicious links or scripts in text. More trusted registered users may be granted permission to use less restrictive text formats in order to create rich text. <strong>Improper text format configuration is a security risk.</strong>') . '</dd>';
31       $output .= '<dt>' . t('Selecting filters') . '</dt>';
32       $output .= '<dd>' . t('Each text format uses filters that add, remove, or transform elements within user-entered text. For example, one filter removes unapproved HTML tags, while another transforms URLs into clickable links. Filters are applied in a specific order. They do not change the <em>stored</em> content: they define how it is processed and displayed.') . '</dd>';
33       $output .= '<dd>' . t('Each filter can have additional configuration options. For example, for the "Limit allowed HTML tags" filter you need to define the list of HTML tags that the filter leaves in the text.') . '</dd>';
34       $output .= '<dt>' . t('Using text fields with text formats') . '</dt>';
35       $output .= '<dd>' . t('Text fields that allow text formats are those with "formatted" in the description. These are <em>Text (formatted, long, with summary)</em>, <em>Text (formatted)</em>, and <em>Text (formatted, long)</em>. You cannot change the type of field once a field has been created.') . '</dd>';
36       $output .= '<dt>' . t('Choosing a text format') . '</dt>';
37       $output .= '<dd>' . t('When creating or editing data in a field that has text formats enabled, users can select the format under the field from the Text format select list.') . '</dd>';
38       $output .= '</dl>';
39       return $output;
40
41     case 'filter.admin_overview':
42       $output = '<p>' . t('Text formats define how text is filtered for output and how HTML tags and other text is displayed, replaced, or removed. <strong>Improper text format configuration is a security risk.</strong> Learn more on the <a href=":filter_help">Filter module help page</a>.', [':filter_help' => \Drupal::url('help.page', ['name' => 'filter'])]) . '</p>';
43       $output .= '<p>' . t('Text formats are presented on content editing pages in the order defined on this page. The first format available to a user will be selected by default.') . '</p>';
44       return $output;
45
46     case 'entity.filter_format.edit_form':
47       $output = '<p>' . t('A text format contains filters that change the display of user input; for example, stripping out malicious HTML or making URLs clickable. Filters are executed from top to bottom and the order is important, since one filter may prevent another filter from doing its job. For example, when URLs are converted into links before disallowed HTML tags are removed, all links may be removed. When this happens, the order of filters may need to be rearranged.') . '</p>';
48       return $output;
49   }
50 }
51
52 /**
53  * Implements hook_theme().
54  */
55 function filter_theme() {
56   return [
57     'filter_tips' => [
58       'variables' => ['tips' => NULL, 'long' => FALSE],
59     ],
60     'text_format_wrapper' => [
61       'variables' => [
62         'children' => NULL,
63         'description' => NULL,
64         'attributes' => [],
65       ],
66     ],
67     'filter_guidelines' => [
68       'variables' => ['format' => NULL],
69     ],
70     'filter_caption' => [
71       'variables' => [
72         'node' => NULL,
73         'tag' => NULL,
74         'caption' => NULL,
75         'classes' => NULL,
76       ],
77     ]
78   ];
79 }
80
81 /**
82  * Retrieves a list of enabled text formats, ordered by weight.
83  *
84  * @param \Drupal\Core\Session\AccountInterface|null $account
85  *   (optional) If provided, only those formats that are allowed for this user
86  *   account will be returned. All enabled formats will be returned otherwise.
87  *   Defaults to NULL.
88  *
89  * @return \Drupal\filter\FilterFormatInterface[]
90  *   An array of text format objects, keyed by the format ID and ordered by
91  *   weight.
92  *
93  * @see filter_formats_reset()
94  */
95 function filter_formats(AccountInterface $account = NULL) {
96   $formats = &drupal_static(__FUNCTION__, []);
97
98   // All available formats are cached for performance.
99   if (!isset($formats['all'])) {
100     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
101     if ($cache = \Drupal::cache()->get("filter_formats:{$language_interface->getId()}")) {
102       $formats['all'] = $cache->data;
103     }
104     else {
105       $formats['all'] = \Drupal::entityManager()->getStorage('filter_format')->loadByProperties(['status' => TRUE]);
106       uasort($formats['all'], 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
107       \Drupal::cache()->set("filter_formats:{$language_interface->getId()}", $formats['all'], Cache::PERMANENT, \Drupal::entityManager()->getDefinition('filter_format')->getListCacheTags());
108     }
109   }
110
111   // If no user was specified, return all formats.
112   if (!isset($account)) {
113     return $formats['all'];
114   }
115
116   // Build a list of user-specific formats.
117   $account_id = $account->id();
118   if (!isset($formats['user'][$account_id])) {
119     $formats['user'][$account_id] = [];
120     foreach ($formats['all'] as $format) {
121       if ($format->access('use', $account)) {
122         $formats['user'][$account_id][$format->id()] = $format;
123       }
124     }
125   }
126
127   return $formats['user'][$account_id];
128 }
129
130 /**
131  * Resets the text format caches.
132  *
133  * @see filter_formats()
134  */
135 function filter_formats_reset() {
136   drupal_static_reset('filter_formats');
137 }
138
139 /**
140  * Retrieves a list of roles that are allowed to use a given text format.
141  *
142  * @param \Drupal\filter\FilterFormatInterface $format
143  *   An object representing the text format.
144  *
145  * @return array
146  *   An array of role names, keyed by role ID.
147  */
148 function filter_get_roles_by_format(FilterFormatInterface $format) {
149   // Handle the fallback format upfront (all roles have access to this format).
150   if ($format->isFallbackFormat()) {
151     return user_role_names();
152   }
153   // Do not list any roles if the permission does not exist.
154   $permission = $format->getPermissionName();
155   return !empty($permission) ? user_role_names(FALSE, $permission) : [];
156 }
157
158 /**
159  * Retrieves a list of text formats that are allowed for a given role.
160  *
161  * @param string $rid
162  *   The user role ID to retrieve text formats for.
163  *
164  * @return \Drupal\filter\FilterFormatInterface[]
165  *   An array of text format objects that are allowed for the role, keyed by
166  *   the text format ID and ordered by weight.
167  */
168 function filter_get_formats_by_role($rid) {
169   $formats = [];
170   foreach (filter_formats() as $format) {
171     $roles = filter_get_roles_by_format($format);
172     if (isset($roles[$rid])) {
173       $formats[$format->id()] = $format;
174     }
175   }
176   return $formats;
177 }
178
179 /**
180  * Returns the ID of the default text format for a particular user.
181  *
182  * The default text format is the first available format that the user is
183  * allowed to access, when the formats are ordered by weight. It should
184  * generally be used as a default choice when presenting the user with a list
185  * of possible text formats (for example, in a node creation form).
186  *
187  * Conversely, when existing content that does not have an assigned text format
188  * needs to be filtered for display, the default text format is the wrong
189  * choice, because it is not guaranteed to be consistent from user to user, and
190  * some trusted users may have an unsafe text format set by default, which
191  * should not be used on text of unknown origin. Instead, the fallback format
192  * returned by filter_fallback_format() should be used, since that is intended
193  * to be a safe, consistent format that is always available to all users.
194  *
195  * @param \Drupal\Core\Session\AccountInterface|null $account
196  *   (optional) The user account to check. Defaults to the currently logged-in
197  *   user. Defaults to NULL.
198  *
199  * @return string
200  *   The ID of the user's default text format.
201  *
202  * @see filter_fallback_format()
203  */
204 function filter_default_format(AccountInterface $account = NULL) {
205   if (!isset($account)) {
206     $account = \Drupal::currentUser();
207   }
208   // Get a list of formats for this user, ordered by weight. The first one
209   // available is the user's default format.
210   $formats = filter_formats($account);
211   $format = reset($formats);
212   return $format->id();
213 }
214
215 /**
216  * Returns the ID of the fallback text format that all users have access to.
217  *
218  * The fallback text format is a regular text format in every respect, except
219  * it does not participate in the filter permission system and cannot be
220  * disabled. It needs to exist because any user who has permission to create
221  * formatted content must always have at least one text format they can use.
222  *
223  * Because the fallback format is available to all users, it should always be
224  * configured securely. For example, when the Filter module is installed, this
225  * format is initialized to output plain text. Installation profiles and site
226  * administrators have the freedom to configure it further.
227  *
228  * Note that the fallback format is completely distinct from the default format,
229  * which differs per user and is simply the first format which that user has
230  * access to. The default and fallback formats are only guaranteed to be the
231  * same for users who do not have access to any other format; otherwise, the
232  * fallback format's weight determines its placement with respect to the user's
233  * other formats.
234  *
235  * Any modules implementing a format deletion functionality must not delete this
236  * format.
237  *
238  * @return string|null
239  *   The ID of the fallback text format.
240  *
241  * @see hook_filter_format_disable()
242  * @see filter_default_format()
243  */
244 function filter_fallback_format() {
245   // This variable is automatically set in the database for all installations
246   // of Drupal. In the event that it gets disabled or deleted somehow, there
247   // is no safe default to return, since we do not want to risk making an
248   // existing (and potentially unsafe) text format on the site automatically
249   // available to all users. Returning NULL at least guarantees that this
250   // cannot happen.
251   return \Drupal::config('filter.settings')->get('fallback_format');
252 }
253
254 /**
255  * Runs all the enabled filters on a piece of text.
256  *
257  * Note: Because filters can inject JavaScript or execute PHP code, security is
258  * vital here. When a user supplies a text format, you should validate it using
259  * $format->access() before accepting/using it. This is normally done in the
260  * validation stage of the Form API. You should for example never make a
261  * preview of content in a disallowed format.
262  *
263  * Note: this function should only be used when filtering text for use elsewhere
264  * than on a rendered HTML page. If this is part of a HTML page, then a
265  * renderable array with a #type 'processed_text' element should be used instead
266  * of this, because that will allow cacheability metadata to be set and bubbled
267  * up and attachments to be associated (assets, placeholders, etc.). In other
268  * words: if you are presenting the filtered text in a HTML page, the only way
269  * this will be presented correctly, is by using the 'processed_text' element.
270  *
271  * @param string $text
272  *   The text to be filtered.
273  * @param string|null $format_id
274  *   (optional) The machine name of the filter format to be used to filter the
275  *   text. Defaults to the fallback format. See filter_fallback_format().
276  * @param string $langcode
277  *   (optional) The language code of the text to be filtered, e.g. 'en' for
278  *   English. This allows filters to be language-aware so language-specific
279  *   text replacement can be implemented. Defaults to an empty string.
280  * @param array $filter_types_to_skip
281  *   (optional) An array of filter types to skip, or an empty array (default)
282  *   to skip no filter types. All of the format's filters will be applied,
283  *   except for filters of the types that are marked to be skipped.
284  *   FilterInterface::TYPE_HTML_RESTRICTOR is the only type that cannot be
285  *   skipped.
286  *
287  * @return \Drupal\Component\Render\MarkupInterface
288  *   The filtered text.
289  *
290  * @see filter_process_text()
291  *
292  * @ingroup sanitization
293  */
294 function check_markup($text, $format_id = NULL, $langcode = '', $filter_types_to_skip = []) {
295   $build = [
296     '#type' => 'processed_text',
297     '#text' => $text,
298     '#format' => $format_id,
299     '#filter_types_to_skip' => $filter_types_to_skip,
300     '#langcode' => $langcode,
301   ];
302   return \Drupal::service('renderer')->renderPlain($build);
303 }
304
305 /**
306  * Render API callback: Hides the field value of 'text_format' elements.
307  *
308  * To not break form processing and previews if a user does not have access to
309  * a stored text format, the expanded form elements in filter_process_format()
310  * are forced to take over the stored #default_values for 'value' and 'format'.
311  * However, to prevent the unfiltered, original #value from being displayed to
312  * the user, we replace it with a friendly notice here.
313  *
314  * @see filter_process_format()
315  */
316 function filter_form_access_denied($element) {
317   $element['#value'] = t('This field has been disabled because you do not have sufficient permissions to edit it.');
318   return $element;
319 }
320
321 /**
322  * Retrieves the filter tips.
323  *
324  * @param string $format_id
325  *   The ID of the text format for which to retrieve tips, or -1 to return tips
326  *   for all formats accessible to the current user.
327  * @param bool $long
328  *   (optional) Boolean indicating whether the long form of tips should be
329  *   returned. Defaults to FALSE.
330  *
331  * @return array
332  *   An associative array of filtering tips, keyed by filter name. Each
333  *   filtering tip is an associative array with elements:
334  *   - tip: Tip text.
335  *   - id: Filter ID.
336  */
337 function _filter_tips($format_id, $long = FALSE) {
338   $formats = filter_formats(\Drupal::currentUser());
339
340   $tips = [];
341
342   // If only listing one format, extract it from the $formats array.
343   if ($format_id != -1) {
344     $formats = [$formats[$format_id]];
345   }
346
347   foreach ($formats as $format) {
348     foreach ($format->filters() as $name => $filter) {
349       if ($filter->status) {
350         $tip = $filter->tips($long);
351         if (isset($tip)) {
352           $tips[$format->label()][$name] = [
353             'tip' => ['#markup' => $tip],
354             'id' => $name,
355           ];
356         }
357       }
358     }
359   }
360
361   return $tips;
362 }
363
364 /**
365  * Prepares variables for text format guideline templates.
366  *
367  * Default template: filter-guidelines.html.twig.
368  *
369  * @param array $variables
370  *   An associative array containing:
371  *   - format: An object representing a text format.
372  */
373 function template_preprocess_filter_guidelines(&$variables) {
374   $format = $variables['format'];
375   $variables['tips'] = [
376     '#theme' => 'filter_tips',
377     '#tips' => _filter_tips($format->id(), FALSE),
378   ];
379 }
380
381 /**
382  * Prepares variables for text format wrapper templates.
383  *
384  * Default template: text-format-wrapper.html.twig.
385  *
386  * @param array $variables
387  *   An associative array containing:
388  *   - attributes: An associative array containing properties of the element.
389  */
390 function template_preprocess_text_format_wrapper(&$variables) {
391   $variables['aria_description'] = FALSE;
392   // Add element class and id for screen readers.
393   if (isset($variables['attributes']['aria-describedby'])) {
394     $variables['aria_description'] = TRUE;
395     $variables['attributes']['id'] = $variables['attributes']['aria-describedby'];
396     // Remove aria-describedby attribute as it shouldn't be visible here.
397     unset($variables['attributes']['aria-describedby']);
398   }
399 }
400
401 /**
402  * Prepares variables for filter tips templates.
403  *
404  * Default template: filter-tips.html.twig.
405  *
406  * @param array $variables
407  *   An associative array containing:
408  *   - tips: An array containing descriptions and a CSS ID in the form of
409  *     'module-name/filter-id' (only used when $long is TRUE) for each
410  *     filter in one or more text formats. Example:
411  *     @code
412  *       array(
413  *         'Full HTML' => array(
414  *           0 => array(
415  *             'tip' => 'Web page addresses and email addresses turn into links automatically.',
416  *             'id' => 'filter/2',
417  *           ),
418  *         ),
419  *       );
420  *     @endcode
421  *   - long: (optional) Whether the passed-in filter tips contain extended
422  *     explanations, i.e. intended to be output on the path 'filter/tips'
423  *     (TRUE), or are in a short format, i.e. suitable to be displayed below a
424  *     form element. Defaults to FALSE.
425  */
426 function template_preprocess_filter_tips(&$variables) {
427   $tips = $variables['tips'];
428
429   foreach ($variables['tips'] as $name => $tiplist) {
430     foreach ($tiplist as $tip_key => $tip) {
431       $tiplist[$tip_key]['attributes'] = new Attribute();
432     }
433
434     $variables['tips'][$name] = [
435       'attributes' => new Attribute(),
436       'name' => $name,
437       'list' => $tiplist,
438     ];
439   }
440
441   $variables['multiple'] = count($tips) > 1;
442 }
443
444 /**
445  * @defgroup standard_filters Standard filters
446  * @{
447  * Filters implemented by the Filter module.
448  */
449
450 /**
451  * Converts text into hyperlinks automatically.
452  *
453  * This filter identifies and makes clickable three types of "links".
454  * - URLs like http://example.com.
455  * - Email addresses like name@example.com.
456  * - Web addresses without the "http://" protocol defined, like
457  *   www.example.com.
458  * Each type must be processed separately, as there is no one regular
459  * expression that could possibly match all of the cases in one pass.
460  */
461 function _filter_url($text, $filter) {
462   // Tags to skip and not recurse into.
463   $ignore_tags = 'a|script|style|code|pre';
464
465   // Pass length to regexp callback.
466   _filter_url_trim(NULL, $filter->settings['filter_url_length']);
467
468   // Create an array which contains the regexps for each type of link.
469   // The key to the regexp is the name of a function that is used as
470   // callback function to process matches of the regexp. The callback function
471   // is to return the replacement for the match. The array is used and
472   // matching/replacement done below inside some loops.
473   $tasks = [];
474
475   // Prepare protocols pattern for absolute URLs.
476   // \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() will replace
477   // any bad protocols with HTTP, so we need to support the identical list.
478   // While '//' is technically optional for MAILTO only, we cannot cleanly
479   // differ between protocols here without hard-coding MAILTO, so '//' is
480   // optional for all protocols.
481   // @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
482   $protocols = \Drupal::getContainer()->getParameter('filter_protocols');
483   $protocols = implode(':(?://)?|', $protocols) . ':(?://)?';
484
485   $valid_url_path_characters = "[\p{L}\p{M}\p{N}!\*\';:=\+,\.\$\/%#\[\]\-_~@&]";
486
487   // Allow URL paths to contain balanced parens
488   // 1. Used in Wikipedia URLs like /Primer_(film)
489   // 2. Used in IIS sessions like /S(dfd346)/
490   $valid_url_balanced_parens = '\(' . $valid_url_path_characters . '+\)';
491
492   // Valid end-of-path characters (so /foo. does not gobble the period).
493   // 1. Allow =&# for empty URL parameters and other URL-join artifacts
494   $valid_url_ending_characters = '[\p{L}\p{M}\p{N}:_+~#=/]|(?:' . $valid_url_balanced_parens . ')';
495
496   $valid_url_query_chars = '[a-zA-Z0-9!?\*\'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]';
497   $valid_url_query_ending_chars = '[a-zA-Z0-9_&=#\/]';
498
499   //full path
500   //and allow @ in a url, but only in the middle. Catch things like http://example.com/@user/
501   $valid_url_path = '(?:(?:' . $valid_url_path_characters . '*(?:' . $valid_url_balanced_parens . $valid_url_path_characters . '*)*' . $valid_url_ending_characters . ')|(?:@' . $valid_url_path_characters . '+\/))';
502
503   // Prepare domain name pattern.
504   // The ICANN seems to be on track towards accepting more diverse top level
505   // domains, so this pattern has been "future-proofed" to allow for TLDs
506   // of length 2-64.
507   $domain = '(?:[\p{L}\p{M}\p{N}._+-]+\.)?[\p{L}\p{M}]{2,64}\b';
508   $ip = '(?:[0-9]{1,3}\.){3}[0-9]{1,3}';
509   $auth = '[\p{L}\p{M}\p{N}:%_+*~#?&=.,/;-]+@';
510   $trail = '(' . $valid_url_path . '*)?(\\?' . $valid_url_query_chars . '*' . $valid_url_query_ending_chars . ')?';
511
512   // Match absolute URLs.
513   $url_pattern = "(?:$auth)?(?:$domain|$ip)/?(?:$trail)?";
514   $pattern = "`((?:$protocols)(?:$url_pattern))`u";
515   $tasks['_filter_url_parse_full_links'] = $pattern;
516
517   // Match email addresses.
518   $url_pattern = "[\p{L}\p{M}\p{N}._+-]{1,254}@(?:$domain)";
519   $pattern = "`($url_pattern)`u";
520   $tasks['_filter_url_parse_email_links'] = $pattern;
521
522   // Match www domains.
523   $url_pattern = "www\.(?:$domain)/?(?:$trail)?";
524   $pattern = "`($url_pattern)`u";
525   $tasks['_filter_url_parse_partial_links'] = $pattern;
526
527   // Each type of URL needs to be processed separately. The text is joined and
528   // re-split after each task, since all injected HTML tags must be correctly
529   // protected before the next task.
530   foreach ($tasks as $task => $pattern) {
531     // HTML comments need to be handled separately, as they may contain HTML
532     // markup, especially a '>'. Therefore, remove all comment contents and add
533     // them back later.
534     _filter_url_escape_comments('', TRUE);
535     $text = preg_replace_callback('`<!--(.*?)-->`s', '_filter_url_escape_comments', $text);
536
537     // Split at all tags; ensures that no tags or attributes are processed.
538     $chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
539     // PHP ensures that the array consists of alternating delimiters and
540     // literals, and begins and ends with a literal (inserting NULL as
541     // required). Therefore, the first chunk is always text:
542     $chunk_type = 'text';
543     // If a tag of $ignore_tags is found, it is stored in $open_tag and only
544     // removed when the closing tag is found. Until the closing tag is found,
545     // no replacements are made.
546     $open_tag = '';
547
548     for ($i = 0; $i < count($chunks); $i++) {
549       if ($chunk_type == 'text') {
550         // Only process this text if there are no unclosed $ignore_tags.
551         if ($open_tag == '') {
552           // If there is a match, inject a link into this chunk via the callback
553           // function contained in $task.
554           $chunks[$i] = preg_replace_callback($pattern, $task, $chunks[$i]);
555         }
556         // Text chunk is done, so next chunk must be a tag.
557         $chunk_type = 'tag';
558       }
559       else {
560         // Only process this tag if there are no unclosed $ignore_tags.
561         if ($open_tag == '') {
562           // Check whether this tag is contained in $ignore_tags.
563           if (preg_match("`<($ignore_tags)(?:\s|>)`i", $chunks[$i], $matches)) {
564             $open_tag = $matches[1];
565           }
566         }
567         // Otherwise, check whether this is the closing tag for $open_tag.
568         else {
569           if (preg_match("`<\/$open_tag>`i", $chunks[$i], $matches)) {
570             $open_tag = '';
571           }
572         }
573         // Tag chunk is done, so next chunk must be text.
574         $chunk_type = 'text';
575       }
576     }
577
578     $text = implode($chunks);
579     // Revert to the original comment contents
580     _filter_url_escape_comments('', FALSE);
581     $text = preg_replace_callback('`<!--(.*?)-->`', '_filter_url_escape_comments', $text);
582   }
583
584   return $text;
585 }
586
587 /**
588  * Makes links out of absolute URLs.
589  *
590  * Callback for preg_replace_callback() within _filter_url().
591  */
592 function _filter_url_parse_full_links($match) {
593   // The $i:th parenthesis in the regexp contains the URL.
594   $i = 1;
595
596   $match[$i] = Html::decodeEntities($match[$i]);
597   $caption = Html::escape(_filter_url_trim($match[$i]));
598   $match[$i] = Html::escape($match[$i]);
599   return '<a href="' . $match[$i] . '">' . $caption . '</a>';
600 }
601
602 /**
603  * Makes links out of email addresses.
604  *
605  * Callback for preg_replace_callback() within _filter_url().
606  */
607 function _filter_url_parse_email_links($match) {
608   // The $i:th parenthesis in the regexp contains the URL.
609   $i = 0;
610
611   $match[$i] = Html::decodeEntities($match[$i]);
612   $caption = Html::escape(_filter_url_trim($match[$i]));
613   $match[$i] = Html::escape($match[$i]);
614   return '<a href="mailto:' . $match[$i] . '">' . $caption . '</a>';
615 }
616
617 /**
618  * Makes links out of domain names starting with "www."
619  *
620  * Callback for preg_replace_callback() within _filter_url().
621  */
622 function _filter_url_parse_partial_links($match) {
623   // The $i:th parenthesis in the regexp contains the URL.
624   $i = 1;
625
626   $match[$i] = Html::decodeEntities($match[$i]);
627   $caption = Html::escape(_filter_url_trim($match[$i]));
628   $match[$i] = Html::escape($match[$i]);
629   return '<a href="http://' . $match[$i] . '">' . $caption . '</a>';
630 }
631
632 /**
633  * Escapes the contents of HTML comments.
634  *
635  * Callback for preg_replace_callback() within _filter_url().
636  *
637  * @param array $match
638  *   An array containing matches to replace from preg_replace_callback(),
639  *   whereas $match[1] is expected to contain the content to be filtered.
640  * @param bool|null $escape
641  *   (optional) A Boolean indicating whether to escape (TRUE) or unescape
642  *   comments (FALSE). Defaults to NULL, indicating neither. If TRUE, statically
643  *   cached $comments are reset.
644  */
645 function _filter_url_escape_comments($match, $escape = NULL) {
646   static $mode, $comments = [];
647
648   if (isset($escape)) {
649     $mode = $escape;
650     if ($escape) {
651       $comments = [];
652     }
653     return;
654   }
655
656   // Replace all HTML comments with a '<!-- [hash] -->' placeholder.
657   if ($mode) {
658     $content = $match[1];
659     $hash = hash('sha256', $content);
660     $comments[$hash] = $content;
661     return "<!-- $hash -->";
662   }
663   // Or replace placeholders with actual comment contents.
664   else {
665     $hash = $match[1];
666     $hash = trim($hash);
667     $content = $comments[$hash];
668     return "<!--$content-->";
669   }
670 }
671
672 /**
673  * Shortens long URLs to http://www.example.com/long/url…
674  */
675 function _filter_url_trim($text, $length = NULL) {
676   static $_length;
677   if ($length !== NULL) {
678     $_length = $length;
679   }
680
681   if (isset($_length)) {
682     $text = Unicode::truncate($text, $_length, FALSE, TRUE);
683   }
684
685   return $text;
686 }
687
688 /**
689  * Converts line breaks into <p> and <br> in an intelligent fashion.
690  *
691  * Based on: http://photomatt.net/scripts/autop
692  */
693 function _filter_autop($text) {
694   // All block level tags
695   $block = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|input|p|h[1-6]|fieldset|legend|hr|article|aside|details|figcaption|figure|footer|header|hgroup|menu|nav|section|summary)';
696
697   // Split at opening and closing PRE, SCRIPT, STYLE, OBJECT, IFRAME tags
698   // and comments. We don't apply any processing to the contents of these tags
699   // to avoid messing up code. We look for matched pairs and allow basic
700   // nesting. For example:
701   // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
702   $chunks = preg_split('@(<!--.*?-->|</?(?:pre|script|style|object|iframe|!--)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
703   // Note: PHP ensures the array consists of alternating delimiters and literals
704   // and begins and ends with a literal (inserting NULL as required).
705   $ignore = FALSE;
706   $ignoretag = '';
707   $output = '';
708   foreach ($chunks as $i => $chunk) {
709     if ($i % 2) {
710       $comment = (substr($chunk, 0, 4) == '<!--');
711       if ($comment) {
712         // Nothing to do, this is a comment.
713         $output .= $chunk;
714         continue;
715       }
716       // Opening or closing tag?
717       $open = ($chunk[1] != '/');
718       list($tag) = preg_split('/[ >]/', substr($chunk, 2 - $open), 2);
719       if (!$ignore) {
720         if ($open) {
721           $ignore = TRUE;
722           $ignoretag = $tag;
723         }
724       }
725       // Only allow a matching tag to close it.
726       elseif (!$open && $ignoretag == $tag) {
727         $ignore = FALSE;
728         $ignoretag = '';
729       }
730     }
731     elseif (!$ignore) {
732       $chunk = preg_replace('|\n*$|', '', $chunk) . "\n\n"; // just to make things a little easier, pad the end
733       $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
734       $chunk = preg_replace('!(<' . $block . '[^>]*>)!', "\n$1", $chunk); // Space things out a little
735       $chunk = preg_replace('!(</' . $block . '>)!', "$1\n\n", $chunk); // Space things out a little
736       $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
737       $chunk = preg_replace('/^\n|\n\s*\n$/', '', $chunk);
738       $chunk = '<p>' . preg_replace('/\n\s*\n\n?(.)/', "</p>\n<p>$1", $chunk) . "</p>\n"; // make paragraphs, including one at the end
739       $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
740       $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
741       $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
742       $chunk = preg_replace('|<p>\s*</p>\n?|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
743       $chunk = preg_replace('!<p>\s*(</?' . $block . '[^>]*>)!', "$1", $chunk);
744       $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*</p>!', "$1", $chunk);
745       $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
746       $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*<br />!', "$1", $chunk);
747       $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)!', '$1', $chunk);
748       $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
749     }
750     $output .= $chunk;
751   }
752   return $output;
753 }
754
755 /**
756  * Escapes all HTML tags, so they will be visible instead of being effective.
757  */
758 function _filter_html_escape($text) {
759   return trim(Html::escape($text));
760 }
761
762 /**
763  * Process callback for local image filter.
764  */
765 function _filter_html_image_secure_process($text) {
766   // Find the path (e.g. '/') to Drupal root.
767   $base_path = base_path();
768   $base_path_length = Unicode::strlen($base_path);
769
770   // Find the directory on the server where index.php resides.
771   $local_dir = \Drupal::root() . '/';
772
773   $html_dom = Html::load($text);
774   $images = $html_dom->getElementsByTagName('img');
775   foreach ($images as $image) {
776     $src = $image->getAttribute('src');
777     // Transform absolute image URLs to relative image URLs: prevent problems on
778     // multisite set-ups and prevent mixed content errors.
779     $image->setAttribute('src', file_url_transform_relative($src));
780
781     // Verify that $src starts with $base_path.
782     // This also ensures that external images cannot be referenced.
783     $src = $image->getAttribute('src');
784     if (Unicode::substr($src, 0, $base_path_length) === $base_path) {
785       // Remove the $base_path to get the path relative to the Drupal root.
786       // Ensure the path refers to an actual image by prefixing the image source
787       // with the Drupal root and running getimagesize() on it.
788       $local_image_path = $local_dir . Unicode::substr($src, $base_path_length);
789       $local_image_path = rawurldecode($local_image_path);
790       if (@getimagesize($local_image_path)) {
791         // The image has the right path. Erroneous images are dealt with below.
792         continue;
793       }
794     }
795     // Allow modules and themes to replace an invalid image with an error
796     // indicator. See filter_filter_secure_image_alter().
797     \Drupal::moduleHandler()->alter('filter_secure_image', $image);
798   }
799   $text = Html::serialize($html_dom);
800   return $text;
801 }
802
803 /**
804  * Implements hook_filter_secure_image_alter().
805  *
806  * Formats an image DOM element that has an invalid source.
807  *
808  * @param DOMElement $image
809  *   An IMG node to format, parsed from the filtered text.
810  *
811  * @see _filter_html_image_secure_process()
812  */
813 function filter_filter_secure_image_alter(&$image) {
814   // Turn an invalid image into an error indicator.
815   $image->setAttribute('src', base_path() . 'core/misc/icons/e32700/error.svg');
816   $image->setAttribute('alt', t('Image removed.'));
817   $image->setAttribute('title', t('This image has been removed. For security reasons, only images from the local domain are allowed.'));
818   $image->setAttribute('height', '16');
819   $image->setAttribute('width', '16');
820
821   // Add a CSS class to aid in styling.
822   $class = ($image->getAttribute('class') ? trim($image->getAttribute('class')) . ' ' : '');
823   $class .= 'filter-image-invalid';
824   $image->setAttribute('class', $class);
825 }
826
827 /**
828  * @} End of "defgroup standard_filters".
829  */