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