filter.module 34 KB

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