4 * @link http://dompdf.github.com/
5 * @author Benj Carson <benjcarson@digitaljunkies.ca>
6 * @author Helmut Tischer <htischer@weihenstephan.org>
7 * @author Fabien Ménager <fabien.menager@gmail.com>
8 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16 use Dompdf\FontMetrics
;
17 use Dompdf\Frame\FrameTree
;
20 * The master stylesheet class
22 * The Stylesheet class is responsible for parsing stylesheets and style
23 * tags/attributes. It also acts as a registry of the individual Style
24 * objects generated by the current set of loaded CSS files and style
33 * The location of the default built-in CSS file.
35 const DEFAULT_STYLESHEET
= "/lib/res/html.css";
38 * User agent stylesheet origin
45 * User normal stylesheet origin
52 * Author normal stylesheet origin
56 const ORIG_AUTHOR
= 3;
58 private static $_stylesheet_origins = array(
59 self
::ORIG_UA
=> -0x0FFFFFFF, // user agent style sheets
60 self
::ORIG_USER
=> -0x0000FFFF, // user normal style sheets
61 self
::ORIG_AUTHOR
=> 0x00000000, // author normal style sheets
65 * Current dompdf instance
72 * Array of currently defined styles
79 * Base protocol of the document being parsed
80 * Used to handle relative urls.
87 * Base hostname of the document being parsed
88 * Used to handle relative urls.
95 * Base path of the document being parsed
96 * Used to handle relative urls.
103 * The styles defined by @page rules
107 private $_page_styles;
110 * List of loaded files, used to prevent recursion
114 private $_loaded_files;
117 * Current stylesheet origin
121 private $_current_origin = self
::ORIG_UA
;
124 * Accepted CSS media types
125 * List of types and parsing rules for future extensions:
126 * http://www.w3.org/TR/REC-html40/types.html
127 * screen, tty, tv, projection, handheld, print, braille, aural, all
128 * The following are non standard extensions for undocumented specific environments.
129 * static, visual, bitmap, paged, dompdf
130 * Note, even though the generated pdf file is intended for print output,
131 * the desired content might be different (e.g. screen or projection view of html file).
132 * Therefore allow specification of content by dompdf setting Options::defaultMediaType.
133 * If given, replace media "print" by Options::defaultMediaType.
134 * (Previous version $ACCEPTED_MEDIA_TYPES = $ACCEPTED_GENERIC_MEDIA_TYPES + $ACCEPTED_DEFAULT_MEDIA_TYPE)
136 static $ACCEPTED_DEFAULT_MEDIA_TYPE = "print";
137 static $ACCEPTED_GENERIC_MEDIA_TYPES = array("all", "static", "visual", "bitmap", "paged", "dompdf");
142 private $fontMetrics;
145 * The class constructor.
147 * The base protocol, host & path are initialized to those of
148 * the current script.
150 function __construct(Dompdf
$dompdf)
152 $this->_dompdf
= $dompdf;
153 $this->setFontMetrics($dompdf->getFontMetrics());
154 $this->_styles
= array();
155 $this->_loaded_files
= array();
156 list($this->_protocol
, $this->_base_host
, $this->_base_path
) = Helpers
::explode_url($_SERVER["SCRIPT_FILENAME"]);
157 $this->_page_styles
= array("base" => null);
161 * Set the base protocol
163 * @param string $protocol
165 function set_protocol($protocol)
167 $this->_protocol
= $protocol;
173 * @param string $host
175 function set_host($host)
177 $this->_base_host
= $host;
183 * @param string $path
185 function set_base_path($path)
187 $this->_base_path
= $path;
191 * Return the Dompdf object
195 function get_dompdf()
197 return $this->_dompdf
;
201 * Return the base protocol for this stylesheet
205 function get_protocol()
207 return $this->_protocol
;
211 * Return the base host for this stylesheet
217 return $this->_base_host
;
221 * Return the base path for this stylesheet
225 function get_base_path()
227 return $this->_base_path
;
231 * Return the array of page styles
235 function get_page_styles()
237 return $this->_page_styles
;
241 * Add a new Style object to the stylesheet
242 * add_style() adds a new Style object to the current stylesheet, or
243 * merges a new Style with an existing one.
245 * @param string $key the Style's selector
246 * @param Style $style the Style to be added
248 * @throws \Dompdf\Exception
250 function add_style($key, Style
$style)
252 if (!is_string($key)) {
253 throw new Exception("CSS rule must be keyed by a string.");
256 if (isset($this->_styles
[$key])) {
257 $this->_styles
[$key]->merge($style);
259 $this->_styles
[$key] = clone $style;
262 $this->_styles
[$key]->set_origin($this->_current_origin
);
266 * lookup a specifc Style object
268 * lookup() returns the Style specified by $key, or null if the Style is
271 * @param string $key the selector of the requested Style
274 function lookup($key)
276 if (!isset($this->_styles
[$key])) {
280 return $this->_styles
[$key];
284 * create a new Style object associated with this stylesheet
286 * @param Style $parent The style of this style's parent in the DOM tree
289 function create_style(Style
$parent = null)
291 return new Style($this, $this->_current_origin
);
295 * load and parse a CSS string
299 function load_css(&$css)
301 $this->_parse_css($css);
306 * load and parse a CSS file
308 * @param string $file
311 function load_css_file($file, $origin = self
::ORIG_AUTHOR
)
314 $this->_current_origin
= $origin;
317 // Prevent circular references
318 if (isset($this->_loaded_files
[$file])) {
322 $this->_loaded_files
[$file] = true;
324 if (strpos($file, "data:") === 0) {
325 $parsed = Helpers
::parse_data_uri($file);
326 $css = $parsed["data"];
328 $parsed_url = Helpers
::explode_url($file);
330 list($this->_protocol
, $this->_base_host
, $this->_base_path
, $filename) = $parsed_url;
332 // Fix submitted by Nick Oostveen for aliased directory support:
333 if ($this->_protocol
== "") {
334 $file = $this->_base_path
. $filename;
336 $file = Helpers
::build_url($this->_protocol
, $this->_base_host
, $this->_base_path
, $filename);
339 set_error_handler(array("\\Dompdf\\Helpers", "record_warnings"));
340 $css = file_get_contents($file, null, $this->_dompdf
->get_http_context());
341 restore_error_handler();
343 $good_mime_type = true;
345 // See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
346 if (isset($http_response_header) && !$this->_dompdf
->get_quirksmode()) {
347 foreach ($http_response_header as $_header) {
348 if (preg_match("@Content-Type:\s*([\w/]+)@i", $_header, $matches) &&
349 ($matches[1] !== "text/css")
351 $good_mime_type = false;
356 if (!$good_mime_type ||
$css == "") {
357 Helpers
::record_warnings(E_USER_WARNING
, "Unable to load css file $file", __FILE__
, __LINE__
);
362 $this->_parse_css($css);
366 * @link http://www.w3.org/TR/CSS21/cascade.html#specificity
368 * @param string $selector
369 * @param int $origin :
370 * - ua: user agent style sheets
371 * - un: user normal style sheets
372 * - an: author normal style sheets
373 * - ai: author important style sheets
374 * - ui: user important style sheets
378 private function _specificity($selector, $origin = self
::ORIG_AUTHOR
)
380 // http://www.w3.org/TR/CSS21/cascade.html#specificity
381 // ignoring the ":" pseudoclass modifiers
382 // also ignored in _css_selector_to_xpath
384 $a = ($selector === "!attr") ?
1 : 0;
386 $b = min(mb_substr_count($selector, "#"), 255);
388 $c = min(mb_substr_count($selector, ".") +
389 mb_substr_count($selector, "["), 255);
391 $d = min(mb_substr_count($selector, " ") +
392 mb_substr_count($selector, ">") +
393 mb_substr_count($selector, "+"), 255);
395 //If a normal element name is at the beginning of the string,
396 //a leading whitespace might have been removed on whitespace collapsing and removal
397 //therefore there might be one whitespace less as selected element names
398 //this can lead to a too small specificity
399 //see _css_selector_to_xpath
401 if (!in_array($selector[0], array(" ", ">", ".", "#", "+", ":", "[")) /* && $selector !== "*"*/) {
405 if ($this->_dompdf
->get_option('debugCss')) {
409 printf("_specificity(): 0x%08x \"%s\"\n", ($a << 24) |
($b << 16) |
($c << 8) |
($d), $selector);
414 return self
::$_stylesheet_origins[$origin] +
($a << 24) |
($b << 16) |
($c << 8) |
($d);
418 * Converts a CSS selector to an XPath query.
420 * @param string $selector
421 * @param bool $first_pass
426 private function _css_selector_to_xpath($selector, $first_pass = false)
429 // Collapse white space and strip whitespace around delimiters
430 // $search = array("/\\s+/", "/\\s+([.>#+:])\\s+/");
431 // $replace = array(" ", "\\1");
432 // $selector = preg_replace($search, $replace, trim($selector));
434 // Initial query (non-absolute)
437 // Will contain :before and :after if they must be created
438 $pseudo_elements = array();
440 // Parse the selector
441 //$s = preg_split("/([ :>.#+])/", $selector, -1, PREG_SPLIT_DELIM_CAPTURE);
443 $delimiters = array(" ", ">", ".", "#", "+", ":", "[", "(");
445 // Add an implicit * at the beginning of the selector
446 // if it begins with an attribute selector
447 if ($selector[0] === "[") {
448 $selector = "*$selector";
451 // Add an implicit space at the beginning of the selector if there is no
452 // delimiter there already.
453 if (!in_array($selector[0], $delimiters)) {
454 $selector = " $selector";
458 $len = mb_strlen($selector);
466 // Eat characters up to the next delimiter
472 $c_prev = $selector[$i - 1];
474 if (!$in_attr && in_array($c, $delimiters)) {
478 if ($c_prev === "[") {
482 $tok .= $selector[$i++
];
484 if ($in_attr && $c === "]") {
494 // All elements matching the next token that are direct children of
496 $expr = $s === " " ?
"descendant" : "child";
498 if (mb_substr($query, -1, 1) !== "/") {
502 // Tag names are case-insensitive
503 $tok = strtolower($tok);
509 $query .= "$expr::$tok";
515 // All elements matching the current token with a class/id equal to
518 $attr = $s === "." ?
"class" : "id";
520 // empty class/id == *
521 if (mb_substr($query, -1, 1) === "/") {
525 // Match multiple classes: $tok contains the current selected
526 // class. Search for class attributes with class="$tok",
527 // class=".* $tok .*" and class=".* $tok"
529 // This doesn't work because libxml only supports XPath 1.0...
530 //$query .= "[matches(@$attr,\"^${tok}\$|^${tok}[ ]+|[ ]+${tok}\$|[ ]+${tok}[ ]+\")]";
532 // Query improvement by Michael Sheakoski <michael@mjsdigital.com>:
533 $query .= "[contains(concat(' ', @$attr, ' '), concat(' ', '$tok', ' '))]";
538 // All sibling elements that folow the current token
539 if (mb_substr($query, -1, 1) !== "/") {
543 $query .= "following-sibling::$tok";
548 $i2 = $i - strlen($tok) - 2; // the char before ":"
549 if (!isset($selector[$i2]) ||
in_array($selector[$i2], $delimiters)) {
564 $query .= "[not(following-sibling::*)]";
568 case "first-of-type":
569 $query .= "[position() = 1]";
574 $query .= "[position() = last()]";
578 // an+b, n, odd, and even
579 case "nth-last-of-type":
580 case "nth-last-child":
586 $nth = trim(mb_substr($selector, $p, strpos($selector, ")", $i) - $p));
589 if (preg_match("/^\d+$/", $nth)) {
590 $condition = "position() = $nth";
592 elseif ($nth === "odd") {
593 $condition = "(position() mod 2) = 1";
595 elseif ($nth === "even") {
596 $condition = "(position() mod 2) = 0";
599 $condition = $this->_selector_an_plus_b($nth, $last);
602 $query .= "[$condition]";
611 case "first-line": // TODO
612 case "first-letter": // TODO
618 $query .= "[false()]";
622 /* Pseudo-elements */
626 $pseudo_elements[$tok] = $tok;
628 $query .= "/*[@$tok]";
635 $query .= "[not(*) and not(normalize-space())]";
646 $query .= "[not(@disabled)]";
654 // Attribute selectors. All with an attribute matching the following token(s)
655 $attr_delimiters = array("=", "]", "~", "|", "$", "^", "*");
656 $tok_len = mb_strlen($tok);
663 while ($j < $tok_len) {
664 if (in_array($tok[$j], $attr_delimiters)) {
679 if ($tok[$j] !== "=") {
680 throw new Exception("Invalid CSS selector syntax: invalid attribute selector: $selector");
692 // Read the attribute value, if required
695 while ($j < $tok_len) {
696 if ($tok[$j] === "]") {
699 $value .= $tok[$j++
];
704 throw new Exception("Invalid CSS selector syntax: missing attribute name");
707 $value = trim($value, "\"'");
712 $query .= "[@$attr]";
716 $query .= "[@$attr=\"$value\"]";
720 // FIXME: this will break if $value contains quoted strings
721 // (e.g. [type~="a b c" "d e f"])
722 $values = explode(" ", $value);
725 foreach ($values as $val) {
726 $query .= "@$attr=\"$val\" or ";
729 $query = rtrim($query, " or ") . "]";
733 $values = explode("-", $value);
736 foreach ($values as $val) {
737 $query .= "starts-with(@$attr, \"$val\") or ";
740 $query = rtrim($query, " or ") . "]";
744 $query .= "[substring(@$attr, string-length(@$attr)-" . (strlen($value) - 1) . ")=\"$value\"]";
748 $query .= "[starts-with(@$attr,\"$value\")]";
752 $query .= "[contains(@$attr,\"$value\")]";
762 // // Pseudo selectors: ignore for now. Partially handled directly
765 // // Skip until the next special character, leaving the token as-is
766 // while ( $i < $len ) {
767 // if ( in_array($selector[$i], $delimiters) )
774 // // Add the character to the token
775 // $tok .= $selector[$i++];
782 // Trim the trailing '/' from the query
783 if (mb_strlen($query) > 2) {
784 $query = rtrim($query, "/");
787 return array("query" => $query, "pseudo_elements" => $pseudo_elements);
790 // https://github.com/tenderlove/nokogiri/blob/master/lib/nokogiri/css/xpath_visitor.rb
791 protected function _selector_an_plus_b($expr, $last = false)
793 $expr = preg_replace("/\s/", "", $expr);
794 if (!preg_match("/^(?P<a>-?[0-9]*)?n(?P<b>[-+]?[0-9]+)?$/", $expr, $matches)) {
798 $a = ((isset($matches["a"]) && $matches["a"] !== "") ?
intval($matches["a"]) : 1);
799 $b = ((isset($matches["b"]) && $matches["b"] !== "") ?
intval($matches["b"]) : 0);
801 $position = ($last ?
"(last()-position()+1)" : "position()");
804 return "($position mod $a) = 0";
806 $compare = (($a < 0) ?
"<=" : ">=");
811 return "($position $compare $b) and ((($position $b2) mod " . abs($a) . ") = 0)";
816 * applies all current styles to a particular document tree
818 * apply_styles() applies all currently loaded styles to the provided
819 * {@link FrameTree}. Aside from parsing CSS, this is the main purpose
822 * @param \Dompdf\Frame\FrameTree $tree
824 function apply_styles(FrameTree
$tree)
826 // Use XPath to select nodes. This would be easier if we could attach
827 // Frame objects directly to DOMNodes using the setUserData() method, but
828 // we can't do that just yet. Instead, we set a _node attribute_ in
829 // Frame->set_id() and use that as a handle on the Frame object via
830 // FrameTree::$_registry.
832 // We create a scratch array of styles indexed by frame id. Once all
833 // styles have been assigned, we order the cached styles by specificity
834 // and create a final style object to assign to the frame.
836 // FIXME: this is not particularly robust...
839 $xp = new DOMXPath($tree->get_dom());
841 // Add generated content
842 foreach ($this->_styles
as $selector => $style) {
843 if (strpos($selector, ":before") === false && strpos($selector, ":after") === false) {
847 $query = $this->_css_selector_to_xpath($selector, true);
849 // Retrieve the nodes, limit to body for generated content
850 $nodes = @$xp->query('.' . $query["query"]);
851 if ($nodes == null) {
852 Helpers
::record_warnings(E_USER_WARNING
, "The CSS selector '$selector' is not valid", __FILE__
, __LINE__
);
856 foreach ($nodes as $node) {
857 foreach ($query["pseudo_elements"] as $pos) {
858 // Do not add a new pseudo element if another one already matched
859 if ($node->hasAttribute("dompdf_{$pos}_frame_id")) {
863 if (($src = $this->_image($style->content
)) !== "none") {
864 $new_node = $node->ownerDocument
->createElement("img_generated");
865 $new_node->setAttribute("src", $src);
867 $new_node = $node->ownerDocument
->createElement("dompdf_generated");
870 $new_node->setAttribute($pos, $pos);
871 $new_frame_id = $tree->insert_node($node, $new_node, $pos);
872 $node->setAttribute("dompdf_{$pos}_frame_id", $new_frame_id);
877 // Apply all styles in stylesheet
878 foreach ($this->_styles
as $selector => $style) {
879 $query = $this->_css_selector_to_xpath($selector);
881 // Retrieve the nodes
882 $nodes = @$xp->query($query["query"]);
883 if ($nodes == null) {
884 Helpers
::record_warnings(E_USER_WARNING
, "The CSS selector '$selector' is not valid", __FILE__
, __LINE__
);
888 foreach ($nodes as $node) {
889 // Retrieve the node id
890 // Only DOMElements get styles
891 if ($node->nodeType
!= XML_ELEMENT_NODE
) {
895 $id = $node->getAttribute("frame_id");
897 // Assign the current style to the scratch array
898 $spec = $this->_specificity($selector);
899 $styles[$id][$spec][] = $style;
903 // Now create the styles and assign them to the appropriate frames. (We
904 // iterate over the tree using an implicit FrameTree iterator.)
906 foreach ($tree->get_frames() as $frame) {
907 // Helpers::pre_r($frame->get_node()->nodeName . ":");
908 if (!$root_flg && $this->_page_styles
["base"]) {
909 $style = $this->_page_styles
["base"];
912 $style = $this->create_style();
915 // Find nearest DOMElement parent
917 while ($p = $p->get_parent()) {
918 if ($p->get_node()->nodeType
== XML_ELEMENT_NODE
) {
923 // Styles can only be applied directly to DOMElements; anonymous
924 // frames inherit from their parent
925 if ($frame->get_node()->nodeType
!= XML_ELEMENT_NODE
) {
927 $style->inherit($p->get_style());
930 $frame->set_style($style);
934 $id = $frame->get_id();
936 // Handle HTML 4.0 attributes
937 AttributeTranslator
::translate_attributes($frame);
938 if (($str = $frame->get_node()->getAttribute(AttributeTranslator
::$_style_attr)) !== "") {
939 // Lowest specificity
940 $styles[$id][1][] = $this->_parse_properties($str);
943 // Locate any additional style attributes
944 if (($str = $frame->get_node()->getAttribute("style")) !== "") {
945 // Destroy CSS comments
946 $str = preg_replace("'/\*.*?\*/'si", "", $str);
948 $spec = $this->_specificity("!attr");
949 $styles[$id][$spec][] = $this->_parse_properties($str);
952 // Grab the applicable styles
953 if (isset($styles[$id])) {
955 $applied_styles = $styles[$frame->get_id()];
957 // Sort by specificity
958 ksort($applied_styles);
960 if ($this->_dompdf
->get_option('debugCss')) {
961 $debug_nodename = $frame->get_node()->nodeName
;
962 print "<pre>\n[$debug_nodename\n";
963 foreach ($applied_styles as $spec => $arr) {
964 printf("specificity: 0x%08x\n", $spec);
965 foreach ($arr as $s) {
973 // Merge the new styles with the inherited styles
974 foreach ($applied_styles as $arr) {
975 foreach ($arr as $s) {
981 // Inherit parent's styles if required
984 if ($this->_dompdf
->get_option('debugCss')) {
987 $p->get_style()->debug_print();
991 $style->inherit($p->get_style());
994 if ($this->_dompdf
->get_option('debugCss')) {
995 print "DomElementStyle:\n";
997 $style->debug_print();
999 print "/$debug_nodename]\n</pre>";
1002 /*DEBUGCSS print: see below different print debugging method
1003 Helpers::pre_r($frame->get_node()->nodeName . ":");
1007 $frame->set_style($style);
1011 // We're done! Clean out the registry of all styles since we
1012 // won't be needing this later.
1013 foreach (array_keys($this->_styles
) as $key) {
1014 $this->_styles
[$key] = null;
1015 unset($this->_styles
[$key]);
1021 * parse a CSS string using a regex parser
1022 * Called by {@link Stylesheet::parse_css()}
1024 * @param string $str
1028 private function _parse_css($str)
1033 // Destroy comments and remove HTML comments
1034 $css = preg_replace(array(
1040 // FIXME: handle '{' within strings, e.g. [attr="string {}"]
1042 // Something more legible:
1044 "/\s* # Skip leading whitespace \n" .
1045 "( @([^\s{]+)\s*([^{;]*) (?:;|({)) )? # Match @rules followed by ';' or '{' \n" .
1046 "(?(1) # Only parse sub-sections if we're in an @rule... \n" .
1047 " (?(4) # ...and if there was a leading '{' \n" .
1048 " \s*( (?:(?>[^{}]+) ({)? # Parse rulesets and individual @page rules \n" .
1049 " (?(6) (?>[^}]*) }) \s*)+? \n" .
1051 " }) # Balancing '}' \n" .
1052 "| # Branch to match regular rules (not preceded by '@')\n" .
1053 "([^{]*{[^}]*})) # Parse normal rulesets\n" .
1056 if (preg_match_all($re, $css, $matches, PREG_SET_ORDER
) === false) {
1057 // An error occurred
1058 throw new Exception("Error parsing css file: preg_match_all() failed.");
1061 // After matching, the array indicies are set as follows:
1063 // [0] => complete text of match
1064 // [1] => contains '@import ...;' or '@media {' if applicable
1065 // [2] => text following @ for cases where [1] is set
1066 // [3] => media types or full text following '@import ...;'
1067 // [4] => '{', if present
1068 // [5] => rulesets within media rules
1069 // [6] => '{', within media rules
1070 // [7] => individual rules, outside of media rules
1072 //Helpers::pre_r($matches);
1073 foreach ($matches as $match) {
1074 $match[2] = trim($match[2]);
1076 if ($match[2] !== "") {
1078 switch ($match[2]) {
1081 $this->_parse_import($match[3]);
1085 $acceptedmedia = self
::$ACCEPTED_GENERIC_MEDIA_TYPES;
1086 $acceptedmedia[] = $this->_dompdf
->get_option("default_media_type");
1088 $media = preg_split("/\s*,\s*/", mb_strtolower(trim($match[3])));
1090 if (count(array_intersect($acceptedmedia, $media))) {
1091 $this->_parse_sections($match[5]);
1096 //This handles @page to be applied to page oriented media
1097 //Note: This has a reduced syntax:
1098 //@page { margin:1cm; color:blue; }
1099 //Not a sequence of styles like a full.css, but only the properties
1100 //of a single style, which is applied to the very first "root" frame before
1101 //processing other styles of the frame.
1102 //Working properties:
1103 // margin (for margin around edge of paper)
1104 // font-family (default font of pages)
1105 // color (default text color of pages)
1106 //Non working properties:
1110 //Todo:Reason is unknown
1111 //Other properties (like further font or border attributes) not tested.
1112 //If a border or background color around each paper sheet is desired,
1113 //assign it to the <body> tag, possibly only for the css of the correct media type.
1115 // If the page has a name, skip the style.
1116 $page_selector = trim($match[3]);
1119 switch ($page_selector) {
1129 $key = $page_selector;
1135 // Store the style for later...
1136 if (empty($this->_page_styles
[$key])) {
1137 $this->_page_styles
[$key] = $this->_parse_properties($match[5]);
1139 $this->_page_styles
[$key]->merge($this->_parse_properties($match[5]));
1144 $this->_parse_font_face($match[5]);
1148 // ignore everything else
1155 if ($match[7] !== "") {
1156 $this->_parse_sections($match[7]);
1162 /* See also style.cls Style::_image(), refactoring?, works also for imported css files */
1163 protected function _image($val)
1165 $DEBUGCSS = $this->_dompdf
->get_option('debugCss');
1166 $parsed_url = "none";
1168 if (mb_strpos($val, "url") === false) {
1169 $path = "none"; //Don't resolve no image -> otherwise would prefix path and no longer recognize as none
1171 $val = preg_replace("/url\(['\"]?([^'\")]+)['\"]?\)/", "\\1", trim($val));
1173 // Resolve the url now in the context of the current stylesheet
1174 $parsed_url = Helpers
::explode_url($val);
1175 if ($parsed_url["protocol"] == "" && $this->get_protocol() == "") {
1176 if ($parsed_url["path"][0] === '/' ||
$parsed_url["path"][0] === '\\') {
1177 $path = $_SERVER["DOCUMENT_ROOT"] . '/';
1179 $path = $this->get_base_path();
1182 $path .= $parsed_url["path"] . $parsed_url["file"];
1183 $path = realpath($path);
1184 // If realpath returns FALSE then specifically state that there is no background image
1185 // FIXME: Is this causing problems for imported CSS files? There are some './none' references when running the test cases.
1190 $path = Helpers
::build_url($this->get_protocol(),
1192 $this->get_base_path(),
1198 print "<pre>[_image\n";
1199 print_r($parsed_url);
1200 print $this->get_protocol() . "\n" . $this->get_base_path() . "\n" . $path . "\n";
1201 print "_image]</pre>";;
1208 * parse @import{} sections
1210 * @param string $url the url of the imported CSS file
1212 private function _parse_import($url)
1214 $arr = preg_split("/[\s\n,]/", $url, -1, PREG_SPLIT_NO_EMPTY
);
1215 $url = array_shift($arr);
1218 if (count($arr) > 0) {
1219 $acceptedmedia = self
::$ACCEPTED_GENERIC_MEDIA_TYPES;
1220 $acceptedmedia[] = $this->_dompdf
->get_option("default_media_type");
1222 // @import url media_type [media_type...]
1223 foreach ($arr as $type) {
1224 if (in_array(mb_strtolower(trim($type)), $acceptedmedia)) {
1231 // unconditional import
1236 // Store our current base url properties in case the new url is elsewhere
1237 $protocol = $this->_protocol
;
1238 $host = $this->_base_host
;
1239 $path = $this->_base_path
;
1241 // $url = str_replace(array('"',"url", "(", ")"), "", $url);
1242 // If the protocol is php, assume that we will import using file://
1243 // $url = Helpers::build_url($protocol == "php://" ? "file://" : $protocol, $host, $path, $url);
1244 // Above does not work for subfolders and absolute urls.
1245 // Todo: As above, do we need to replace php or file to an empty protocol for local files?
1247 $url = $this->_image($url);
1249 $this->load_css_file($url);
1251 // Restore the current base url
1252 $this->_protocol
= $protocol;
1253 $this->_base_host
= $host;
1254 $this->_base_path
= $path;
1260 * parse @font-face{} sections
1261 * http://www.w3.org/TR/css3-fonts/#the-font-face-rule
1263 * @param string $str CSS @font-face rules
1266 private function _parse_font_face($str)
1268 $descriptors = $this->_parse_properties($str);
1270 preg_match_all("/(url|local)\s*\([\"\']?([^\"\'\)]+)[\"\']?\)\s*(format\s*\([\"\']?([^\"\'\)]+)[\"\']?\))?/i", $descriptors->src
, $src);
1273 $valid_sources = array();
1275 foreach ($src[0] as $i => $value) {
1277 "local" => strtolower($src[1][$i]) === "local",
1278 "uri" => $src[2][$i],
1279 "format" => $src[4][$i],
1280 "path" => Helpers
::build_url($this->_protocol
, $this->_base_host
, $this->_base_path
, $src[2][$i]),
1283 if (!$source["local"] && in_array($source["format"], array("", "truetype"))) {
1284 $valid_sources[] = $source;
1287 $sources[] = $source;
1291 if (empty($valid_sources)) {
1296 "family" => $descriptors->get_font_family_raw(),
1297 "weight" => $descriptors->font_weight
,
1298 "style" => $descriptors->font_style
,
1301 $this->getFontMetrics()->registerFont($style, $valid_sources[0]["path"], $this->_dompdf
->getHttpContext());
1305 * parse regular CSS blocks
1307 * _parse_properties() creates a new Style object based on the provided
1310 * @param string $str CSS rules
1313 private function _parse_properties($str)
1315 $properties = preg_split("/;(?=(?:[^\(]*\([^\)]*\))*(?![^\)]*\)))/", $str);
1317 if ($this->_dompdf
->get_option('debugCss')) print '[_parse_properties';
1320 $style = new Style($this, Stylesheet
::ORIG_AUTHOR
);
1322 foreach ($properties as $prop) {
1323 // If the $prop contains an url, the regex may be wrong
1324 // @todo: fix the regex so that it works everytime
1325 /*if (strpos($prop, "url(") === false) {
1326 if (preg_match("/([a-z-]+)\s*:\s*[^:]+$/i", $prop, $m))
1329 //A css property can have " ! important" appended (whitespace optional)
1330 //strip this off to decode core of the property correctly.
1331 //Pass on in the style to allow proper handling:
1332 //!important properties can only be overridden by other !important ones.
1333 //$style->$prop_name = is a shortcut of $style->__set($prop_name,$value);.
1334 //If no specific set function available, set _props["prop_name"]
1335 //style is always copied completely, or $_props handled separately
1336 //Therefore set a _important_props["prop_name"]=true to indicate the modifier
1338 /* Instead of short code, prefer the typical case with fast code
1339 $important = preg_match("/(.*?)!\s*important/",$prop,$match);
1343 $prop = trim($prop);
1345 if ($this->_dompdf
->get_option('debugCss')) print '(';
1348 $prop = trim($prop);
1350 if (substr($prop, -9) === 'important') {
1351 $prop_tmp = rtrim(substr($prop, 0, -9));
1353 if (substr($prop_tmp, -1) === '!') {
1354 $prop = rtrim(substr($prop_tmp, 0, -1));
1360 if ($this->_dompdf
->get_option('debugCss')) print 'empty)';
1364 $i = mb_strpos($prop, ":");
1366 if ($this->_dompdf
->get_option('debugCss')) print 'novalue' . $prop . ')';
1370 $prop_name = rtrim(mb_strtolower(mb_substr($prop, 0, $i)));
1371 $value = ltrim(mb_substr($prop, $i +
1));
1372 if ($this->_dompdf
->get_option('debugCss')) print $prop_name . ':=' . $value . ($important ?
'!IMPORTANT' : '') . ')';
1373 //New style, anyway empty
1374 //if ($important || !$style->important_get($prop_name) ) {
1375 //$style->$prop_name = array($value,$important);
1376 //assignment might be replaced by overloading through __set,
1377 //and overloaded functions might check _important_props,
1378 //therefore set _important_props first.
1380 $style->important_set($prop_name);
1382 //For easier debugging, don't use overloading of assignments with __set
1383 $style->$prop_name = $value;
1384 //$style->props_set($prop_name, $value);
1386 if ($this->_dompdf
->get_option('debugCss')) print '_parse_properties]';
1392 * parse selector + rulesets
1394 * @param string $str CSS selectors and rulesets
1396 private function _parse_sections($str)
1398 // Pre-process: collapse all whitespace and strip whitespace around '>',
1399 // '.', ':', '+', '#'
1401 $patterns = array("/[\\s\n]+/", "/\\s+([>.:+#])\\s+/");
1402 $replacements = array(" ", "\\1");
1403 $str = preg_replace($patterns, $replacements, $str);
1405 $sections = explode("}", $str);
1406 if ($this->_dompdf
->get_option('debugCss')) print '[_parse_sections';
1407 foreach ($sections as $sect) {
1408 $i = mb_strpos($sect, "{");
1410 $selectors = explode(",", mb_substr($sect, 0, $i));
1411 if ($this->_dompdf
->get_option('debugCss')) print '[section';
1412 $style = $this->_parse_properties(trim(mb_substr($sect, $i +
1)));
1414 // Assign it to the selected elements
1415 foreach ($selectors as $selector) {
1416 $selector = trim($selector);
1418 if ($selector == "") {
1419 if ($this->_dompdf
->get_option('debugCss')) print '#empty#';
1422 if ($this->_dompdf
->get_option('debugCss')) print '#' . $selector . '#';
1423 //if ($this->_dompdf->get_option('debugCss')) { if (strpos($selector,'p') !== false) print '!!!p!!!#'; }
1425 $this->add_style($selector, $style);
1428 if ($this->_dompdf
->get_option('debugCss')) print 'section]';
1431 if ($this->_dompdf
->get_option('debugCss')) print '_parse_sections]';
1434 public static function getDefaultStylesheet()
1436 $dir = realpath(__DIR__
. "/../..");
1437 return $dir . self
::DEFAULT_STYLESHEET
;
1441 * @param FontMetrics $fontMetrics
1444 public function setFontMetrics(FontMetrics
$fontMetrics)
1446 $this->fontMetrics
= $fontMetrics;
1451 * @return FontMetrics
1453 public function getFontMetrics()
1455 return $this->fontMetrics
;
1459 * dumps the entire stylesheet as a string
1461 * Generates a string of each selector and associated style in the
1462 * Stylesheet. Useful for debugging.
1466 function __toString()
1469 foreach ($this->_styles
as $selector => $style) {
1470 $str .= "$selector => " . $style->__toString() . "\n";