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