FieldFilteredMarkup.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Drupal\Core\Field;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Render\MarkupInterface;
  5. use Drupal\Component\Render\MarkupTrait;
  6. use Drupal\Component\Utility\Xss;
  7. /**
  8. * Defines an object that passes safe strings through the Field system.
  9. *
  10. * This object filters the string using a very restrictive tag list when it is
  11. * created.
  12. *
  13. * @internal
  14. * This object is marked as internal because it should only be used by the
  15. * Field module and field-related plugins.
  16. *
  17. * @see \Drupal\Core\Render\Markup
  18. */
  19. final class FieldFilteredMarkup implements MarkupInterface, \Countable {
  20. use MarkupTrait;
  21. /**
  22. * Overrides \Drupal\Component\Render\MarkupTrait::create().
  23. *
  24. * @return string|\Drupal\Component\Render\MarkupInterface
  25. * A safe string filtered with the allowed tag list and normalized.
  26. *
  27. * @see \Drupal\Core\Field\FieldFilteredMarkup::allowedTags()
  28. * @see \Drupal\Component\Utility\Xss::filter()
  29. * @see \Drupal\Component\Utility\Html::normalize()
  30. */
  31. public static function create($string) {
  32. $string = (string) $string;
  33. if ($string === '') {
  34. return '';
  35. }
  36. $safe_string = new static();
  37. // All known XSS vectors are filtered out by
  38. // \Drupal\Component\Utility\Xss::filter(), all tags in the markup are
  39. // allowed intentionally by the trait, and no danger is added in by
  40. // \Drupal\Component\Utility\HTML::normalize(). Since the normalized value
  41. // is essentially the same markup, designate this string as safe as well.
  42. // This method is an internal part of field sanitization, so the resultant,
  43. // sanitized string should be printable as is.
  44. $safe_string->string = Html::normalize(Xss::filter($string, static::allowedTags()));
  45. return $safe_string;
  46. }
  47. /**
  48. * Returns the allowed tag list.
  49. *
  50. * @return string[]
  51. * A list of allowed tags.
  52. */
  53. public static function allowedTags() {
  54. return ['a', 'b', 'big', 'code', 'del', 'em', 'i', 'ins', 'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'tt', 'ol', 'ul', 'li', 'p', 'br', 'img'];
  55. }
  56. /**
  57. * Returns a human-readable list of allowed tags for display in help texts.
  58. *
  59. * @return string
  60. * A human-readable list of allowed tags for display in help texts.
  61. */
  62. public static function displayAllowedTags() {
  63. return '<' . implode('> <', static::allowedTags()) . '>';
  64. }
  65. }