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