1. 8.3.x core/modules/filter/filter.module
  2. 8.0.x core/modules/filter/filter.module
  3. 8.1.x core/modules/filter/filter.module
  4. 8.2.x core/modules/filter/filter.module
  5. 8.4.x core/modules/filter/filter.module
  6. 4.6.x modules/filter.module
  7. 4.7.x modules/filter.module
  8. 5.x modules/filter/filter.module
  9. 6.x modules/filter/filter.module
  10. 7.x modules/filter/filter.module

Framework for handling the filtering of content.

File

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

Functions

Namesort descending Description
check_markup Runs all the enabled filters on a piece of text.
filter_default_format Returns the ID of the default text format for a particular user.
filter_fallback_format Returns the ID of the fallback text format that all users have access to.
filter_filter_secure_image_alter Implements hook_filter_secure_image_alter().
filter_formats Retrieves a list of enabled text formats, ordered by weight.
filter_formats_reset Resets the text format caches.
filter_form_access_denied Render API callback: Hides the field value of 'text_format' elements.
filter_get_formats_by_role Retrieves a list of text formats that are allowed for a given role.
filter_get_roles_by_format Retrieves a list of roles that are allowed to use a given text format.
filter_help Implements hook_help().
filter_theme Implements hook_theme().
template_preprocess_filter_guidelines Prepares variables for text format guideline templates.
template_preprocess_filter_tips Prepares variables for filter tips templates.
template_preprocess_text_format_wrapper Prepares variables for text format wrapper templates.
_filter_autop Converts line breaks into <p> and <br> in an intelligent fashion.
_filter_html_escape Escapes all HTML tags, so they will be visible instead of being effective.
_filter_html_image_secure_process Process callback for local image filter.
_filter_tips Retrieves the filter tips.
_filter_url Converts text into hyperlinks automatically.
_filter_url_escape_comments Escapes the contents of HTML comments.
_filter_url_parse_email_links Makes links out of email addresses.
_filter_url_parse_full_links Makes links out of absolute URLs.
_filter_url_parse_partial_links Makes links out of domain names starting with "www."
_filter_url_trim Shortens long URLs to http://www.example.com/long/url