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