stylesheet.cls.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. <?php
  2. /**
  3. * DOMPDF - PHP5 HTML to PDF renderer
  4. *
  5. * File: $RCSfile: stylesheet.cls.php,v $
  6. * Created on: 2004-06-01
  7. *
  8. * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca>
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public License
  21. * along with this library in the file LICENSE.LGPL; if not, write to the
  22. * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  23. * 02111-1307 USA
  24. *
  25. * Alternatively, you may distribute this software under the terms of the
  26. * PHP License, version 3.0 or later. A copy of this license should have
  27. * been distributed with this file in the file LICENSE.PHP . If this is not
  28. * the case, you can obtain a copy at http://www.php.net/license/3_0.txt.
  29. *
  30. * The latest version of DOMPDF might be available at:
  31. * http://www.dompdf.com/
  32. *
  33. * @link http://www.dompdf.com/
  34. * @copyright 2004 Benj Carson
  35. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  36. * @contributor Helmut Tischer <htischer@weihenstephan.org>
  37. * @package dompdf
  38. *
  39. * Changes
  40. * @contributor Helmut Tischer <htischer@weihenstephan.org>
  41. * @version 0.5.1.htischer.20090507
  42. * - Specifity of css selector chain was too small because leading whitespace
  43. * to be counted as number of elements was removed
  44. * - On parsing css properties accept and register !important attribute
  45. * - Add optional debug output
  46. * @version 20090610
  47. * - _parse_properties on style property name and value remove augmenting superflous
  48. * space for consistent parsing, in particular combined values like background
  49. */
  50. /* $Id: stylesheet.cls.php 216 2010-03-11 22:49:18Z ryan.masten $ */
  51. /**
  52. * The location of the default built-in CSS file.
  53. * {@link Stylesheet::DEFAULT_STYLESHEET}
  54. */
  55. define('__DEFAULT_STYLESHEET', DOMPDF_LIB_DIR . DIRECTORY_SEPARATOR . "res" . DIRECTORY_SEPARATOR . "html.css");
  56. /**
  57. * The master stylesheet class
  58. *
  59. * The Stylesheet class is responsible for parsing stylesheets and style
  60. * tags/attributes. It also acts as a registry of the individual Style
  61. * objects generated by the current set of loaded CSS files and style
  62. * elements.
  63. *
  64. * @see Style
  65. * @package dompdf
  66. */
  67. class Stylesheet {
  68. /**
  69. * the location of the default built-in CSS file.
  70. *
  71. */
  72. const DEFAULT_STYLESHEET = __DEFAULT_STYLESHEET; // Hack: can't
  73. // concatenate stuff in
  74. // const declarations,
  75. // but I can do this?
  76. // protected members
  77. /**
  78. * array of currently defined styles
  79. * @var array
  80. */
  81. private $_styles;
  82. /**
  83. * base protocol of the document being parsed
  84. *
  85. * Used to handle relative urls.
  86. *
  87. * @var string
  88. */
  89. private $_protocol;
  90. /**
  91. * base hostname of the document being parsed
  92. *
  93. * Used to handle relative urls.
  94. * @var string
  95. */
  96. private $_base_host;
  97. /**
  98. * base path of the document being parsed
  99. *
  100. * Used to handle relative urls.
  101. * @var string
  102. */
  103. private $_base_path;
  104. /**
  105. * the style defined by @page rules
  106. *
  107. * @var Style
  108. */
  109. private $_page_style;
  110. /**
  111. * list of loaded files, used to prevent recursion
  112. *
  113. * @var array
  114. */
  115. private $_loaded_files;
  116. /**
  117. * accepted CSS media types
  118. * List of types and parsing rules for future extensions:
  119. * http://www.w3.org/TR/REC-html40/types.html
  120. * screen, tty, tv, projection, handheld, print, braille, aural, all
  121. * The following are non standard extensions for undocumented specific environments.
  122. * static, visual, bitmap, paged
  123. * Note, even though the generated pdf file is intended for print output,
  124. * the desired content might be different (e.g. screen or projection view of html file).
  125. * Therefore allow specification of content by dompdf setting DOMPDF_DEFAULT_MEDIA_TYPE.
  126. * If given, replace media "print" by DOMPDF_DEFAULT_MEDIA_TYPE.
  127. * (Previous version $ACCEPTED_MEDIA_TYPES = $ACCEPTED_GENERIC_MEDIA_TYPES + $ACCEPTED_DEFAULT_MEDIA_TYPE)
  128. */
  129. static $ACCEPTED_DEFAULT_MEDIA_TYPE = "print";
  130. static $ACCEPTED_GENERIC_MEDIA_TYPES = array("all", "static", "visual", "bitmap", "paged");
  131. /**
  132. * The class constructor.
  133. *
  134. * The base protocol, host & path are initialized to those of
  135. * the current script.
  136. */
  137. function __construct() {
  138. $this->_styles = array();
  139. $this->_loaded_files = array();
  140. list($this->_protocol, $this->_base_host, $this->_base_path) = explode_url($_SERVER["SCRIPT_FILENAME"]);
  141. $this->_page_style = null;
  142. }
  143. /**
  144. * Set the base protocol
  145. *
  146. * @param string $proto
  147. */
  148. function set_protocol($proto) { $this->_protocol = $proto; }
  149. /**
  150. * Set the base host
  151. *
  152. * @param string $host
  153. */
  154. function set_host($host) { $this->_base_host = $host; }
  155. /**
  156. * Set the base path
  157. *
  158. * @param string $path
  159. */
  160. function set_base_path($path) { $this->_base_path = $path; }
  161. /**
  162. * Return the base protocol for this stylesheet
  163. *
  164. * @return string
  165. */
  166. function get_protocol() { return $this->_protocol; }
  167. /**
  168. * Return the base host for this stylesheet
  169. *
  170. * @return string
  171. */
  172. function get_host() { return $this->_base_host; }
  173. /**
  174. * Return the base path for this stylesheet
  175. *
  176. * @return string
  177. */
  178. function get_base_path() { return $this->_base_path; }
  179. /**
  180. * add a new Style object to the stylesheet
  181. *
  182. * add_style() adds a new Style object to the current stylesheet, or
  183. * merges a new Style with an existing one.
  184. *
  185. * @param string $key the Style's selector
  186. * @param Style $style the Style to be added
  187. */
  188. function add_style($key, Style $style) {
  189. if (!is_string($key))
  190. throw new DOMPDF_Exception("CSS rule must be keyed by a string.");
  191. if ( isset($this->_styles[$key]) )
  192. $this->_styles[$key]->merge($style);
  193. else
  194. $this->_styles[$key] = clone $style;
  195. }
  196. /**
  197. * lookup a specifc Style object
  198. *
  199. * lookup() returns the Style specified by $key, or null if the Style is
  200. * not found.
  201. *
  202. * @param string $key the selector of the requested Style
  203. * @return Style
  204. */
  205. function lookup($key) {
  206. if ( !isset($this->_styles[$key]) )
  207. return null;
  208. return $this->_styles[$key];
  209. }
  210. /**
  211. * create a new Style object associated with this stylesheet
  212. *
  213. * @param Style $parent The style of this style's parent in the DOM tree
  214. * @return Style
  215. */
  216. function create_style($parent = null) {
  217. return new Style($this, $parent);
  218. }
  219. /**
  220. * load and parse a CSS string
  221. *
  222. * @param string $css
  223. */
  224. function load_css(&$css) { $this->_parse_css($css); }
  225. /**
  226. * load and parse a CSS file
  227. *
  228. * @param string $file
  229. */
  230. function load_css_file($file) {
  231. global $_dompdf_warnings;
  232. // Prevent circular references
  233. if ( isset($this->_loaded_files[$file]) )
  234. return;
  235. $this->_loaded_files[$file] = true;
  236. $parsed_url = explode_url($file);
  237. list($this->_protocol, $this->_base_host, $this->_base_path, $filename) = $parsed_url;
  238. if ( !DOMPDF_ENABLE_REMOTE &&
  239. ($this->_protocol != "" && $this->_protocol !== "file://") ) {
  240. record_warnings(E_USER_WARNING, "Remote CSS file '$file' requested, but DOMPDF_ENABLE_REMOTE is false.", __FILE__, __LINE__);
  241. return;
  242. }
  243. // Fix submitted by Nick Oostveen for aliased directory support:
  244. if ( $this->_protocol == "" )
  245. $file = $this->_base_path . $filename;
  246. else
  247. $file = build_url($this->_protocol, $this->_base_host, $this->_base_path, $filename);
  248. set_error_handler("record_warnings");
  249. $css = file_get_contents($file);
  250. restore_error_handler();
  251. if ( $css == "" ) {
  252. record_warnings(E_USER_WARNING, "Unable to load css file $file", __FILE__, __LINE__);;
  253. return;
  254. }
  255. $this->_parse_css($css);
  256. }
  257. /**
  258. * @link http://www.w3.org/TR/CSS21/cascade.html#specificity}
  259. *
  260. * @param string $selector
  261. * @return int
  262. */
  263. private function _specificity($selector) {
  264. // http://www.w3.org/TR/CSS21/cascade.html#specificity
  265. // ignoring the ":" pseudoclass modifyers
  266. // also ignored in _css_selector_to_xpath
  267. $a = ($selector === "!style attribute") ? 1 : 0;
  268. $b = min(mb_substr_count($selector, "#"), 255);
  269. $c = min(mb_substr_count($selector, ".") +
  270. mb_substr_count($selector, ">") +
  271. mb_substr_count($selector, "+"), 255);
  272. $d = min(mb_substr_count($selector, " "), 255);
  273. //If a normal element name is at the begining of the string,
  274. //a leading whitespace might have been removed on whitespace collapsing and removal
  275. //therefore there might be one whitespace less as selected element names
  276. //this can lead to a too small specificity
  277. //see _css_selector_to_xpath
  278. if ( !in_array($selector[0], array(" ", ">", ".", "#", "+", ":", "[")) ) {
  279. $d++;
  280. }
  281. if (DEBUGCSS) {
  282. /*DEBUGCSS*/ print "<pre>\n";
  283. /*DEBUGCSS*/ printf("_specificity(): 0x%08x \"%s\"\n", ($a << 24) | ($b << 16) | ($c << 8) | ($d), $selector);
  284. /*DEBUGCSS*/ print "</pre>";
  285. }
  286. return ($a << 24) | ($b << 16) | ($c << 8) | ($d);
  287. }
  288. /**
  289. * converts a CSS selector to an XPath query.
  290. *
  291. * @param string $selector
  292. * @return string
  293. */
  294. private function _css_selector_to_xpath($selector) {
  295. // Collapse white space and strip whitespace around delimiters
  296. // $search = array("/\\s+/", "/\\s+([.>#+:])\\s+/");
  297. // $replace = array(" ", "\\1");
  298. // $selector = preg_replace($search, $replace, trim($selector));
  299. // Initial query (non-absolute)
  300. $query = "//";
  301. // Parse the selector
  302. //$s = preg_split("/([ :>.#+])/", $selector, -1, PREG_SPLIT_DELIM_CAPTURE);
  303. $delimiters = array(" ", ">", ".", "#", "+", ":", "[");
  304. // Add an implicit space at the beginning of the selector if there is no
  305. // delimiter there already.
  306. if ( !in_array($selector[0], $delimiters) )
  307. $selector = " $selector";
  308. $tok = "";
  309. $len = mb_strlen($selector);
  310. $i = 0;
  311. while ( $i < $len ) {
  312. $s = $selector[$i];
  313. $i++;
  314. // Eat characters up to the next delimiter
  315. $tok = "";
  316. while ($i < $len) {
  317. if ( in_array($selector[$i], $delimiters) )
  318. break;
  319. $tok .= $selector[$i++];
  320. }
  321. switch ($s) {
  322. case " ":
  323. case ">":
  324. // All elements matching the next token that are direct children of
  325. // the current token
  326. $expr = $s === " " ? "descendant" : "child";
  327. if ( mb_substr($query, -1, 1) !== "/" )
  328. $query .= "/";
  329. if ( !$tok )
  330. $tok = "*";
  331. $query .= "$expr::$tok";
  332. $tok = "";
  333. break;
  334. case ".":
  335. case "#":
  336. // All elements matching the current token with a class/id equal to
  337. // the _next_ token.
  338. $attr = $s === "." ? "class" : "id";
  339. // empty class/id == *
  340. if ( mb_substr($query, -1, 1) === "/" )
  341. $query .= "*";
  342. // Match multiple classes: $tok contains the current selected
  343. // class. Search for class attributes with class="$tok",
  344. // class=".* $tok .*" and class=".* $tok"
  345. // This doesn't work because libxml only supports XPath 1.0...
  346. //$query .= "[matches(@$attr,\"^${tok}\$|^${tok}[ ]+|[ ]+${tok}\$|[ ]+${tok}[ ]+\")]";
  347. // Query improvement by Michael Sheakoski <michael@mjsdigital.com>:
  348. $query .= "[contains(concat(' ', @$attr, ' '), concat(' ', '$tok', ' '))]";
  349. $tok = "";
  350. break;
  351. case "+":
  352. // All sibling elements that folow the current token
  353. if ( mb_substr($query, -1, 1) !== "/" )
  354. $query .= "/";
  355. $query .= "following-sibling::$tok";
  356. $tok = "";
  357. break;
  358. case ":":
  359. // Pseudo-classes
  360. switch ($tok) {
  361. case "first-child":
  362. $query .= "[1]";
  363. $tok = "";
  364. break;
  365. case "link":
  366. $query .= "[@href]";
  367. $tok = "";
  368. break;
  369. case "first-line":
  370. break;
  371. case "first-letter":
  372. break;
  373. case "before":
  374. break;
  375. case "after":
  376. break;
  377. }
  378. break;
  379. case "[":
  380. // Attribute selectors. All with an attribute matching the following token(s)
  381. $attr_delimiters = array("=", "]", "~", "|");
  382. $tok_len = mb_strlen($tok);
  383. $j = 0;
  384. $attr = "";
  385. $op = "";
  386. $value = "";
  387. while ( $j < $tok_len ) {
  388. if ( in_array($tok[$j], $attr_delimiters) )
  389. break;
  390. $attr .= $tok[$j++];
  391. }
  392. switch ( $tok[$j] ) {
  393. case "~":
  394. case "|":
  395. $op .= $tok[$j++];
  396. if ( $tok[$j] !== "=" )
  397. throw new DOMPDF_Exception("Invalid CSS selector syntax: invalid attribute selector: $selector");
  398. $op .= $tok[$j];
  399. break;
  400. case "=":
  401. $op = "=";
  402. break;
  403. }
  404. // Read the attribute value, if required
  405. if ( $op != "" ) {
  406. $j++;
  407. while ( $j < $tok_len ) {
  408. if ( $tok[$j] === "]" )
  409. break;
  410. $value .= $tok[$j++];
  411. }
  412. }
  413. if ( $attr == "" )
  414. throw new DOMPDF_Exception("Invalid CSS selector syntax: missing attribute name");
  415. switch ( $op ) {
  416. case "":
  417. $query .= "[@$attr]";
  418. break;
  419. case "=":
  420. $query .= "[@$attr$op\"$value\"]";
  421. break;
  422. case "~=":
  423. // FIXME: this will break if $value contains quoted strings
  424. // (e.g. [type~="a b c" "d e f"])
  425. $values = explode(" ", $value);
  426. $query .= "[";
  427. foreach ( $values as $val )
  428. $query .= "@$attr=\"$val\" or ";
  429. $query = rtrim($query, " or ") . "]";
  430. break;
  431. case "|=":
  432. $values = explode("-", $value);
  433. $query .= "[";
  434. foreach ($values as $val)
  435. $query .= "starts-with(@$attr, \"$val\") or ";
  436. $query = rtrim($query, " or ") . "]";
  437. break;
  438. }
  439. break;
  440. }
  441. }
  442. $i++;
  443. // case ":":
  444. // // Pseudo selectors: ignore for now. Partially handled directly
  445. // // below.
  446. // // Skip until the next special character, leaving the token as-is
  447. // while ( $i < $len ) {
  448. // if ( in_array($selector[$i], $delimiters) )
  449. // break;
  450. // $i++;
  451. // }
  452. // break;
  453. // default:
  454. // // Add the character to the token
  455. // $tok .= $selector[$i++];
  456. // break;
  457. // }
  458. // }
  459. // Trim the trailing '/' from the query
  460. if ( mb_strlen($query) > 2 )
  461. $query = rtrim($query, "/");
  462. return $query;
  463. }
  464. /**
  465. * applies all current styles to a particular document tree
  466. *
  467. * apply_styles() applies all currently loaded styles to the provided
  468. * {@link Frame_Tree}. Aside from parsing CSS, this is the main purpose
  469. * of this class.
  470. *
  471. * @param Frame_Tree $tree
  472. */
  473. function apply_styles(Frame_Tree $tree) {
  474. // Use XPath to select nodes. This would be easier if we could attach
  475. // Frame objects directly to DOMNodes using the setUserData() method, but
  476. // we can't do that just yet. Instead, we set a _node attribute_ in
  477. // Frame->set_id() and use that as a handle on the Frame object via
  478. // Frame_Tree::$_registry.
  479. // We create a scratch array of styles indexed by frame id. Once all
  480. // styles have been assigned, we order the cached styles by specificity
  481. // and create a final style object to assign to the frame.
  482. // FIXME: this is not particularly robust...
  483. $styles = array();
  484. $xp = new DOMXPath($tree->get_dom());
  485. // Apply all styles in stylesheet
  486. foreach ($this->_styles as $selector => $style) {
  487. $query = $this->_css_selector_to_xpath($selector);
  488. // pre_var_dump($selector);
  489. // pre_var_dump($query);
  490. // echo ($style);
  491. // Retrieve the nodes
  492. $nodes = $xp->query($query);
  493. foreach ($nodes as $node) {
  494. //echo $node->nodeName . "\n";
  495. // Retrieve the node id
  496. if ( $node->nodeType != 1 ) // Only DOMElements get styles
  497. continue;
  498. $id = $node->getAttribute("frame_id");
  499. // Assign the current style to the scratch array
  500. $spec = $this->_specificity($selector);
  501. $styles[$id][$spec][] = $style;
  502. }
  503. }
  504. // Now create the styles and assign them to the appropriate frames. (We
  505. // iterate over the tree using an implicit Frame_Tree iterator.)
  506. $root_flg = false;
  507. foreach ($tree->get_frames() as $frame) {
  508. // pre_r($frame->get_node()->nodeName . ":");
  509. if ( !$root_flg && $this->_page_style ) {
  510. $style = $this->_page_style;
  511. $root_flg = true;
  512. } else
  513. $style = $this->create_style();
  514. // Find nearest DOMElement parent
  515. $p = $frame;
  516. while ( $p = $p->get_parent() )
  517. if ($p->get_node()->nodeType == 1 )
  518. break;
  519. // Styles can only be applied directly to DOMElements; anonymous
  520. // frames inherit from their parent
  521. if ( $frame->get_node()->nodeType != 1 ) {
  522. if ( $p )
  523. $style->inherit($p->get_style());
  524. $frame->set_style($style);
  525. continue;
  526. }
  527. $id = $frame->get_id();
  528. // Handle HTML 4.0 attributes
  529. Attribute_Translator::translate_attributes($frame);
  530. // Locate any additional style attributes
  531. if ( ($str = $frame->get_node()->getAttribute("style")) !== "" ) {
  532. $spec = $this->_specificity("!style attribute");
  533. $styles[$id][$spec][] = $this->_parse_properties($str);
  534. }
  535. // Grab the applicable styles
  536. if ( isset($styles[$id]) ) {
  537. $applied_styles = $styles[ $frame->get_id() ];
  538. // Sort by specificity
  539. ksort($applied_styles);
  540. if (DEBUGCSS) {
  541. $debug_nodename = $frame->get_node()->nodeName;
  542. print "<pre>\n[$debug_nodename\n";
  543. foreach ($applied_styles as $spec => $arr) {
  544. printf("specificity: 0x%08x\n",$spec);
  545. foreach ($arr as $s) {
  546. print "[\n";
  547. $s->debug_print();
  548. print "]\n";
  549. }
  550. }
  551. }
  552. // Merge the new styles with the inherited styles
  553. foreach ($applied_styles as $arr) {
  554. foreach ($arr as $s)
  555. $style->merge($s);
  556. }
  557. }
  558. // Inherit parent's styles if required
  559. if ( $p ) {
  560. if (DEBUGCSS) {
  561. print "inherit:\n";
  562. print "[\n";
  563. $p->get_style()->debug_print();
  564. print "]\n";
  565. }
  566. $style->inherit( $p->get_style() );
  567. }
  568. if (DEBUGCSS) {
  569. print "DomElementStyle:\n";
  570. print "[\n";
  571. $style->debug_print();
  572. print "]\n";
  573. print "/$debug_nodename]\n</pre>";
  574. }
  575. /*DEBUGCSS print: see below different print debugging method
  576. pre_r($frame->get_node()->nodeName . ":");
  577. echo "<pre>";
  578. echo $style;
  579. echo "</pre>";*/
  580. $frame->set_style($style);
  581. }
  582. // We're done! Clean out the registry of all styles since we
  583. // won't be needing this later.
  584. foreach ( array_keys($this->_styles) as $key ) {
  585. unset($this->_styles[$key]);
  586. }
  587. }
  588. /**
  589. * parse a CSS string using a regex parser
  590. *
  591. * Called by {@link Stylesheet::parse_css()}
  592. *
  593. * @param string $str
  594. */
  595. private function _parse_css($str) {
  596. $str = trim($str);
  597. // Destroy comments and remove HTML comments
  598. $css = preg_replace(array(
  599. "'/\*.*?\*/'si",
  600. "/^<!--/",
  601. "/-->$/"
  602. ), "", $str);
  603. // FIXME: handle '{' within strings, e.g. [attr="string {}"]
  604. // Something more legible:
  605. $re =
  606. "/\s* # Skip leading whitespace \n".
  607. "( @([^\s]+)\s+([^{;]*) (?:;|({)) )? # Match @rules followed by ';' or '{' \n".
  608. "(?(1) # Only parse sub-sections if we're in an @rule... \n".
  609. " (?(4) # ...and if there was a leading '{' \n".
  610. " \s*( (?:(?>[^{}]+) ({)? # Parse rulesets and individual @page rules \n".
  611. " (?(6) (?>[^}]*) }) \s*)+? \n".
  612. " ) \n".
  613. " }) # Balancing '}' \n".
  614. "| # Branch to match regular rules (not preceeded by '@')\n".
  615. "([^{]*{[^}]*})) # Parse normal rulesets\n".
  616. "/xs";
  617. if ( preg_match_all($re, $css, $matches, PREG_SET_ORDER) === false )
  618. // An error occured
  619. throw new DOMPDF_Exception("Error parsing css file: preg_match_all() failed.");
  620. // After matching, the array indicies are set as follows:
  621. //
  622. // [0] => complete text of match
  623. // [1] => contains '@import ...;' or '@media {' if applicable
  624. // [2] => text following @ for cases where [1] is set
  625. // [3] => media types or full text following '@import ...;'
  626. // [4] => '{', if present
  627. // [5] => rulesets within media rules
  628. // [6] => '{', within media rules
  629. // [7] => individual rules, outside of media rules
  630. //
  631. //pre_r($matches);
  632. foreach ( $matches as $match ) {
  633. $match[2] = trim($match[2]);
  634. if ( $match[2] !== "" ) {
  635. // Handle @rules
  636. switch ($match[2]) {
  637. case "import":
  638. $this->_parse_import($match[3]);
  639. break;
  640. case "media":
  641. $acceptedmedia = self::$ACCEPTED_GENERIC_MEDIA_TYPES;
  642. if ( defined("DOMPDF_DEFAULT_MEDIA_TYPE") ) {
  643. $acceptedmedia[] = DOMPDF_DEFAULT_MEDIA_TYPE;
  644. } else {
  645. $acceptedmedia[] = self::$ACCEPTED_DEFAULT_MEDIA_TYPE;
  646. }
  647. if ( in_array(mb_strtolower(trim($match[3])), $acceptedmedia ) ) {
  648. $this->_parse_sections($match[5]);
  649. }
  650. break;
  651. case "page":
  652. //This handles @page to be applied to page oriented media
  653. //Note: This has a reduced syntax:
  654. //@page { margin:1cm; color:blue; }
  655. //Not a sequence of styles like a full.css, but only the properties
  656. //of a single style, which is applied to the very first "root" frame before
  657. //processing other styles of the frame.
  658. //Working properties:
  659. // margin (for margin around edge of paper)
  660. // font-family (default font of pages)
  661. // color (default text color of pages)
  662. //Non working properties:
  663. // border
  664. // padding
  665. // background-color
  666. //Todo:Reason is unknown
  667. //Other properties (like further font or border attributes) not tested.
  668. //If a border or background color around each paper sheet is desired,
  669. //assign it to the <body> tag, possibly only for the css of the correct media type.
  670. // Store the style for later...
  671. if ( is_null($this->_page_style) )
  672. $this->_page_style = $this->_parse_properties($match[5]);
  673. else
  674. $this->_page_style->merge($this->_parse_properties($match[5]));
  675. break;
  676. default:
  677. // ignore everything else
  678. break;
  679. }
  680. continue;
  681. }
  682. if ( $match[7] !== "" )
  683. $this->_parse_sections($match[7]);
  684. }
  685. }
  686. /* See also style.cls Style::_image(), refactoring?, works also for imported css files */
  687. protected function _image($val) {
  688. $DEBUGCSS=DEBUGCSS;
  689. if ( mb_strpos($val, "url") === false ) {
  690. $path = "none"; //Don't resolve no image -> otherwise would prefix path and no longer recognize as none
  691. }
  692. else {
  693. $val = preg_replace("/url\(['\"]?([^'\")]+)['\"]?\)/","\\1", trim($val));
  694. // Resolve the url now in the context of the current stylesheet
  695. $parsed_url = explode_url($val);
  696. if ( $parsed_url["protocol"] == "" && $this->get_protocol() == "" ) {
  697. if ($parsed_url["path"]{0} === '/' || $parsed_url["path"]{0} === '\\' ) {
  698. $path = $_SERVER["DOCUMENT_ROOT"].'/';
  699. } else {
  700. $path = $this->get_base_path();
  701. }
  702. $path .= $parsed_url["path"] . $parsed_url["file"];
  703. $path = realpath($path);
  704. // If realpath returns FALSE then specifically state that there is no background image
  705. if (!$path) { $path = 'none'; }
  706. } else {
  707. $path = build_url($this->get_protocol(),
  708. $this->get_host(),
  709. $this->get_base_path(),
  710. $val);
  711. }
  712. }
  713. if ($DEBUGCSS) {
  714. print "<pre>[_image\n";
  715. print_r($parsed_url);
  716. print $this->get_protocol()."\n".$this->get_base_path()."\n".$path."\n";
  717. print "_image]</pre>";;
  718. }
  719. return $path;
  720. }
  721. /**
  722. * parse @import{} sections
  723. *
  724. * @param string $url the url of the imported CSS file
  725. */
  726. private function _parse_import($url) {
  727. $arr = preg_split("/[\s\n,]/", $url,-1, PREG_SPLIT_NO_EMPTY);
  728. $url = array_shift($arr);
  729. $accept = false;
  730. if ( count($arr) > 0 ) {
  731. $acceptedmedia = self::$ACCEPTED_GENERIC_MEDIA_TYPES;
  732. if ( defined("DOMPDF_DEFAULT_MEDIA_TYPE") ) {
  733. $acceptedmedia[] = DOMPDF_DEFAULT_MEDIA_TYPE;
  734. } else {
  735. $acceptedmedia[] = self::$ACCEPTED_DEFAULT_MEDIA_TYPE;
  736. }
  737. // @import url media_type [media_type...]
  738. foreach ( $arr as $type ) {
  739. if ( in_array(mb_strtolower(trim($type)), $acceptedmedia) ) {
  740. $accept = true;
  741. break;
  742. }
  743. }
  744. } else {
  745. // unconditional import
  746. $accept = true;
  747. }
  748. if ( $accept ) {
  749. // Store our current base url properties in case the new url is elsewhere
  750. $protocol = $this->_protocol;
  751. $host = $this->_base_host;
  752. $path = $this->_base_path;
  753. // $url = str_replace(array('"',"url", "(", ")"), "", $url);
  754. // If the protocol is php, assume that we will import using file://
  755. // $url = build_url($protocol == "php://" ? "file://" : $protocol, $host, $path, $url);
  756. // Above does not work for subfolders and absolute urls.
  757. // Todo: As above, do we need to replace php or file to an empty protocol for local files?
  758. $url = $this->_image($url);
  759. $this->load_css_file($url);
  760. // Restore the current base url
  761. $this->_protocol = $protocol;
  762. $this->_base_host = $host;
  763. $this->_base_path = $path;
  764. }
  765. }
  766. /**
  767. * parse regular CSS blocks
  768. *
  769. * _parse_properties() creates a new Style object based on the provided
  770. * CSS rules.
  771. *
  772. * @param string $str CSS rules
  773. * @return Style
  774. */
  775. private function _parse_properties($str) {
  776. $properties = explode(";", $str);
  777. if (DEBUGCSS) print '[_parse_properties';
  778. // Create the style
  779. $style = new Style($this);
  780. foreach ($properties as $prop) {
  781. //A css property can have " ! important" appended (whitespace optional)
  782. //strip this off to decode core of the property correctly.
  783. //Pass on in the style to allow proper handling:
  784. //!important properties can only be overridden by other !important ones.
  785. //$style->$prop_name = is a shortcut of $style->__set($prop_name,$value);.
  786. //If no specific set function available, set _props["prop_name"]
  787. //style is always copied completely, or $_props handled separately
  788. //Therefore set a _important_props["prop_name"]=true to indicate the modifier
  789. /* Instead of short code, prefer the typical case with fast code
  790. $important = preg_match("/(.*?)!\s*important/",$prop,$match);
  791. if ( $important ) {
  792. $prop = $match[1];
  793. }
  794. $prop = trim($prop);
  795. */
  796. if (DEBUGCSS) print '(';
  797. $important = false;
  798. $prop = trim($prop);
  799. if (substr($prop,-9) === 'important') {
  800. $prop_tmp = rtrim(substr($prop,0,-9));
  801. if (substr($prop_tmp,-1) === '!') {
  802. $prop = rtrim(substr($prop_tmp,0,-1));
  803. $important = true;
  804. }
  805. }
  806. if ($prop == "") {
  807. if (DEBUGCSS) print 'empty)';
  808. continue;
  809. }
  810. $i = mb_strpos($prop, ":");
  811. if ( $i === false ) {
  812. if (DEBUGCSS) print 'novalue'.$prop.')';
  813. continue;
  814. }
  815. $prop_name = rtrim(mb_strtolower(mb_substr($prop, 0, $i)));
  816. $value = ltrim(mb_substr($prop, $i+1));
  817. if (DEBUGCSS) print $prop_name.':='.$value.($important?'!IMPORTANT':'').')';
  818. //New style, anyway empty
  819. //if ($important || !$style->important_get($prop_name) ) {
  820. //$style->$prop_name = array($value,$important);
  821. //assignment might be replaced by overloading through __set,
  822. //and overloaded functions might check _important_props,
  823. //therefore set _important_props first.
  824. if ($important) {
  825. $style->important_set($prop_name);
  826. }
  827. //For easier debugging, don't use overloading of assignments with __set
  828. $style->$prop_name = $value;
  829. //$style->props_set($prop_name, $value);
  830. }
  831. if (DEBUGCSS) print '_parse_properties]';
  832. return $style;
  833. }
  834. /**
  835. * parse selector + rulesets
  836. *
  837. * @param string $str CSS selectors and rulesets
  838. */
  839. private function _parse_sections($str) {
  840. // Pre-process: collapse all whitespace and strip whitespace around '>',
  841. // '.', ':', '+', '#'
  842. $patterns = array("/[\\s\n]+/", "/\\s+([>.:+#])\\s+/");
  843. $replacements = array(" ", "\\1");
  844. $str = preg_replace($patterns, $replacements, $str);
  845. $sections = explode("}", $str);
  846. if (DEBUGCSS) print '[_parse_sections';
  847. foreach ($sections as $sect) {
  848. $i = mb_strpos($sect, "{");
  849. $selectors = explode(",", mb_substr($sect, 0, $i));
  850. if (DEBUGCSS) print '[section';
  851. $style = $this->_parse_properties(trim(mb_substr($sect, $i+1)));
  852. // Assign it to the selected elements
  853. foreach ($selectors as $selector) {
  854. $selector = trim($selector);
  855. if ($selector == "") {
  856. if (DEBUGCSS) print '#empty#';
  857. continue;
  858. }
  859. if (DEBUGCSS) print '#'.$selector.'#';
  860. //if (DEBUGCSS) { if (strpos($selector,'p') !== false) print '!!!p!!!#'; }
  861. $this->add_style($selector, $style);
  862. }
  863. if (DEBUGCSS) print 'section]';
  864. }
  865. if (DEBUGCSS) print '_parse_sections]';
  866. }
  867. /**
  868. * dumps the entire stylesheet as a string
  869. *
  870. * Generates a string of each selector and associated style in the
  871. * Stylesheet. Useful for debugging.
  872. *
  873. * @return string
  874. */
  875. function __toString() {
  876. $str = "";
  877. foreach ($this->_styles as $selector => $style)
  878. $str .= "$selector => " . $style->__toString() . "\n";
  879. return $str;
  880. }
  881. }