RichTextContent.php 5.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Support;
  3. /** Table-capable HTML fragment for public editorial content. */
  4. final class RichTextContent
  5. {
  6. private const TAGS = ['p', 'br', 'div', 'span', 'strong', 'b', 'em', 'i', 'u', 's', 'strike', 'del',
  7. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'hr', 'sup', 'sub',
  8. 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col', 'a'];
  9. private const DROP = ['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'template',
  10. 'form', 'input', 'button', 'textarea', 'select', 'link', 'meta', 'base', 'noscript'];
  11. private const STYLES = ['color', 'background-color', 'font-size', 'font-weight', 'font-style', 'font-family',
  12. 'text-align', 'text-decoration', 'line-height', 'vertical-align', 'white-space',
  13. 'width', 'height', 'min-width', 'max-width', 'table-layout', 'border', 'border-collapse', 'border-spacing',
  14. 'border-width', 'border-style', 'border-color', 'border-top', 'border-right', 'border-bottom', 'border-left',
  15. 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
  16. 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left'];
  17. public static function clean(string $html): string
  18. {
  19. if (trim($html) === '') return '';
  20. $doc = new \DOMDocument('1.0', 'UTF-8');
  21. $previous = libxml_use_internal_errors(true);
  22. try {
  23. $doc->loadHTML('<?xml encoding="UTF-8" ?><!DOCTYPE html><html><body>' . $html . '</body></html>', LIBXML_NONET);
  24. $body = $doc->getElementsByTagName('body')->item(0);
  25. if (!$body) return '';
  26. self::children($body);
  27. $output = '';
  28. foreach ($body->childNodes as $node) $output .= $doc->saveHTML($node);
  29. return trim($output);
  30. } finally { libxml_clear_errors(); libxml_use_internal_errors($previous); }
  31. }
  32. private static function children(\DOMNode $parent): void
  33. {
  34. foreach (iterator_to_array($parent->childNodes) as $node) {
  35. if ($node instanceof \DOMComment || $node instanceof \DOMProcessingInstruction) { $parent->removeChild($node); continue; }
  36. if (!$node instanceof \DOMElement) continue;
  37. $tag = strtolower($node->tagName);
  38. if (in_array($tag, self::DROP, true)) { $parent->removeChild($node); continue; }
  39. self::children($node);
  40. if (!in_array($tag, self::TAGS, true)) {
  41. while ($node->firstChild) $parent->insertBefore($node->firstChild, $node);
  42. $parent->removeChild($node);
  43. continue;
  44. }
  45. foreach (iterator_to_array($node->attributes) as $attribute) {
  46. $name = strtolower($attribute->name); $value = $attribute->value;
  47. $allowed = in_array($name, ['title', 'dir'], true);
  48. if ($name === 'style') { $value = self::style($value); $allowed = $value !== ''; }
  49. if (in_array($name, ['colspan', 'rowspan'], true)) $allowed = in_array($tag, ['td', 'th'], true) && (bool)preg_match('/^[1-9]\d{0,2}$/D', $value);
  50. if (in_array($name, ['width', 'height', 'border', 'cellpadding', 'cellspacing', 'span'], true)) $allowed = (bool)preg_match('/^\d{1,4}%?$/D', $value);
  51. if ($name === 'align') $allowed = in_array($value, ['left', 'right', 'center', 'justify'], true);
  52. if ($name === 'valign') $allowed = in_array($value, ['top', 'middle', 'bottom', 'baseline'], true);
  53. if ($name === 'scope') $allowed = $tag === 'th' && in_array($value, ['row', 'col', 'rowgroup', 'colgroup'], true);
  54. if ($name === 'href') $allowed = $tag === 'a' && self::link($value);
  55. if ($name === 'target') $allowed = $tag === 'a' && in_array($value, ['_self', '_blank'], true);
  56. if (!$allowed) $node->removeAttributeNode($attribute);
  57. else $node->setAttribute($name, $value);
  58. }
  59. if ($tag === 'a' && $node->getAttribute('target') === '_blank') $node->setAttribute('rel', 'noopener noreferrer');
  60. }
  61. }
  62. private static function style(string $style): string
  63. {
  64. $result = [];
  65. foreach (explode(';', $style) as $declaration) {
  66. $parts = explode(':', $declaration, 2);
  67. if (count($parts) !== 2) continue;
  68. $property = strtolower(trim($parts[0])); $value = trim($parts[1]);
  69. if (!in_array($property, self::STYLES, true) || !preg_match('/^[#a-zA-Z0-9\s.,()%+\-\x27"]+$/D', $value)
  70. || preg_match('/(?:url|expression|image-set|attr)\s*\(/i', $value)) continue;
  71. $result[] = $property . ': ' . $value;
  72. }
  73. return implode('; ', $result);
  74. }
  75. private static function link(string $value): bool
  76. {
  77. if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) return false;
  78. if (str_starts_with($value, '#') || (str_starts_with($value, '/') && !str_starts_with($value, '//'))) return true;
  79. $parts = parse_url($value);
  80. return filter_var($value, FILTER_VALIDATE_URL) && $parts && in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true)
  81. && !isset($parts['user']) && !isset($parts['pass']);
  82. }
  83. }