PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/woocommerce/includes/libraries/class-emogrifier.php

https://gitlab.com/webkod3r/tripolis
PHP | 788 lines | 384 code | 95 blank | 309 comment | 49 complexity | 1ff5e3cc700dfd14148fbec3e4df4b63 MD5 | raw file
  1. <?php
  2. /**
  3. * This class provides functions for converting CSS styles into inline style attributes in your HTML code
  4. *
  5. * For more information, please see the README.md file.
  6. *
  7. * @author Cameron Brooks
  8. * @author Jaime Prado
  9. * @author Roman Ožana <ozana@omdesign.cz>
  10. */
  11. class Emogrifier {
  12. /**
  13. * @var string
  14. */
  15. const ENCODING = 'UTF-8';
  16. /**
  17. * @var integer
  18. */
  19. const CACHE_KEY_CSS = 0;
  20. /**
  21. * @var integer
  22. */
  23. const CACHE_KEY_SELECTOR = 1;
  24. /**
  25. * @var integer
  26. */
  27. const CACHE_KEY_XPATH = 2;
  28. /**
  29. * @var integer
  30. */
  31. const CACHE_KEY_CSS_DECLARATION_BLOCK = 3;
  32. /**
  33. * for calculating nth-of-type and nth-child selectors.
  34. *
  35. * @var integer
  36. */
  37. const INDEX = 0;
  38. /**
  39. * for calculating nth-of-type and nth-child selectors.
  40. *
  41. * @var integer
  42. */
  43. const MULTIPLIER = 1;
  44. /**
  45. * @var string
  46. */
  47. const ID_ATTRIBUTE_MATCHER = '/(\\w+)?\\#([\\w\\-]+)/';
  48. /**
  49. * @var string
  50. */
  51. const CLASS_ATTRIBUTE_MATCHER = '/(\\w+|[\\*\\]])?((\\.[\\w\\-]+)+)/';
  52. /**
  53. * @var string
  54. */
  55. private $html = '';
  56. /**
  57. * @var string
  58. */
  59. private $css = '';
  60. /**
  61. * @var array<string>
  62. */
  63. private $unprocessableHtmlTags = array('wbr');
  64. /**
  65. * @var array<array>
  66. */
  67. private $caches = array(
  68. self::CACHE_KEY_CSS => array(),
  69. self::CACHE_KEY_SELECTOR => array(),
  70. self::CACHE_KEY_XPATH => array(),
  71. self::CACHE_KEY_CSS_DECLARATION_BLOCK => array(),
  72. );
  73. /**
  74. * the visited nodes with the XPath paths as array keys.
  75. *
  76. * @var array<\DOMNode>
  77. */
  78. private $visitedNodes = array();
  79. /**
  80. * the styles to apply to the nodes with the XPath paths as array keys for the outer array and the attribute names/values.
  81. * as key/value pairs for the inner array.
  82. *
  83. * @var array<array><string>
  84. */
  85. private $styleAttributesForNodes = array();
  86. /**
  87. * This attribute applies to the case where you want to preserve your original text encoding.
  88. *
  89. * By default, emogrifier translates your text into HTML entities for two reasons:
  90. *
  91. * 1. Because of client incompatibilities, it is better practice to send out HTML entities rather than unicode over email.
  92. *
  93. * 2. It translates any illegal XML characters that DOMDocument cannot work with.
  94. *
  95. * If you would like to preserve your original encoding, set this attribute to TRUE.
  96. *
  97. * @var boolean
  98. */
  99. public $preserveEncoding = false;
  100. public static $_media = '';
  101. /**
  102. * The constructor.
  103. *
  104. * @param string $html the HTML to emogrify, must be UTF-8-encoded
  105. * @param string $css the CSS to merge, must be UTF-8-encoded
  106. */
  107. public function __construct($html = '', $css = '') {
  108. $this->setHtml($html);
  109. $this->setCss($css);
  110. }
  111. /**
  112. * The destructor.
  113. */
  114. public function __destruct() {
  115. $this->purgeVisitedNodes();
  116. }
  117. /**
  118. * Sets the HTML to emogrify.
  119. *
  120. * @param string $html the HTML to emogrify, must be UTF-8-encoded
  121. */
  122. public function setHtml($html = '') {
  123. $this->html = $html;
  124. }
  125. /**
  126. * Sets the CSS to merge with the HTML.
  127. *
  128. * @param string $css the CSS to merge, must be UTF-8-encoded
  129. */
  130. public function setCss($css = '') {
  131. $this->css = $css;
  132. }
  133. /**
  134. * Clears all caches.
  135. */
  136. private function clearAllCaches() {
  137. $this->clearCache(self::CACHE_KEY_CSS);
  138. $this->clearCache(self::CACHE_KEY_SELECTOR);
  139. $this->clearCache(self::CACHE_KEY_XPATH);
  140. $this->clearCache(self::CACHE_KEY_CSS_DECLARATION_BLOCK);
  141. }
  142. /**
  143. * Clears a single cache by key.
  144. *
  145. * @param integer $key the cache key, must be CACHE_KEY_CSS, CACHE_KEY_SELECTOR, CACHE_KEY_XPATH or CACHE_KEY_CSS_DECLARATION_BLOCK
  146. *
  147. * @throws InvalidArgumentException
  148. */
  149. private function clearCache($key) {
  150. $allowedCacheKeys = array(self::CACHE_KEY_CSS, self::CACHE_KEY_SELECTOR, self::CACHE_KEY_XPATH, self::CACHE_KEY_CSS_DECLARATION_BLOCK);
  151. if (!in_array($key, $allowedCacheKeys, true)) {
  152. throw new InvalidArgumentException('Invalid cache key: ' . $key, 1391822035);
  153. }
  154. $this->caches[$key] = array();
  155. }
  156. /**
  157. * Purges the visited nodes.
  158. */
  159. private function purgeVisitedNodes() {
  160. $this->visitedNodes = array();
  161. $this->styleAttributesForNodes = array();
  162. }
  163. /**
  164. * Marks a tag for removal.
  165. *
  166. * There are some HTML tags that DOMDocument cannot process, and it will throw an error if it encounters them.
  167. * In particular, DOMDocument will complain if you try to use HTML5 tags in an XHTML document.
  168. *
  169. * Note: The tags will not be removed if they have any content.
  170. *
  171. * @param string $tagName the tag name, e.g., "p"
  172. */
  173. public function addUnprocessableHtmlTag($tagName) {
  174. $this->unprocessableHtmlTags[] = $tagName;
  175. }
  176. /**
  177. * Drops a tag from the removal list.
  178. *
  179. * @param string $tagName the tag name, e.g., "p"
  180. */
  181. public function removeUnprocessableHtmlTag($tagName) {
  182. $key = array_search($tagName, $this->unprocessableHtmlTags, true);
  183. if ($key !== false) {
  184. unset($this->unprocessableHtmlTags[$key]);
  185. }
  186. }
  187. /**
  188. * Applies the CSS you submit to the HTML you submit.
  189. *
  190. * This method places the CSS inline.
  191. *
  192. * @return string
  193. *
  194. * @throws BadMethodCallException
  195. */
  196. public function emogrify() {
  197. if ($this->html === '') {
  198. throw new BadMethodCallException('Please set some HTML first before calling emogrify.', 1390393096);
  199. }
  200. $xmlDocument = $this->createXmlDocument();
  201. $xpath = new DOMXPath($xmlDocument);
  202. $this->clearAllCaches();
  203. // before be begin processing the CSS file, parse the document and normalize all existing CSS attributes (changes 'DISPLAY: none' to 'display: none');
  204. // we wouldn't have to do this if DOMXPath supported XPath 2.0.
  205. // also store a reference of nodes with existing inline styles so we don't overwrite them
  206. $this->purgeVisitedNodes();
  207. $nodesWithStyleAttributes = $xpath->query('//*[@style]');
  208. if ($nodesWithStyleAttributes !== false) {
  209. /** @var $nodeWithStyleAttribute DOMNode */
  210. foreach ($nodesWithStyleAttributes as $node) {
  211. $normalizedOriginalStyle = preg_replace_callback( '/[A-z\\-]+(?=\\:)/S', array( $this, 'strtolower' ), $node->getAttribute('style') );
  212. // in order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles
  213. $nodePath = $node->getNodePath();
  214. if (!isset($this->styleAttributesForNodes[$nodePath])) {
  215. $this->styleAttributesForNodes[$nodePath] = $this->parseCssDeclarationBlock($normalizedOriginalStyle);
  216. $this->visitedNodes[$nodePath] = $node;
  217. }
  218. $node->setAttribute('style', $normalizedOriginalStyle);
  219. }
  220. }
  221. // grab any existing style blocks from the html and append them to the existing CSS
  222. // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
  223. $allCss = $this->css;
  224. $allCss .= $this->getCssFromAllStyleNodes($xpath);
  225. $cssParts = $this->splitCssAndMediaQuery($allCss);
  226. self::$_media = ''; // reset
  227. $cssKey = md5($cssParts['css']);
  228. if (!isset($this->caches[self::CACHE_KEY_CSS][$cssKey])) {
  229. // process the CSS file for selectors and definitions
  230. preg_match_all('/(?:^|[\\s^{}]*)([^{]+){([^}]*)}/mis', $cssParts['css'], $matches, PREG_SET_ORDER);
  231. $allSelectors = array();
  232. foreach ($matches as $key => $selectorString) {
  233. // if there is a blank definition, skip
  234. if (!strlen(trim($selectorString[2]))) {
  235. continue;
  236. }
  237. // else split by commas and duplicate attributes so we can sort by selector precedence
  238. $selectors = explode(',', $selectorString[1]);
  239. foreach ($selectors as $selector) {
  240. // don't process pseudo-elements and behavioral (dynamic) pseudo-classes; ONLY allow structural pseudo-classes
  241. if (strpos($selector, ':') !== false && !preg_match('/:\\S+\\-(child|type)\\(/i', $selector)) {
  242. continue;
  243. }
  244. $allSelectors[] = array('selector' => trim($selector),
  245. 'attributes' => trim($selectorString[2]),
  246. // keep track of where it appears in the file, since order is important
  247. 'line' => $key,
  248. );
  249. }
  250. }
  251. // now sort the selectors by precedence
  252. usort($allSelectors, array($this,'sortBySelectorPrecedence'));
  253. $this->caches[self::CACHE_KEY_CSS][$cssKey] = $allSelectors;
  254. }
  255. foreach ($this->caches[self::CACHE_KEY_CSS][$cssKey] as $value) {
  256. // query the body for the xpath selector
  257. $nodesMatchingCssSelectors = $xpath->query($this->translateCssToXpath($value['selector']));
  258. /** @var $node \DOMNode */
  259. foreach ($nodesMatchingCssSelectors as $node) {
  260. // if it has a style attribute, get it, process it, and append (overwrite) new stuff
  261. if ($node->hasAttribute('style')) {
  262. // break it up into an associative array
  263. $oldStyleDeclarations = $this->parseCssDeclarationBlock($node->getAttribute('style'));
  264. } else {
  265. $oldStyleDeclarations = array();
  266. }
  267. $newStyleDeclarations = $this->parseCssDeclarationBlock($value['attributes']);
  268. $node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations));
  269. }
  270. }
  271. // now iterate through the nodes that contained inline styles in the original HTML
  272. foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
  273. $node = $this->visitedNodes[$nodePath];
  274. $currentStyleAttributes = $this->parseCssDeclarationBlock($node->getAttribute('style'));
  275. $node->setAttribute('style', $this->generateStyleStringFromDeclarationsArrays($currentStyleAttributes, $styleAttributesForNode));
  276. }
  277. // This removes styles from your email that contain display:none.
  278. // We need to look for display:none, but we need to do a case-insensitive search. Since DOMDocument only supports XPath 1.0,
  279. // lower-case() isn't available to us. We've thus far only set attributes to lowercase, not attribute values. Consequently, we need
  280. // to translate() the letters that would be in 'NONE' ("NOE") to lowercase.
  281. $nodesWithStyleDisplayNone = $xpath->query('//*[contains(translate(translate(@style," ",""),"NOE","noe"),"display:none")]');
  282. // The checks on parentNode and is_callable below ensure that if we've deleted the parent node,
  283. // we don't try to call removeChild on a nonexistent child node
  284. if ($nodesWithStyleDisplayNone->length > 0) {
  285. /** @var $node \DOMNode */
  286. foreach ($nodesWithStyleDisplayNone as $node) {
  287. if ($node->parentNode && is_callable(array($node->parentNode,'removeChild'))) {
  288. $node->parentNode->removeChild($node);
  289. }
  290. }
  291. }
  292. $this->copyCssWithMediaToStyleNode($cssParts, $xmlDocument);
  293. if ($this->preserveEncoding) {
  294. if ( function_exists( 'mb_convert_encoding' ) ) {
  295. return mb_convert_encoding( $xmlDocument->saveHTML(), self::ENCODING, 'HTML-ENTITIES' );
  296. } else {
  297. return htmlspecialchars_decode( utf8_encode( html_entity_decode( $xmlDocument->saveHTML(), ENT_COMPAT, self::ENCODING ) ) );
  298. }
  299. } else {
  300. return $xmlDocument->saveHTML();
  301. }
  302. }
  303. public function strtolower(array $m) {
  304. return strtolower($m[0]);
  305. }
  306. /**
  307. * This method merges old or existing name/value array with new name/value array.
  308. * and then generates a string of the combined style suitable for placing inline.
  309. * This becomes the single point for CSS string generation allowing for consistent.
  310. * CSS output no matter where the CSS originally came from.
  311. * @param array $oldStyles
  312. * @param array $newStyles
  313. * @return string
  314. */
  315. private function generateStyleStringFromDeclarationsArrays(array $oldStyles, array $newStyles) {
  316. $combinedStyles = array_merge($oldStyles, $newStyles);
  317. $style = '';
  318. foreach ($combinedStyles as $attributeName => $attributeValue) {
  319. $style .= (strtolower(trim($attributeName)) . ': ' . trim($attributeValue) . '; ');
  320. }
  321. return trim($style);
  322. }
  323. /**
  324. * Copies the media part from CSS array parts to $xmlDocument.
  325. *
  326. * @param array $cssParts
  327. * @param DOMDocument $xmlDocument
  328. */
  329. public function copyCssWithMediaToStyleNode(array $cssParts, DOMDocument $xmlDocument) {
  330. if (isset($cssParts['media']) && $cssParts['media'] !== '') {
  331. $this->addStyleElementToDocument($xmlDocument, $cssParts['media']);
  332. }
  333. }
  334. /**
  335. * Returns CSS content.
  336. *
  337. * @param DOMXPath $xpath
  338. * @return string
  339. */
  340. private function getCssFromAllStyleNodes(DOMXPath $xpath) {
  341. $styleNodes = $xpath->query('//style');
  342. if ($styleNodes === false) {
  343. return '';
  344. }
  345. $css = '';
  346. /** @var $styleNode DOMNode */
  347. foreach ($styleNodes as $styleNode) {
  348. $css .= "\n\n" . $styleNode->nodeValue;
  349. $styleNode->parentNode->removeChild($styleNode);
  350. }
  351. return $css;
  352. }
  353. /**
  354. * Adds a style element with $css to $document.
  355. *
  356. * @param DOMDocument $document
  357. * @param string $css
  358. */
  359. private function addStyleElementToDocument(DOMDocument $document, $css) {
  360. $styleElement = $document->createElement('style', $css);
  361. $styleAttribute = $document->createAttribute('type');
  362. $styleAttribute->value = 'text/css';
  363. $styleElement->appendChild($styleAttribute);
  364. $head = $this->getOrCreateHeadElement($document);
  365. $head->appendChild($styleElement);
  366. }
  367. /**
  368. * Returns the existing or creates a new head element in $document.
  369. *
  370. * @param DOMDocument $document
  371. * @return DOMNode the head element
  372. */
  373. private function getOrCreateHeadElement(DOMDocument $document) {
  374. $head = $document->getElementsByTagName('head')->item(0);
  375. if ($head === null) {
  376. $head = $document->createElement('head');
  377. $html = $document->getElementsByTagName('html')->item(0);
  378. $html->insertBefore($head, $document->getElementsByTagName('body')->item(0));
  379. }
  380. return $head;
  381. }
  382. /**
  383. * Splits input CSS code to an array where:
  384. *
  385. * - key "css" will be contains clean CSS code.
  386. * - key "media" will be contains all valuable media queries.
  387. *
  388. * Example:
  389. *
  390. * The CSS code.
  391. *
  392. * "@import "file.css"; h1 { color:red; } @media { h1 {}} @media tv { h1 {}}"
  393. *
  394. * will be parsed into the following array:
  395. *
  396. * "css" => "h1 { color:red; }"
  397. * "media" => "@media { h1 {}}"
  398. *
  399. * @param string $css
  400. * @return array
  401. */
  402. private function splitCssAndMediaQuery($css) {
  403. $css = preg_replace_callback( '#@media\\s+(?:only\\s)?(?:[\\s{\(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#misU', array( $this, '_media_concat' ), $css );
  404. // filter the CSS
  405. $search = array(
  406. // get rid of css comment code
  407. '/\\/\\*.*\\*\\//sU',
  408. // strip out any import directives
  409. '/^\\s*@import\\s[^;]+;/misU',
  410. // strip remains media enclosures
  411. '/^\\s*@media\\s[^{]+{(.*)}\\s*}\\s/misU',
  412. );
  413. $replace = array(
  414. '',
  415. '',
  416. '',
  417. );
  418. // clean CSS before output
  419. $css = preg_replace($search, $replace, $css);
  420. return array('css' => $css, 'media' => self::$_media);
  421. }
  422. private function _media_concat( $matches ) {
  423. self::$_media .= $matches[0];
  424. }
  425. /**
  426. * Creates a DOMDocument instance with the current HTML.
  427. *
  428. * @return DOMDocument
  429. */
  430. private function createXmlDocument() {
  431. $xmlDocument = new DOMDocument;
  432. $xmlDocument->encoding = self::ENCODING;
  433. $xmlDocument->strictErrorChecking = false;
  434. $xmlDocument->formatOutput = true;
  435. $libXmlState = libxml_use_internal_errors(true);
  436. $xmlDocument->loadHTML($this->getUnifiedHtml());
  437. libxml_clear_errors();
  438. libxml_use_internal_errors($libXmlState);
  439. $xmlDocument->normalizeDocument();
  440. return $xmlDocument;
  441. }
  442. /**
  443. * Returns the HTML with the non-ASCII characters converts into HTML entities and the unprocessable HTML tags removed.
  444. *
  445. * @return string the unified HTML
  446. *
  447. * @throws BadMethodCallException
  448. */
  449. private function getUnifiedHtml() {
  450. if (!empty($this->unprocessableHtmlTags)) {
  451. $unprocessableHtmlTags = implode('|', $this->unprocessableHtmlTags);
  452. $bodyWithoutUnprocessableTags = preg_replace('/<\\/?(' . $unprocessableHtmlTags . ')[^>]*>/i', '', $this->html);
  453. } else {
  454. $bodyWithoutUnprocessableTags = $this->html;
  455. }
  456. if ( function_exists( 'mb_convert_encoding' ) ) {
  457. return mb_convert_encoding( $bodyWithoutUnprocessableTags, 'HTML-ENTITIES', self::ENCODING );
  458. } else {
  459. return htmlspecialchars_decode( utf8_decode( htmlentities( $bodyWithoutUnprocessableTags, ENT_COMPAT, self::ENCODING, false ) ) );
  460. }
  461. }
  462. /**
  463. * @param array $a
  464. * @param array $b
  465. *
  466. * @return integer
  467. */
  468. private function sortBySelectorPrecedence(array $a, array $b) {
  469. $precedenceA = $this->getCssSelectorPrecedence($a['selector']);
  470. $precedenceB = $this->getCssSelectorPrecedence($b['selector']);
  471. // We want these sorted in ascending order so selectors with lesser precedence get processed first and
  472. // selectors with greater precedence get sorted last.
  473. // The parenthesis around the -1 are necessary to avoid a PHP_CodeSniffer warning about missing spaces around
  474. // arithmetic operators.
  475. // @see http://forge.typo3.org/issues/55605
  476. $precedenceForEquals = ($a['line'] < $b['line'] ? (-1) : 1);
  477. $precedenceForNotEquals = ($precedenceA < $precedenceB ? (-1) : 1);
  478. return ($precedenceA === $precedenceB) ? $precedenceForEquals : $precedenceForNotEquals;
  479. }
  480. /**
  481. * @param string $selector
  482. *
  483. * @return integer
  484. */
  485. private function getCssSelectorPrecedence($selector) {
  486. $selectorKey = md5($selector);
  487. if (!isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) {
  488. $precedence = 0;
  489. $value = 100;
  490. // ids: worth 100, classes: worth 10, elements: worth 1
  491. $search = array('\\#','\\.','');
  492. foreach ($search as $s) {
  493. if (trim($selector == '')) {
  494. break;
  495. }
  496. $number = 0;
  497. $selector = preg_replace('/' . $s . '\\w+/', '', $selector, -1, $number);
  498. $precedence += ($value * $number);
  499. $value /= 10;
  500. }
  501. $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
  502. }
  503. return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey];
  504. }
  505. /**
  506. * Right now, we support all CSS 1 selectors and most CSS2/3 selectors.
  507. *
  508. * @see http://plasmasturm.org/log/444/
  509. *
  510. * @param string $paramCssSelector
  511. *
  512. * @return string
  513. */
  514. private function translateCssToXpath($paramCssSelector) {
  515. $cssSelector = ' ' . $paramCssSelector . ' ';
  516. $cssSelector = preg_replace_callback( '/\s+\w+\s+/', array( $this, 'strtolower' ), $cssSelector );
  517. $cssSelector = trim($cssSelector);
  518. $xpathKey = md5($cssSelector);
  519. if (!isset($this->caches[self::CACHE_KEY_XPATH][$xpathKey])) {
  520. // returns an Xpath selector
  521. $search = array(
  522. // Matches any element that is a child of parent.
  523. '/\\s+>\\s+/',
  524. // Matches any element that is an adjacent sibling.
  525. '/\\s+\\+\\s+/',
  526. // Matches any element that is a descendant of an parent element element.
  527. '/\\s+/',
  528. // first-child pseudo-selector
  529. '/([^\\/]+):first-child/i',
  530. // last-child pseudo-selector
  531. '/([^\\/]+):last-child/i',
  532. // Matches attribute only selector
  533. '/^\\[(\\w+)\\]/',
  534. // Matches element with attribute
  535. '/(\\w)\\[(\\w+)\\]/',
  536. // Matches element with EXACT attribute
  537. '/(\\w)\\[(\\w+)\\=[\'"]?(\\w+)[\'"]?\\]/',
  538. );
  539. $replace = array(
  540. '/',
  541. '/following-sibling::*[1]/self::',
  542. '//',
  543. '*[1]/self::\\1',
  544. '*[last()]/self::\\1',
  545. '*[@\\1]',
  546. '\\1[@\\2]',
  547. '\\1[@\\2="\\3"]',
  548. );
  549. $cssSelector = '//' . preg_replace($search, $replace, $cssSelector);
  550. $cssSelector = preg_replace_callback(self::ID_ATTRIBUTE_MATCHER, array($this, 'matchIdAttributes'), $cssSelector);
  551. $cssSelector = preg_replace_callback(self::CLASS_ATTRIBUTE_MATCHER, array($this, 'matchClassAttributes'), $cssSelector);
  552. // Advanced selectors are going to require a bit more advanced emogrification.
  553. // When we required PHP 5.3, we could do this with closures.
  554. $cssSelector = preg_replace_callback(
  555. '/([^\\/]+):nth-child\\(\s*(odd|even|[+\-]?\\d|[+\\-]?\\d?n(\\s*[+\\-]\\s*\\d)?)\\s*\\)/i',
  556. array($this, 'translateNthChild'), $cssSelector
  557. );
  558. $cssSelector = preg_replace_callback(
  559. '/([^\\/]+):nth-of-type\\(\s*(odd|even|[+\-]?\\d|[+\\-]?\\d?n(\\s*[+\\-]\\s*\\d)?)\\s*\\)/i',
  560. array($this, 'translateNthOfType'), $cssSelector
  561. );
  562. $this->caches[self::CACHE_KEY_SELECTOR][$xpathKey] = $cssSelector;
  563. }
  564. return $this->caches[self::CACHE_KEY_SELECTOR][$xpathKey];
  565. }
  566. /**
  567. * @param array $match
  568. *
  569. * @return string
  570. */
  571. private function matchIdAttributes(array $match) {
  572. return (strlen($match[1]) ? $match[1] : '*') . '[@id="' . $match[2] . '"]';
  573. }
  574. /**
  575. * @param array $match
  576. *
  577. * @return string
  578. */
  579. private function matchClassAttributes(array $match) {
  580. return (strlen($match[1]) ? $match[1] : '*') . '[contains(concat(" ",@class," "),concat(" ","' .
  581. implode(
  582. '"," "))][contains(concat(" ",@class," "),concat(" ","',
  583. explode('.', substr($match[2], 1))
  584. ) . '"," "))]';
  585. }
  586. /**
  587. * @param array $match
  588. *
  589. * @return string
  590. */
  591. private function translateNthChild(array $match) {
  592. $result = $this->parseNth($match);
  593. if (isset($result[self::MULTIPLIER])) {
  594. if ($result[self::MULTIPLIER] < 0) {
  595. $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
  596. return sprintf('*[(last() - position()) mod %u = %u]/self::%s', $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
  597. } else {
  598. return sprintf('*[position() mod %u = %u]/self::%s', $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
  599. }
  600. } else {
  601. return sprintf('*[%u]/self::%s', $result[self::INDEX], $match[1]);
  602. }
  603. }
  604. /**
  605. * @param array $match
  606. *
  607. * @return string
  608. */
  609. private function translateNthOfType(array $match) {
  610. $result = $this->parseNth($match);
  611. if (isset($result[self::MULTIPLIER])) {
  612. if ($result[self::MULTIPLIER] < 0) {
  613. $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
  614. return sprintf('%s[(last() - position()) mod %u = %u]', $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
  615. } else {
  616. return sprintf('%s[position() mod %u = %u]', $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
  617. }
  618. } else {
  619. return sprintf('%s[%u]', $match[1], $result[self::INDEX]);
  620. }
  621. }
  622. /**
  623. * @param array $match
  624. *
  625. * @return array
  626. */
  627. private function parseNth(array $match) {
  628. if (in_array(strtolower($match[2]), array('even','odd'))) {
  629. $index = strtolower($match[2]) == 'even' ? 0 : 1;
  630. return array(self::MULTIPLIER => 2, self::INDEX => $index);
  631. } elseif (stripos($match[2], 'n') === false) {
  632. // if there is a multiplier
  633. $index = intval(str_replace(' ', '', $match[2]));
  634. return array(self::INDEX => $index);
  635. } else {
  636. if (isset($match[3])) {
  637. $multipleTerm = str_replace($match[3], '', $match[2]);
  638. $index = intval(str_replace(' ', '', $match[3]));
  639. } else {
  640. $multipleTerm = $match[2];
  641. $index = 0;
  642. }
  643. $multiplier = str_ireplace('n', '', $multipleTerm);
  644. if (!strlen($multiplier)) {
  645. $multiplier = 1;
  646. } elseif ($multiplier == 0) {
  647. return array(self::INDEX => $index);
  648. } else {
  649. $multiplier = intval($multiplier);
  650. }
  651. while ($index < 0) {
  652. $index += abs($multiplier);
  653. }
  654. return array(self::MULTIPLIER => $multiplier, self::INDEX => $index);
  655. }
  656. }
  657. /**
  658. * Parses a CSS declaration block into property name/value pairs.
  659. *
  660. * Example:
  661. *
  662. * The declaration block.
  663. *
  664. * "color: #000; font-weight: bold;".
  665. *
  666. * will be parsed into the following array:
  667. *
  668. * "color" => "#000"
  669. * "font-weight" => "bold"
  670. *
  671. * @param string $cssDeclarationBlock the CSS declaration block without the curly braces, may be empty
  672. *
  673. * @return array the CSS declarations with the property names as array keys and the property values as array values
  674. */
  675. private function parseCssDeclarationBlock($cssDeclarationBlock) {
  676. if (isset($this->caches[self::CACHE_KEY_CSS_DECLARATION_BLOCK][$cssDeclarationBlock])) {
  677. return $this->caches[self::CACHE_KEY_CSS_DECLARATION_BLOCK][$cssDeclarationBlock];
  678. }
  679. $properties = array();
  680. $declarations = explode(';', $cssDeclarationBlock);
  681. foreach ($declarations as $declaration) {
  682. $matches = array();
  683. if (!preg_match('/ *([A-Za-z\\-]+) *: *([^;]+) */', $declaration, $matches)) {
  684. continue;
  685. }
  686. $propertyName = strtolower($matches[1]);
  687. $propertyValue = $matches[2];
  688. $properties[$propertyName] = $propertyValue;
  689. }
  690. $this->caches[self::CACHE_KEY_CSS_DECLARATION_BLOCK][$cssDeclarationBlock] = $properties;
  691. return $properties;
  692. }
  693. }