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