1<?php 2/** 3 * dw2Pdf Plugin: Conversion from dokuwiki content to pdf. 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Luigi Micco <l.micco@tiscali.it> 7 * @author Andreas Gohr <andi@splitbrain.org> 8 */ 9 10/** 11 * Class action_plugin_dw2pdf 12 * 13 * Export html content to pdf, for different url parameter configurations 14 * DokuPDF which extends mPDF is used for generating the pdf from html. 15 */ 16 17use dokuwiki\Cache\Cache; 18use dokuwiki\plugin\dw2pdf\MenuItem; 19use dokuwiki\StyleUtils; 20use Mpdf\MpdfException; 21 22class action_plugin_dw2pdf extends DokuWiki_Action_Plugin 23{ 24 /** 25 * Settings for current export, collected from url param, plugin config, global config 26 * 27 * @var array 28 */ 29 protected $exportConfig = null; 30 /** @var string template name, to use templates from dw2pdf/tpl/<template name> */ 31 protected $tpl; 32 /** @var string title of exported pdf */ 33 protected $title; 34 /** @var array list of pages included in exported pdf */ 35 protected $list = []; 36 /** @var bool|string path to temporary cachefile */ 37 protected $onetimefile = false; 38 protected $currentBookChapter = 0; 39 40 /** 41 * Constructor. Sets the correct template 42 */ 43 public function __construct() 44 { 45 $this->tpl = $this->getExportConfig('template'); 46 } 47 48 /** 49 * Delete cached files that were for one-time use 50 */ 51 public function __destruct() 52 { 53 if ($this->onetimefile) { 54 unlink($this->onetimefile); 55 } 56 } 57 58 /** 59 * Return the value of currentBookChapter, which is the order of the file to be added in a book generation 60 */ 61 public function getCurrentBookChapter() 62 { 63 return $this->currentBookChapter; 64 } 65 66 /** 67 * Register the events 68 * 69 * @param Doku_Event_Handler $controller 70 */ 71 public function register(Doku_Event_Handler $controller) 72 { 73 $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert'); 74 $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton'); 75 $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton'); 76 } 77 78 /** 79 * Do the HTML to PDF conversion work 80 * 81 * @param Doku_Event $event 82 */ 83 public function convert(Doku_Event $event) 84 { 85 global $REV, $DATE_AT; 86 global $conf, $INPUT; 87 88 // our event? 89 $allowedEvents = ['export_pdfbook', 'export_pdf', 'export_pdfns']; 90 if (!in_array($event->data, $allowedEvents)) return; 91 92 try { 93 //collect pages and check permissions 94 list($this->title, $this->list) = $this->collectExportablePages($event); 95 96 if ($event->data === 'export_pdf' && ($REV || $DATE_AT)) { 97 $cachefile = tempnam($conf['tmpdir'] . '/dwpdf', 'dw2pdf_'); 98 $this->onetimefile = $cachefile; 99 $generateNewPdf = true; 100 } else { 101 // prepare cache and its dependencies 102 $depends = []; 103 $cache = $this->prepareCache($depends); 104 $cachefile = $cache->cache; 105 $generateNewPdf = !$this->getConf('usecache') 106 || $this->getExportConfig('isDebug') 107 || !$cache->useCache($depends); 108 } 109 110 // hard work only when no cache available or needed for debugging 111 if ($generateNewPdf) { 112 // generating the pdf may take a long time for larger wikis / namespaces with many pages 113 set_time_limit(0); 114 //may throw Mpdf\MpdfException as well 115 $this->generatePDF($cachefile, $event); 116 } 117 } catch (Exception $e) { 118 if ($INPUT->has('selection')) { 119 http_status(400); 120 print $e->getMessage(); 121 exit(); 122 } else { 123 //prevent Action/Export() 124 msg($e->getMessage(), -1); 125 $event->data = 'redirect'; 126 return; 127 } 128 } 129 $event->preventDefault(); // after prevent, $event->data cannot be changed 130 131 // deliver the file 132 $this->sendPDFFile($cachefile); //exits 133 } 134 135 /** 136 * Obtain list of pages and title, for different methods of exporting the pdf. 137 * - Return a title and selection, throw otherwise an exception 138 * - Check permisions 139 * 140 * @param Doku_Event $event 141 * @return array 142 * @throws Exception 143 */ 144 protected function collectExportablePages(Doku_Event $event) 145 { 146 global $ID, $REV; 147 global $INPUT; 148 global $conf, $lang; 149 150 // list of one or multiple pages 151 $list = []; 152 153 if ($event->data == 'export_pdf') { 154 if (auth_quickaclcheck($ID) < AUTH_READ) { // set more specific denied message 155 throw new Exception($lang['accessdenied']); 156 } 157 $list[0] = $ID; 158 $title = $INPUT->str('pdftitle'); //DEPRECATED 159 $title = $INPUT->str('book_title', $title, true); 160 if (empty($title)) { 161 $title = p_get_first_heading($ID); 162 } 163 // use page name if title is still empty 164 if (empty($title)) { 165 $title = noNS($ID); 166 } 167 168 $filename = wikiFN($ID, $REV); 169 if (!file_exists($filename)) { 170 throw new Exception($this->getLang('notexist')); 171 } 172 173 } elseif ($event->data == 'export_pdfns') { 174 //check input for title and ns 175 if (!$title = $INPUT->str('book_title')) { 176 throw new Exception($this->getLang('needtitle')); 177 } 178 $pdfnamespace = cleanID($INPUT->str('book_ns')); 179 if (!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) { 180 throw new Exception($this->getLang('needns')); 181 } 182 183 //sort order 184 $order = $INPUT->str('book_order', 'natural', true); 185 $sortoptions = ['pagename', 'date', 'natural']; 186 if (!in_array($order, $sortoptions)) { 187 $order = 'natural'; 188 } 189 190 //search depth 191 $depth = $INPUT->int('book_nsdepth', 0); 192 if ($depth < 0) { 193 $depth = 0; 194 } 195 196 //page search 197 $result = []; 198 $opts = ['depth' => $depth]; //recursive all levels 199 $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace)); 200 search($result, $conf['datadir'], 'search_allpages', $opts, $dir); 201 202 // exclude ids 203 $excludes = $INPUT->arr('excludes'); 204 if (!empty($excludes)) { 205 $result = array_filter($result, function ($item) use ($excludes) { 206 return !in_array($item['id'], $excludes); 207 }); 208 } 209 // exclude namespaces 210 $excludesns = $INPUT->arr('excludesns'); 211 if (!empty($excludesns)) { 212 $result = array_filter($result, function ($item) use ($excludesns) { 213 foreach ($excludesns as $ns) { 214 if (strpos($item['id'], $ns . ':') === 0) return false; 215 } 216 return true; 217 }); 218 } 219 220 //sorting 221 if (count($result) > 0) { 222 if ($order == 'date') { 223 usort($result, [$this, '_datesort']); 224 } elseif ($order == 'pagename' || $order == 'natural') { 225 usort($result, [$this, '_pagenamesort']); 226 } 227 } 228 229 foreach ($result as $item) { 230 $list[] = $item['id']; 231 } 232 233 if ($pdfnamespace !== '') { 234 if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) { 235 if (file_exists(wikiFN(rtrim($pdfnamespace, ':')))) { 236 array_unshift($list, rtrim($pdfnamespace, ':')); 237 } 238 } 239 } 240 241 } elseif (!empty($_COOKIE['list-pagelist'])) { 242 /** @deprecated April 2016 replaced by localStorage version of Bookcreator */ 243 //is in Bookmanager of bookcreator plugin a title given? 244 $title = $INPUT->str('pdfbook_title'); //DEPRECATED 245 $title = $INPUT->str('book_title', $title, true); 246 if (empty($title)) { 247 throw new Exception($this->getLang('needtitle')); 248 } 249 250 $list = explode("|", $_COOKIE['list-pagelist']); 251 252 } elseif ($INPUT->has('selection')) { 253 //handle Bookcreator requests based at localStorage 254// if(!checkSecurityToken()) { 255// http_status(403); 256// print $this->getLang('empty'); 257// exit(); 258// } 259 260 $list = json_decode($INPUT->str('selection', '', true), true); 261 if (!is_array($list) || empty($list)) { 262 throw new Exception($this->getLang('empty')); 263 } 264 265 $title = $INPUT->str('pdfbook_title'); //DEPRECATED 266 $title = $INPUT->str('book_title', $title, true); 267 if (empty($title)) { 268 throw new Exception($this->getLang('needtitle')); 269 } 270 271 } elseif ($INPUT->has('savedselection')) { 272 //export a saved selection of the Bookcreator Plugin 273 if (plugin_isdisabled('bookcreator')) { 274 throw new Exception($this->getLang('missingbookcreator')); 275 } 276 /** @var action_plugin_bookcreator_handleselection $SelectionHandling */ 277 $SelectionHandling = plugin_load('action', 'bookcreator_handleselection'); 278 $savedselection = $SelectionHandling->loadSavedSelection($INPUT->str('savedselection')); 279 $title = $savedselection['title']; 280 $title = $INPUT->str('book_title', $title, true); 281 $list = $savedselection['selection']; 282 283 if (empty($title)) { 284 throw new Exception($this->getLang('needtitle')); 285 } 286 287 } else { 288 //show empty bookcreator message 289 throw new Exception($this->getLang('empty')); 290 } 291 292 $list = array_map('cleanID', $list); 293 294 $skippedpages = []; 295 foreach ($list as $index => $pageid) { 296 if (auth_quickaclcheck($pageid) < AUTH_READ) { 297 $skippedpages[] = $pageid; 298 unset($list[$index]); 299 } 300 } 301 $list = array_filter($list, 'strlen'); //use of strlen() callback prevents removal of pagename '0' 302 303 //if selection contains forbidden pages throw (overridable) warning 304 if (!$INPUT->bool('book_skipforbiddenpages') && !empty($skippedpages)) { 305 $msg = hsc(join(', ', $skippedpages)); 306 throw new Exception(sprintf($this->getLang('forbidden'), $msg)); 307 } 308 309 return [$title, $list]; 310 } 311 312 /** 313 * Prepare cache 314 * 315 * @param array $depends (reference) array with dependencies 316 * @return cache 317 */ 318 protected function prepareCache(&$depends) 319 { 320 global $REV; 321 322 $cachekey = join(',', $this->list) 323 . $REV 324 . $this->getExportConfig('template') 325 . $this->getExportConfig('pagesize') 326 . $this->getExportConfig('orientation') 327 . $this->getExportConfig('font-size') 328 . $this->getExportConfig('doublesided') 329 . $this->getExportConfig('headernumber') 330 . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0') 331 . $this->title; 332 $cache = new Cache($cachekey, '.dw2.pdf'); 333 334 $dependencies = []; 335 foreach ($this->list as $pageid) { 336 $relations = p_get_metadata($pageid, 'relation'); 337 338 if (is_array($relations)) { 339 if (array_key_exists('media', $relations) && is_array($relations['media'])) { 340 foreach ($relations['media'] as $mediaid => $exists) { 341 if ($exists) { 342 $dependencies[] = mediaFN($mediaid); 343 } 344 } 345 } 346 347 if (array_key_exists('haspart', $relations) && is_array($relations['haspart'])) { 348 foreach ($relations['haspart'] as $part_pageid => $exists) { 349 if ($exists) { 350 $dependencies[] = wikiFN($part_pageid); 351 } 352 } 353 } 354 } 355 356 $dependencies[] = metaFN($pageid, '.meta'); 357 } 358 359 $depends['files'] = array_map('wikiFN', $this->list); 360 $depends['files'][] = __FILE__; 361 $depends['files'][] = dirname(__FILE__) . '/renderer.php'; 362 $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php'; 363 $depends['files'] = array_merge( 364 $depends['files'], 365 $dependencies, 366 getConfigFiles('main') 367 ); 368 return $cache; 369 } 370 371 /** 372 * Returns the parsed Wikitext in dw2pdf for the given id and revision 373 * 374 * @param string $id page id 375 * @param string|int $rev revision timestamp or empty string 376 * @param string $date_at 377 * @return null|string 378 */ 379 protected function p_wiki_dw2pdf($id, $rev = '', $date_at = '') 380 { 381 $file = wikiFN($id, $rev); 382 383 if (!file_exists($file)) return ''; 384 385 //ensure $id is in global $ID (needed for parsing) 386 global $ID; 387 $keep = $ID; 388 $ID = $id; 389 390 if ($rev || $date_at) { 391 $ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at); //no caching on old revisions 392 } else { 393 $ret = p_cached_output($file, 'dw2pdf', $id); 394 } 395 396 //restore ID (just in case) 397 $ID = $keep; 398 399 return $ret; 400 } 401 402 /** 403 * Build a pdf from the html 404 * 405 * @param string $cachefile 406 * @param Doku_Event $event 407 * @throws MpdfException 408 */ 409 protected function generatePDF($cachefile, $event) 410 { 411 global $REV, $INPUT, $DATE_AT; 412 413 if ($event->data == 'export_pdf') { //only one page is exported 414 $rev = $REV; 415 $date_at = $DATE_AT; 416 } else { //we are exporting entire namespace, ommit revisions 417 $rev = $date_at = ''; 418 } 419 420 //some shortcuts to export settings 421 $hasToC = $this->getExportConfig('hasToC'); 422 $levels = $this->getExportConfig('levels'); 423 $isDebug = $this->getExportConfig('isDebug'); 424 $watermark = $this->getExportConfig('watermark'); 425 426 // initialize PDF library 427 require_once(dirname(__FILE__) . "/DokuPDF.class.php"); 428 429 $mpdf = new DokuPDF( 430 $this->getExportConfig('pagesize'), 431 $this->getExportConfig('orientation'), 432 $this->getExportConfig('font-size'), 433 $this->getDocumentLanguage($this->list[0]) //use language of first page 434 ); 435 436 // let mpdf fix local links 437 $self = parse_url(DOKU_URL); 438 $url = $self['scheme'] . '://' . $self['host']; 439 if (!empty($self['port'])) { 440 $url .= ':' . $self['port']; 441 } 442 $mpdf->SetBasePath($url); 443 444 // Set the title 445 $mpdf->SetTitle($this->title); 446 447 // some default document settings 448 //note: double-sided document, starts at an odd page (first page is a right-hand side page) 449 // single-side document has only odd pages 450 $mpdf->mirrorMargins = $this->getExportConfig('doublesided'); 451 $mpdf->setAutoTopMargin = 'stretch'; 452 $mpdf->setAutoBottomMargin = 'stretch'; 453// $mpdf->pagenumSuffix = '/'; //prefix for {nbpg} 454 if ($hasToC) { 455 $mpdf->h2toc = $levels; 456 } 457 $mpdf->PageNumSubstitutions[] = ['from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off']; 458 459 // Watermarker 460 if ($watermark) { 461 $mpdf->SetWatermarkText($watermark); 462 $mpdf->showWatermarkText = true; 463 } 464 465 // load the template 466 $template = $this->load_template(); 467 468 // prepare HTML header styles 469 $html = ''; 470 if ($isDebug) { 471 $html .= '<html><head>'; 472 $html .= '<style>'; 473 } 474 475 $styles = '@page { size:auto; ' . $template['page'] . '}'; 476 $styles .= '@page :first {' . $template['first'] . '}'; 477 478 $styles .= '@page landscape-page { size:landscape }'; 479 $styles .= 'div.dw2pdf-landscape { page:landscape-page }'; 480 $styles .= '@page portrait-page { size:portrait }'; 481 $styles .= 'div.dw2pdf-portrait { page:portrait-page }'; 482 $styles .= $this->load_css(); 483 484 $mpdf->WriteHTML($styles, 1); 485 486 if ($isDebug) { 487 $html .= $styles; 488 $html .= '</style>'; 489 $html .= '</head><body>'; 490 } 491 492 $body_start = $template['html']; 493 $body_start .= '<div class="dokuwiki">'; 494 495 // insert the cover page 496 $body_start .= $template['cover']; 497 498 $mpdf->WriteHTML($body_start, 2, true, false); //start body html 499 if ($isDebug) { 500 $html .= $body_start; 501 } 502 if ($hasToC) { 503 //Note: - for double-sided document the ToC is always on an even number of pages, so that the following content is on a correct odd/even page 504 // - first page of ToC starts always at odd page (so eventually an additional blank page is included before) 505 // - there is no page numbering at the pages of the ToC 506 $mpdf->TOCpagebreakByArray([ 507 'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>', 508 'toc-bookmarkText' => $this->getLang('tocheader'), 509 'links' => true, 510 'outdent' => '1em', 511 'pagenumstyle' => '1' 512 ]); 513 $html .= '<tocpagebreak>'; 514 } 515 516 // loop over all pages 517 $counter = 0; 518 $no_pages = count($this->list); 519 foreach ($this->list as $page) { 520 $this->currentBookChapter = $counter; 521 $counter++; 522 523 $pagehtml = $this->p_wiki_dw2pdf($page, $rev, $date_at); 524 //file doesn't exists 525 if ($pagehtml == '') { 526 continue; 527 } 528 $pagehtml .= $this->page_depend_replacements($template['cite'], $page); 529 if ($counter < $no_pages) { 530 $pagehtml .= '<pagebreak />'; 531 } 532 533 $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html 534 if ($isDebug) { 535 $html .= $pagehtml; 536 } 537 } 538 539 // insert the back page 540 $body_end = $template['back']; 541 542 $body_end .= '</div>'; 543 544 $mpdf->WriteHTML($body_end, 2, false, true); // finish body html 545 if ($isDebug) { 546 $html .= $body_end; 547 $html .= '</body>'; 548 $html .= '</html>'; 549 } 550 551 //Return html for debugging 552 if ($isDebug) { 553 if ($INPUT->str('debughtml', 'text', true) == 'text') { 554 header('Content-Type: text/plain; charset=utf-8'); 555 } 556 echo $html; 557 exit(); 558 } 559 560 // write to cache file 561 $mpdf->Output($cachefile, 'F'); 562 } 563 564 /** 565 * @param string $cachefile 566 */ 567 protected function sendPDFFile($cachefile) 568 { 569 header('Content-Type: application/pdf'); 570 header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0'); 571 header('Pragma: public'); 572 http_conditionalRequest(filemtime($cachefile)); 573 global $INPUT; 574 $outputTarget = $INPUT->str('outputTarget', $this->getConf('output')); 575 576 $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', ' '))); 577 if ($outputTarget === 'file') { 578 header('Content-Disposition: attachment; filename="' . $filename . '.pdf";'); 579 } else { 580 header('Content-Disposition: inline; filename="' . $filename . '.pdf";'); 581 } 582 583 //Bookcreator uses jQuery.fileDownload.js, which requires a cookie. 584 header('Set-Cookie: fileDownload=true; path=/'); 585 586 //try to send file, and exit if done 587 http_sendfile($cachefile); 588 589 $fp = @fopen($cachefile, "rb"); 590 if ($fp) { 591 http_rangeRequest($fp, filesize($cachefile), 'application/pdf'); 592 } else { 593 header("HTTP/1.0 500 Internal Server Error"); 594 print "Could not read file - bad permissions?"; 595 } 596 exit(); 597 } 598 599 /** 600 * Load the various template files and prepare the HTML/CSS for insertion 601 * 602 * @return array 603 */ 604 protected function load_template() 605 { 606 global $ID; 607 global $conf; 608 global $INFO; 609 610 // this is what we'll return 611 $output = [ 612 'cover' => '', 613 'back' => '', 614 'html' => '', 615 'page' => '', 616 'first' => '', 617 'cite' => '', 618 ]; 619 620 // prepare header/footer elements 621 $html = ''; 622 foreach (['header', 'footer'] as $section) { 623 foreach (['', '_odd', '_even', '_first'] as $order) { 624 $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html'; 625 if (file_exists($file)) { 626 $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF; 627 $html .= file_get_contents($file) . DOKU_LF; 628 $html .= '</htmlpage' . $section . '>' . DOKU_LF; 629 630 // register the needed pseudo CSS 631 if ($order == '_first') { 632 $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 633 } elseif ($order == '_even') { 634 $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 635 } elseif ($order == '_odd') { 636 $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 637 } else { 638 $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 639 } 640 } 641 } 642 } 643 644 // prepare replacements 645 $replace = [ 646 '@PAGE@' => '{PAGENO}', 647 '@PAGES@' => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / ' 648 '@TITLE@' => hsc($this->title), 649 '@WIKI@' => $conf['title'], 650 '@WIKIURL@' => DOKU_URL, 651 '@DATE@' => dformat(time()), 652 '@USERNAME@' => $INFO['userinfo']['name'] ?? '', 653 '@BASE@' => DOKU_BASE, 654 '@INC@' => DOKU_INC, 655 '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/', 656 '@TPLINC@' => DOKU_INC . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/' 657 ]; 658 659 // set HTML element 660 $html = str_replace(array_keys($replace), array_values($replace), $html); 661 //TODO For bookcreator $ID (= bookmanager page) makes no sense 662 $output['html'] = $this->page_depend_replacements($html, $ID); 663 664 // cover page 665 $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html'; 666 if (file_exists($coverfile)) { 667 $output['cover'] = file_get_contents($coverfile); 668 $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']); 669 $output['cover'] = $this->page_depend_replacements($output['cover'], $ID); 670 $output['cover'] .= '<pagebreak />'; 671 } 672 673 // cover page 674 $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html'; 675 if (file_exists($backfile)) { 676 $output['back'] = '<pagebreak />'; 677 $output['back'] .= file_get_contents($backfile); 678 $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']); 679 $output['back'] = $this->page_depend_replacements($output['back'], $ID); 680 } 681 682 // citation box 683 $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html'; 684 if (file_exists($citationfile)) { 685 $output['cite'] = file_get_contents($citationfile); 686 $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']); 687 } 688 689 return $output; 690 } 691 692 /** 693 * @param string $raw code with placeholders 694 * @param string $id pageid 695 * @return string 696 */ 697 protected function page_depend_replacements($raw, $id) 698 { 699 global $REV, $DATE_AT; 700 701 // generate qr code for this page 702 $qr_code = ''; 703 if ($this->getConf('qrcodescale')) { 704 $url = hsc(wl($id, '', '&', true)); 705 $size = floatval($this->getConf('qrcodescale')); 706 $qr_code = '<barcode type="QR" code="' . $url . '" error="Q" disableborder="1" class="qrcode" size="' . $size . '" />'; 707 } 708 // prepare replacements 709 $replace['@ID@'] = $id; 710 $replace['@UPDATE@'] = dformat(filemtime(wikiFN($id, $REV))); 711 712 $params = []; 713 if ($DATE_AT) { 714 $params['at'] = $DATE_AT; 715 } elseif ($REV) { 716 $params['rev'] = $REV; 717 } 718 $replace['@PAGEURL@'] = wl($id, $params, true, "&"); 719 $replace['@QRCODE@'] = $qr_code; 720 721 $content = $raw; 722 723 // let other plugins define their own replacements 724 $evdata = ['id' => $id, 'replace' => &$replace, 'content' => &$content]; 725 $event = new Doku_Event('PLUGIN_DW2PDF_REPLACE', $evdata); 726 if ($event->advise_before()) { 727 $content = str_replace(array_keys($replace), array_values($replace), $raw); 728 } 729 730 // plugins may post-process HTML, e.g to clean up unused replacements 731 $event->advise_after(); 732 733 // @DATE(<date>[, <format>])@ 734 $content = preg_replace_callback( 735 '/@DATE\((.*?)(?:,\s*(.*?))?\)@/', 736 [$this, 'replacedate'], 737 $content 738 ); 739 740 return $content; 741 } 742 743 744 /** 745 * (callback) Replace date by request datestring 746 * e.g. '%m(30-11-1975)' is replaced by '11' 747 * 748 * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern 749 * @return string 750 */ 751 function replacedate($match) 752 { 753 global $conf; 754 //no 2nd argument for default date format 755 if ($match[2] == null) { 756 $match[2] = $conf['dformat']; 757 } 758 return strftime($match[2], strtotime($match[1])); 759 } 760 761 /** 762 * Load all the style sheets and apply the needed replacements 763 */ 764 protected function load_css() 765 { 766 global $conf; 767 //reuse the CSS dispatcher functions without triggering the main function 768 define('SIMPLE_TEST', 1); 769 require_once(DOKU_INC . 'lib/exe/css.php'); 770 771 // prepare CSS files 772 $files = array_merge( 773 [ 774 DOKU_INC . 'lib/styles/screen.css' => DOKU_BASE . 'lib/styles/', 775 DOKU_INC . 'lib/styles/print.css' => DOKU_BASE . 'lib/styles/', 776 ], 777 $this->css_pluginPDFstyles(), 778 [ 779 DOKU_PLUGIN . 'dw2pdf/conf/style.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 780 DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/', 781 DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 782 ] 783 ); 784 $css = ''; 785 foreach ($files as $file => $location) { 786 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 787 $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 788 $css .= css_loadfile($file, $location); 789 } 790 791 if (function_exists('css_parseless')) { 792 // apply pattern replacements 793 if (function_exists('css_styleini')) { 794 // compatiblity layer for pre-Greebo releases of DokuWiki 795 $styleini = css_styleini($conf['template']); 796 } else { 797 // Greebo functionality 798 $styleUtils = new StyleUtils(); 799 $styleini = $styleUtils->cssStyleini($conf['template']); // older versions need still the template 800 } 801 $css = css_applystyle($css, $styleini['replacements']); 802 803 // parse less 804 $css = css_parseless($css); 805 } else { 806 // @deprecated 2013-12-19: fix backward compatibility 807 $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/'); 808 } 809 810 return $css; 811 } 812 813 /** 814 * Returns a list of possible Plugin PDF Styles 815 * 816 * Checks for a pdf.css, falls back to print.css 817 * 818 * @author Andreas Gohr <andi@splitbrain.org> 819 */ 820 protected function css_pluginPDFstyles() 821 { 822 $list = []; 823 $plugins = plugin_list(); 824 825 $usestyle = explode(',', $this->getConf('usestyles')); 826 foreach ($plugins as $p) { 827 if (in_array($p, $usestyle)) { 828 $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/"; 829 $list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/"; 830 831 $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/"; 832 $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/"; 833 } 834 835 $list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/"; 836 $list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/"; 837 838 if (file_exists(DOKU_PLUGIN . "$p/pdf.css") || file_exists(DOKU_PLUGIN . "$p/pdf.less")) { 839 $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/"; 840 $list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/"; 841 } else { 842 $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/"; 843 $list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/"; 844 } 845 } 846 847 // template support 848 foreach (['pdf.css', 'pdf.less', 'css/pdf.css', 'css/pdf.less', 'styles/pdf.css', 'styles/pdf.less'] as $file) { 849 if (file_exists(tpl_incdir() . $file)) { 850 $list[tpl_incdir() . $file] = tpl_basedir() . $file; 851 } 852 } 853 854 return $list; 855 } 856 857 /** 858 * Returns array of pages which will be included in the exported pdf 859 * 860 * @return array 861 */ 862 public function getExportedPages() 863 { 864 return $this->list; 865 } 866 867 /** 868 * usort callback to sort by file lastmodified time 869 * 870 * @param array $a 871 * @param array $b 872 * @return int 873 */ 874 public function _datesort($a, $b) 875 { 876 if ($b['rev'] < $a['rev']) return -1; 877 if ($b['rev'] > $a['rev']) return 1; 878 return strcmp($b['id'], $a['id']); 879 } 880 881 /** 882 * usort callback to sort by page id 883 * @param array $a 884 * @param array $b 885 * @return int 886 */ 887 public function _pagenamesort($a, $b) 888 { 889 global $conf; 890 891 $partsA = explode(':', $a['id']); 892 $countA = count($partsA); 893 $partsB = explode(':', $b['id']); 894 $countB = count($partsB); 895 $max = max($countA, $countB); 896 897 898 // compare namepsace by namespace 899 for ($i = 0; $i < $max; $i++) { 900 $partA = $partsA[$i] ?: null; 901 $partB = $partsB[$i] ?: null; 902 903 // have we reached the page level? 904 if ($i === ($countA - 1) || $i === ($countB - 1)) { 905 // start page first 906 if ($partA == $conf['start']) return -1; 907 if ($partB == $conf['start']) return 1; 908 } 909 910 // prefer page over namespace 911 if ($partA === $partB) { 912 if (!isset($partsA[$i + 1])) return -1; 913 if (!isset($partsB[$i + 1])) return 1; 914 continue; 915 } 916 917 918 // simply compare 919 return strnatcmp($partA, $partB); 920 } 921 922 return strnatcmp($a['id'], $b['id']); 923 } 924 925 /** 926 * Collects settings from: 927 * 1. url parameters 928 * 2. plugin config 929 * 3. global config 930 */ 931 protected function loadExportConfig() 932 { 933 global $INPUT; 934 global $conf; 935 936 $this->exportConfig = []; 937 938 // decide on the paper setup from param or config 939 $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true); 940 $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true); 941 942 // decide on the font-size from param or config 943 $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true); 944 945 $doublesided = $INPUT->bool('doublesided', (bool)$this->getConf('doublesided')); 946 $this->exportConfig['doublesided'] = $doublesided ? '1' : '0'; 947 948 $this->exportConfig['watermark'] = $INPUT->str('watermark', ''); 949 950 $hasToC = $INPUT->bool('toc', (bool)$this->getConf('toc')); 951 $levels = []; 952 if ($hasToC) { 953 $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true); 954 list($top_input, $max_input) = array_pad(explode('-', $toclevels, 2), 2, ''); 955 list($top_conf, $max_conf) = array_pad(explode('-', $this->getConf('toclevels'), 2), 2, ''); 956 $bounds_input = [ 957 'top' => [ 958 (int)$top_input, 959 (int)$top_conf 960 ], 961 'max' => [ 962 (int)$max_input, 963 (int)$max_conf 964 ] 965 ]; 966 $bounds = [ 967 'top' => $conf['toptoclevel'], 968 'max' => $conf['maxtoclevel'] 969 970 ]; 971 foreach ($bounds_input as $bound => $values) { 972 foreach ($values as $value) { 973 if ($value > 0 && $value <= 5) { 974 //stop at valid value and store 975 $bounds[$bound] = $value; 976 break; 977 } 978 } 979 } 980 981 if ($bounds['max'] < $bounds['top']) { 982 $bounds['max'] = $bounds['top']; 983 } 984 985 for ($level = $bounds['top']; $level <= $bounds['max']; $level++) { 986 $levels["H$level"] = $level - 1; 987 } 988 } 989 $this->exportConfig['hasToC'] = $hasToC; 990 $this->exportConfig['levels'] = $levels; 991 992 $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true); 993 994 $tplconf = $this->getConf('template'); 995 $tpl = $INPUT->str('tpl', $tplconf, true); 996 if (!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) { 997 $tpl = $tplconf; 998 } 999 if (!$tpl) { 1000 $tpl = 'default'; 1001 } 1002 $this->exportConfig['template'] = $tpl; 1003 1004 $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml'); 1005 } 1006 1007 /** 1008 * Returns requested config 1009 * 1010 * @param string $name 1011 * @param mixed $notset 1012 * @return mixed|bool 1013 */ 1014 public function getExportConfig($name, $notset = false) 1015 { 1016 if ($this->exportConfig === null) { 1017 $this->loadExportConfig(); 1018 } 1019 1020 return $this->exportConfig[$name] ?? $notset; 1021 } 1022 1023 /** 1024 * Add 'export pdf'-button to pagetools 1025 * 1026 * @param Doku_Event $event 1027 */ 1028 public function addbutton(Doku_Event $event) 1029 { 1030 global $ID, $REV, $DATE_AT; 1031 1032 if ($this->getConf('showexportbutton') && $event->data['view'] == 'main') { 1033 $params = ['do' => 'export_pdf']; 1034 if ($DATE_AT) { 1035 $params['at'] = $DATE_AT; 1036 } elseif ($REV) { 1037 $params['rev'] = $REV; 1038 } 1039 1040 // insert button at position before last (up to top) 1041 $event->data['items'] = array_slice($event->data['items'], 0, -1, true) + 1042 ['export_pdf' => 1043 '<li>' 1044 . '<a href="' . wl($ID, $params) . '" class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">' 1045 . '<span>' . $this->getLang('export_pdf_button') . '</span>' 1046 . '</a>' 1047 . '</li>' 1048 ] + 1049 array_slice($event->data['items'], -1, 1, true); 1050 } 1051 } 1052 1053 /** 1054 * Add 'export pdf' button to page tools, new SVG based mechanism 1055 * 1056 * @param Doku_Event $event 1057 */ 1058 public function addsvgbutton(Doku_Event $event) 1059 { 1060 global $INFO; 1061 if ($event->data['view'] != 'page' || !$this->getConf('showexportbutton')) { 1062 return; 1063 } 1064 1065 if (!$INFO['exists']) { 1066 return; 1067 } 1068 1069 array_splice($event->data['items'], -1, 0, [new MenuItem()]); 1070 } 1071 1072 /** 1073 * Get the language of the current document 1074 * 1075 * Uses the translation plugin if available 1076 * @return string 1077 */ 1078 protected function getDocumentLanguage($pageid) 1079 { 1080 global $conf; 1081 1082 $lang = $conf['lang']; 1083 /** @var helper_plugin_translation $trans */ 1084 $trans = plugin_load('helper', 'translation'); 1085 if ($trans) { 1086 $tr = $trans->getLangPart($pageid); 1087 if ($tr) $lang = $tr; 1088 } 1089 1090 return $lang; 1091 } 1092} 1093