AbstractHtmlProcessor.php
2 years ago
CssToAttributeConverter.php
2 years ago
HtmlNormalizer.php
2 years ago
HtmlPruner.php
2 years ago
index.php
2 years ago
AbstractHtmlProcessor.php
196 lines
| 1 | <?php |
| 2 | declare (strict_types=1); |
| 3 | namespace MailPoetVendor\Pelago\Emogrifier\HtmlProcessor; |
| 4 | if (!defined('ABSPATH')) exit; |
| 5 | abstract class AbstractHtmlProcessor |
| 6 | { |
| 7 | protected const DEFAULT_DOCUMENT_TYPE = '<!DOCTYPE html>'; |
| 8 | protected const CONTENT_TYPE_META_TAG = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'; |
| 9 | protected const PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER = '(?:command|embed|keygen|source|track|wbr)'; |
| 10 | protected const TAGNAME_ALLOWED_BEFORE_BODY_MATCHER = '(?:html|head|base|command|link|meta|noscript|script|style|template|title)'; |
| 11 | protected const HTML_COMMENT_PATTERN = '/<!--[^-]*+(?:-(?!->)[^-]*+)*+(?:-->|$)/'; |
| 12 | protected const HTML_TEMPLATE_ELEMENT_PATTERN = '%<template[\\s>][^<]*+(?:<(?!/template>)[^<]*+)*+(?:</template>|$)%i'; |
| 13 | protected $domDocument = null; |
| 14 | private $xPath = null; |
| 15 | private function __construct() |
| 16 | { |
| 17 | } |
| 18 | public static function fromHtml(string $unprocessedHtml) : self |
| 19 | { |
| 20 | if ($unprocessedHtml === '') { |
| 21 | throw new \InvalidArgumentException('The provided HTML must not be empty.', 1515763647); |
| 22 | } |
| 23 | $instance = new static(); |
| 24 | $instance->setHtml($unprocessedHtml); |
| 25 | return $instance; |
| 26 | } |
| 27 | public static function fromDomDocument(\DOMDocument $document) : self |
| 28 | { |
| 29 | $instance = new static(); |
| 30 | $instance->setDomDocument($document); |
| 31 | return $instance; |
| 32 | } |
| 33 | private function setHtml(string $html) : void |
| 34 | { |
| 35 | $this->createUnifiedDomDocument($html); |
| 36 | } |
| 37 | public function getDomDocument() : \DOMDocument |
| 38 | { |
| 39 | if (!$this->domDocument instanceof \DOMDocument) { |
| 40 | $message = self::class . '::setDomDocument() has not yet been called on ' . static::class; |
| 41 | throw new \UnexpectedValueException($message, 1570472239); |
| 42 | } |
| 43 | return $this->domDocument; |
| 44 | } |
| 45 | private function setDomDocument(\DOMDocument $domDocument) : void |
| 46 | { |
| 47 | $this->domDocument = $domDocument; |
| 48 | $this->xPath = new \DOMXPath($this->domDocument); |
| 49 | } |
| 50 | protected function getXPath() : \DOMXPath |
| 51 | { |
| 52 | if (!$this->xPath instanceof \DOMXPath) { |
| 53 | $message = self::class . '::setDomDocument() has not yet been called on ' . static::class; |
| 54 | throw new \UnexpectedValueException($message, 1617819086); |
| 55 | } |
| 56 | return $this->xPath; |
| 57 | } |
| 58 | public function render() : string |
| 59 | { |
| 60 | $htmlWithPossibleErroneousClosingTags = $this->getDomDocument()->saveHTML(); |
| 61 | return $this->removeSelfClosingTagsClosingTags($htmlWithPossibleErroneousClosingTags); |
| 62 | } |
| 63 | public function renderBodyContent() : string |
| 64 | { |
| 65 | $htmlWithPossibleErroneousClosingTags = $this->getDomDocument()->saveHTML($this->getBodyElement()); |
| 66 | $bodyNodeHtml = $this->removeSelfClosingTagsClosingTags($htmlWithPossibleErroneousClosingTags); |
| 67 | return \preg_replace('%</?+body(?:\\s[^>]*+)?+>%', '', $bodyNodeHtml); |
| 68 | } |
| 69 | private function removeSelfClosingTagsClosingTags(string $html) : string |
| 70 | { |
| 71 | return \preg_replace('%</' . self::PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER . '>%', '', $html); |
| 72 | } |
| 73 | private function getBodyElement() : \DOMElement |
| 74 | { |
| 75 | $node = $this->getDomDocument()->getElementsByTagName('body')->item(0); |
| 76 | if (!$node instanceof \DOMElement) { |
| 77 | throw new \RuntimeException('There is no body element.', 1617922607); |
| 78 | } |
| 79 | return $node; |
| 80 | } |
| 81 | private function createUnifiedDomDocument(string $html) : void |
| 82 | { |
| 83 | $this->createRawDomDocument($html); |
| 84 | $this->ensureExistenceOfBodyElement(); |
| 85 | } |
| 86 | private function createRawDomDocument(string $html) : void |
| 87 | { |
| 88 | $domDocument = new \DOMDocument(); |
| 89 | $domDocument->strictErrorChecking = \false; |
| 90 | $domDocument->formatOutput = \false; |
| 91 | $libXmlState = \libxml_use_internal_errors(\true); |
| 92 | $domDocument->loadHTML($this->prepareHtmlForDomConversion($html)); |
| 93 | \libxml_clear_errors(); |
| 94 | \libxml_use_internal_errors($libXmlState); |
| 95 | $this->setDomDocument($domDocument); |
| 96 | } |
| 97 | private function prepareHtmlForDomConversion(string $html) : string |
| 98 | { |
| 99 | $htmlWithSelfClosingSlashes = $this->ensurePhpUnrecognizedSelfClosingTagsAreXml($html); |
| 100 | $htmlWithDocumentType = $this->ensureDocumentType($htmlWithSelfClosingSlashes); |
| 101 | return $this->addContentTypeMetaTag($htmlWithDocumentType); |
| 102 | } |
| 103 | private function ensureDocumentType(string $html) : string |
| 104 | { |
| 105 | $hasDocumentType = \stripos($html, '<!DOCTYPE') !== \false; |
| 106 | if ($hasDocumentType) { |
| 107 | return $this->normalizeDocumentType($html); |
| 108 | } |
| 109 | return self::DEFAULT_DOCUMENT_TYPE . $html; |
| 110 | } |
| 111 | private function normalizeDocumentType(string $html) : string |
| 112 | { |
| 113 | // Limit to replacing the first occurrence: as an optimization; and in case an example exists as unescaped text. |
| 114 | return \preg_replace('/<!DOCTYPE\\s++html(?=[\\s>])/i', '<!DOCTYPE html', $html, 1); |
| 115 | } |
| 116 | private function addContentTypeMetaTag(string $html) : string |
| 117 | { |
| 118 | if ($this->hasContentTypeMetaTagInHead($html)) { |
| 119 | return $html; |
| 120 | } |
| 121 | // We are trying to insert the meta tag to the right spot in the DOM. |
| 122 | // If we just prepended it to the HTML, we would lose attributes set to the HTML tag. |
| 123 | $hasHeadTag = \preg_match('/<head[\\s>]/i', $html); |
| 124 | $hasHtmlTag = \stripos($html, '<html') !== \false; |
| 125 | if ($hasHeadTag) { |
| 126 | $reworkedHtml = \preg_replace('/<head(?=[\\s>])([^>]*+)>/i', '<head$1>' . self::CONTENT_TYPE_META_TAG, $html); |
| 127 | } elseif ($hasHtmlTag) { |
| 128 | $reworkedHtml = \preg_replace('/<html(.*?)>/is', '<html$1><head>' . self::CONTENT_TYPE_META_TAG . '</head>', $html); |
| 129 | } else { |
| 130 | $reworkedHtml = self::CONTENT_TYPE_META_TAG . $html; |
| 131 | } |
| 132 | return $reworkedHtml; |
| 133 | } |
| 134 | private function hasContentTypeMetaTagInHead(string $html) : bool |
| 135 | { |
| 136 | \preg_match('%^.*?(?=<meta(?=\\s)[^>]*\\shttp-equiv=(["\']?+)Content-Type\\g{-1}[\\s/>])%is', $html, $matches); |
| 137 | if (isset($matches[0])) { |
| 138 | $htmlBefore = $matches[0]; |
| 139 | try { |
| 140 | $hasContentTypeMetaTagInHead = !$this->hasEndOfHeadElement($htmlBefore); |
| 141 | } catch (\RuntimeException $exception) { |
| 142 | // If something unexpected occurs, assume the `Content-Type` that was found is valid. |
| 143 | \trigger_error($exception->getMessage()); |
| 144 | $hasContentTypeMetaTagInHead = \true; |
| 145 | } |
| 146 | } else { |
| 147 | $hasContentTypeMetaTagInHead = \false; |
| 148 | } |
| 149 | return $hasContentTypeMetaTagInHead; |
| 150 | } |
| 151 | private function hasEndOfHeadElement(string $html) : bool |
| 152 | { |
| 153 | $headEndTagMatchCount = \preg_match('%<(?!' . self::TAGNAME_ALLOWED_BEFORE_BODY_MATCHER . '[\\s/>])\\w|</head>%i', $html); |
| 154 | if (\is_int($headEndTagMatchCount) && $headEndTagMatchCount > 0) { |
| 155 | // An exception to the implicit end of the `<head>` is any content within a `<template>` element, as well in |
| 156 | // comments. As an optimization, this is only checked for if a potential `<head>` end tag is found. |
| 157 | $htmlWithoutCommentsOrTemplates = $this->removeHtmlTemplateElements($this->removeHtmlComments($html)); |
| 158 | $hasEndOfHeadElement = $htmlWithoutCommentsOrTemplates === $html || $this->hasEndOfHeadElement($htmlWithoutCommentsOrTemplates); |
| 159 | } else { |
| 160 | $hasEndOfHeadElement = \false; |
| 161 | } |
| 162 | return $hasEndOfHeadElement; |
| 163 | } |
| 164 | private function removeHtmlComments(string $html) : string |
| 165 | { |
| 166 | $result = \preg_replace(self::HTML_COMMENT_PATTERN, '', $html); |
| 167 | if (!\is_string($result)) { |
| 168 | throw new \RuntimeException('Internal PCRE error', 1616521475); |
| 169 | } |
| 170 | return $result; |
| 171 | } |
| 172 | private function removeHtmlTemplateElements(string $html) : string |
| 173 | { |
| 174 | $result = \preg_replace(self::HTML_TEMPLATE_ELEMENT_PATTERN, '', $html); |
| 175 | if (!\is_string($result)) { |
| 176 | throw new \RuntimeException('Internal PCRE error', 1616519652); |
| 177 | } |
| 178 | return $result; |
| 179 | } |
| 180 | private function ensurePhpUnrecognizedSelfClosingTagsAreXml(string $html) : string |
| 181 | { |
| 182 | return \preg_replace('%<' . self::PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER . '\\b[^>]*+(?<!/)(?=>)%', '$0/', $html); |
| 183 | } |
| 184 | private function ensureExistenceOfBodyElement() : void |
| 185 | { |
| 186 | if ($this->getDomDocument()->getElementsByTagName('body')->item(0) instanceof \DOMElement) { |
| 187 | return; |
| 188 | } |
| 189 | $htmlElement = $this->getDomDocument()->getElementsByTagName('html')->item(0); |
| 190 | if (!$htmlElement instanceof \DOMElement) { |
| 191 | throw new \UnexpectedValueException('There is no HTML element although there should be one.', 1569930853); |
| 192 | } |
| 193 | $htmlElement->appendChild($this->getDomDocument()->createElement('body')); |
| 194 | } |
| 195 | } |
| 196 |