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