Dompdf~20171216-130154.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. <?php
  2. /**
  3. * @package dompdf
  4. * @link http://dompdf.github.com/
  5. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  6. * @author Fabien Ménager <fabien.menager@gmail.com>
  7. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  8. */
  9. namespace Dompdf;
  10. use DOMDocument;
  11. use DOMNode;
  12. use Dompdf\Adapter\CPDF;
  13. use DOMXPath;
  14. use Dompdf\Frame\Factory;
  15. use Dompdf\Frame\FrameTree;
  16. use HTML5_Tokenizer;
  17. use HTML5_TreeBuilder;
  18. use Dompdf\Image\Cache;
  19. use Dompdf\Renderer\ListBullet;
  20. use Dompdf\Css\Stylesheet;
  21. /**
  22. * Dompdf - PHP5 HTML to PDF renderer
  23. *
  24. * Dompdf loads HTML and does its best to render it as a PDF. It gets its
  25. * name from the new DomDocument PHP5 extension. Source HTML is first
  26. * parsed by a DomDocument object. Dompdf takes the resulting DOM tree and
  27. * attaches a {@link Frame} object to each node. {@link Frame} objects store
  28. * positioning and layout information and each has a reference to a {@link
  29. * Style} object.
  30. *
  31. * Style information is loaded and parsed (see {@link Stylesheet}) and is
  32. * applied to the frames in the tree by using XPath. CSS selectors are
  33. * converted into XPath queries, and the computed {@link Style} objects are
  34. * applied to the {@link Frame}s.
  35. *
  36. * {@link Frame}s are then decorated (in the design pattern sense of the
  37. * word) based on their CSS display property ({@link
  38. * http://www.w3.org/TR/CSS21/visuren.html#propdef-display}).
  39. * Frame_Decorators augment the basic {@link Frame} class by adding
  40. * additional properties and methods specific to the particular type of
  41. * {@link Frame}. For example, in the CSS layout model, block frames
  42. * (display: block;) contain line boxes that are usually filled with text or
  43. * other inline frames. The Block therefore adds a $lines
  44. * property as well as methods to add {@link Frame}s to lines and to add
  45. * additional lines. {@link Frame}s also are attached to specific
  46. * AbstractPositioner and {@link AbstractFrameReflower} objects that contain the
  47. * positioining and layout algorithm for a specific type of frame,
  48. * respectively. This is an application of the Strategy pattern.
  49. *
  50. * Layout, or reflow, proceeds recursively (post-order) starting at the root
  51. * of the document. Space constraints (containing block width & height) are
  52. * pushed down, and resolved positions and sizes bubble up. Thus, every
  53. * {@link Frame} in the document tree is traversed once (except for tables
  54. * which use a two-pass layout algorithm). If you are interested in the
  55. * details, see the reflow() method of the Reflower classes.
  56. *
  57. * Rendering is relatively straightforward once layout is complete. {@link
  58. * Frame}s are rendered using an adapted {@link Cpdf} class, originally
  59. * written by Wayne Munro, http://www.ros.co.nz/pdf/. (Some performance
  60. * related changes have been made to the original {@link Cpdf} class, and
  61. * the {@link Dompdf\Adapter\CPDF} class provides a simple, stateless interface to
  62. * PDF generation.) PDFLib support has now also been added, via the {@link
  63. * Dompdf\Adapter\PDFLib}.
  64. *
  65. *
  66. * @package dompdf
  67. */
  68. class Dompdf
  69. {
  70. /**
  71. * Version string for dompdf
  72. *
  73. * @var string
  74. */
  75. private $version = 'dompdf';
  76. /**
  77. * DomDocument representing the HTML document
  78. *
  79. * @var DOMDocument
  80. */
  81. private $dom;
  82. /**
  83. * FrameTree derived from the DOM tree
  84. *
  85. * @var FrameTree
  86. */
  87. private $tree;
  88. /**
  89. * Stylesheet for the document
  90. *
  91. * @var Stylesheet
  92. */
  93. private $css;
  94. /**
  95. * Actual PDF renderer
  96. *
  97. * @var Canvas
  98. */
  99. private $canvas;
  100. /**
  101. * Desired paper size ('letter', 'legal', 'A4', etc.)
  102. *
  103. * @var string
  104. */
  105. private $paperSize;
  106. /**
  107. * Paper orientation ('portrait' or 'landscape')
  108. *
  109. * @var string
  110. */
  111. private $paperOrientation = "portrait";
  112. /**
  113. * Callbacks on new page and new element
  114. *
  115. * @var array
  116. */
  117. private $callbacks = array();
  118. /**
  119. * Experimental caching capability
  120. *
  121. * @var string
  122. */
  123. private $cacheId;
  124. /**
  125. * Base hostname
  126. *
  127. * Used for relative paths/urls
  128. * @var string
  129. */
  130. private $baseHost = "";
  131. /**
  132. * Absolute base path
  133. *
  134. * Used for relative paths/urls
  135. * @var string
  136. */
  137. private $basePath = "";
  138. /**
  139. * Protcol used to request file (file://, http://, etc)
  140. *
  141. * @var string
  142. */
  143. private $protocol;
  144. /**
  145. * HTTP context created with stream_context_create()
  146. * Will be used for file_get_contents
  147. *
  148. * @var resource
  149. */
  150. private $httpContext;
  151. /**
  152. * Timestamp of the script start time
  153. *
  154. * @var int
  155. */
  156. private $startTime = null;
  157. /**
  158. * The system's locale
  159. *
  160. * @var string
  161. */
  162. private $systemLocale = null;
  163. /**
  164. * Tells if the system's locale is the C standard one
  165. *
  166. * @var bool
  167. */
  168. private $localeStandard = false;
  169. /**
  170. * The default view of the PDF in the viewer
  171. *
  172. * @var string
  173. */
  174. private $defaultView = "Fit";
  175. /**
  176. * The default view options of the PDF in the viewer
  177. *
  178. * @var array
  179. */
  180. private $defaultViewOptions = array();
  181. /**
  182. * Tells wether the DOM document is in quirksmode (experimental)
  183. *
  184. * @var bool
  185. */
  186. private $quirksmode = false;
  187. /**
  188. * Protocol whitelist
  189. *
  190. * Protocols and PHP wrappers allowed in URLs. Full support is not
  191. * guarantee for the protocols/wrappers contained in this array.
  192. *
  193. * @var array
  194. */
  195. private $allowedProtocols = array(null, "", "file://", "http://", "https://");
  196. /**
  197. * Local file extension whitelist
  198. *
  199. * File extensions supported by dompdf for local files.
  200. *
  201. * @var array
  202. */
  203. private $allowedLocalFileExtensions = array("htm", "html");
  204. /**
  205. * @var array
  206. */
  207. private $messages = array();
  208. /**
  209. * @var Options
  210. */
  211. private $options;
  212. /**
  213. * @var FontMetrics
  214. */
  215. private $fontMetrics;
  216. /**
  217. * The list of built-in fonts
  218. *
  219. * @var array
  220. * @deprecated
  221. */
  222. public static $native_fonts = array(
  223. "courier", "courier-bold", "courier-oblique", "courier-boldoblique",
  224. "helvetica", "helvetica-bold", "helvetica-oblique", "helvetica-boldoblique",
  225. "times-roman", "times-bold", "times-italic", "times-bolditalic",
  226. "symbol", "zapfdinbats"
  227. );
  228. /**
  229. * The list of built-in fonts
  230. *
  231. * @var array
  232. */
  233. public static $nativeFonts = array(
  234. "courier", "courier-bold", "courier-oblique", "courier-boldoblique",
  235. "helvetica", "helvetica-bold", "helvetica-oblique", "helvetica-boldoblique",
  236. "times-roman", "times-bold", "times-italic", "times-bolditalic",
  237. "symbol", "zapfdinbats"
  238. );
  239. /**
  240. * Class constructor
  241. *
  242. * @param array|Options $options
  243. */
  244. public function __construct($options = null)
  245. {
  246. mb_internal_encoding('UTF-8');
  247. if (isset($options) && $options instanceof Options) {
  248. $this->setOptions($options);
  249. } elseif (is_array($options)) {
  250. $this->setOptions(new Options($options));
  251. } else {
  252. $this->setOptions(new Options());
  253. }
  254. $versionFile = realpath(__DIR__ . '/../VERSION');
  255. if (file_exists($versionFile) && ($version = file_get_contents($versionFile)) !== false && $version !== '$Format:<%h>$') {
  256. $this->version = sprintf('dompdf %s', $version);
  257. }
  258. $this->localeStandard = sprintf('%.1f', 1.0) == '1.0';
  259. $this->saveLocale();
  260. $this->paperSize = $this->options->getDefaultPaperSize();
  261. $this->paperOrientation = $this->options->getDefaultPaperOrientation();
  262. $this->setCanvas(CanvasFactory::get_instance($this, $this->paperSize, $this->paperOrientation));
  263. $this->setFontMetrics(new FontMetrics($this->getCanvas(), $this->getOptions()));
  264. $this->css = new Stylesheet($this);
  265. $this->restoreLocale();
  266. }
  267. /**
  268. * Save the system's locale configuration and
  269. * set the right value for numeric formatting
  270. */
  271. private function saveLocale()
  272. {
  273. if ($this->localeStandard) {
  274. return;
  275. }
  276. $this->systemLocale = setlocale(LC_NUMERIC, "0");
  277. setlocale(LC_NUMERIC, "C");
  278. }
  279. /**
  280. * Restore the system's locale configuration
  281. */
  282. private function restoreLocale()
  283. {
  284. if ($this->localeStandard) {
  285. return;
  286. }
  287. setlocale(LC_NUMERIC, $this->systemLocale);
  288. }
  289. /**
  290. * @param $file
  291. * @deprecated
  292. */
  293. public function load_html_file($file)
  294. {
  295. $this->loadHtmlFile($file);
  296. }
  297. /**
  298. * Loads an HTML file
  299. * Parse errors are stored in the global array _dompdf_warnings.
  300. *
  301. * @param string $file a filename or url to load
  302. *
  303. * @throws Exception
  304. */
  305. public function loadHtmlFile($file)
  306. {
  307. $this->saveLocale();
  308. if (!$this->protocol && !$this->baseHost && !$this->basePath) {
  309. list($this->protocol, $this->baseHost, $this->basePath) = Helpers::explode_url($file);
  310. }
  311. $protocol = strtolower($this->protocol);
  312. if ( !in_array($protocol, $this->allowedProtocols) ) {
  313. throw new Exception("Permission denied on $file. The communication protocol is not supported.");
  314. }
  315. if (!$this->options->isRemoteEnabled() && ($protocol != "" && $protocol !== "file://")) {
  316. throw new Exception("Remote file requested, but remote file download is disabled.");
  317. }
  318. if ($protocol == "" || $protocol === "file://") {
  319. $realfile = realpath($file);
  320. $chroot = realpath($this->options->getChroot());
  321. if ($chroot && strpos($realfile, $chroot) !== 0) {
  322. throw new Exception("Permission denied on $file. The file could not be found under the directory specified by Options::chroot.");
  323. }
  324. $ext = strtolower(pathinfo($realfile, PATHINFO_EXTENSION));
  325. if (!in_array($ext, $this->allowedLocalFileExtensions)) {
  326. throw new Exception("Permission denied on $file.");
  327. }
  328. if (!$realfile) {
  329. throw new Exception("File '$file' not found.");
  330. }
  331. $file = $realfile;
  332. }
  333. list($contents, $http_response_header) = Helpers::getFileContent($file, $this->httpContext);
  334. $encoding = 'UTF-8';
  335. // See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
  336. if (isset($http_response_header)) {
  337. foreach ($http_response_header as $_header) {
  338. if (preg_match("@Content-Type:\s*[\w/]+;\s*?charset=([^\s]+)@i", $_header, $matches)) {
  339. $encoding = strtoupper($matches[1]);
  340. break;
  341. }
  342. }
  343. }
  344. $this->restoreLocale();
  345. $this->loadHtml($contents, $encoding);
  346. }
  347. /**
  348. * @param $str
  349. * @param null $encoding
  350. * @deprecated
  351. */
  352. public function load_html($str, $encoding = 'UTF-8')
  353. {
  354. $this->loadHtml($str, $encoding);
  355. }
  356. /**
  357. * Loads an HTML string
  358. * Parse errors are stored in the global array _dompdf_warnings.
  359. * @todo use the $encoding variable
  360. *
  361. * @param string $str HTML text to load
  362. * @param string $encoding Not used yet
  363. */
  364. public function loadHtml($str, $encoding = 'UTF-8')
  365. {
  366. $this->saveLocale();
  367. // FIXME: Determine character encoding, switch to UTF8, update meta tag. Need better http/file stream encoding detection, currently relies on text or meta tag.
  368. $known_encodings = mb_list_encodings();
  369. mb_detect_order('auto');
  370. if (($file_encoding = mb_detect_encoding($str, null, true)) === false) {
  371. $file_encoding = "auto";
  372. }
  373. if (in_array(strtoupper($file_encoding), array('UTF-8','UTF8')) === false) {
  374. $str = mb_convert_encoding($str, 'UTF-8', $file_encoding);
  375. }
  376. $metatags = array(
  377. '@<meta\s+http-equiv="Content-Type"\s+content="(?:[\w/]+)(?:;\s*?charset=([^\s"]+))?@i',
  378. '@<meta\s+content="(?:[\w/]+)(?:;\s*?charset=([^\s"]+))"?\s+http-equiv="Content-Type"@i',
  379. '@<meta [^>]*charset\s*=\s*["\']?\s*([^"\' ]+)@i',
  380. );
  381. foreach ($metatags as $metatag) {
  382. if (preg_match($metatag, $str, $matches)) {
  383. if (isset($matches[1]) && in_array($matches[1], $known_encodings)) {
  384. $document_encoding = $matches[1];
  385. break;
  386. }
  387. }
  388. }
  389. if (isset($document_encoding) && in_array(strtoupper($document_encoding), array('UTF-8','UTF8')) === false) {
  390. $str = preg_replace('/charset=([^\s"]+)/i', 'charset=UTF-8', $str);
  391. } elseif (isset($document_encoding) === false && strpos($str, '<head>') !== false) {
  392. $str = str_replace('<head>', '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">', $str);
  393. } elseif (isset($document_encoding) === false) {
  394. $str = '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">' . $str;
  395. }
  396. //FIXME: since we're not using this just yet
  397. $encoding = 'UTF-8';
  398. // remove BOM mark from UTF-8, it's treated as document text by DOMDocument
  399. // FIXME: roll this into the encoding detection using UTF-8/16/32 BOM (http://us2.php.net/manual/en/function.mb-detect-encoding.php#91051)?
  400. if (substr($str, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF)) {
  401. $str = substr($str, 3);
  402. }
  403. // Store parsing warnings as messages
  404. set_error_handler(array("\\Dompdf\\Helpers", "record_warnings"));
  405. // @todo Take the quirksmode into account
  406. // http://hsivonen.iki.fi/doctype/
  407. // https://developer.mozilla.org/en/mozilla's_quirks_mode
  408. $quirksmode = false;
  409. if ($this->options->isHtml5ParserEnabled()) {
  410. $tokenizer = new HTML5_Tokenizer($str);
  411. $tokenizer->parse();
  412. $doc = $tokenizer->save();
  413. // Remove #text children nodes in nodes that shouldn't have
  414. $tag_names = array("html", "table", "tbody", "thead", "tfoot", "tr");
  415. foreach ($tag_names as $tag_name) {
  416. $nodes = $doc->getElementsByTagName($tag_name);
  417. foreach ($nodes as $node) {
  418. self::removeTextNodes($node);
  419. }
  420. }
  421. $quirksmode = ($tokenizer->getTree()->getQuirksMode() > HTML5_TreeBuilder::NO_QUIRKS);
  422. } else {
  423. // loadHTML assumes ISO-8859-1 unless otherwise specified on the HTML document header.
  424. // http://devzone.zend.com/1538/php-dom-xml-extension-encoding-processing/ (see #4)
  425. // http://stackoverflow.com/a/11310258/264628
  426. $doc = new DOMDocument("1.0", $encoding);
  427. $doc->preserveWhiteSpace = true;
  428. $doc->loadHTML($str);
  429. $doc->encoding = $encoding;
  430. // If some text is before the doctype, we are in quirksmode
  431. if (preg_match("/^(.+)<!doctype/i", ltrim($str), $matches)) {
  432. $quirksmode = true;
  433. } // If no doctype is provided, we are in quirksmode
  434. elseif (!preg_match("/^<!doctype/i", ltrim($str), $matches)) {
  435. $quirksmode = true;
  436. } else {
  437. // HTML5 <!DOCTYPE html>
  438. if (!$doc->doctype->publicId && !$doc->doctype->systemId) {
  439. $quirksmode = false;
  440. }
  441. // not XHTML
  442. if (!preg_match("/xhtml/i", $doc->doctype->publicId)) {
  443. $quirksmode = true;
  444. }
  445. }
  446. }
  447. $this->dom = $doc;
  448. $this->quirksmode = $quirksmode;
  449. $this->tree = new FrameTree($this->dom);
  450. restore_error_handler();
  451. $this->restoreLocale();
  452. }
  453. /**
  454. * @param DOMNode $node
  455. * @deprecated
  456. */
  457. public static function remove_text_nodes(DOMNode $node)
  458. {
  459. self::removeTextNodes($node);
  460. }
  461. /**
  462. * @param DOMNode $node
  463. */
  464. public static function removeTextNodes(DOMNode $node)
  465. {
  466. $children = array();
  467. for ($i = 0; $i < $node->childNodes->length; $i++) {
  468. $child = $node->childNodes->item($i);
  469. if ($child->nodeName === "#text") {
  470. $children[] = $child;
  471. }
  472. }
  473. foreach ($children as $child) {
  474. $node->removeChild($child);
  475. }
  476. }
  477. /**
  478. * Builds the {@link FrameTree}, loads any CSS and applies the styles to
  479. * the {@link FrameTree}
  480. */
  481. private function processHtml()
  482. {
  483. $this->tree->build_tree();
  484. $this->css->load_css_file(Stylesheet::getDefaultStylesheet(), Stylesheet::ORIG_UA);
  485. $acceptedmedia = Stylesheet::$ACCEPTED_GENERIC_MEDIA_TYPES;
  486. $acceptedmedia[] = $this->options->getDefaultMediaType();
  487. // <base href="" />
  488. $base_nodes = $this->dom->getElementsByTagName("base");
  489. if ($base_nodes->length && ($href = $base_nodes->item(0)->getAttribute("href"))) {
  490. list($this->protocol, $this->baseHost, $this->basePath) = Helpers::explode_url($href);
  491. }
  492. // Set the base path of the Stylesheet to that of the file being processed
  493. $this->css->set_protocol($this->protocol);
  494. $this->css->set_host($this->baseHost);
  495. $this->css->set_base_path($this->basePath);
  496. // Get all the stylesheets so that they are processed in document order
  497. $xpath = new DOMXPath($this->dom);
  498. $stylesheets = $xpath->query("//*[name() = 'link' or name() = 'style']");
  499. /** @var \DOMElement $tag */
  500. foreach ($stylesheets as $tag) {
  501. switch (strtolower($tag->nodeName)) {
  502. // load <link rel="STYLESHEET" ... /> tags
  503. case "link":
  504. if (mb_strtolower(stripos($tag->getAttribute("rel"), "stylesheet") !== false) || // may be "appendix stylesheet"
  505. mb_strtolower($tag->getAttribute("type")) === "text/css"
  506. ) {
  507. //Check if the css file is for an accepted media type
  508. //media not given then always valid
  509. $formedialist = preg_split("/[\s\n,]/", $tag->getAttribute("media"), -1, PREG_SPLIT_NO_EMPTY);
  510. if (count($formedialist) > 0) {
  511. $accept = false;
  512. foreach ($formedialist as $type) {
  513. if (in_array(mb_strtolower(trim($type)), $acceptedmedia)) {
  514. $accept = true;
  515. break;
  516. }
  517. }
  518. if (!$accept) {
  519. //found at least one mediatype, but none of the accepted ones
  520. //Skip this css file.
  521. continue;
  522. }
  523. }
  524. $url = $tag->getAttribute("href");
  525. $url = Helpers::build_url($this->protocol, $this->baseHost, $this->basePath, $url);
  526. $this->css->load_css_file($url, Stylesheet::ORIG_AUTHOR);
  527. }
  528. break;
  529. // load <style> tags
  530. case "style":
  531. // Accept all <style> tags by default (note this is contrary to W3C
  532. // HTML 4.0 spec:
  533. // http://www.w3.org/TR/REC-html40/present/styles.html#adef-media
  534. // which states that the default media type is 'screen'
  535. if ($tag->hasAttributes() &&
  536. ($media = $tag->getAttribute("media")) &&
  537. !in_array($media, $acceptedmedia)
  538. ) {
  539. continue;
  540. }
  541. $css = "";
  542. if ($tag->hasChildNodes()) {
  543. $child = $tag->firstChild;
  544. while ($child) {
  545. $css .= $child->nodeValue; // Handle <style><!-- blah --></style>
  546. $child = $child->nextSibling;
  547. }
  548. } else {
  549. $css = $tag->nodeValue;
  550. }
  551. $this->css->load_css($css, Stylesheet::ORIG_AUTHOR);
  552. break;
  553. }
  554. }
  555. }
  556. /**
  557. * @param string $cacheId
  558. * @deprecated
  559. */
  560. public function enable_caching($cacheId)
  561. {
  562. $this->enableCaching($cacheId);
  563. }
  564. /**
  565. * Enable experimental caching capability
  566. *
  567. * @param string $cacheId
  568. */
  569. public function enableCaching($cacheId)
  570. {
  571. $this->cacheId = $cacheId;
  572. }
  573. /**
  574. * @param string $value
  575. * @return bool
  576. * @deprecated
  577. */
  578. public function parse_default_view($value)
  579. {
  580. return $this->parseDefaultView($value);
  581. }
  582. /**
  583. * @param string $value
  584. * @return bool
  585. */
  586. public function parseDefaultView($value)
  587. {
  588. $valid = array("XYZ", "Fit", "FitH", "FitV", "FitR", "FitB", "FitBH", "FitBV");
  589. $options = preg_split("/\s*,\s*/", trim($value));
  590. $defaultView = array_shift($options);
  591. if (!in_array($defaultView, $valid)) {
  592. return false;
  593. }
  594. $this->setDefaultView($defaultView, $options);
  595. return true;
  596. }
  597. /**
  598. * Renders the HTML to PDF
  599. */
  600. public function render()
  601. {
  602. $this->saveLocale();
  603. $options = $this->options;
  604. $logOutputFile = $options->getLogOutputFile();
  605. if ($logOutputFile) {
  606. if (!file_exists($logOutputFile) && is_writable(dirname($logOutputFile))) {
  607. touch($logOutputFile);
  608. }
  609. $this->startTime = microtime(true);
  610. if (is_writable($logOutputFile)) {
  611. ob_start();
  612. }
  613. }
  614. $this->processHtml();
  615. $this->css->apply_styles($this->tree);
  616. // @page style rules : size, margins
  617. $pageStyles = $this->css->get_page_styles();
  618. $basePageStyle = $pageStyles["base"];
  619. unset($pageStyles["base"]);
  620. foreach ($pageStyles as $pageStyle) {
  621. $pageStyle->inherit($basePageStyle);
  622. }
  623. $defaultOptionPaperSize = $this->getPaperSize($options->getDefaultPaperSize());
  624. // If there is a CSS defined paper size compare to the paper size used to create the canvas to determine a
  625. // recreation need
  626. if (is_array($basePageStyle->size)) {
  627. $basePageStyleSize = $basePageStyle->size;
  628. $this->setPaper(array(0, 0, $basePageStyleSize[0], $basePageStyleSize[1]));
  629. }
  630. $paperSize = $this->getPaperSize();
  631. if (
  632. $defaultOptionPaperSize[2] !== $paperSize[2] ||
  633. $defaultOptionPaperSize[3] !== $paperSize[3] ||
  634. $options->getDefaultPaperOrientation() !== $this->paperOrientation
  635. ) {
  636. $this->setCanvas(CanvasFactory::get_instance($this, $this->paperSize, $this->paperOrientation));
  637. $this->fontMetrics->setCanvas($this->getCanvas());
  638. }
  639. $canvas = $this->getCanvas();
  640. if ($options->isFontSubsettingEnabled() && $canvas instanceof CPDF) {
  641. foreach ($this->tree->get_frames() as $frame) {
  642. $style = $frame->get_style();
  643. $node = $frame->get_node();
  644. // Handle text nodes
  645. if ($node->nodeName === "#text") {
  646. $chars = mb_strtoupper($node->nodeValue) . mb_strtolower($node->nodeValue);
  647. $canvas->register_string_subset($style->font_family, $chars);
  648. continue;
  649. }
  650. // Handle generated content (list items)
  651. if ($style->display === "list-item") {
  652. $chars = ListBullet::get_counter_chars($style->list_style_type);
  653. $canvas->register_string_subset($style->font_family, $chars);
  654. continue;
  655. }
  656. // Handle other generated content (pseudo elements)
  657. // FIXME: This only captures the text of the stylesheet declaration,
  658. // not the actual generated content, and forces all possible counter
  659. // values. See notes in issue #750.
  660. if ($frame->get_node()->nodeName == "dompdf_generated") {
  661. // all possible counter values, just in case
  662. $chars = ListBullet::get_counter_chars('decimal');
  663. $canvas->register_string_subset($style->font_family, $chars);
  664. $chars = ListBullet::get_counter_chars('upper-alpha');
  665. $canvas->register_string_subset($style->font_family, $chars);
  666. $chars = ListBullet::get_counter_chars('lower-alpha');
  667. $canvas->register_string_subset($style->font_family, $chars);
  668. $chars = ListBullet::get_counter_chars('lower-greek');
  669. $canvas->register_string_subset($style->font_family, $chars);
  670. // the hex-decoded text of the content property, duplicated from AbstrctFrameReflower::_parse_string
  671. $decoded_string = preg_replace_callback("/\\\\([0-9a-fA-F]{0,6})/",
  672. function ($matches) { return \Dompdf\Helpers::unichr(hexdec($matches[1])); },
  673. $style->content);
  674. $chars = mb_strtoupper($style->content) . mb_strtolower($style->content) . mb_strtoupper($decoded_string) . mb_strtolower($decoded_string);
  675. $canvas->register_string_subset($style->font_family, $chars);
  676. continue;
  677. }
  678. }
  679. }
  680. $root = null;
  681. foreach ($this->tree->get_frames() as $frame) {
  682. // Set up the root frame
  683. if (is_null($root)) {
  684. $root = Factory::decorate_root($this->tree->get_root(), $this);
  685. continue;
  686. }
  687. // Create the appropriate decorators, reflowers & positioners.
  688. Factory::decorate_frame($frame, $this, $root);
  689. }
  690. // Add meta information
  691. $title = $this->dom->getElementsByTagName("title");
  692. if ($title->length) {
  693. $canvas->add_info("Title", trim($title->item(0)->nodeValue));
  694. }
  695. $metas = $this->dom->getElementsByTagName("meta");
  696. $labels = array(
  697. "author" => "Author",
  698. "keywords" => "Keywords",
  699. "description" => "Subject",
  700. );
  701. /** @var \DOMElement $meta */
  702. foreach ($metas as $meta) {
  703. $name = mb_strtolower($meta->getAttribute("name"));
  704. $value = trim($meta->getAttribute("content"));
  705. if (isset($labels[$name])) {
  706. $canvas->add_info($labels[$name], $value);
  707. continue;
  708. }
  709. if ($name === "dompdf.view" && $this->parseDefaultView($value)) {
  710. $canvas->set_default_view($this->defaultView, $this->defaultViewOptions);
  711. }
  712. }
  713. $root->set_containing_block(0, 0,$canvas->get_width(), $canvas->get_height());
  714. $root->set_renderer(new Renderer($this));
  715. // This is where the magic happens:
  716. $root->reflow();
  717. // Clean up cached images
  718. Cache::clear();
  719. global $_dompdf_warnings, $_dompdf_show_warnings;
  720. if ($_dompdf_show_warnings && isset($_dompdf_warnings)) {
  721. echo '<b>Dompdf Warnings</b><br><pre>';
  722. foreach ($_dompdf_warnings as $msg) {
  723. echo $msg . "\n";
  724. }
  725. if ($canvas instanceof CPDF) {
  726. echo $canvas->get_cpdf()->messages;
  727. }
  728. echo '</pre>';
  729. flush();
  730. }
  731. if ($logOutputFile && is_writable($logOutputFile)) {
  732. $this->write_log();
  733. ob_end_clean();
  734. }
  735. $this->restoreLocale();
  736. }
  737. /**
  738. * Add meta information to the PDF after rendering
  739. */
  740. public function add_info($label, $value)
  741. {
  742. $canvas = $this->getCanvas();
  743. if (!is_null($canvas)) {
  744. $canvas->add_info($label, $value);
  745. }
  746. }
  747. /**
  748. * Writes the output buffer in the log file
  749. *
  750. * @return void
  751. */
  752. private function write_log()
  753. {
  754. $log_output_file = $this->getOptions()->getLogOutputFile();
  755. if (!$log_output_file || !is_writable($log_output_file)) {
  756. return;
  757. }
  758. $frames = Frame::$ID_COUNTER;
  759. $memory = memory_get_peak_usage(true) / 1024;
  760. $time = (microtime(true) - $this->startTime) * 1000;
  761. $out = sprintf(
  762. "<span style='color: #000' title='Frames'>%6d</span>" .
  763. "<span style='color: #009' title='Memory'>%10.2f KB</span>" .
  764. "<span style='color: #900' title='Time'>%10.2f ms</span>" .
  765. "<span title='Quirksmode'> " .
  766. ($this->quirksmode ? "<span style='color: #d00'> ON</span>" : "<span style='color: #0d0'>OFF</span>") .
  767. "</span><br />", $frames, $memory, $time);
  768. $out .= ob_get_contents();
  769. ob_clean();
  770. file_put_contents($log_output_file, $out);
  771. }
  772. /**
  773. * Streams the PDF to the client
  774. *
  775. * The file will open a download dialog by default. The options
  776. * parameter controls the output. Accepted options (array keys) are:
  777. *
  778. * 'Accept-Ranges' => 1 or 0 (=default): Send an 'Accept-Ranges:'
  779. * HTTP header, see https://tools.ietf.org/html/rfc2616#section-14.5
  780. * This header seems to have caused some problems, despite the fact
  781. * that it is supposed to solve them, so I am leaving it off by default.
  782. *
  783. * 'compress' = > 1 (=default) or 0:
  784. * Apply content stream compression
  785. *
  786. * 'Attachment' => 1 (=default) or 0:
  787. * Set the 'Content-Disposition:' HTTP header to 'attachment'
  788. * (thereby causing the browser to open a download dialog)
  789. *
  790. * @param string $filename the name of the streamed file
  791. * @param array $options header options (see above)
  792. */
  793. public function stream($filename = 'document.pdf', $options = null)
  794. {
  795. $this->saveLocale();
  796. $canvas = $this->getCanvas();
  797. if (!is_null($canvas)) {
  798. $canvas->stream($filename, $options);
  799. }
  800. $this->restoreLocale();
  801. }
  802. /**
  803. * Returns the PDF as a string
  804. *
  805. * The file will open a download dialog by default. The options
  806. * parameter controls the output. Accepted options are:
  807. *
  808. *
  809. * 'compress' = > 1 or 0 - apply content stream compression, this is
  810. * on (1) by default
  811. *
  812. *
  813. * @param array $options options (see above)
  814. *
  815. * @return string
  816. */
  817. public function output($options = null)
  818. {
  819. $this->saveLocale();
  820. $canvas = $this->getCanvas();
  821. if (is_null($canvas)) {
  822. return null;
  823. }
  824. $output = $canvas->output($options);
  825. $this->restoreLocale();
  826. return $output;
  827. }
  828. /**
  829. * @return string
  830. * @deprecated
  831. */
  832. public function output_html()
  833. {
  834. return $this->outputHtml();
  835. }
  836. /**
  837. * Returns the underlying HTML document as a string
  838. *
  839. * @return string
  840. */
  841. public function outputHtml()
  842. {
  843. return $this->dom->saveHTML();
  844. }
  845. /**
  846. * Get the dompdf option value
  847. *
  848. * @param string $key
  849. * @return mixed
  850. * @deprecated
  851. */
  852. public function get_option($key)
  853. {
  854. return $this->options->get($key);
  855. }
  856. /**
  857. * @param string $key
  858. * @param mixed $value
  859. * @return $this
  860. * @deprecated
  861. */
  862. public function set_option($key, $value)
  863. {
  864. $this->options->set($key, $value);
  865. return $this;
  866. }
  867. /**
  868. * @param array $options
  869. * @return $this
  870. * @deprecated
  871. */
  872. public function set_options(array $options)
  873. {
  874. $this->options->set($options);
  875. return $this;
  876. }
  877. /**
  878. * @param string $size
  879. * @param string $orientation
  880. * @deprecated
  881. */
  882. public function set_paper($size, $orientation = "portrait")
  883. {
  884. $this->setPaper($size, $orientation);
  885. }
  886. /**
  887. * Sets the paper size & orientation
  888. *
  889. * @param string $size 'letter', 'legal', 'A4', etc. {@link Dompdf\Adapter\CPDF::$PAPER_SIZES}
  890. * @param string $orientation 'portrait' or 'landscape'
  891. * @return $this
  892. */
  893. public function setPaper($size, $orientation = "portrait")
  894. {
  895. $this->paperSize = $size;
  896. $this->paperOrientation = $orientation;
  897. return $this;
  898. }
  899. /**
  900. * Gets the paper size
  901. *
  902. * @param null|string|array $paperSize
  903. * @return \int[] A four-element integer array
  904. */
  905. public function getPaperSize($paperSize = null)
  906. {
  907. $size = $paperSize !== null ? $paperSize : $this->paperSize;
  908. if (is_array($size)) {
  909. return $size;
  910. } else if (isset(Adapter\CPDF::$PAPER_SIZES[mb_strtolower($size)])) {
  911. return Adapter\CPDF::$PAPER_SIZES[mb_strtolower($size)];
  912. } else {
  913. return Adapter\CPDF::$PAPER_SIZES["letter"];
  914. }
  915. }
  916. /**
  917. * Gets the paper orientation
  918. *
  919. * @return string Either "portrait" or "landscape"
  920. */
  921. public function getPaperOrientation()
  922. {
  923. return $this->paperOrientation;
  924. }
  925. /**
  926. * @param FrameTree $tree
  927. * @return $this
  928. */
  929. public function setTree(FrameTree $tree)
  930. {
  931. $this->tree = $tree;
  932. return $this;
  933. }
  934. /**
  935. * @return FrameTree
  936. * @deprecated
  937. */
  938. public function get_tree()
  939. {
  940. return $this->getTree();
  941. }
  942. /**
  943. * Returns the underlying {@link FrameTree} object
  944. *
  945. * @return FrameTree
  946. */
  947. public function getTree()
  948. {
  949. return $this->tree;
  950. }
  951. /**
  952. * @param string $protocol
  953. * @return $this
  954. * @deprecated
  955. */
  956. public function set_protocol($protocol)
  957. {
  958. return $this->setProtocol($protocol);
  959. }
  960. /**
  961. * Sets the protocol to use
  962. * FIXME validate these
  963. *
  964. * @param string $protocol
  965. * @return $this
  966. */
  967. public function setProtocol($protocol)
  968. {
  969. $this->protocol = $protocol;
  970. return $this;
  971. }
  972. /**
  973. * @return string
  974. * @deprecated
  975. */
  976. public function get_protocol()
  977. {
  978. return $this->getProtocol();
  979. }
  980. /**
  981. * Returns the protocol in use
  982. *
  983. * @return string
  984. */
  985. public function getProtocol()
  986. {
  987. return $this->protocol;
  988. }
  989. /**
  990. * @param string $host
  991. * @deprecated
  992. */
  993. public function set_host($host)
  994. {
  995. $this->setBaseHost($host);
  996. }
  997. /**
  998. * Sets the base hostname
  999. *
  1000. * @param string $baseHost
  1001. * @return $this
  1002. */
  1003. public function setBaseHost($baseHost)
  1004. {
  1005. $this->baseHost = $baseHost;
  1006. return $this;
  1007. }
  1008. /**
  1009. * @return string
  1010. * @deprecated
  1011. */
  1012. public function get_host()
  1013. {
  1014. return $this->getBaseHost();
  1015. }
  1016. /**
  1017. * Returns the base hostname
  1018. *
  1019. * @return string
  1020. */
  1021. public function getBaseHost()
  1022. {
  1023. return $this->baseHost;
  1024. }
  1025. /**
  1026. * Sets the base path
  1027. *
  1028. * @param string $path
  1029. * @deprecated
  1030. */
  1031. public function set_base_path($path)
  1032. {
  1033. $this->setBasePath($path);
  1034. }
  1035. /**
  1036. * Sets the base path
  1037. *
  1038. * @param string $basePath
  1039. * @return $this
  1040. */
  1041. public function setBasePath($basePath)
  1042. {
  1043. $this->basePath = $basePath;
  1044. return $this;
  1045. }
  1046. /**
  1047. * @return string
  1048. * @deprecated
  1049. */
  1050. public function get_base_path()
  1051. {
  1052. return $this->getBasePath();
  1053. }
  1054. /**
  1055. * Returns the base path
  1056. *
  1057. * @return string
  1058. */
  1059. public function getBasePath()
  1060. {
  1061. return $this->basePath;
  1062. }
  1063. /**
  1064. * @param string $default_view The default document view
  1065. * @param array $options The view's options
  1066. * @return $this
  1067. * @deprecated
  1068. */
  1069. public function set_default_view($default_view, $options)
  1070. {
  1071. return $this->setDefaultView($default_view, $options);
  1072. }
  1073. /**
  1074. * Sets the default view
  1075. *
  1076. * @param string $defaultView The default document view
  1077. * @param array $options The view's options
  1078. * @return $this
  1079. */
  1080. public function setDefaultView($defaultView, $options)
  1081. {
  1082. $this->defaultView = $defaultView;
  1083. $this->defaultViewOptions = $options;
  1084. return $this;
  1085. }
  1086. /**
  1087. * @param resource $http_context
  1088. * @return $this
  1089. * @deprecated
  1090. */
  1091. public function set_http_context($http_context)
  1092. {
  1093. return $this->setHttpContext($http_context);
  1094. }
  1095. /**
  1096. * Sets the HTTP context
  1097. *
  1098. * @param resource $httpContext
  1099. * @return $this
  1100. */
  1101. public function setHttpContext($httpContext)
  1102. {
  1103. $this->httpContext = $httpContext;
  1104. return $this;
  1105. }
  1106. /**
  1107. * @return resource
  1108. * @deprecated
  1109. */
  1110. public function get_http_context()
  1111. {
  1112. return $this->getHttpContext();
  1113. }
  1114. /**
  1115. * Returns the HTTP context
  1116. *
  1117. * @return resource
  1118. */
  1119. public function getHttpContext()
  1120. {
  1121. return $this->httpContext;
  1122. }
  1123. /**
  1124. * @param Canvas $canvas
  1125. * @return $this
  1126. */
  1127. public function setCanvas(Canvas $canvas)
  1128. {
  1129. $this->canvas = $canvas;
  1130. return $this;
  1131. }
  1132. /**
  1133. * @return Canvas
  1134. * @deprecated
  1135. */
  1136. public function get_canvas()
  1137. {
  1138. return $this->getCanvas();
  1139. }
  1140. /**
  1141. * Return the underlying Canvas instance (e.g. Dompdf\Adapter\CPDF, Dompdf\Adapter\GD)
  1142. *
  1143. * @return Canvas
  1144. */
  1145. public function getCanvas()
  1146. {
  1147. return $this->canvas;
  1148. }
  1149. /**
  1150. * @param Stylesheet $css
  1151. * @return $this
  1152. */
  1153. public function setCss(Stylesheet $css)
  1154. {
  1155. $this->css = $css;
  1156. return $this;
  1157. }
  1158. /**
  1159. * @return Stylesheet
  1160. * @deprecated
  1161. */
  1162. public function get_css()
  1163. {
  1164. return $this->getCss();
  1165. }
  1166. /**
  1167. * Returns the stylesheet
  1168. *
  1169. * @return Stylesheet
  1170. */
  1171. public function getCss()
  1172. {
  1173. return $this->css;
  1174. }
  1175. /**
  1176. * @param DOMDocument $dom
  1177. * @return $this
  1178. */
  1179. public function setDom(DOMDocument $dom)
  1180. {
  1181. $this->dom = $dom;
  1182. return $this;
  1183. }
  1184. /**
  1185. * @return DOMDocument
  1186. * @deprecated
  1187. */
  1188. public function get_dom()
  1189. {
  1190. return $this->getDom();
  1191. }
  1192. /**
  1193. * @return DOMDocument
  1194. */
  1195. public function getDom()
  1196. {
  1197. return $this->dom;
  1198. }
  1199. /**
  1200. * @param Options $options
  1201. * @return $this
  1202. */
  1203. public function setOptions(Options $options)
  1204. {
  1205. $this->options = $options;
  1206. $fontMetrics = $this->getFontMetrics();
  1207. if (isset($fontMetrics)) {
  1208. $fontMetrics->setOptions($options);
  1209. }
  1210. return $this;
  1211. }
  1212. /**
  1213. * @return Options
  1214. */
  1215. public function getOptions()
  1216. {
  1217. return $this->options;
  1218. }
  1219. /**
  1220. * @return array
  1221. * @deprecated
  1222. */
  1223. public function get_callbacks()
  1224. {
  1225. return $this->getCallbacks();
  1226. }
  1227. /**
  1228. * Returns the callbacks array
  1229. *
  1230. * @return array
  1231. */
  1232. public function getCallbacks()
  1233. {
  1234. return $this->callbacks;
  1235. }
  1236. /**
  1237. * @param array $callbacks the set of callbacks to set
  1238. * @deprecated
  1239. */
  1240. public function set_callbacks($callbacks)
  1241. {
  1242. $this->setCallbacks($callbacks);
  1243. }
  1244. /**
  1245. * Sets callbacks for events like rendering of pages and elements.
  1246. * The callbacks array contains arrays with 'event' set to 'begin_page',
  1247. * 'end_page', 'begin_frame', or 'end_frame' and 'f' set to a function or
  1248. * object plus method to be called.
  1249. *
  1250. * The function 'f' must take an array as argument, which contains info
  1251. * about the event.
  1252. *
  1253. * @param array $callbacks the set of callbacks to set
  1254. */
  1255. public function setCallbacks($callbacks)
  1256. {
  1257. if (is_array($callbacks)) {
  1258. $this->callbacks = array();
  1259. foreach ($callbacks as $c) {
  1260. if (is_array($c) && isset($c['event']) && isset($c['f'])) {
  1261. $event = $c['event'];
  1262. $f = $c['f'];
  1263. if (is_callable($f) && is_string($event)) {
  1264. $this->callbacks[$event][] = $f;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. }
  1270. /**
  1271. * @return boolean
  1272. * @deprecated
  1273. */
  1274. public function get_quirksmode()
  1275. {
  1276. return $this->getQuirksmode();
  1277. }
  1278. /**
  1279. * Get the quirks mode
  1280. *
  1281. * @return boolean true if quirks mode is active
  1282. */
  1283. public function getQuirksmode()
  1284. {
  1285. return $this->quirksmode;
  1286. }
  1287. /**
  1288. * @param FontMetrics $fontMetrics
  1289. * @return $this
  1290. */
  1291. public function setFontMetrics(FontMetrics $fontMetrics)
  1292. {
  1293. $this->fontMetrics = $fontMetrics;
  1294. return $this;
  1295. }
  1296. /**
  1297. * @return FontMetrics
  1298. */
  1299. public function getFontMetrics()
  1300. {
  1301. return $this->fontMetrics;
  1302. }
  1303. /**
  1304. * PHP5 overloaded getter
  1305. * Along with {@link Dompdf::__set()} __get() provides access to all
  1306. * properties directly. Typically __get() is not called directly outside
  1307. * of this class.
  1308. *
  1309. * @param string $prop
  1310. *
  1311. * @throws Exception
  1312. * @return mixed
  1313. */
  1314. function __get($prop)
  1315. {
  1316. switch ($prop)
  1317. {
  1318. case 'version' :
  1319. return $this->version;
  1320. default:
  1321. throw new Exception( 'Invalid property: ' . $prop );
  1322. }
  1323. }
  1324. }