filter.module 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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>.', [':filter_do' => 'https://www.drupal.org/documentation/modules/filter/', ':editor_help' => (\Drupal::moduleHandler()->moduleExists('editor')) ? \Drupal::url('help.page', ['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>".', [':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>.', [':filter_help' => \Drupal::url('help.page', ['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 [
  51. 'filter_tips' => [
  52. 'variables' => ['tips' => NULL, 'long' => FALSE],
  53. ],
  54. 'text_format_wrapper' => [
  55. 'variables' => [
  56. 'children' => NULL,
  57. 'description' => NULL,
  58. 'attributes' => [],
  59. ],
  60. ],
  61. 'filter_guidelines' => [
  62. 'variables' => ['format' => NULL],
  63. ],
  64. 'filter_caption' => [
  65. 'variables' => [
  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__, []);
  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(['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] = [];
  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) : [];
  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 = [];
  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 \Drupal\filter\Plugin\FilterInterface::process()
  274. *
  275. * @ingroup sanitization
  276. */
  277. function check_markup($text, $format_id = NULL, $langcode = '', $filter_types_to_skip = []) {
  278. $build = [
  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 = [];
  321. // If only listing one format, extract it from the $formats array.
  322. if ($format_id != -1) {
  323. $formats = [$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] = [
  331. 'tip' => ['#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'] = [
  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] = [
  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 = [];
  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 = [];
  592. if (isset($escape)) {
  593. $mode = $escape;
  594. if ($escape) {
  595. $comments = [];
  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. // just to make things a little easier, pad the end
  671. $chunk = preg_replace('|\n*$|', '', $chunk) . "\n\n";
  672. $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
  673. // Space things out a little
  674. $chunk = preg_replace('!(<' . $block . '[^>]*>)!', "\n$1", $chunk);
  675. // Space things out a little
  676. $chunk = preg_replace('!(</' . $block . '>)!', "$1\n\n", $chunk);
  677. // take care of duplicates
  678. $chunk = preg_replace("/\n\n+/", "\n\n", $chunk);
  679. $chunk = preg_replace('/^\n|\n\s*\n$/', '', $chunk);
  680. // make paragraphs, including one at the end
  681. $chunk = '<p>' . preg_replace('/\n\s*\n\n?(.)/', "</p>\n<p>$1", $chunk) . "</p>\n";
  682. // problem with nested lists
  683. $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk);
  684. $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
  685. $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
  686. // under certain strange conditions it could create a P of entirely whitespace
  687. $chunk = preg_replace('|<p>\s*</p>\n?|', '', $chunk);
  688. $chunk = preg_replace('!<p>\s*(</?' . $block . '[^>]*>)!', "$1", $chunk);
  689. $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*</p>!', "$1", $chunk);
  690. // make line breaks
  691. $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk);
  692. $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*<br />!', "$1", $chunk);
  693. $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)!', '$1', $chunk);
  694. $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
  695. }
  696. $output .= $chunk;
  697. }
  698. return $output;
  699. }
  700. /**
  701. * Escapes all HTML tags, so they will be visible instead of being effective.
  702. */
  703. function _filter_html_escape($text) {
  704. return trim(Html::escape($text));
  705. }
  706. /**
  707. * Process callback for local image filter.
  708. */
  709. function _filter_html_image_secure_process($text) {
  710. // Find the path (e.g. '/') to Drupal root.
  711. $base_path = base_path();
  712. $base_path_length = mb_strlen($base_path);
  713. // Find the directory on the server where index.php resides.
  714. $local_dir = \Drupal::root() . '/';
  715. $html_dom = Html::load($text);
  716. $images = $html_dom->getElementsByTagName('img');
  717. foreach ($images as $image) {
  718. $src = $image->getAttribute('src');
  719. // Transform absolute image URLs to relative image URLs: prevent problems on
  720. // multisite set-ups and prevent mixed content errors.
  721. $image->setAttribute('src', file_url_transform_relative($src));
  722. // Verify that $src starts with $base_path.
  723. // This also ensures that external images cannot be referenced.
  724. $src = $image->getAttribute('src');
  725. if (mb_substr($src, 0, $base_path_length) === $base_path) {
  726. // Remove the $base_path to get the path relative to the Drupal root.
  727. // Ensure the path refers to an actual image by prefixing the image source
  728. // with the Drupal root and running getimagesize() on it.
  729. $local_image_path = $local_dir . mb_substr($src, $base_path_length);
  730. $local_image_path = rawurldecode($local_image_path);
  731. if (@getimagesize($local_image_path)) {
  732. // The image has the right path. Erroneous images are dealt with below.
  733. continue;
  734. }
  735. }
  736. // Allow modules and themes to replace an invalid image with an error
  737. // indicator. See filter_filter_secure_image_alter().
  738. \Drupal::moduleHandler()->alter('filter_secure_image', $image);
  739. }
  740. $text = Html::serialize($html_dom);
  741. return $text;
  742. }
  743. /**
  744. * Implements hook_filter_secure_image_alter().
  745. *
  746. * Formats an image DOM element that has an invalid source.
  747. *
  748. * @param DOMElement $image
  749. * An IMG node to format, parsed from the filtered text.
  750. *
  751. * @see _filter_html_image_secure_process()
  752. */
  753. function filter_filter_secure_image_alter(&$image) {
  754. // Turn an invalid image into an error indicator.
  755. $image->setAttribute('src', base_path() . 'core/misc/icons/e32700/error.svg');
  756. $image->setAttribute('alt', t('Image removed.'));
  757. $image->setAttribute('title', t('This image has been removed. For security reasons, only images from the local domain are allowed.'));
  758. $image->setAttribute('height', '16');
  759. $image->setAttribute('width', '16');
  760. // Add a CSS class to aid in styling.
  761. $class = ($image->getAttribute('class') ? trim($image->getAttribute('class')) . ' ' : '');
  762. $class .= 'filter-image-invalid';
  763. $image->setAttribute('class', $class);
  764. }
  765. /**
  766. * @} End of "defgroup standard_filters".
  767. */