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