init
This commit is contained in:
@@ -0,0 +1 @@
|
||||
<?php
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\Caching;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
class SimpleStringCache
|
||||
{
|
||||
private $values = [];
|
||||
public function has(string $key) : bool
|
||||
{
|
||||
$this->assertNotEmptyKey($key);
|
||||
return isset($this->values[$key]);
|
||||
}
|
||||
public function get(string $key) : string
|
||||
{
|
||||
if (!$this->has($key)) {
|
||||
throw new \BadMethodCallException('You can only call `get` with a key for an existing value.', 1625996246);
|
||||
}
|
||||
return $this->values[$key];
|
||||
}
|
||||
public function set(string $key, string $value) : void
|
||||
{
|
||||
$this->assertNotEmptyKey($key);
|
||||
$this->values[$key] = $value;
|
||||
}
|
||||
private function assertNotEmptyKey(string $key) : void
|
||||
{
|
||||
if ($key === '') {
|
||||
throw new \InvalidArgumentException('Please provide a non-empty key.', 1625995840);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\Css;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
use MailPoetVendor\Sabberworm\CSS\CSSList\AtRuleBlockList as CssAtRuleBlockList;
|
||||
use MailPoetVendor\Sabberworm\CSS\CSSList\Document as SabberwormCssDocument;
|
||||
use MailPoetVendor\Sabberworm\CSS\Parser as CssParser;
|
||||
use MailPoetVendor\Sabberworm\CSS\Property\AtRule as CssAtRule;
|
||||
use MailPoetVendor\Sabberworm\CSS\Property\Charset as CssCharset;
|
||||
use MailPoetVendor\Sabberworm\CSS\Property\Import as CssImport;
|
||||
use MailPoetVendor\Sabberworm\CSS\Renderable as CssRenderable;
|
||||
use MailPoetVendor\Sabberworm\CSS\RuleSet\DeclarationBlock as CssDeclarationBlock;
|
||||
use MailPoetVendor\Sabberworm\CSS\RuleSet\RuleSet as CssRuleSet;
|
||||
use MailPoetVendor\Sabberworm\CSS\Settings as ParserSettings;
|
||||
class CssDocument
|
||||
{
|
||||
private $sabberwormCssDocument;
|
||||
private $isImportRuleAllowed = \true;
|
||||
public function __construct(string $css, bool $debug)
|
||||
{
|
||||
// CSS Parser currently throws exception with nested at-rules (like `@media`) in strict parsing mode
|
||||
$parserSettings = ParserSettings::create()->withLenientParsing(!$debug || $this->hasNestedAtRule($css));
|
||||
// CSS Parser currently throws exception with non-empty whitespace-only CSS in strict parsing mode, so `trim()`
|
||||
// @see https://github.com/sabberworm/PHP-CSS-Parser/issues/349
|
||||
$this->sabberwormCssDocument = (new CssParser(\trim($css), $parserSettings))->parse();
|
||||
}
|
||||
private function hasNestedAtRule(string $css) : bool
|
||||
{
|
||||
return \preg_match('/@(?:media|supports|(?:-webkit-|-moz-|-ms-|-o-)?+(keyframes|document))\\b/', $css) === 1;
|
||||
}
|
||||
public function getStyleRulesData(array $allowedMediaTypes) : array
|
||||
{
|
||||
$ruleMatches = [];
|
||||
foreach ($this->sabberwormCssDocument->getContents() as $rule) {
|
||||
if ($rule instanceof CssAtRuleBlockList) {
|
||||
$containingAtRule = $this->getFilteredAtIdentifierAndRule($rule, $allowedMediaTypes);
|
||||
if (\is_string($containingAtRule)) {
|
||||
foreach ($rule->getContents() as $nestedRule) {
|
||||
if ($nestedRule instanceof CssDeclarationBlock) {
|
||||
$ruleMatches[] = new StyleRule($nestedRule, $containingAtRule);
|
||||
}
|
||||
}
|
||||
}
|
||||
} elseif ($rule instanceof CssDeclarationBlock) {
|
||||
$ruleMatches[] = new StyleRule($rule);
|
||||
}
|
||||
}
|
||||
return $ruleMatches;
|
||||
}
|
||||
public function renderNonConditionalAtRules() : string
|
||||
{
|
||||
$this->isImportRuleAllowed = \true;
|
||||
$cssContents = $this->sabberwormCssDocument->getContents();
|
||||
$atRules = \array_filter($cssContents, [$this, 'isValidAtRuleToRender']);
|
||||
if ($atRules === []) {
|
||||
return '';
|
||||
}
|
||||
$atRulesDocument = new SabberwormCssDocument();
|
||||
$atRulesDocument->setContents($atRules);
|
||||
return $atRulesDocument->render();
|
||||
}
|
||||
private function getFilteredAtIdentifierAndRule(CssAtRuleBlockList $rule, array $allowedMediaTypes) : ?string
|
||||
{
|
||||
$result = null;
|
||||
if ($rule->atRuleName() === 'media') {
|
||||
$mediaQueryList = $rule->atRuleArgs();
|
||||
[$mediaType] = \explode('(', $mediaQueryList, 2);
|
||||
if (\trim($mediaType) !== '') {
|
||||
$escapedAllowedMediaTypes = \array_map(static function (string $allowedMediaType) : string {
|
||||
return \preg_quote($allowedMediaType, '/');
|
||||
}, $allowedMediaTypes);
|
||||
$mediaTypesMatcher = \implode('|', $escapedAllowedMediaTypes);
|
||||
$isAllowed = \preg_match('/^\\s*+(?:only\\s++)?+(?:' . $mediaTypesMatcher . ')/i', $mediaType) > 0;
|
||||
} else {
|
||||
$isAllowed = \true;
|
||||
}
|
||||
if ($isAllowed) {
|
||||
$result = '@media ' . $mediaQueryList;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private function isValidAtRuleToRender(CssRenderable $rule) : bool
|
||||
{
|
||||
if ($rule instanceof CssCharset) {
|
||||
return \false;
|
||||
}
|
||||
if ($rule instanceof CssImport) {
|
||||
return $this->isImportRuleAllowed;
|
||||
}
|
||||
$this->isImportRuleAllowed = \false;
|
||||
if (!$rule instanceof CssAtRule) {
|
||||
return \false;
|
||||
}
|
||||
switch ($rule->atRuleName()) {
|
||||
case 'media':
|
||||
$result = \false;
|
||||
break;
|
||||
case 'font-face':
|
||||
$result = $rule instanceof CssRuleSet && $rule->getRules('font-family') !== [] && $rule->getRules('src') !== [];
|
||||
break;
|
||||
default:
|
||||
$result = \true;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\Css;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
use MailPoetVendor\Sabberworm\CSS\Property\Selector;
|
||||
use MailPoetVendor\Sabberworm\CSS\RuleSet\DeclarationBlock;
|
||||
class StyleRule
|
||||
{
|
||||
private $declarationBlock;
|
||||
private $containingAtRule;
|
||||
public function __construct(DeclarationBlock $declarationBlock, string $containingAtRule = '')
|
||||
{
|
||||
$this->declarationBlock = $declarationBlock;
|
||||
$this->containingAtRule = \trim($containingAtRule);
|
||||
}
|
||||
public function getSelectors() : array
|
||||
{
|
||||
$selectors = $this->declarationBlock->getSelectors();
|
||||
return \array_map(static function (Selector $selector) : string {
|
||||
return (string) $selector;
|
||||
}, $selectors);
|
||||
}
|
||||
public function getDeclarationAsText() : string
|
||||
{
|
||||
return \implode(' ', $this->declarationBlock->getRules());
|
||||
}
|
||||
public function hasAtLeastOneDeclaration() : bool
|
||||
{
|
||||
return $this->declarationBlock->getRules() !== [];
|
||||
}
|
||||
public function getContainingAtRule() : string
|
||||
{
|
||||
return $this->containingAtRule;
|
||||
}
|
||||
public function hasContainingAtRule() : bool
|
||||
{
|
||||
return $this->getContainingAtRule() !== '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
@@ -0,0 +1,521 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
use MailPoetVendor\Pelago\Emogrifier\Css\CssDocument;
|
||||
use MailPoetVendor\Pelago\Emogrifier\HtmlProcessor\AbstractHtmlProcessor;
|
||||
use MailPoetVendor\Pelago\Emogrifier\Utilities\CssConcatenator;
|
||||
use MailPoetVendor\Symfony\Component\CssSelector\CssSelectorConverter;
|
||||
use MailPoetVendor\Symfony\Component\CssSelector\Exception\ParseException;
|
||||
class CssInliner extends AbstractHtmlProcessor
|
||||
{
|
||||
private const CACHE_KEY_SELECTOR = 0;
|
||||
private const CACHE_KEY_CSS_DECLARATIONS_BLOCK = 1;
|
||||
private const CACHE_KEY_COMBINED_STYLES = 2;
|
||||
private const PSEUDO_CLASS_MATCHER = 'empty|(?:first|last|nth(?:-last)?+|only)-(?:child|of-type)|not\\([[:ascii:]]*\\)';
|
||||
private const OF_TYPE_PSEUDO_CLASS_MATCHER = '(?:first|last|nth(?:-last)?+|only)-of-type';
|
||||
private const COMBINATOR_MATCHER = '(?:\\s++|\\s*+[>+~]\\s*+)(?=[[:alpha:]_\\-.#*:\\[])';
|
||||
private $excludedSelectors = [];
|
||||
private $allowedMediaTypes = ['all' => \true, 'screen' => \true, 'print' => \true];
|
||||
private $caches = [self::CACHE_KEY_SELECTOR => [], self::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [], self::CACHE_KEY_COMBINED_STYLES => []];
|
||||
private $cssSelectorConverter = null;
|
||||
private $visitedNodes = [];
|
||||
private $styleAttributesForNodes = [];
|
||||
private $isInlineStyleAttributesParsingEnabled = \true;
|
||||
private $isStyleBlocksParsingEnabled = \true;
|
||||
private $selectorPrecedenceMatchers = [
|
||||
// IDs: worth 10000
|
||||
'\\#' => 10000,
|
||||
// classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100
|
||||
'(?:\\.|\\[|(?<!:):(?!not\\())' => 100,
|
||||
// elements (not attribute values or `:not`), pseudo-elements: worth 1
|
||||
'(?:(?<![="\':\\w\\-])|::)' => 1,
|
||||
];
|
||||
private $matchingUninlinableCssRules = null;
|
||||
private $debug = \false;
|
||||
public function inlineCss(string $css = '') : self
|
||||
{
|
||||
$this->clearAllCaches();
|
||||
$this->purgeVisitedNodes();
|
||||
$this->normalizeStyleAttributesOfAllNodes();
|
||||
$combinedCss = $css;
|
||||
// grab any existing style blocks from the HTML and append them to the existing CSS
|
||||
// (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
|
||||
if ($this->isStyleBlocksParsingEnabled) {
|
||||
$combinedCss .= $this->getCssFromAllStyleNodes();
|
||||
}
|
||||
$parsedCss = new CssDocument($combinedCss, $this->debug);
|
||||
$excludedNodes = $this->getNodesToExclude();
|
||||
$cssRules = $this->collateCssRules($parsedCss);
|
||||
$cssSelectorConverter = $this->getCssSelectorConverter();
|
||||
foreach ($cssRules['inlinable'] as $cssRule) {
|
||||
try {
|
||||
$nodesMatchingCssSelectors = $this->getXPath()->query($cssSelectorConverter->toXPath($cssRule['selector']));
|
||||
foreach ($nodesMatchingCssSelectors as $node) {
|
||||
if (\in_array($node, $excludedNodes, \true)) {
|
||||
continue;
|
||||
}
|
||||
$this->copyInlinableCssToStyleAttribute($node, $cssRule);
|
||||
}
|
||||
} catch (ParseException $e) {
|
||||
if ($this->debug) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($this->isInlineStyleAttributesParsingEnabled) {
|
||||
$this->fillStyleAttributesWithMergedStyles();
|
||||
}
|
||||
$this->removeImportantAnnotationFromAllInlineStyles();
|
||||
$this->determineMatchingUninlinableCssRules($cssRules['uninlinable']);
|
||||
$this->copyUninlinableCssToStyleNode($parsedCss);
|
||||
return $this;
|
||||
}
|
||||
public function disableInlineStyleAttributesParsing() : self
|
||||
{
|
||||
$this->isInlineStyleAttributesParsingEnabled = \false;
|
||||
return $this;
|
||||
}
|
||||
public function disableStyleBlocksParsing() : self
|
||||
{
|
||||
$this->isStyleBlocksParsingEnabled = \false;
|
||||
return $this;
|
||||
}
|
||||
public function addAllowedMediaType(string $mediaName) : self
|
||||
{
|
||||
$this->allowedMediaTypes[$mediaName] = \true;
|
||||
return $this;
|
||||
}
|
||||
public function removeAllowedMediaType(string $mediaName) : self
|
||||
{
|
||||
if (isset($this->allowedMediaTypes[$mediaName])) {
|
||||
unset($this->allowedMediaTypes[$mediaName]);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
public function addExcludedSelector(string $selector) : self
|
||||
{
|
||||
$this->excludedSelectors[$selector] = \true;
|
||||
return $this;
|
||||
}
|
||||
public function removeExcludedSelector(string $selector) : self
|
||||
{
|
||||
if (isset($this->excludedSelectors[$selector])) {
|
||||
unset($this->excludedSelectors[$selector]);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
public function setDebug(bool $debug) : self
|
||||
{
|
||||
$this->debug = $debug;
|
||||
return $this;
|
||||
}
|
||||
public function getMatchingUninlinableSelectors() : array
|
||||
{
|
||||
return \array_column($this->getMatchingUninlinableCssRules(), 'selector');
|
||||
}
|
||||
private function getMatchingUninlinableCssRules() : array
|
||||
{
|
||||
if (!\is_array($this->matchingUninlinableCssRules)) {
|
||||
throw new \BadMethodCallException('inlineCss must be called first', 1568385221);
|
||||
}
|
||||
return $this->matchingUninlinableCssRules;
|
||||
}
|
||||
private function clearAllCaches() : void
|
||||
{
|
||||
$this->caches = [self::CACHE_KEY_SELECTOR => [], self::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [], self::CACHE_KEY_COMBINED_STYLES => []];
|
||||
}
|
||||
private function purgeVisitedNodes() : void
|
||||
{
|
||||
$this->visitedNodes = [];
|
||||
$this->styleAttributesForNodes = [];
|
||||
}
|
||||
private function normalizeStyleAttributesOfAllNodes() : void
|
||||
{
|
||||
foreach ($this->getAllNodesWithStyleAttribute() as $node) {
|
||||
if ($this->isInlineStyleAttributesParsingEnabled) {
|
||||
$this->normalizeStyleAttributes($node);
|
||||
}
|
||||
// Remove style attribute in every case, so we can add them back (if inline style attributes
|
||||
// parsing is enabled) to the end of the style list, thus keeping the right priority of CSS rules;
|
||||
// else original inline style rules may remain at the beginning of the final inline style definition
|
||||
// of a node, which may give not the desired results
|
||||
$node->removeAttribute('style');
|
||||
}
|
||||
}
|
||||
private function getAllNodesWithStyleAttribute() : \DOMNodeList
|
||||
{
|
||||
$query = '//*[@style]';
|
||||
$matches = $this->getXPath()->query($query);
|
||||
if (!$matches instanceof \DOMNodeList) {
|
||||
throw new \RuntimeException('XPatch query failed: ' . $query, 1618577797);
|
||||
}
|
||||
return $matches;
|
||||
}
|
||||
private function normalizeStyleAttributes(\DOMElement $node) : void
|
||||
{
|
||||
$normalizedOriginalStyle = \preg_replace_callback(
|
||||
'/-?+[_a-zA-Z][\\w\\-]*+(?=:)/S',
|
||||
static function (array $propertyNameMatches) : string {
|
||||
return \strtolower($propertyNameMatches[0]);
|
||||
},
|
||||
$node->getAttribute('style')
|
||||
);
|
||||
// In order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles.
|
||||
$nodePath = $node->getNodePath();
|
||||
if (\is_string($nodePath) && !isset($this->styleAttributesForNodes[$nodePath])) {
|
||||
$this->styleAttributesForNodes[$nodePath] = $this->parseCssDeclarationsBlock($normalizedOriginalStyle);
|
||||
$this->visitedNodes[$nodePath] = $node;
|
||||
}
|
||||
$node->setAttribute('style', $normalizedOriginalStyle);
|
||||
}
|
||||
private function parseCssDeclarationsBlock(string $cssDeclarationsBlock) : array
|
||||
{
|
||||
if (isset($this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock])) {
|
||||
return $this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock];
|
||||
}
|
||||
$properties = [];
|
||||
foreach (\preg_split('/;(?!base64|charset)/', $cssDeclarationsBlock) as $declaration) {
|
||||
$matches = [];
|
||||
if (!\preg_match('/^([A-Za-z\\-]+)\\s*:\\s*(.+)$/s', \trim($declaration), $matches)) {
|
||||
continue;
|
||||
}
|
||||
$propertyName = \strtolower($matches[1]);
|
||||
$propertyValue = $matches[2];
|
||||
$properties[$propertyName] = $propertyValue;
|
||||
}
|
||||
$this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock] = $properties;
|
||||
return $properties;
|
||||
}
|
||||
private function getCssFromAllStyleNodes() : string
|
||||
{
|
||||
$styleNodes = $this->getXPath()->query('//style');
|
||||
if ($styleNodes === \false) {
|
||||
return '';
|
||||
}
|
||||
$css = '';
|
||||
foreach ($styleNodes as $styleNode) {
|
||||
if (\is_string($styleNode->nodeValue)) {
|
||||
$css .= "\n\n" . $styleNode->nodeValue;
|
||||
}
|
||||
$parentNode = $styleNode->parentNode;
|
||||
if ($parentNode instanceof \DOMNode) {
|
||||
$parentNode->removeChild($styleNode);
|
||||
}
|
||||
}
|
||||
return $css;
|
||||
}
|
||||
private function getNodesToExclude() : array
|
||||
{
|
||||
$excludedNodes = [];
|
||||
foreach (\array_keys($this->excludedSelectors) as $selectorToExclude) {
|
||||
try {
|
||||
$matchingNodes = $this->getXPath()->query($this->getCssSelectorConverter()->toXPath($selectorToExclude));
|
||||
foreach ($matchingNodes as $node) {
|
||||
if (!$node instanceof \DOMElement) {
|
||||
$path = $node->getNodePath() ?? '$node';
|
||||
throw new \UnexpectedValueException($path . ' is not a DOMElement.', 1617975914);
|
||||
}
|
||||
$excludedNodes[] = $node;
|
||||
}
|
||||
} catch (ParseException $e) {
|
||||
if ($this->debug) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $excludedNodes;
|
||||
}
|
||||
private function getCssSelectorConverter() : CssSelectorConverter
|
||||
{
|
||||
if (!$this->cssSelectorConverter instanceof CssSelectorConverter) {
|
||||
$this->cssSelectorConverter = new CssSelectorConverter();
|
||||
}
|
||||
return $this->cssSelectorConverter;
|
||||
}
|
||||
private function collateCssRules(CssDocument $parsedCss) : array
|
||||
{
|
||||
$matches = $parsedCss->getStyleRulesData(\array_keys($this->allowedMediaTypes));
|
||||
$cssRules = ['inlinable' => [], 'uninlinable' => []];
|
||||
foreach ($matches as $key => $cssRule) {
|
||||
if (!$cssRule->hasAtLeastOneDeclaration()) {
|
||||
continue;
|
||||
}
|
||||
$mediaQuery = $cssRule->getContainingAtRule();
|
||||
$declarationsBlock = $cssRule->getDeclarationAsText();
|
||||
foreach ($cssRule->getSelectors() as $selector) {
|
||||
// don't process pseudo-elements and behavioral (dynamic) pseudo-classes;
|
||||
// only allow structural pseudo-classes
|
||||
$hasPseudoElement = \strpos($selector, '::') !== \false;
|
||||
$hasUnmatchablePseudo = $hasPseudoElement || $this->hasUnsupportedPseudoClass($selector);
|
||||
$parsedCssRule = [
|
||||
'media' => $mediaQuery,
|
||||
'selector' => $selector,
|
||||
'hasUnmatchablePseudo' => $hasUnmatchablePseudo,
|
||||
'declarationsBlock' => $declarationsBlock,
|
||||
// keep track of where it appears in the file, since order is important
|
||||
'line' => $key,
|
||||
];
|
||||
$ruleType = !$cssRule->hasContainingAtRule() && !$hasUnmatchablePseudo ? 'inlinable' : 'uninlinable';
|
||||
$cssRules[$ruleType][] = $parsedCssRule;
|
||||
}
|
||||
}
|
||||
\usort(
|
||||
$cssRules['inlinable'],
|
||||
function (array $first, array $second) : int {
|
||||
return $this->sortBySelectorPrecedence($first, $second);
|
||||
}
|
||||
);
|
||||
return $cssRules;
|
||||
}
|
||||
private function hasUnsupportedPseudoClass(string $selector) : bool
|
||||
{
|
||||
if (\preg_match('/:(?!' . self::PSEUDO_CLASS_MATCHER . ')[\\w\\-]/i', $selector)) {
|
||||
return \true;
|
||||
}
|
||||
if (!\preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector)) {
|
||||
return \false;
|
||||
}
|
||||
foreach (\preg_split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) {
|
||||
if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
|
||||
return \true;
|
||||
}
|
||||
}
|
||||
return \false;
|
||||
}
|
||||
private function selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart) : bool
|
||||
{
|
||||
if (\preg_match('/^[\\w\\-]/', $selectorPart)) {
|
||||
return \false;
|
||||
}
|
||||
return (bool) \preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart);
|
||||
}
|
||||
private function sortBySelectorPrecedence(array $first, array $second) : int
|
||||
{
|
||||
$precedenceOfFirst = $this->getCssSelectorPrecedence($first['selector']);
|
||||
$precedenceOfSecond = $this->getCssSelectorPrecedence($second['selector']);
|
||||
// We want these sorted in ascending order so selectors with lesser precedence get processed first and
|
||||
// selectors with greater precedence get sorted last.
|
||||
$precedenceForEquals = $first['line'] < $second['line'] ? -1 : 1;
|
||||
$precedenceForNotEquals = $precedenceOfFirst < $precedenceOfSecond ? -1 : 1;
|
||||
return $precedenceOfFirst === $precedenceOfSecond ? $precedenceForEquals : $precedenceForNotEquals;
|
||||
}
|
||||
private function getCssSelectorPrecedence(string $selector) : int
|
||||
{
|
||||
$selectorKey = \md5($selector);
|
||||
if (isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) {
|
||||
return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey];
|
||||
}
|
||||
$precedence = 0;
|
||||
foreach ($this->selectorPrecedenceMatchers as $matcher => $value) {
|
||||
if (\trim($selector) === '') {
|
||||
break;
|
||||
}
|
||||
$number = 0;
|
||||
$selector = \preg_replace('/' . $matcher . '\\w+/', '', $selector, -1, $number);
|
||||
$precedence += $value * (int) $number;
|
||||
}
|
||||
$this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
|
||||
return $precedence;
|
||||
}
|
||||
private function copyInlinableCssToStyleAttribute(\DOMElement $node, array $cssRule) : void
|
||||
{
|
||||
$declarationsBlock = $cssRule['declarationsBlock'];
|
||||
$newStyleDeclarations = $this->parseCssDeclarationsBlock($declarationsBlock);
|
||||
if ($newStyleDeclarations === []) {
|
||||
return;
|
||||
}
|
||||
// if it has a style attribute, get it, process it, and append (overwrite) new stuff
|
||||
if ($node->hasAttribute('style')) {
|
||||
// break it up into an associative array
|
||||
$oldStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
|
||||
} else {
|
||||
$oldStyleDeclarations = [];
|
||||
}
|
||||
$node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations));
|
||||
}
|
||||
private function generateStyleStringFromDeclarationsArrays(array $oldStyles, array $newStyles) : string
|
||||
{
|
||||
$cacheKey = \serialize([$oldStyles, $newStyles]);
|
||||
if (isset($this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey])) {
|
||||
return $this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey];
|
||||
}
|
||||
// Unset the overridden styles to preserve order, important if shorthand and individual properties are mixed
|
||||
foreach ($oldStyles as $attributeName => $attributeValue) {
|
||||
if (!isset($newStyles[$attributeName])) {
|
||||
continue;
|
||||
}
|
||||
$newAttributeValue = $newStyles[$attributeName];
|
||||
if ($this->attributeValueIsImportant($attributeValue) && !$this->attributeValueIsImportant($newAttributeValue)) {
|
||||
unset($newStyles[$attributeName]);
|
||||
} else {
|
||||
unset($oldStyles[$attributeName]);
|
||||
}
|
||||
}
|
||||
$combinedStyles = \array_merge($oldStyles, $newStyles);
|
||||
$style = '';
|
||||
foreach ($combinedStyles as $attributeName => $attributeValue) {
|
||||
$style .= \strtolower(\trim($attributeName)) . ': ' . \trim($attributeValue) . '; ';
|
||||
}
|
||||
$trimmedStyle = \rtrim($style);
|
||||
$this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey] = $trimmedStyle;
|
||||
return $trimmedStyle;
|
||||
}
|
||||
private function attributeValueIsImportant(string $attributeValue) : bool
|
||||
{
|
||||
return (bool) \preg_match('/!\\s*+important$/i', $attributeValue);
|
||||
}
|
||||
private function fillStyleAttributesWithMergedStyles() : void
|
||||
{
|
||||
foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
|
||||
$node = $this->visitedNodes[$nodePath];
|
||||
$currentStyleAttributes = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
|
||||
$node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($currentStyleAttributes, $styleAttributesForNode));
|
||||
}
|
||||
}
|
||||
private function removeImportantAnnotationFromAllInlineStyles() : void
|
||||
{
|
||||
foreach ($this->getAllNodesWithStyleAttribute() as $node) {
|
||||
$this->removeImportantAnnotationFromNodeInlineStyle($node);
|
||||
}
|
||||
}
|
||||
private function removeImportantAnnotationFromNodeInlineStyle(\DOMElement $node) : void
|
||||
{
|
||||
$inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
|
||||
$regularStyleDeclarations = [];
|
||||
$importantStyleDeclarations = [];
|
||||
foreach ($inlineStyleDeclarations as $property => $value) {
|
||||
if ($this->attributeValueIsImportant($value)) {
|
||||
$importantStyleDeclarations[$property] = $this->pregReplace('/\\s*+!\\s*+important$/i', '', $value);
|
||||
} else {
|
||||
$regularStyleDeclarations[$property] = $value;
|
||||
}
|
||||
}
|
||||
$inlineStyleDeclarationsInNewOrder = \array_merge($regularStyleDeclarations, $importantStyleDeclarations);
|
||||
$node->setAttribute('style', $this->generateStyleStringFromSingleDeclarationsArray($inlineStyleDeclarationsInNewOrder));
|
||||
}
|
||||
private function generateStyleStringFromSingleDeclarationsArray(array $styleDeclarations) : string
|
||||
{
|
||||
return $this->generateStyleStringFromDeclarationsArrays([], $styleDeclarations);
|
||||
}
|
||||
private function determineMatchingUninlinableCssRules(array $cssRules) : void
|
||||
{
|
||||
$this->matchingUninlinableCssRules = \array_filter($cssRules, function (array $cssRule) : bool {
|
||||
return $this->existsMatchForSelectorInCssRule($cssRule);
|
||||
});
|
||||
}
|
||||
private function existsMatchForSelectorInCssRule(array $cssRule) : bool
|
||||
{
|
||||
$selector = $cssRule['selector'];
|
||||
if ($cssRule['hasUnmatchablePseudo']) {
|
||||
$selector = $this->removeUnmatchablePseudoComponents($selector);
|
||||
}
|
||||
return $this->existsMatchForCssSelector($selector);
|
||||
}
|
||||
private function existsMatchForCssSelector(string $cssSelector) : bool
|
||||
{
|
||||
try {
|
||||
$nodesMatchingSelector = $this->getXPath()->query($this->getCssSelectorConverter()->toXPath($cssSelector));
|
||||
} catch (ParseException $e) {
|
||||
if ($this->debug) {
|
||||
throw $e;
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
return $nodesMatchingSelector !== \false && $nodesMatchingSelector->length !== 0;
|
||||
}
|
||||
private function removeUnmatchablePseudoComponents(string $selector) : string
|
||||
{
|
||||
// The regex allows nested brackets via `(?2)`.
|
||||
// A space is temporarily prepended because the callback can't determine if the match was at the very start.
|
||||
$selectorWithoutNots = \ltrim(\preg_replace_callback(
|
||||
'/([\\s>+~]?+):not(\\([^()]*+(?:(?2)[^()]*+)*+\\))/i',
|
||||
function (array $matches) : string {
|
||||
return $this->replaceUnmatchableNotComponent($matches);
|
||||
},
|
||||
' ' . $selector
|
||||
));
|
||||
$selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+', $selectorWithoutNots);
|
||||
if (!\preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorWithoutUnmatchablePseudoComponents)) {
|
||||
return $selectorWithoutUnmatchablePseudoComponents;
|
||||
}
|
||||
return \implode('', \array_map(function (string $selectorPart) : string {
|
||||
return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
|
||||
}, \preg_split('/(' . self::COMBINATOR_MATCHER . ')/', $selectorWithoutUnmatchablePseudoComponents, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY)));
|
||||
}
|
||||
private function replaceUnmatchableNotComponent(array $matches) : string
|
||||
{
|
||||
[$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches;
|
||||
if ($this->hasUnsupportedPseudoClass($notArgumentInBrackets)) {
|
||||
return $anyPrecedingCombinator !== '' ? $anyPrecedingCombinator . '*' : '';
|
||||
}
|
||||
return $notComponentWithAnyPrecedingCombinator;
|
||||
}
|
||||
private function removeSelectorComponents(string $matcher, string $selector) : string
|
||||
{
|
||||
return \preg_replace(['/([\\s>+~]|^)' . $matcher . '/i', '/' . $matcher . '/i'], ['$1*', ''], $selector);
|
||||
}
|
||||
private function removeUnsupportedOfTypePseudoClasses(string $selectorPart) : string
|
||||
{
|
||||
if (!$this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
|
||||
return $selectorPart;
|
||||
}
|
||||
return $this->removeSelectorComponents(':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+', $selectorPart);
|
||||
}
|
||||
private function copyUninlinableCssToStyleNode(CssDocument $parsedCss) : void
|
||||
{
|
||||
$css = $parsedCss->renderNonConditionalAtRules();
|
||||
// avoid including unneeded class dependency if there are no rules
|
||||
if ($this->getMatchingUninlinableCssRules() !== []) {
|
||||
$cssConcatenator = new CssConcatenator();
|
||||
foreach ($this->getMatchingUninlinableCssRules() as $cssRule) {
|
||||
$cssConcatenator->append([$cssRule['selector']], $cssRule['declarationsBlock'], $cssRule['media']);
|
||||
}
|
||||
$css .= $cssConcatenator->getCss();
|
||||
}
|
||||
// avoid adding empty style element
|
||||
if ($css !== '') {
|
||||
$this->addStyleElementToDocument($css);
|
||||
}
|
||||
}
|
||||
protected function addStyleElementToDocument(string $css) : void
|
||||
{
|
||||
$domDocument = $this->getDomDocument();
|
||||
$styleElement = $domDocument->createElement('style', $css);
|
||||
$styleAttribute = $domDocument->createAttribute('type');
|
||||
$styleAttribute->value = 'text/css';
|
||||
$styleElement->appendChild($styleAttribute);
|
||||
$headElement = $this->getHeadElement();
|
||||
$headElement->appendChild($styleElement);
|
||||
}
|
||||
private function getHeadElement() : \DOMElement
|
||||
{
|
||||
$node = $this->getDomDocument()->getElementsByTagName('head')->item(0);
|
||||
if (!$node instanceof \DOMElement) {
|
||||
throw new \UnexpectedValueException('There is no HEAD element. This should never happen.', 1617923227);
|
||||
}
|
||||
return $node;
|
||||
}
|
||||
private function pregReplace(string $pattern, string $replacement, string $subject) : string
|
||||
{
|
||||
$result = \preg_replace($pattern, $replacement, $subject);
|
||||
if (!\is_string($result)) {
|
||||
$this->logOrThrowPregLastError();
|
||||
$result = $subject;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private function logOrThrowPregLastError() : void
|
||||
{
|
||||
$pcreConstants = \get_defined_constants(\true)['pcre'];
|
||||
$pcreErrorConstantNames = \array_flip(\array_filter($pcreConstants, static function (string $key) : bool {
|
||||
return \substr($key, -6) === '_ERROR';
|
||||
}, \ARRAY_FILTER_USE_KEY));
|
||||
$pregLastError = \preg_last_error();
|
||||
$message = 'PCRE regex execution error `' . (string) ($pcreErrorConstantNames[$pregLastError] ?? $pregLastError) . '`';
|
||||
if ($this->debug) {
|
||||
throw new \RuntimeException($message, 1592870147);
|
||||
}
|
||||
\trigger_error($message);
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\HtmlProcessor;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
abstract class AbstractHtmlProcessor
|
||||
{
|
||||
protected const DEFAULT_DOCUMENT_TYPE = '<!DOCTYPE html>';
|
||||
protected const CONTENT_TYPE_META_TAG = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
|
||||
protected const PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER = '(?:command|embed|keygen|source|track|wbr)';
|
||||
protected const TAGNAME_ALLOWED_BEFORE_BODY_MATCHER = '(?:html|head|base|command|link|meta|noscript|script|style|template|title)';
|
||||
protected const HTML_COMMENT_PATTERN = '/<!--[^-]*+(?:-(?!->)[^-]*+)*+(?:-->|$)/';
|
||||
protected const HTML_TEMPLATE_ELEMENT_PATTERN = '%<template[\\s>][^<]*+(?:<(?!/template>)[^<]*+)*+(?:</template>|$)%i';
|
||||
protected $domDocument = null;
|
||||
private $xPath = null;
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
public static function fromHtml(string $unprocessedHtml) : self
|
||||
{
|
||||
if ($unprocessedHtml === '') {
|
||||
throw new \InvalidArgumentException('The provided HTML must not be empty.', 1515763647);
|
||||
}
|
||||
$instance = new static();
|
||||
$instance->setHtml($unprocessedHtml);
|
||||
return $instance;
|
||||
}
|
||||
public static function fromDomDocument(\DOMDocument $document) : self
|
||||
{
|
||||
$instance = new static();
|
||||
$instance->setDomDocument($document);
|
||||
return $instance;
|
||||
}
|
||||
private function setHtml(string $html) : void
|
||||
{
|
||||
$this->createUnifiedDomDocument($html);
|
||||
}
|
||||
public function getDomDocument() : \DOMDocument
|
||||
{
|
||||
if (!$this->domDocument instanceof \DOMDocument) {
|
||||
$message = self::class . '::setDomDocument() has not yet been called on ' . static::class;
|
||||
throw new \UnexpectedValueException($message, 1570472239);
|
||||
}
|
||||
return $this->domDocument;
|
||||
}
|
||||
private function setDomDocument(\DOMDocument $domDocument) : void
|
||||
{
|
||||
$this->domDocument = $domDocument;
|
||||
$this->xPath = new \DOMXPath($this->domDocument);
|
||||
}
|
||||
protected function getXPath() : \DOMXPath
|
||||
{
|
||||
if (!$this->xPath instanceof \DOMXPath) {
|
||||
$message = self::class . '::setDomDocument() has not yet been called on ' . static::class;
|
||||
throw new \UnexpectedValueException($message, 1617819086);
|
||||
}
|
||||
return $this->xPath;
|
||||
}
|
||||
public function render() : string
|
||||
{
|
||||
$htmlWithPossibleErroneousClosingTags = $this->getDomDocument()->saveHTML();
|
||||
return $this->removeSelfClosingTagsClosingTags($htmlWithPossibleErroneousClosingTags);
|
||||
}
|
||||
public function renderBodyContent() : string
|
||||
{
|
||||
$htmlWithPossibleErroneousClosingTags = $this->getDomDocument()->saveHTML($this->getBodyElement());
|
||||
$bodyNodeHtml = $this->removeSelfClosingTagsClosingTags($htmlWithPossibleErroneousClosingTags);
|
||||
return \preg_replace('%</?+body(?:\\s[^>]*+)?+>%', '', $bodyNodeHtml);
|
||||
}
|
||||
private function removeSelfClosingTagsClosingTags(string $html) : string
|
||||
{
|
||||
return \preg_replace('%</' . self::PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER . '>%', '', $html);
|
||||
}
|
||||
private function getBodyElement() : \DOMElement
|
||||
{
|
||||
$node = $this->getDomDocument()->getElementsByTagName('body')->item(0);
|
||||
if (!$node instanceof \DOMElement) {
|
||||
throw new \RuntimeException('There is no body element.', 1617922607);
|
||||
}
|
||||
return $node;
|
||||
}
|
||||
private function createUnifiedDomDocument(string $html) : void
|
||||
{
|
||||
$this->createRawDomDocument($html);
|
||||
$this->ensureExistenceOfBodyElement();
|
||||
}
|
||||
private function createRawDomDocument(string $html) : void
|
||||
{
|
||||
$domDocument = new \DOMDocument();
|
||||
$domDocument->strictErrorChecking = \false;
|
||||
$domDocument->formatOutput = \false;
|
||||
$libXmlState = \libxml_use_internal_errors(\true);
|
||||
$domDocument->loadHTML($this->prepareHtmlForDomConversion($html));
|
||||
\libxml_clear_errors();
|
||||
\libxml_use_internal_errors($libXmlState);
|
||||
$this->setDomDocument($domDocument);
|
||||
}
|
||||
private function prepareHtmlForDomConversion(string $html) : string
|
||||
{
|
||||
$htmlWithSelfClosingSlashes = $this->ensurePhpUnrecognizedSelfClosingTagsAreXml($html);
|
||||
$htmlWithDocumentType = $this->ensureDocumentType($htmlWithSelfClosingSlashes);
|
||||
return $this->addContentTypeMetaTag($htmlWithDocumentType);
|
||||
}
|
||||
private function ensureDocumentType(string $html) : string
|
||||
{
|
||||
$hasDocumentType = \stripos($html, '<!DOCTYPE') !== \false;
|
||||
if ($hasDocumentType) {
|
||||
return $this->normalizeDocumentType($html);
|
||||
}
|
||||
return self::DEFAULT_DOCUMENT_TYPE . $html;
|
||||
}
|
||||
private function normalizeDocumentType(string $html) : string
|
||||
{
|
||||
// Limit to replacing the first occurrence: as an optimization; and in case an example exists as unescaped text.
|
||||
return \preg_replace('/<!DOCTYPE\\s++html(?=[\\s>])/i', '<!DOCTYPE html', $html, 1);
|
||||
}
|
||||
private function addContentTypeMetaTag(string $html) : string
|
||||
{
|
||||
if ($this->hasContentTypeMetaTagInHead($html)) {
|
||||
return $html;
|
||||
}
|
||||
// We are trying to insert the meta tag to the right spot in the DOM.
|
||||
// If we just prepended it to the HTML, we would lose attributes set to the HTML tag.
|
||||
$hasHeadTag = \preg_match('/<head[\\s>]/i', $html);
|
||||
$hasHtmlTag = \stripos($html, '<html') !== \false;
|
||||
if ($hasHeadTag) {
|
||||
$reworkedHtml = \preg_replace('/<head(?=[\\s>])([^>]*+)>/i', '<head$1>' . self::CONTENT_TYPE_META_TAG, $html);
|
||||
} elseif ($hasHtmlTag) {
|
||||
$reworkedHtml = \preg_replace('/<html(.*?)>/is', '<html$1><head>' . self::CONTENT_TYPE_META_TAG . '</head>', $html);
|
||||
} else {
|
||||
$reworkedHtml = self::CONTENT_TYPE_META_TAG . $html;
|
||||
}
|
||||
return $reworkedHtml;
|
||||
}
|
||||
private function hasContentTypeMetaTagInHead(string $html) : bool
|
||||
{
|
||||
\preg_match('%^.*?(?=<meta(?=\\s)[^>]*\\shttp-equiv=(["\']?+)Content-Type\\g{-1}[\\s/>])%is', $html, $matches);
|
||||
if (isset($matches[0])) {
|
||||
$htmlBefore = $matches[0];
|
||||
try {
|
||||
$hasContentTypeMetaTagInHead = !$this->hasEndOfHeadElement($htmlBefore);
|
||||
} catch (\RuntimeException $exception) {
|
||||
// If something unexpected occurs, assume the `Content-Type` that was found is valid.
|
||||
\trigger_error($exception->getMessage());
|
||||
$hasContentTypeMetaTagInHead = \true;
|
||||
}
|
||||
} else {
|
||||
$hasContentTypeMetaTagInHead = \false;
|
||||
}
|
||||
return $hasContentTypeMetaTagInHead;
|
||||
}
|
||||
private function hasEndOfHeadElement(string $html) : bool
|
||||
{
|
||||
$headEndTagMatchCount = \preg_match('%<(?!' . self::TAGNAME_ALLOWED_BEFORE_BODY_MATCHER . '[\\s/>])\\w|</head>%i', $html);
|
||||
if (\is_int($headEndTagMatchCount) && $headEndTagMatchCount > 0) {
|
||||
// An exception to the implicit end of the `<head>` is any content within a `<template>` element, as well in
|
||||
// comments. As an optimization, this is only checked for if a potential `<head>` end tag is found.
|
||||
$htmlWithoutCommentsOrTemplates = $this->removeHtmlTemplateElements($this->removeHtmlComments($html));
|
||||
$hasEndOfHeadElement = $htmlWithoutCommentsOrTemplates === $html || $this->hasEndOfHeadElement($htmlWithoutCommentsOrTemplates);
|
||||
} else {
|
||||
$hasEndOfHeadElement = \false;
|
||||
}
|
||||
return $hasEndOfHeadElement;
|
||||
}
|
||||
private function removeHtmlComments(string $html) : string
|
||||
{
|
||||
$result = \preg_replace(self::HTML_COMMENT_PATTERN, '', $html);
|
||||
if (!\is_string($result)) {
|
||||
throw new \RuntimeException('Internal PCRE error', 1616521475);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private function removeHtmlTemplateElements(string $html) : string
|
||||
{
|
||||
$result = \preg_replace(self::HTML_TEMPLATE_ELEMENT_PATTERN, '', $html);
|
||||
if (!\is_string($result)) {
|
||||
throw new \RuntimeException('Internal PCRE error', 1616519652);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private function ensurePhpUnrecognizedSelfClosingTagsAreXml(string $html) : string
|
||||
{
|
||||
return \preg_replace('%<' . self::PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER . '\\b[^>]*+(?<!/)(?=>)%', '$0/', $html);
|
||||
}
|
||||
private function ensureExistenceOfBodyElement() : void
|
||||
{
|
||||
if ($this->getDomDocument()->getElementsByTagName('body')->item(0) instanceof \DOMElement) {
|
||||
return;
|
||||
}
|
||||
$htmlElement = $this->getDomDocument()->getElementsByTagName('html')->item(0);
|
||||
if (!$htmlElement instanceof \DOMElement) {
|
||||
throw new \UnexpectedValueException('There is no HTML element although there should be one.', 1569930853);
|
||||
}
|
||||
$htmlElement->appendChild($this->getDomDocument()->createElement('body'));
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\HtmlProcessor;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
class CssToAttributeConverter extends AbstractHtmlProcessor
|
||||
{
|
||||
private $cssToHtmlMap = ['background-color' => ['attribute' => 'bgcolor'], 'text-align' => ['attribute' => 'align', 'nodes' => ['p', 'div', 'td', 'th'], 'values' => ['left', 'right', 'center', 'justify']], 'float' => ['attribute' => 'align', 'nodes' => ['table', 'img'], 'values' => ['left', 'right']], 'border-spacing' => ['attribute' => 'cellspacing', 'nodes' => ['table']]];
|
||||
private static $parsedCssCache = [];
|
||||
public function convertCssToVisualAttributes() : self
|
||||
{
|
||||
foreach ($this->getAllNodesWithStyleAttribute() as $node) {
|
||||
$inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
|
||||
$this->mapCssToHtmlAttributes($inlineStyleDeclarations, $node);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
private function getAllNodesWithStyleAttribute() : \DOMNodeList
|
||||
{
|
||||
return $this->getXPath()->query('//*[@style]');
|
||||
}
|
||||
private function parseCssDeclarationsBlock(string $cssDeclarationsBlock) : array
|
||||
{
|
||||
if (isset(self::$parsedCssCache[$cssDeclarationsBlock])) {
|
||||
return self::$parsedCssCache[$cssDeclarationsBlock];
|
||||
}
|
||||
$properties = [];
|
||||
foreach (\preg_split('/;(?!base64|charset)/', $cssDeclarationsBlock) as $declaration) {
|
||||
$matches = [];
|
||||
if (!\preg_match('/^([A-Za-z\\-]+)\\s*:\\s*(.+)$/s', \trim($declaration), $matches)) {
|
||||
continue;
|
||||
}
|
||||
$propertyName = \strtolower($matches[1]);
|
||||
$propertyValue = $matches[2];
|
||||
$properties[$propertyName] = $propertyValue;
|
||||
}
|
||||
self::$parsedCssCache[$cssDeclarationsBlock] = $properties;
|
||||
return $properties;
|
||||
}
|
||||
private function mapCssToHtmlAttributes(array $styles, \DOMElement $node) : void
|
||||
{
|
||||
foreach ($styles as $property => $value) {
|
||||
// Strip !important indicator
|
||||
$value = \trim(\str_replace('!important', '', $value));
|
||||
$this->mapCssToHtmlAttribute($property, $value, $node);
|
||||
}
|
||||
}
|
||||
private function mapCssToHtmlAttribute(string $property, string $value, \DOMElement $node) : void
|
||||
{
|
||||
if (!$this->mapSimpleCssProperty($property, $value, $node)) {
|
||||
$this->mapComplexCssProperty($property, $value, $node);
|
||||
}
|
||||
}
|
||||
private function mapSimpleCssProperty(string $property, string $value, \DOMElement $node) : bool
|
||||
{
|
||||
if (!isset($this->cssToHtmlMap[$property])) {
|
||||
return \false;
|
||||
}
|
||||
$mapping = $this->cssToHtmlMap[$property];
|
||||
$nodesMatch = !isset($mapping['nodes']) || \in_array($node->nodeName, $mapping['nodes'], \true);
|
||||
$valuesMatch = !isset($mapping['values']) || \in_array($value, $mapping['values'], \true);
|
||||
$canBeMapped = $nodesMatch && $valuesMatch;
|
||||
if ($canBeMapped) {
|
||||
$node->setAttribute($mapping['attribute'], $value);
|
||||
}
|
||||
return $canBeMapped;
|
||||
}
|
||||
private function mapComplexCssProperty(string $property, string $value, \DOMElement $node) : void
|
||||
{
|
||||
switch ($property) {
|
||||
case 'background':
|
||||
$this->mapBackgroundProperty($node, $value);
|
||||
break;
|
||||
case 'width':
|
||||
// intentional fall-through
|
||||
case 'height':
|
||||
$this->mapWidthOrHeightProperty($node, $value, $property);
|
||||
break;
|
||||
case 'margin':
|
||||
$this->mapMarginProperty($node, $value);
|
||||
break;
|
||||
case 'border':
|
||||
$this->mapBorderProperty($node, $value);
|
||||
break;
|
||||
default:
|
||||
}
|
||||
}
|
||||
private function mapBackgroundProperty(\DOMElement $node, string $value) : void
|
||||
{
|
||||
// parse out the color, if any
|
||||
$styles = \explode(' ', $value, 2);
|
||||
$first = $styles[0];
|
||||
if (\is_numeric($first[0]) || \strncmp($first, 'url', 3) === 0) {
|
||||
return;
|
||||
}
|
||||
// as this is not a position or image, assume it's a color
|
||||
$node->setAttribute('bgcolor', $first);
|
||||
}
|
||||
private function mapWidthOrHeightProperty(\DOMElement $node, string $value, string $property) : void
|
||||
{
|
||||
// only parse values in px and %, but not values like "auto"
|
||||
if (!\preg_match('/^(\\d+)(\\.(\\d+))?(px|%)$/', $value)) {
|
||||
return;
|
||||
}
|
||||
$number = \preg_replace('/[^0-9.%]/', '', $value);
|
||||
$node->setAttribute($property, $number);
|
||||
}
|
||||
private function mapMarginProperty(\DOMElement $node, string $value) : void
|
||||
{
|
||||
if (!$this->isTableOrImageNode($node)) {
|
||||
return;
|
||||
}
|
||||
$margins = $this->parseCssShorthandValue($value);
|
||||
if ($margins['left'] === 'auto' && $margins['right'] === 'auto') {
|
||||
$node->setAttribute('align', 'center');
|
||||
}
|
||||
}
|
||||
private function mapBorderProperty(\DOMElement $node, string $value) : void
|
||||
{
|
||||
if (!$this->isTableOrImageNode($node)) {
|
||||
return;
|
||||
}
|
||||
if ($value === 'none' || $value === '0') {
|
||||
$node->setAttribute('border', '0');
|
||||
}
|
||||
}
|
||||
private function isTableOrImageNode(\DOMElement $node) : bool
|
||||
{
|
||||
return $node->nodeName === 'table' || $node->nodeName === 'img';
|
||||
}
|
||||
private function parseCssShorthandValue(string $value) : array
|
||||
{
|
||||
$values = \preg_split('/\\s+/', $value);
|
||||
$css = [];
|
||||
$css['top'] = $values[0];
|
||||
$css['right'] = \count($values) > 1 ? $values[1] : $css['top'];
|
||||
$css['bottom'] = \count($values) > 2 ? $values[2] : $css['top'];
|
||||
$css['left'] = \count($values) > 3 ? $values[3] : $css['right'];
|
||||
return $css;
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\HtmlProcessor;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
class HtmlNormalizer extends AbstractHtmlProcessor
|
||||
{
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\HtmlProcessor;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
use MailPoetVendor\Pelago\Emogrifier\CssInliner;
|
||||
use MailPoetVendor\Pelago\Emogrifier\Utilities\ArrayIntersector;
|
||||
class HtmlPruner extends AbstractHtmlProcessor
|
||||
{
|
||||
private const DISPLAY_NONE_MATCHER = '//*[@style and contains(translate(translate(@style," ",""),"NOE","noe"),"display:none")' . ' and not(@class and contains(concat(" ", normalize-space(@class), " "), " -emogrifier-keep "))]';
|
||||
public function removeElementsWithDisplayNone() : self
|
||||
{
|
||||
$elementsWithStyleDisplayNone = $this->getXPath()->query(self::DISPLAY_NONE_MATCHER);
|
||||
if ($elementsWithStyleDisplayNone->length === 0) {
|
||||
return $this;
|
||||
}
|
||||
foreach ($elementsWithStyleDisplayNone as $element) {
|
||||
$parentNode = $element->parentNode;
|
||||
if ($parentNode !== null) {
|
||||
$parentNode->removeChild($element);
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
public function removeRedundantClasses(array $classesToKeep = []) : self
|
||||
{
|
||||
$elementsWithClassAttribute = $this->getXPath()->query('//*[@class]');
|
||||
if ($classesToKeep !== []) {
|
||||
$this->removeClassesFromElements($elementsWithClassAttribute, $classesToKeep);
|
||||
} else {
|
||||
// Avoid unnecessary processing if there are no classes to keep.
|
||||
$this->removeClassAttributeFromElements($elementsWithClassAttribute);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
private function removeClassesFromElements(\DOMNodeList $elements, array $classesToKeep) : void
|
||||
{
|
||||
$classesToKeepIntersector = new ArrayIntersector($classesToKeep);
|
||||
foreach ($elements as $element) {
|
||||
$elementClasses = \preg_split('/\\s++/', \trim($element->getAttribute('class')));
|
||||
$elementClassesToKeep = $classesToKeepIntersector->intersectWith($elementClasses);
|
||||
if ($elementClassesToKeep !== []) {
|
||||
$element->setAttribute('class', \implode(' ', $elementClassesToKeep));
|
||||
} else {
|
||||
$element->removeAttribute('class');
|
||||
}
|
||||
}
|
||||
}
|
||||
private function removeClassAttributeFromElements(\DOMNodeList $elements) : void
|
||||
{
|
||||
foreach ($elements as $element) {
|
||||
$element->removeAttribute('class');
|
||||
}
|
||||
}
|
||||
public function removeRedundantClassesAfterCssInlined(CssInliner $cssInliner) : self
|
||||
{
|
||||
$classesToKeepAsKeys = [];
|
||||
foreach ($cssInliner->getMatchingUninlinableSelectors() as $selector) {
|
||||
\preg_match_all('/\\.(-?+[_a-zA-Z][\\w\\-]*+)/', $selector, $matches);
|
||||
$classesToKeepAsKeys += \array_fill_keys($matches[1], \true);
|
||||
}
|
||||
$this->removeRedundantClasses(\array_keys($classesToKeepAsKeys));
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
<?php
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\Utilities;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
class ArrayIntersector
|
||||
{
|
||||
private $invertedArray;
|
||||
public function __construct(array $array)
|
||||
{
|
||||
$this->invertedArray = \array_flip($array);
|
||||
}
|
||||
public function intersectWith(array $array) : array
|
||||
{
|
||||
$invertedArray = \array_flip($array);
|
||||
$invertedIntersection = \array_intersect_key($invertedArray, $this->invertedArray);
|
||||
return \array_flip($invertedIntersection);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
namespace MailPoetVendor\Pelago\Emogrifier\Utilities;
|
||||
if (!defined('ABSPATH')) exit;
|
||||
class CssConcatenator
|
||||
{
|
||||
private $mediaRules = [];
|
||||
public function append(array $selectors, string $declarationsBlock, string $media = '') : void
|
||||
{
|
||||
$selectorsAsKeys = \array_flip($selectors);
|
||||
$mediaRule = $this->getOrCreateMediaRuleToAppendTo($media);
|
||||
$ruleBlocks = $mediaRule->ruleBlocks;
|
||||
$lastRuleBlock = \end($ruleBlocks);
|
||||
$hasSameDeclarationsAsLastRule = \is_object($lastRuleBlock) && $declarationsBlock === $lastRuleBlock->declarationsBlock;
|
||||
if ($hasSameDeclarationsAsLastRule) {
|
||||
$lastRuleBlock->selectorsAsKeys += $selectorsAsKeys;
|
||||
} else {
|
||||
$lastRuleBlockSelectors = \is_object($lastRuleBlock) ? $lastRuleBlock->selectorsAsKeys : [];
|
||||
$hasSameSelectorsAsLastRule = \is_object($lastRuleBlock) && self::hasEquivalentSelectors($selectorsAsKeys, $lastRuleBlockSelectors);
|
||||
if ($hasSameSelectorsAsLastRule) {
|
||||
$lastDeclarationsBlockWithoutSemicolon = \rtrim(\rtrim($lastRuleBlock->declarationsBlock), ';');
|
||||
$lastRuleBlock->declarationsBlock = $lastDeclarationsBlockWithoutSemicolon . ';' . $declarationsBlock;
|
||||
} else {
|
||||
$mediaRule->ruleBlocks[] = (object) \compact('selectorsAsKeys', 'declarationsBlock');
|
||||
}
|
||||
}
|
||||
}
|
||||
public function getCss() : string
|
||||
{
|
||||
return \implode('', \array_map([self::class, 'getMediaRuleCss'], $this->mediaRules));
|
||||
}
|
||||
private function getOrCreateMediaRuleToAppendTo(string $media) : object
|
||||
{
|
||||
$lastMediaRule = \end($this->mediaRules);
|
||||
if (\is_object($lastMediaRule) && $media === $lastMediaRule->media) {
|
||||
return $lastMediaRule;
|
||||
}
|
||||
$newMediaRule = (object) ['media' => $media, 'ruleBlocks' => []];
|
||||
$this->mediaRules[] = $newMediaRule;
|
||||
return $newMediaRule;
|
||||
}
|
||||
private static function hasEquivalentSelectors(array $selectorsAsKeys1, array $selectorsAsKeys2) : bool
|
||||
{
|
||||
return \count($selectorsAsKeys1) === \count($selectorsAsKeys2) && \count($selectorsAsKeys1) === \count($selectorsAsKeys1 + $selectorsAsKeys2);
|
||||
}
|
||||
private static function getMediaRuleCss(object $mediaRule) : string
|
||||
{
|
||||
$ruleBlocks = $mediaRule->ruleBlocks;
|
||||
$css = \implode('', \array_map([self::class, 'getRuleBlockCss'], $ruleBlocks));
|
||||
$media = $mediaRule->media;
|
||||
if ($media !== '') {
|
||||
$css = $media . '{' . $css . '}';
|
||||
}
|
||||
return $css;
|
||||
}
|
||||
private static function getRuleBlockCss(object $ruleBlock) : string
|
||||
{
|
||||
$selectorsAsKeys = $ruleBlock->selectorsAsKeys;
|
||||
$selectors = \array_keys($selectorsAsKeys);
|
||||
$declarationsBlock = $ruleBlock->declarationsBlock;
|
||||
return \implode(',', $selectors) . '{' . $declarationsBlock . '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
Reference in New Issue
Block a user