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