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 protected $tpl; 22 protected $list = array(); 23 24 /** 25 * Constructor. Sets the correct template 26 */ 27 public function __construct() { 28 $tpl = false; 29 if(isset($_REQUEST['tpl'])) { 30 $tpl = trim(preg_replace('/[^A-Za-z0-9_\-]+/', '', $_REQUEST['tpl'])); 31 } 32 if(!$tpl) $tpl = $this->getConf('template'); 33 if(!$tpl) $tpl = 'default'; 34 if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) $tpl = 'default'; 35 36 $this->tpl = $tpl; 37 } 38 39 /** 40 * Register the events 41 */ 42 public function register(Doku_Event_Handler $controller) { 43 $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array()); 44 $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array()); 45 } 46 47 /** 48 * Do the HTML to PDF conversion work 49 * 50 * @param Doku_Event $event 51 * @param array $param 52 * @return bool 53 */ 54 public function convert(&$event, $param) { 55 global $ACT; 56 global $REV; 57 global $ID; 58 global $INPUT, $conf; 59 60 // our event? 61 if(($ACT != 'export_pdfbook') && ($ACT != 'export_pdf') && ($ACT != 'export_pdfns')) return false; 62 63 // check user's rights 64 if(auth_quickaclcheck($ID) < AUTH_READ) return false; 65 66 // one or multiple pages? 67 $this->list = array(); 68 69 if($ACT == 'export_pdf') { 70 $this->list[0] = $ID; 71 $title = p_get_first_heading($ID); 72 73 } elseif($ACT == 'export_pdfns') { 74 //check input for title and ns 75 if(!$title = $INPUT->str('pdfns_title')) { 76 $this->showPageWithErrorMsg($event, 'needtitle'); 77 return false; 78 } 79 $pdfnamespace = cleanID($INPUT->str('pdfns_ns')); 80 if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) { 81 $this->showPageWithErrorMsg($event, 'needns'); 82 return false; 83 } 84 85 //sort order 86 $order = $INPUT->str('pdfns_order', 'natural', true); 87 $sortoptions = array('pagename', 'date', 'natural'); 88 if(!in_array($order, $sortoptions)) { 89 $order = 'natural'; 90 } 91 92 //search depth 93 $depth = $INPUT->int('pdfns_depth', 0); 94 if($depth < 0) { 95 $depth = 0; 96 } 97 98 //page search 99 $result = array(); 100 $opts = array('depth' => $depth); //recursive all levels 101 $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace)); 102 search($result, $conf['datadir'], 'search_allpages', $opts, $dir); 103 104 //sorting 105 if(count($result) > 0) { 106 if($order == 'date') { 107 usort($result, array($this, '_datesort')); 108 } elseif($order == 'pagename') { 109 usort($result, array($this, '_pagenamesort')); 110 } 111 } 112 113 foreach($result as $item) { 114 $this->list[] = $item['id']; 115 } 116 117 } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) { 118 //is in Bookmanager of bookcreator plugin a title given? 119 if(!$title = $INPUT->str('pdfbook_title')) { //TODO when title is changed, the cached file contains the old title 120 $this->showPageWithErrorMsg($event, 'needtitle'); 121 return false; 122 } else { 123 $this->list = explode("|", $_COOKIE['list-pagelist']); 124 } 125 126 } else { 127 //show empty bookcreator message 128 $this->showPageWithErrorMsg($event, 'empty'); 129 return false; 130 } 131 132 // it's ours, no one else's 133 $event->preventDefault(); 134 135 // decide on the paper setup from param or config 136 $pagesize = $INPUT->str('pagesize', $this->getConf('pagesize'), true); 137 $orientation = $INPUT->str('orientation', $this->getConf('orientation'), true); 138 139 // prepare cache 140 $cache = new cache(join(',', $this->list) . $REV . $this->tpl . $pagesize . $orientation, '.dw2.pdf'); 141 $depends['files'] = array_map('wikiFN', $this->list); 142 $depends['files'][] = __FILE__; 143 $depends['files'][] = dirname(__FILE__) . '/renderer.php'; 144 $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php'; 145 $depends['files'] = array_merge($depends['files'], getConfigFiles('main')); 146 147 // hard work only when no cache available 148 if(!$this->getConf('usecache') || !$cache->useCache($depends)) { 149 // initialize PDF library 150 require_once(dirname(__FILE__) . "/DokuPDF.class.php"); 151 152 $mpdf = new DokuPDF($pagesize, $orientation); 153 154 // let mpdf fix local links 155 $self = parse_url(DOKU_URL); 156 $url = $self['scheme'] . '://' . $self['host']; 157 if($self['port']) $url .= ':' . $self['port']; 158 $mpdf->setBasePath($url); 159 160 // Set the title 161 $mpdf->SetTitle($title); 162 163 // some default settings 164 $mpdf->mirrorMargins = 1; 165 $mpdf->useOddEven = 1; 166 $mpdf->setAutoTopMargin = 'stretch'; 167 $mpdf->setAutoBottomMargin = 'stretch'; 168 169 // load the template 170 $template = $this->load_template($title); 171 172 // prepare HTML header styles 173 $html = '<html><head>'; 174 $html .= '<style type="text/css">'; 175 $html .= $this->load_css(); 176 $html .= '@page { size:auto; ' . $template['page'] . '}'; 177 $html .= '@page :first {' . $template['first'] . '}'; 178 $html .= '</style>'; 179 $html .= '</head><body>'; 180 $html .= $template['html']; 181 $html .= '<div class="dokuwiki">'; 182 183 // insert the cover page 184 $html .= $template['cover']; 185 186 // store original pageid 187 $keep = $ID; 188 189 // loop over all pages 190 $cnt = count($list); 191 for($n = 0; $n < $cnt; $n++) { 192 $page = $list[$n]; 193 194 // set global pageid to the rendered page 195 $ID = $page; 196 197 $html .= p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page); 198 $html .= $this->page_depend_replacements($template['cite'], cleanID($page)); 199 if($n < ($cnt - 1)) { 200 $html .= '<pagebreak />'; 201 } 202 } 203 //restore ID 204 $ID = $keep; 205 206 // insert the back page 207 $html .= $template['back']; 208 209 $html .= '</div>'; 210 $html .= '</body>'; 211 $html .= '</html>'; 212 213 //Return html for debugging 214 if($conf['allowdebug'] && $_GET['debughtml'] == 'html') { 215 echo $html; 216 exit(); 217 }; 218 219 $mpdf->WriteHTML($html); 220 221 // write to cache file 222 $mpdf->Output($cache->cache, 'F'); 223 } 224 225 // deliver the file 226 header('Content-Type: application/pdf'); 227 header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0'); 228 header('Pragma: public'); 229 http_conditionalRequest(filemtime($cache->cache)); 230 231 $filename = rawurlencode(cleanID(strtr($title, ':/;"', ' '))); 232 if($this->getConf('output') == 'file') { 233 header('Content-Disposition: attachment; filename="' . $filename . '.pdf";'); 234 } else { 235 header('Content-Disposition: inline; filename="' . $filename . '.pdf";'); 236 } 237 238 //try to send file, and exit if done 239 http_sendfile($cache->cache); 240 241 $fp = @fopen($cache->cache, "rb"); 242 if($fp) { 243 http_rangeRequest($fp, filesize($cache->cache), 'application/pdf'); 244 } else { 245 header("HTTP/1.0 500 Internal Server Error"); 246 print "Could not read file - bad permissions?"; 247 } 248 exit(); 249 } 250 251 /** 252 * Add 'export pdf'-button to pagetools 253 * 254 * @param Doku_Event $event 255 * @param mixed $param not defined 256 */ 257 public function addbutton(&$event, $param) { 258 global $ID, $REV; 259 260 if($this->getConf('showexportbutton') && $event->data['view'] == 'main') { 261 $params = array('do' => 'export_pdf'); 262 if($REV) $params['rev'] = $REV; 263 264 // insert button at position before last (up to top) 265 $event->data['items'] = array_slice($event->data['items'], 0, -1, true) + 266 array('export_pdf' => 267 '<li>' 268 . '<a href=' . wl($ID, $params) . ' class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">' 269 . '<span>' . $this->getLang('export_pdf_button') . '</span>' 270 . '</a>' 271 . '</li>' 272 ) + 273 array_slice($event->data['items'], -1, 1, true); 274 } 275 } 276 277 /** 278 * Load the various template files and prepare the HTML/CSS for insertion 279 */ 280 protected function load_template($title) { 281 global $ID; 282 global $conf; 283 $tpl = $this->tpl; 284 285 // this is what we'll return 286 $output = array( 287 'cover' => '', 288 'html' => '', 289 'page' => '', 290 'first' => '', 291 'cite' => '', 292 ); 293 294 // prepare header/footer elements 295 $html = ''; 296 foreach(array('header', 'footer') as $section) { 297 foreach(array('', '_odd', '_even', '_first') as $order) { 298 $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/' . $section . $order . '.html'; 299 if(file_exists($file)) { 300 $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF; 301 $html .= file_get_contents($file) . DOKU_LF; 302 $html .= '</htmlpage' . $section . '>' . DOKU_LF; 303 304 // register the needed pseudo CSS 305 if($order == '_first') { 306 $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 307 } elseif($order == '_even') { 308 $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 309 } elseif($order == '_odd') { 310 $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 311 } else { 312 $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 313 } 314 } 315 } 316 } 317 318 // prepare replacements 319 $replace = array( 320 '@PAGE@' => '{PAGENO}', 321 '@PAGES@' => '{nb}', 322 '@TITLE@' => hsc($title), 323 '@WIKI@' => $conf['title'], 324 '@WIKIURL@' => DOKU_URL, 325 '@DATE@' => dformat(time()), 326 '@BASE@' => DOKU_BASE, 327 '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $tpl . '/' 328 ); 329 330 // set HTML element 331 $html = str_replace(array_keys($replace), array_values($replace), $html); 332 //TODO For bookcreator $ID (= bookmanager page) makes no sense 333 $output['html'] = $this->page_depend_replacements($html, $ID); 334 335 // cover page 336 $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/cover.html'; 337 if(file_exists($coverfile)) { 338 $output['cover'] = file_get_contents($coverfile); 339 $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']); 340 $output['cover'] .= '<pagebreak />'; 341 } 342 343 // cover page 344 $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/back.html'; 345 if(file_exists($backfile)) { 346 $output['back'] = '<pagebreak />'; 347 $output['back'] .= file_get_contents($backfile); 348 $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']); 349 } 350 351 // citation box 352 $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/citation.html'; 353 if(file_exists($citationfile)) { 354 $output['cite'] = file_get_contents($citationfile); 355 $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']); 356 } 357 358 return $output; 359 } 360 361 /** 362 * @param string $raw code with placeholders 363 * @param string $id pageid 364 * @return string 365 */ 366 protected function page_depend_replacements($raw, $id) { 367 global $REV; 368 369 // generate qr code for this page using google infographics api 370 $qr_code = ''; 371 if($this->getConf('qrcodesize')) { 372 $url = urlencode(wl($id, '', '&', true)); 373 $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' . 374 $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />'; 375 } 376 // prepare replacements 377 $replace['@ID@'] = $id; 378 $replace['@UPDATE@'] = dformat(filemtime(wikiFN($id, $REV))); 379 $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&"); 380 $replace['@QRCODE@'] = $qr_code; 381 382 return str_replace(array_keys($replace), array_values($replace), $raw); 383 } 384 385 /** 386 * Load all the style sheets and apply the needed replacements 387 */ 388 protected function load_css() { 389 global $conf; 390 //reusue the CSS dispatcher functions without triggering the main function 391 define('SIMPLE_TEST', 1); 392 require_once(DOKU_INC . 'lib/exe/css.php'); 393 394 // prepare CSS files 395 $files = array_merge( 396 array( 397 DOKU_INC . 'lib/styles/screen.css' 398 => DOKU_BASE . 'lib/styles/', 399 DOKU_INC . 'lib/styles/print.css' 400 => DOKU_BASE . 'lib/styles/', 401 ), 402 css_pluginstyles('all'), 403 $this->css_pluginPDFstyles(), 404 array( 405 DOKU_PLUGIN . 'dw2pdf/conf/style.css' 406 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 407 DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' 408 => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/', 409 DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' 410 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 411 ) 412 ); 413 $css = ''; 414 foreach($files as $file => $location) { 415 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 416 $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 417 $css .= css_loadfile($file, $location); 418 } 419 420 if(function_exists('css_parseless')) { 421 // apply pattern replacements 422 $styleini = css_styleini($conf['template']); 423 $css = css_applystyle($css, $styleini['replacements']); 424 425 // parse less 426 $css = css_parseless($css); 427 } else { 428 // @deprecated 2013-12-19: fix backward compatibility 429 $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/'); 430 } 431 432 return $css; 433 } 434 435 /** 436 * Returns a list of possible Plugin PDF Styles 437 * 438 * Checks for a pdf.css, falls back to print.css 439 * 440 * @author Andreas Gohr <andi@splitbrain.org> 441 */ 442 protected function css_pluginPDFstyles() { 443 $list = array(); 444 $plugins = plugin_list(); 445 446 $usestyle = explode(',', $this->getConf('usestyles')); 447 foreach($plugins as $p) { 448 if(in_array($p, $usestyle)) { 449 $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/"; 450 $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/"; 451 } 452 453 if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) { 454 $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/"; 455 } else { 456 $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/"; 457 } 458 } 459 return $list; 460 } 461 462 /** 463 * Returns array of pages which will be included in the exported pdf 464 * 465 * @return array 466 */ 467 public function getExportedPages() { 468 return $this->list; 469 } 470 471 /** 472 * usort callback to sort by file lastmodified time 473 */ 474 public function _datesort($a, $b) { 475 if($b['rev'] < $a['rev']) return -1; 476 if($b['rev'] > $a['rev']) return 1; 477 return strcmp($b['id'], $a['id']); 478 } 479 480 /** 481 * usort callback to sort by page id 482 */ 483 public function _pagenamesort($a, $b) { 484 if($a['id'] <= $b['id']) return -1; 485 if($a['id'] > $b['id']) return 1; 486 return 0; 487 } 488 489 /** 490 * Set error notification and reload page again 491 * 492 * @param Doku_Event $event 493 * @param string $msglangkey key of translation key 494 */ 495 private function showPageWithErrorMsg(&$event, $msglangkey) { 496 msg($this->getLang($msglangkey), -1); 497 498 $event->data = 'show'; 499 $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url 500 } 501} 502