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