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