CssToInlineStyles.php 22 KB

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