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