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(array_map(function ($item) use ($excludes) { 186 return array_search($item['id'], $excludes) === false ? $item : ''; 187 }, $result)); 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 = str_replace(array_keys($replace), array_values($replace), $raw); 695 696 // @DATE(<date>[, <format>])@ 697 $content = preg_replace_callback( 698 '/@DATE\((.*?)(?:,\s*(.*?))?\)@/', 699 array($this, 'replacedate'), 700 $content 701 ); 702 703 return $content; 704 } 705 706 707 /** 708 * (callback) Replace date by request datestring 709 * e.g. '%m(30-11-1975)' is replaced by '11' 710 * 711 * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern 712 * @return string 713 */ 714 function replacedate($match) { 715 global $conf; 716 //no 2nd argument for default date format 717 if($match[2] == null) { 718 $match[2] = $conf['dformat']; 719 } 720 return strftime($match[2], strtotime($match[1])); 721 } 722 723 /** 724 * Load all the style sheets and apply the needed replacements 725 */ 726 protected function load_css() { 727 global $conf; 728 //reusue the CSS dispatcher functions without triggering the main function 729 define('SIMPLE_TEST', 1); 730 require_once(DOKU_INC . 'lib/exe/css.php'); 731 732 // prepare CSS files 733 $files = array_merge( 734 array( 735 DOKU_INC . 'lib/styles/screen.css' 736 => DOKU_BASE . 'lib/styles/', 737 DOKU_INC . 'lib/styles/print.css' 738 => DOKU_BASE . 'lib/styles/', 739 ), 740 $this->css_pluginPDFstyles(), 741 array( 742 DOKU_PLUGIN . 'dw2pdf/conf/style.css' 743 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 744 DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' 745 => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/', 746 DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' 747 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 748 ) 749 ); 750 $css = ''; 751 foreach($files as $file => $location) { 752 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 753 $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 754 $css .= css_loadfile($file, $location); 755 } 756 757 if(function_exists('css_parseless')) { 758 // apply pattern replacements 759 if (function_exists('css_styleini')) { 760 // compatiblity layer for pre-Greebo releases of DokuWiki 761 $styleini = css_styleini($conf['template']); 762 } else { 763 // Greebo functionality 764 $styleUtils = new \dokuwiki\StyleUtils(); 765 $styleini = $styleUtils->cssStyleini($conf['template']); 766 } 767 $css = css_applystyle($css, $styleini['replacements']); 768 769 // parse less 770 $css = css_parseless($css); 771 } else { 772 // @deprecated 2013-12-19: fix backward compatibility 773 $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/'); 774 } 775 776 return $css; 777 } 778 779 /** 780 * Returns a list of possible Plugin PDF Styles 781 * 782 * Checks for a pdf.css, falls back to print.css 783 * 784 * @author Andreas Gohr <andi@splitbrain.org> 785 */ 786 protected function css_pluginPDFstyles() { 787 $list = array(); 788 $plugins = plugin_list(); 789 790 $usestyle = explode(',', $this->getConf('usestyles')); 791 foreach($plugins as $p) { 792 if(in_array($p, $usestyle)) { 793 $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/"; 794 $list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/"; 795 796 $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/"; 797 $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/"; 798 } 799 800 $list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/"; 801 $list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/"; 802 803 if(file_exists(DOKU_PLUGIN . "$p/pdf.css") || file_exists(DOKU_PLUGIN . "$p/pdf.less")) { 804 $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/"; 805 $list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/"; 806 } else { 807 $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/"; 808 $list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/"; 809 } 810 } 811 return $list; 812 } 813 814 /** 815 * Returns array of pages which will be included in the exported pdf 816 * 817 * @return array 818 */ 819 public function getExportedPages() { 820 return $this->list; 821 } 822 823 /** 824 * usort callback to sort by file lastmodified time 825 * 826 * @param array $a 827 * @param array $b 828 * @return int 829 */ 830 public function _datesort($a, $b) { 831 if($b['rev'] < $a['rev']) return -1; 832 if($b['rev'] > $a['rev']) return 1; 833 return strcmp($b['id'], $a['id']); 834 } 835 836 /** 837 * usort callback to sort by page id 838 * @param array $a 839 * @param array $b 840 * @return int 841 */ 842 public function _pagenamesort($a, $b) { 843 // do not sort numbers before namespace separators 844 $aID = str_replace(':', '/', $a['id']); 845 $bID = str_replace(':', '/', $b['id']); 846 if($aID <= $bID) return -1; 847 if($aID > $bID) return 1; 848 return 0; 849 } 850 851 /** 852 * Return settings read from: 853 * 1. url parameters 854 * 2. plugin config 855 * 3. global config 856 * 857 * @return array 858 */ 859 protected function loadExportConfig() { 860 global $INPUT; 861 global $conf; 862 863 $this->exportConfig = array(); 864 865 // decide on the paper setup from param or config 866 $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true); 867 $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true); 868 869 // decide on the font-size from param or config 870 $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true); 871 872 $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided')); 873 $this->exportConfig['doublesided'] = $doublesided ? '1' : '0'; 874 875 $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc')); 876 $levels = array(); 877 if($hasToC) { 878 $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true); 879 list($top_input, $max_input) = explode('-', $toclevels, 2); 880 list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2); 881 $bounds_input = array( 882 'top' => array( 883 (int) $top_input, 884 (int) $top_conf 885 ), 886 'max' => array( 887 (int) $max_input, 888 (int) $max_conf 889 ) 890 ); 891 $bounds = array( 892 'top' => $conf['toptoclevel'], 893 'max' => $conf['maxtoclevel'] 894 895 ); 896 foreach($bounds_input as $bound => $values) { 897 foreach($values as $value) { 898 if($value > 0 && $value <= 5) { 899 //stop at valid value and store 900 $bounds[$bound] = $value; 901 break; 902 } 903 } 904 } 905 906 if($bounds['max'] < $bounds['top']) { 907 $bounds['max'] = $bounds['top']; 908 } 909 910 for($level = $bounds['top']; $level <= $bounds['max']; $level++) { 911 $levels["H$level"] = $level - 1; 912 } 913 } 914 $this->exportConfig['hasToC'] = $hasToC; 915 $this->exportConfig['levels'] = $levels; 916 917 $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true); 918 919 $tplconf = $this->getConf('template'); 920 $tpl = $INPUT->str('tpl', $tplconf, true); 921 if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) { 922 $tpl = $tplconf; 923 } 924 if(!$tpl){ 925 $tpl = 'default'; 926 } 927 $this->exportConfig['template'] = $tpl; 928 929 $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml'); 930 } 931 932 /** 933 * Returns requested config 934 * 935 * @param string $name 936 * @param mixed $notset 937 * @return mixed|bool 938 */ 939 public function getExportConfig($name, $notset = false) { 940 if ($this->exportConfig === null){ 941 $this->loadExportConfig(); 942 } 943 944 if(isset($this->exportConfig[$name])){ 945 return $this->exportConfig[$name]; 946 }else{ 947 return $notset; 948 } 949 } 950 951 /** 952 * Add 'export pdf'-button to pagetools 953 * 954 * @param Doku_Event $event 955 */ 956 public function addbutton(Doku_Event $event) { 957 global $ID, $REV, $DATE_AT; 958 959 if($this->getConf('showexportbutton') && $event->data['view'] == 'main') { 960 $params = array('do' => 'export_pdf'); 961 if($DATE_AT) { 962 $params['at'] = $DATE_AT; 963 } elseif($REV) { 964 $params['rev'] = $REV; 965 } 966 967 // insert button at position before last (up to top) 968 $event->data['items'] = array_slice($event->data['items'], 0, -1, true) + 969 array('export_pdf' => 970 '<li>' 971 . '<a href="' . wl($ID, $params) . '" class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">' 972 . '<span>' . $this->getLang('export_pdf_button') . '</span>' 973 . '</a>' 974 . '</li>' 975 ) + 976 array_slice($event->data['items'], -1, 1, true); 977 } 978 } 979 980 /** 981 * Add 'export pdf' button to page tools, new SVG based mechanism 982 * 983 * @param Doku_Event $event 984 */ 985 public function addsvgbutton(Doku_Event $event) { 986 global $INFO; 987 if($event->data['view'] != 'page' || !$this->getConf('showexportbutton')) { 988 return; 989 } 990 991 if(!$INFO['exists']) { 992 return; 993 } 994 995 array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dw2pdf\MenuItem()]); 996 } 997} 998