CssToInlineStyles.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. <?php
  2. //namespace TijsVerkoyen\CssToInlineStyles;
  3. /**
  4. * CSS to Inline Styles class
  5. *
  6. * @author Tijs Verkoyen <php-css-to-inline-styles@verkoyen.eu>
  7. * @version 1.2.1
  8. * @copyright Copyright (c), Tijs Verkoyen. All rights reserved.
  9. * @license BSD License
  10. */
  11. class CssToInlineStyles
  12. {
  13. /**
  14. * The CSS to use
  15. *
  16. * @var string
  17. */
  18. private $css;
  19. /**
  20. * The processed CSS rules
  21. *
  22. * @var array
  23. */
  24. private $cssRules;
  25. /**
  26. * Should the generated HTML be cleaned
  27. *
  28. * @var bool
  29. */
  30. private $cleanup = false;
  31. /**
  32. * The encoding to use.
  33. *
  34. * @var string
  35. */
  36. private $encoding = 'UTF-8';
  37. /**
  38. * The HTML to process
  39. *
  40. * @var string
  41. */
  42. private $html;
  43. /**
  44. * Use inline-styles block as CSS
  45. *
  46. * @var bool
  47. */
  48. private $useInlineStylesBlock = false;
  49. /**
  50. * Strip original style tags
  51. *
  52. * @var bool
  53. */
  54. private $stripOriginalStyleTags = false;
  55. /**
  56. * Exclude the media queries from the inlined styles
  57. *
  58. * @var bool
  59. */
  60. private $excludeMediaQueries = false;
  61. /**
  62. * Creates an instance, you could set the HTML and CSS here, or load it
  63. * later.
  64. *
  65. * @return void
  66. * @param string[optional] $html The HTML to process.
  67. * @param string[optional] $css The CSS to use.
  68. */
  69. public function __construct($html = null, $css = null)
  70. {
  71. if($html !== null) $this->setHTML($html);
  72. if($css !== null) $this->setCSS($css);
  73. }
  74. /**
  75. * Convert a CSS-selector into an xPath-query
  76. *
  77. * @return string
  78. * @param string $selector The CSS-selector.
  79. */
  80. private function buildXPathQuery($selector)
  81. {
  82. // redefine
  83. $selector = (string) $selector;
  84. // the CSS selector
  85. $cssSelector = array(
  86. // E F, Matches any F element that is a descendant of an E element
  87. '/(\w)\s+([\w\*])/',
  88. // E > F, Matches any F element that is a child of an element E
  89. '/(\w)\s*>\s*([\w\*])/',
  90. // E:first-child, Matches element E when E is the first child of its parent
  91. '/(\w):first-child/',
  92. // E + F, Matches any F element immediately preceded by an element
  93. '/(\w)\s*\+\s*(\w)/',
  94. // E[foo], Matches any E element with the "foo" attribute set (whatever the value)
  95. '/(\w)\[([\w\-]+)]/',
  96. // E[foo="warning"], Matches any E element whose "foo" attribute value is exactly equal to "warning"
  97. '/(\w)\[([\w\-]+)\=\"(.*)\"]/',
  98. // div.warning, HTML only. The same as DIV[class~="warning"]
  99. '/(\w+|\*)+\.([\w\-]+)+/',
  100. // .warning, HTML only. The same as *[class~="warning"]
  101. '/\.([\w\-]+)/',
  102. // E#myid, Matches any E element with id-attribute equal to "myid"
  103. '/(\w+)+\#([\w\-]+)/',
  104. // #myid, Matches any element with id-attribute equal to "myid"
  105. '/\#([\w\-]+)/'
  106. );
  107. // the xPath-equivalent
  108. $xPathQuery = array(
  109. // E F, Matches any F element that is a descendant of an E element
  110. '\1//\2',
  111. // E > F, Matches any F element that is a child of an element E
  112. '\1/\2',
  113. // E:first-child, Matches element E when E is the first child of its parent
  114. '*[1]/self::\1',
  115. // E + F, Matches any F element immediately preceded by an element
  116. '\1/following-sibling::*[1]/self::\2',
  117. // E[foo], Matches any E element with the "foo" attribute set (whatever the value)
  118. '\1 [ @\2 ]',
  119. // E[foo="warning"], Matches any E element whose "foo" attribute value is exactly equal to "warning"
  120. '\1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]',
  121. // div.warning, HTML only. The same as DIV[class~="warning"]
  122. '\1[ contains( concat( " ", @class, " " ), concat( " ", "\2", " " ) ) ]',
  123. // .warning, HTML only. The same as *[class~="warning"]
  124. '*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]',
  125. // E#myid, Matches any E element with id-attribute equal to "myid"
  126. '\1[ @id = "\2" ]',
  127. // #myid, Matches any element with id-attribute equal to "myid"
  128. '*[ @id = "\1" ]'
  129. );
  130. // return
  131. $xPath = (string) '//' . preg_replace($cssSelector, $xPathQuery, $selector);
  132. return str_replace('] *', ']//*', $xPath);
  133. }
  134. /**
  135. * Calculate the specifity for the CSS-selector
  136. *
  137. * @return integer
  138. * @param string $selector The selector to calculate the specifity for.
  139. */
  140. private function calculateCSSSpecifity($selector)
  141. {
  142. // cleanup selector
  143. $selector = str_replace(array('>', '+'), array(' > ', ' + '), $selector);
  144. // init var
  145. $specifity = 0;
  146. // split the selector into chunks based on spaces
  147. $chunks = explode(' ', $selector);
  148. // loop chunks
  149. foreach ($chunks as $chunk) {
  150. // an ID is important, so give it a high specifity
  151. if(strstr($chunk, '#') !== false) $specifity += 100;
  152. // classes are more important than a tag, but less important then an ID
  153. elseif(strstr($chunk, '.')) $specifity += 10;
  154. // anything else isn't that important
  155. else $specifity += 1;
  156. }
  157. // return
  158. return $specifity;
  159. }
  160. /**
  161. * Cleanup the generated HTML
  162. *
  163. * @return string
  164. * @param string $html The HTML to cleanup.
  165. */
  166. private function cleanupHTML($html)
  167. {
  168. // remove classes
  169. $html = preg_replace('/(\s)+class="(.*)"(\s)*/U', ' ', $html);
  170. // remove IDs
  171. $html = preg_replace('/(\s)+id="(.*)"(\s)*/U', ' ', $html);
  172. // return
  173. return $html;
  174. }
  175. /**
  176. * Converts the loaded HTML into an HTML-string with inline styles based on the loaded CSS
  177. *
  178. * @return string
  179. * @param bool[optional] $outputXHTML Should we output valid XHTML?
  180. */
  181. public function convert($outputXHTML = false)
  182. {
  183. // redefine
  184. $outputXHTML = (bool) $outputXHTML;
  185. // validate
  186. if($this->html == null) throw new Exception('No HTML provided.');
  187. // should we use inline style-block
  188. if ($this->useInlineStylesBlock) {
  189. // init var
  190. $matches = array();
  191. // match the style blocks
  192. preg_match_all('|<style(.*)>(.*)</style>|isU', $this->html, $matches);
  193. // any style-blocks found?
  194. if (!empty($matches[2])) {
  195. // add
  196. foreach($matches[2] as $match) $this->css .= trim($match) ."\n";
  197. }
  198. }
  199. // process css
  200. $this->processCSS();
  201. // create new DOMDocument
  202. $document = new \DOMDocument('1.0', $this->getEncoding());
  203. // set error level
  204. libxml_use_internal_errors(true);
  205. // load HTML
  206. $document->loadHTML($this->html);
  207. // create new XPath
  208. $xPath = new \DOMXPath($document);
  209. // any rules?
  210. if (!empty($this->cssRules)) {
  211. // loop rules
  212. foreach ($this->cssRules as $rule) {
  213. // init var
  214. $query = $this->buildXPathQuery($rule['selector']);
  215. // validate query
  216. if($query === false) continue;
  217. // search elements
  218. $elements = $xPath->query($query);
  219. // validate elements
  220. if($elements === false) continue;
  221. // loop found elements
  222. foreach ($elements as $element) {
  223. // no styles stored?
  224. if ($element->attributes->getNamedItem(
  225. 'data-css-to-inline-styles-original-styles'
  226. ) == null) {
  227. // init var
  228. $originalStyle = '';
  229. if ($element->attributes->getNamedItem('style') !== null) {
  230. $originalStyle = $element->attributes->getNamedItem('style')->value;
  231. }
  232. // store original styles
  233. $element->setAttribute(
  234. 'data-css-to-inline-styles-original-styles',
  235. $originalStyle
  236. );
  237. // clear the styles
  238. $element->setAttribute('style', '');
  239. }
  240. // init var
  241. $properties = array();
  242. // get current styles
  243. $stylesAttribute = $element->attributes->getNamedItem('style');
  244. // any styles defined before?
  245. if ($stylesAttribute !== null) {
  246. // get value for the styles attribute
  247. $definedStyles = (string) $stylesAttribute->value;
  248. // split into properties
  249. $definedProperties = (array) explode(';', $definedStyles);
  250. // loop properties
  251. foreach ($definedProperties as $property) {
  252. // validate property
  253. if($property == '') continue;
  254. // split into chunks
  255. $chunks = (array) explode(':', trim($property), 2);
  256. // validate
  257. if(!isset($chunks[1])) continue;
  258. // loop chunks
  259. $properties[$chunks[0]] = trim($chunks[1]);
  260. }
  261. }
  262. // add new properties into the list
  263. foreach ($rule['properties'] as $key => $value) {
  264. $properties[$key] = $value;
  265. }
  266. // build string
  267. $propertyChunks = array();
  268. // build chunks
  269. foreach ($properties as $key => $values) {
  270. foreach ((array) $values as $value) {
  271. $propertyChunks[] = $key . ': ' . $value . ';';
  272. }
  273. }
  274. // build properties string
  275. $propertiesString = implode(' ', $propertyChunks);
  276. // set attribute
  277. if ($propertiesString != '') {
  278. $element->setAttribute('style', $propertiesString);
  279. }
  280. }
  281. }
  282. // reapply original styles
  283. $query = $this->buildXPathQuery(
  284. '*[@data-css-to-inline-styles-original-styles]'
  285. );
  286. // validate query
  287. if($query === false) return;
  288. // search elements
  289. $elements = $xPath->query($query);
  290. // loop found elements
  291. foreach ($elements as $element) {
  292. // get the original styles
  293. $originalStyle = $element->attributes->getNamedItem(
  294. 'data-css-to-inline-styles-original-styles'
  295. )->value;
  296. if ($originalStyle != '') {
  297. $originalProperties = array();
  298. $originalStyles = (array) explode(';', $originalStyle);
  299. foreach ($originalStyles as $property) {
  300. // validate property
  301. if($property == '') continue;
  302. // split into chunks
  303. $chunks = (array) explode(':', trim($property), 2);
  304. // validate
  305. if(!isset($chunks[1])) continue;
  306. // loop chunks
  307. $originalProperties[$chunks[0]] = trim($chunks[1]);
  308. }
  309. // get current styles
  310. $stylesAttribute = $element->attributes->getNamedItem('style');
  311. $properties = array();
  312. // any styles defined before?
  313. if ($stylesAttribute !== null) {
  314. // get value for the styles attribute
  315. $definedStyles = (string) $stylesAttribute->value;
  316. // split into properties
  317. $definedProperties = (array) explode(';', $definedStyles);
  318. // loop properties
  319. foreach ($definedProperties as $property) {
  320. // validate property
  321. if($property == '') continue;
  322. // split into chunks
  323. $chunks = (array) explode(':', trim($property), 2);
  324. // validate
  325. if(!isset($chunks[1])) continue;
  326. // loop chunks
  327. $properties[$chunks[0]] = trim($chunks[1]);
  328. }
  329. }
  330. // add new properties into the list
  331. foreach ($originalProperties as $key => $value) {
  332. $properties[$key] = $value;
  333. }
  334. // build string
  335. $propertyChunks = array();
  336. // build chunks
  337. foreach ($properties as $key => $values) {
  338. foreach ((array) $values as $value) {
  339. $propertyChunks[] = $key . ': ' . $value . ';';
  340. }
  341. }
  342. // build properties string
  343. $propertiesString = implode(' ', $propertyChunks);
  344. // set attribute
  345. if($propertiesString != '') $element->setAttribute(
  346. 'style', $propertiesString
  347. );
  348. }
  349. // remove placeholder
  350. $element->removeAttribute(
  351. 'data-css-to-inline-styles-original-styles'
  352. );
  353. }
  354. }
  355. // should we output XHTML?
  356. if ($outputXHTML) {
  357. // set formating
  358. $document->formatOutput = true;
  359. // get the HTML as XML
  360. $html = $document->saveXML(null, LIBXML_NOEMPTYTAG);
  361. // get start of the XML-declaration
  362. $startPosition = strpos($html, '<?xml');
  363. // valid start position?
  364. if ($startPosition !== false) {
  365. // get end of the xml-declaration
  366. $endPosition = strpos($html, '?>', $startPosition);
  367. // remove the XML-header
  368. $html = ltrim(substr($html, $endPosition + 1));
  369. }
  370. }
  371. // just regular HTML 4.01 as it should be used in newsletters
  372. else {
  373. // get the HTML
  374. $html = $document->saveHTML();
  375. }
  376. // Correct scrambled UTF8 chars (&atilde;&#131;...) back to their correct representation.
  377. $html = html_entity_decode($html, ENT_XHTML, 'UTF-8');
  378. $html = utf8_decode($html);
  379. // cleanup the HTML if we need to
  380. if($this->cleanup) $html = $this->cleanupHTML($html);
  381. // strip original style tags if we need to
  382. if ($this->stripOriginalStyleTags) {
  383. $html = $this->stripOriginalStyleTags($html);
  384. }
  385. // return
  386. return $html;
  387. }
  388. /**
  389. * Get the encoding to use
  390. *
  391. * @return string
  392. */
  393. private function getEncoding()
  394. {
  395. return $this->encoding;
  396. }
  397. /**
  398. * Process the loaded CSS
  399. *
  400. * @return void
  401. */
  402. private function processCSS()
  403. {
  404. // init vars
  405. $css = (string) $this->css;
  406. // remove newlines
  407. $css = str_replace(array("\r", "\n"), '', $css);
  408. // replace double quotes by single quotes
  409. $css = str_replace('"', '\'', $css);
  410. // remove comments
  411. $css = preg_replace('|/\*.*?\*/|', '', $css);
  412. // remove spaces
  413. $css = preg_replace('/\s\s+/', ' ', $css);
  414. if ($this->excludeMediaQueries) {
  415. $css = preg_replace('/@media [^{]*{([^{}]|{[^{}]*})*}/', '', $css);
  416. }
  417. // rules are splitted by }
  418. $rules = (array) explode('}', $css);
  419. // init var
  420. $i = 1;
  421. // loop rules
  422. foreach ($rules as $rule) {
  423. // split into chunks
  424. $chunks = explode('{', $rule);
  425. // invalid rule?
  426. if(!isset($chunks[1])) continue;
  427. // set the selectors
  428. $selectors = trim($chunks[0]);
  429. // get cssProperties
  430. $cssProperties = trim($chunks[1]);
  431. // split multiple selectors
  432. $selectors = (array) explode(',', $selectors);
  433. // loop selectors
  434. foreach ($selectors as $selector) {
  435. // cleanup
  436. $selector = trim($selector);
  437. // build an array for each selector
  438. $ruleSet = array();
  439. // store selector
  440. $ruleSet['selector'] = $selector;
  441. // process the properties
  442. $ruleSet['properties'] = $this->processCSSProperties(
  443. $cssProperties
  444. );
  445. // calculate specifity
  446. $ruleSet['specifity'] = $this->calculateCSSSpecifity(
  447. $selector
  448. ) + $i;
  449. // add into global rules
  450. $this->cssRules[] = $ruleSet;
  451. }
  452. // increment
  453. $i++;
  454. }
  455. // sort based on specifity
  456. if (!empty($this->cssRules)) {
  457. usort($this->cssRules, array(__CLASS__, 'sortOnSpecifity'));
  458. }
  459. }
  460. /**
  461. * Process the CSS-properties
  462. *
  463. * @return array
  464. * @param string $propertyString The CSS-properties.
  465. */
  466. private function processCSSProperties($propertyString)
  467. {
  468. // split into chunks
  469. $properties = (array) explode(';', $propertyString);
  470. // init var
  471. $pairs = array();
  472. // loop properties
  473. foreach ($properties as $property) {
  474. // split into chunks
  475. $chunks = (array) explode(':', $property, 2);
  476. // validate
  477. if(!isset($chunks[1])) continue;
  478. // cleanup
  479. $chunks[0] = trim($chunks[0]);
  480. $chunks[1] = trim($chunks[1]);
  481. // add to pairs array
  482. if(!isset($pairs[$chunks[0]]) ||
  483. !in_array($chunks[1], $pairs[$chunks[0]])) {
  484. $pairs[$chunks[0]][] = $chunks[1];
  485. }
  486. }
  487. // sort the pairs
  488. ksort($pairs);
  489. // return
  490. return $pairs;
  491. }
  492. /**
  493. * Should the IDs and classes be removed?
  494. *
  495. * @return void
  496. * @param bool[optional] $on Should we enable cleanup?
  497. */
  498. public function setCleanup($on = true)
  499. {
  500. $this->cleanup = (bool) $on;
  501. }
  502. /**
  503. * Set CSS to use
  504. *
  505. * @return void
  506. * @param string $css The CSS to use.
  507. */
  508. public function setCSS($css)
  509. {
  510. $this->css = (string) $css;
  511. }
  512. /**
  513. * Set the encoding to use with the DOMDocument
  514. *
  515. * @return void
  516. * @param string $encoding The encoding to use.
  517. */
  518. public function setEncoding($encoding)
  519. {
  520. $this->encoding = (string) $encoding;
  521. }
  522. /**
  523. * Set HTML to process
  524. *
  525. * @return void
  526. * @param string $html The HTML to process.
  527. */
  528. public function setHTML($html)
  529. {
  530. $this->html = (string) $html;
  531. }
  532. /**
  533. * Set use of inline styles block
  534. * If this is enabled the class will use the style-block in the HTML.
  535. *
  536. * @return void
  537. * @param bool[optional] $on Should we process inline styles?
  538. */
  539. public function setUseInlineStylesBlock($on = true)
  540. {
  541. $this->useInlineStylesBlock = (bool) $on;
  542. }
  543. /**
  544. * Set strip original style tags
  545. * If this is enabled the class will remove all style tags in the HTML.
  546. *
  547. * @return void
  548. * @param bool[optional] $on Should we process inline styles?
  549. */
  550. public function setStripOriginalStyleTags($on = true)
  551. {
  552. $this->stripOriginalStyleTags = (bool) $on;
  553. }
  554. /**
  555. * Set exclude media queries
  556. *
  557. * If this is enabled the media queries will be removed before inlining the rules
  558. *
  559. * @return void
  560. * @param bool[optional] $on
  561. */
  562. public function setExcludeMediaQueries($on = true)
  563. {
  564. $this->excludeMediaQueries = (bool) $on;
  565. }
  566. /**
  567. * Strip style tags into the generated HTML
  568. *
  569. * @return string
  570. * @param string $html The HTML to strip style tags.
  571. */
  572. private function stripOriginalStyleTags($html)
  573. {
  574. return preg_replace('|<style(.*)>(.*)</style>|isU', '', $html);
  575. }
  576. /**
  577. * Sort an array on the specifity element
  578. *
  579. * @return integer
  580. * @param array $e1 The first element.
  581. * @param array $e2 The second element.
  582. */
  583. private static function sortOnSpecifity($e1, $e2)
  584. {
  585. // validate
  586. if(!isset($e1['specifity']) || !isset($e2['specifity'])) return 0;
  587. // lower
  588. if($e1['specifity'] < $e2['specifity']) return -1;
  589. // higher
  590. if($e1['specifity'] > $e2['specifity']) return 1;
  591. // fallback
  592. return 0;
  593. }
  594. }