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 // loop over all pages 186 $cnt = count($list); 187 for($n = 0; $n < $cnt; $n++) { 188 $page = $list[$n]; 189 190 $html .= p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page); 191 $html .= $this->page_depend_replacements($template['cite'], cleanID($page)); 192 if($n < ($cnt - 1)) { 193 $html .= '<pagebreak />'; 194 } 195 } 196 197 // insert the back page 198 $html .= $template['back']; 199 200 $html .= '</div>'; 201 $html .= '</body>'; 202 $html .= '</html>'; 203 204 //Return html for debugging 205 if($conf['allowdebug'] && $_GET['debughtml'] == 'html') { 206 echo $html; 207 exit(); 208 }; 209 210 $mpdf->WriteHTML($html); 211 212 // write to cache file 213 $mpdf->Output($cache->cache, 'F'); 214 } 215 216 // deliver the file 217 header('Content-Type: application/pdf'); 218 header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0'); 219 header('Pragma: public'); 220 http_conditionalRequest(filemtime($cache->cache)); 221 222 $filename = rawurlencode(cleanID(strtr($title, ':/;"', ' '))); 223 if($this->getConf('output') == 'file') { 224 header('Content-Disposition: attachment; filename="' . $filename . '.pdf";'); 225 } else { 226 header('Content-Disposition: inline; filename="' . $filename . '.pdf";'); 227 } 228 229 //try to send file, and exit if done 230 http_sendfile($cache->cache); 231 232 $fp = @fopen($cache->cache, "rb"); 233 if($fp) { 234 http_rangeRequest($fp, filesize($cache->cache), 'application/pdf'); 235 } else { 236 header("HTTP/1.0 500 Internal Server Error"); 237 print "Could not read file - bad permissions?"; 238 } 239 exit(); 240 } 241 242 /** 243 * Add 'export pdf'-button to pagetools 244 * 245 * @param Doku_Event $event 246 * @param mixed $param not defined 247 */ 248 public function addbutton(&$event, $param) { 249 global $ID, $REV; 250 251 if($this->getConf('showexportbutton') && $event->data['view'] == 'main') { 252 $params = array('do' => 'export_pdf'); 253 if($REV) $params['rev'] = $REV; 254 255 // insert button at position before last (up to top) 256 $event->data['items'] = array_slice($event->data['items'], 0, -1, true) + 257 array('export_pdf' => 258 '<li>' 259 . '<a href=' . wl($ID, $params) . ' class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">' 260 . '<span>' . $this->getLang('export_pdf_button') . '</span>' 261 . '</a>' 262 . '</li>' 263 ) + 264 array_slice($event->data['items'], -1, 1, true); 265 } 266 } 267 268 /** 269 * Load the various template files and prepare the HTML/CSS for insertion 270 */ 271 protected function load_template($title) { 272 global $ID; 273 global $conf; 274 $tpl = $this->tpl; 275 276 // this is what we'll return 277 $output = array( 278 'cover' => '', 279 'html' => '', 280 'page' => '', 281 'first' => '', 282 'cite' => '', 283 ); 284 285 // prepare header/footer elements 286 $html = ''; 287 foreach(array('header', 'footer') as $section) { 288 foreach(array('', '_odd', '_even', '_first') as $order) { 289 $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/' . $section . $order . '.html'; 290 if(file_exists($file)) { 291 $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF; 292 $html .= file_get_contents($file) . DOKU_LF; 293 $html .= '</htmlpage' . $section . '>' . DOKU_LF; 294 295 // register the needed pseudo CSS 296 if($order == '_first') { 297 $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 298 } elseif($order == '_even') { 299 $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 300 } elseif($order == '_odd') { 301 $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF; 302 } else { 303 $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF; 304 } 305 } 306 } 307 } 308 309 // prepare replacements 310 $replace = array( 311 '@PAGE@' => '{PAGENO}', 312 '@PAGES@' => '{nb}', 313 '@TITLE@' => hsc($title), 314 '@WIKI@' => $conf['title'], 315 '@WIKIURL@' => DOKU_URL, 316 '@DATE@' => dformat(time()), 317 '@BASE@' => DOKU_BASE, 318 '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $tpl . '/' 319 ); 320 321 // set HTML element 322 $html = str_replace(array_keys($replace), array_values($replace), $html); 323 //TODO For bookcreator $ID (= bookmanager page) makes no sense 324 $output['html'] = $this->page_depend_replacements($html, $ID); 325 326 // cover page 327 $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/cover.html'; 328 if(file_exists($coverfile)) { 329 $output['cover'] = file_get_contents($coverfile); 330 $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']); 331 $output['cover'] .= '<pagebreak />'; 332 } 333 334 // cover page 335 $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/back.html'; 336 if(file_exists($backfile)) { 337 $output['back'] = '<pagebreak />'; 338 $output['back'] .= file_get_contents($backfile); 339 $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']); 340 } 341 342 // citation box 343 $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl . '/citation.html'; 344 if(file_exists($citationfile)) { 345 $output['cite'] = file_get_contents($citationfile); 346 $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']); 347 } 348 349 return $output; 350 } 351 352 /** 353 * @param string $raw code with placeholders 354 * @param string $id pageid 355 * @return string 356 */ 357 protected function page_depend_replacements($raw, $id) { 358 global $REV; 359 360 // generate qr code for this page using google infographics api 361 $qr_code = ''; 362 if($this->getConf('qrcodesize')) { 363 $url = urlencode(wl($id, '', '&', true)); 364 $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' . 365 $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />'; 366 } 367 // prepare replacements 368 $replace['@ID@'] = $id; 369 $replace['@UPDATE@'] = dformat(filemtime(wikiFN($id, $REV))); 370 $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&"); 371 $replace['@QRCODE@'] = $qr_code; 372 373 return str_replace(array_keys($replace), array_values($replace), $raw); 374 } 375 376 /** 377 * Load all the style sheets and apply the needed replacements 378 */ 379 protected function load_css() { 380 global $conf; 381 //reusue the CSS dispatcher functions without triggering the main function 382 define('SIMPLE_TEST', 1); 383 require_once(DOKU_INC . 'lib/exe/css.php'); 384 385 // prepare CSS files 386 $files = array_merge( 387 array( 388 DOKU_INC . 'lib/styles/screen.css' 389 => DOKU_BASE . 'lib/styles/', 390 DOKU_INC . 'lib/styles/print.css' 391 => DOKU_BASE . 'lib/styles/', 392 ), 393 css_pluginstyles('all'), 394 $this->css_pluginPDFstyles(), 395 array( 396 DOKU_PLUGIN . 'dw2pdf/conf/style.css' 397 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 398 DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' 399 => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/', 400 DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' 401 => DOKU_BASE . 'lib/plugins/dw2pdf/conf/', 402 ) 403 ); 404 $css = ''; 405 foreach($files as $file => $location) { 406 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 407 $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 408 $css .= css_loadfile($file, $location); 409 } 410 411 if(function_exists('css_parseless')) { 412 // apply pattern replacements 413 $styleini = css_styleini($conf['template']); 414 $css = css_applystyle($css, $styleini['replacements']); 415 416 // parse less 417 $css = css_parseless($css); 418 } else { 419 // @deprecated 2013-12-19: fix backward compatibility 420 $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/'); 421 } 422 423 return $css; 424 } 425 426 /** 427 * Returns a list of possible Plugin PDF Styles 428 * 429 * Checks for a pdf.css, falls back to print.css 430 * 431 * @author Andreas Gohr <andi@splitbrain.org> 432 */ 433 protected function css_pluginPDFstyles() { 434 $list = array(); 435 $plugins = plugin_list(); 436 437 $usestyle = explode(',', $this->getConf('usestyles')); 438 foreach($plugins as $p) { 439 if(in_array($p, $usestyle)) { 440 $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/"; 441 $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/"; 442 } 443 444 if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) { 445 $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/"; 446 } else { 447 $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/"; 448 } 449 } 450 return $list; 451 } 452 453 /** 454 * usort callback to sort by file lastmodified time 455 */ 456 public function _datesort($a, $b) { 457 if($b['rev'] < $a['rev']) return -1; 458 if($b['rev'] > $a['rev']) return 1; 459 return strcmp($b['id'], $a['id']); 460 } 461 462 /** 463 * usort callback to sort by page id 464 */ 465 public function _pagenamesort($a, $b) { 466 if($a['id'] <= $b['id']) return -1; 467 if($a['id'] > $b['id']) return 1; 468 return 0; 469 } 470 471 /** 472 * Set error notification and reload page again 473 * 474 * @param Doku_Event $event 475 * @param string $msglangkey key of translation key 476 */ 477 private function showPageWithErrorMsg(&$event, $msglangkey) { 478 msg($this->getLang($msglangkey), -1); 479 480 $event->data = 'show'; 481 $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url 482 } 483} 484