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