xref: /plugin/dw2pdf/action.php (revision 02f9a447ac91ae961961e8bb8f6ca67bb3d2bcd5)
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    public $exportConfig = null;
26    protected $tpl;
27    protected $list = array();
28
29    /**
30     * Constructor. Sets the correct template
31     */
32    public function __construct() {
33        $this->tpl = $this->getExportConfig('template');
34    }
35
36    /**
37     * Register the events
38     */
39    public function register(Doku_Event_Handler $controller) {
40        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
41        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
42    }
43
44    /**
45     * Do the HTML to PDF conversion work
46     *
47     * @param Doku_Event $event
48     * @param array      $param
49     * @return bool
50     */
51    public function convert(&$event, $param) {
52        global $ACT;
53        global $REV;
54        global $ID;
55        global $INPUT, $conf;
56
57        // our event?
58        if(($ACT != 'export_pdfbook') && ($ACT != 'export_pdf') && ($ACT != 'export_pdfns')) return false;
59
60        // check user's rights
61        if(auth_quickaclcheck($ID) < AUTH_READ) return false;
62
63        // one or multiple pages?
64        $this->list = array();
65
66        if($ACT == 'export_pdf') {
67            $this->list[0] = $ID;
68            $title = p_get_first_heading($ID);
69
70        } elseif($ACT == 'export_pdfns') {
71            //check input for title and ns
72            if(!$title = $INPUT->str('pdfns_title')) {
73                $this->showPageWithErrorMsg($event, 'needtitle');
74                return false;
75            }
76            $pdfnamespace = cleanID($INPUT->str('pdfns_ns'));
77            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
78                $this->showPageWithErrorMsg($event, 'needns');
79                return false;
80            }
81
82            //sort order
83            $order = $INPUT->str('pdfns_order', 'natural', true);
84            $sortoptions = array('pagename', 'date', 'natural');
85            if(!in_array($order, $sortoptions)) {
86                $order = 'natural';
87            }
88
89            //search depth
90            $depth = $INPUT->int('pdfns_depth', 0);
91            if($depth < 0) {
92                $depth = 0;
93            }
94
95            //page search
96            $result = array();
97            $opts = array('depth' => $depth); //recursive all levels
98            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
99            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
100
101            //sorting
102            if(count($result) > 0) {
103                if($order == 'date') {
104                    usort($result, array($this, '_datesort'));
105                } elseif($order == 'pagename') {
106                    usort($result, array($this, '_pagenamesort'));
107                }
108            }
109
110            foreach($result as $item) {
111                $this->list[] = $item['id'];
112            }
113
114        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
115            //is in Bookmanager of bookcreator plugin a title given?
116            if(!$title = $INPUT->str('pdfbook_title')) { //TODO when title is changed, the cached file contains the old title
117                $this->showPageWithErrorMsg($event, 'needtitle');
118                return false;
119            } else {
120                $this->list = explode("|", $_COOKIE['list-pagelist']);
121            }
122
123        } else {
124            //show empty bookcreator message
125            $this->showPageWithErrorMsg($event, 'empty');
126            return false;
127        }
128
129        // it's ours, no one else's
130        $event->preventDefault();
131
132        //some shortcuts to export settings
133        $hasToC = $this->getExportConfig('hasToC');
134        $levels = $this->getExportConfig('levels');
135        $isDebug = $this->getExportConfig('isDebug');
136
137        // prepare cache
138        $cachekey = join(',', $this->list)
139                    . $REV
140                    . $this->getExportConfig('template')
141                    . $this->getExportConfig('pagesize')
142                    . $this->getExportConfig('orientation')
143                    . ($hasToC ? join('-', $levels) : '0')
144                    . $title;
145        $cache = new cache($cachekey, '.dw2.pdf');
146
147        $depends['files']   = array_map('wikiFN', $this->list);
148        $depends['files'][] = __FILE__;
149        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
150        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
151        $depends['files']   = array_merge($depends['files'], getConfigFiles('main'));
152
153        // hard work only when no cache available
154        if(!$this->getConf('usecache') || !$cache->useCache($depends)) {
155            // debug enabled?
156
157            // initialize PDF library
158            require_once(dirname(__FILE__) . "/DokuPDF.class.php");
159
160            $mpdf = new DokuPDF($this->getExportConfig('pagesize'), $this->getExportConfig('orientation'));
161
162            // let mpdf fix local links
163            $self = parse_url(DOKU_URL);
164            $url = $self['scheme'] . '://' . $self['host'];
165            if($self['port']) {
166                $url .= ':' . $self['port'];
167            }
168            $mpdf->setBasePath($url);
169
170            // Set the title
171            $mpdf->SetTitle($title);
172
173            // some default settings
174            $mpdf->mirrorMargins = 1; //double-sided document, starts at an odd page (first page is a right-hand side page)
175            $mpdf->useOddEven    = 1; //duplicate of mirrorMargins
176            $mpdf->setAutoTopMargin = 'stretch';
177            $mpdf->setAutoBottomMargin = 'stretch';
178//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
179            if($hasToC) {
180                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off');//use italic pageno until ToC
181                $mpdf->h2toc = $levels;
182            } else {
183                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
184            }
185
186            // load the template
187            $template = $this->load_template($title);
188
189            // prepare HTML header styles
190            $html = '';
191            if($isDebug) {
192                $html .= '<html><head>';
193                $html .= '<style type="text/css">';
194            }
195            $styles = $this->load_css();
196            $styles .= '@page { size:auto; ' . $template['page'] . '}';
197            $styles .= '@page :first {' . $template['first'] . '}';
198            $mpdf->WriteHTML($styles, 1);
199
200            if($isDebug) {
201                $html .= $styles;
202                $html .= '</style>';
203                $html .= '</head><body>';
204            }
205
206            $body_start = $template['html'];
207            $body_start .= '<div class="dokuwiki">';
208
209            // insert the cover page
210            $body_start .= $template['cover'];
211
212            $mpdf->WriteHTML($body_start, 2, true, false); //start body html
213            if($isDebug) {
214                $html .= $body_start;
215            }
216            if($hasToC) {
217                //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
218                //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
219                //      - there is no page numbering at the pages of the ToC
220                $mpdf->TOCpagebreakByArray(
221                    array(
222                        'toc-preHTML' => '<h2>Table of contents</h2>',
223                        'toc-bookmarkText'=> 'Table of Content',
224                        'links' => true,
225                        'outdent' => '1em',
226                        'resetpagenum' => true, //start pagenumbering after ToC
227                        'pagenumstyle' => '1'
228                    )
229                );
230                $html .= '<tocpagebreak>';
231            }
232
233
234            // store original pageid
235            $keep = $ID;
236
237            // loop over all pages
238            $cnt = count($this->list);
239            for($n = 0; $n < $cnt; $n++) {
240                $page = $this->list[$n];
241
242                // set global pageid to the rendered page
243                $ID   = $page;
244
245                $pagehtml = p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page);
246                $pagehtml .= $this->page_depend_replacements($template['cite'], cleanID($page));
247                if($n < ($cnt - 1)) {
248                    $pagehtml .= '<pagebreak />';
249                }
250
251                $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
252                if($isDebug) {
253                    $html .= $pagehtml;
254                }
255            }
256            //restore ID
257            $ID = $keep;
258
259            // insert the back page
260            $body_end = $template['back'];
261
262            $body_end .= '</div>';
263
264            $mpdf->WriteHTML($body_end, 2, false, true); // end body html
265            if($isDebug) {
266                $html .= $body_end;
267                $html .= '</body>';
268                $html .= '</html>';
269            }
270
271            //Return html for debugging
272            if($isDebug) {
273                if($INPUT->str('debughtml', 'text', true) == 'html') {
274                    echo $html;
275                } else {
276                    header('Content-Type: text/plain; charset=utf-8');
277                    echo $html;
278                }
279                exit();
280            };
281
282            // write to cache file
283            $mpdf->Output($cache->cache, 'F');
284        }
285
286        // deliver the file
287        header('Content-Type: application/pdf');
288        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
289        header('Pragma: public');
290        http_conditionalRequest(filemtime($cache->cache));
291
292        $filename = rawurlencode(cleanID(strtr($title, ':/;"', '    ')));
293        if($this->getConf('output') == 'file') {
294            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
295        } else {
296            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
297        }
298
299        //try to send file, and exit if done
300        http_sendfile($cache->cache);
301
302        $fp = @fopen($cache->cache, "rb");
303        if($fp) {
304            http_rangeRequest($fp, filesize($cache->cache), 'application/pdf');
305        } else {
306            header("HTTP/1.0 500 Internal Server Error");
307            print "Could not read file - bad permissions?";
308        }
309        exit();
310    }
311
312    /**
313     * Add 'export pdf'-button to pagetools
314     *
315     * @param Doku_Event $event
316     * @param mixed      $param not defined
317     */
318    public function addbutton(Doku_Event $event, $param) {
319        global $ID, $REV;
320
321        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
322            $params = array('do' => 'export_pdf');
323            if($REV) {
324                $params['rev'] = $REV;
325            }
326
327            // insert button at position before last (up to top)
328            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
329                                    array('export_pdf' =>
330                                          '<li>'
331                                          . '<a href=' . wl($ID, $params) . '  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
332                                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
333                                          . '</a>'
334                                          . '</li>'
335                                    ) +
336                                    array_slice($event->data['items'], -1, 1, true);
337        }
338    }
339
340    /**
341     * Load the various template files and prepare the HTML/CSS for insertion
342     */
343    protected function load_template($title) {
344        global $ID;
345        global $conf;
346
347        // this is what we'll return
348        $output = array(
349            'cover' => '',
350            'html'  => '',
351            'page'  => '',
352            'first' => '',
353            'cite'  => '',
354        );
355
356        // prepare header/footer elements
357        $html = '';
358        foreach(array('header', 'footer') as $section) {
359            foreach(array('', '_odd', '_even', '_first') as $order) {
360                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
361                if(file_exists($file)) {
362                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
363                    $html .= file_get_contents($file) . DOKU_LF;
364                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
365
366                    // register the needed pseudo CSS
367                    if($order == '_first') {
368                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
369                    } elseif($order == '_even') {
370                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
371                    } elseif($order == '_odd') {
372                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
373                    } else {
374                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
375                    }
376                }
377            }
378        }
379
380        // prepare replacements
381        $replace = array(
382            '@PAGE@'    => '{PAGENO}',
383            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
384            '@TITLE@'   => hsc($title),
385            '@WIKI@'    => $conf['title'],
386            '@WIKIURL@' => DOKU_URL,
387            '@DATE@'    => dformat(time()),
388            '@BASE@'    => DOKU_BASE,
389            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
390        );
391
392        // set HTML element
393        $html = str_replace(array_keys($replace), array_values($replace), $html);
394        //TODO For bookcreator $ID (= bookmanager page) makes no sense
395        $output['html'] = $this->page_depend_replacements($html, $ID);
396
397        // cover page
398        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
399        if(file_exists($coverfile)) {
400            $output['cover'] = file_get_contents($coverfile);
401            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
402            $output['cover'] .= '<pagebreak />';
403        }
404
405        // cover page
406        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
407        if(file_exists($backfile)) {
408            $output['back'] = '<pagebreak />';
409            $output['back'] .= file_get_contents($backfile);
410            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
411        }
412
413        // citation box
414        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
415        if(file_exists($citationfile)) {
416            $output['cite'] = file_get_contents($citationfile);
417            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
418        }
419
420        return $output;
421    }
422
423    /**
424     * @param string $raw code with placeholders
425     * @param string $id  pageid
426     * @return string
427     */
428    protected function page_depend_replacements($raw, $id) {
429        global $REV;
430
431        // generate qr code for this page using google infographics api
432        $qr_code = '';
433        if($this->getConf('qrcodesize')) {
434            $url = urlencode(wl($id, '', '&', true));
435            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
436                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
437        }
438        // prepare replacements
439        $replace['@ID@']      = $id;
440        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
441        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&");
442        $replace['@QRCODE@']  = $qr_code;
443
444        return str_replace(array_keys($replace), array_values($replace), $raw);
445    }
446
447    /**
448     * Load all the style sheets and apply the needed replacements
449     */
450    protected function load_css() {
451        global $conf;
452        //reusue the CSS dispatcher functions without triggering the main function
453        define('SIMPLE_TEST', 1);
454        require_once(DOKU_INC . 'lib/exe/css.php');
455
456        // prepare CSS files
457        $files = array_merge(
458            array(
459                DOKU_INC . 'lib/styles/screen.css'
460                    => DOKU_BASE . 'lib/styles/',
461                DOKU_INC . 'lib/styles/print.css'
462                    => DOKU_BASE . 'lib/styles/',
463            ),
464            css_pluginstyles('all'),
465            $this->css_pluginPDFstyles(),
466            array(
467                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
468                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
469                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
470                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
471                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
472                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
473            )
474        );
475        $css = '';
476        foreach($files as $file => $location) {
477            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
478            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
479            $css .= css_loadfile($file, $location);
480        }
481
482        if(function_exists('css_parseless')) {
483            // apply pattern replacements
484            $styleini = css_styleini($conf['template']);
485            $css = css_applystyle($css, $styleini['replacements']);
486
487            // parse less
488            $css = css_parseless($css);
489        } else {
490            // @deprecated 2013-12-19: fix backward compatibility
491            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
492        }
493
494        return $css;
495    }
496
497    /**
498     * Returns a list of possible Plugin PDF Styles
499     *
500     * Checks for a pdf.css, falls back to print.css
501     *
502     * @author Andreas Gohr <andi@splitbrain.org>
503     */
504    protected function css_pluginPDFstyles() {
505        $list = array();
506        $plugins = plugin_list();
507
508        $usestyle = explode(',', $this->getConf('usestyles'));
509        foreach($plugins as $p) {
510            if(in_array($p, $usestyle)) {
511                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
512                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
513            }
514
515            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
516                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
517            } else {
518                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
519            }
520        }
521        return $list;
522    }
523
524    /**
525     * Returns array of pages which will be included in the exported pdf
526     *
527     * @return array
528     */
529    public function getExportedPages() {
530        return $this->list;
531    }
532
533    /**
534     * usort callback to sort by file lastmodified time
535     */
536    public function _datesort($a, $b) {
537        if($b['rev'] < $a['rev']) return -1;
538        if($b['rev'] > $a['rev']) return 1;
539        return strcmp($b['id'], $a['id']);
540    }
541
542    /**
543     * usort callback to sort by page id
544     */
545    public function _pagenamesort($a, $b) {
546        if($a['id'] <= $b['id']) return -1;
547        if($a['id'] > $b['id']) return 1;
548        return 0;
549    }
550
551    /**
552     * Set error notification and reload page again
553     *
554     * @param Doku_Event $event
555     * @param string     $msglangkey key of translation key
556     */
557    private function showPageWithErrorMsg(&$event, $msglangkey) {
558        msg($this->getLang($msglangkey), -1);
559
560        $event->data = 'show';
561        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
562    }
563
564    /**
565     * Return settings read from:
566     *   1. url parameters
567     *   2. plugin config
568     *   3. global config
569     *
570     * @return array
571     */
572    protected function loadExportConfig() {
573        global $INPUT;
574        global $conf;
575
576        $this->exportConfig = array();
577
578        // decide on the paper setup from param or config
579        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
580        $this->exportConfig['orientation']  = $INPUT->str('orientation', $this->getConf('orientation'), true);
581
582        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'), true);
583        $levels = array();
584        if($hasToC) {
585            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
586            list($top_input, $max_input) = explode('-', $toclevels, 2);
587            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
588            $bounds_input = array(
589                'top' => array(
590                    (int) $top_input,
591                    (int) $top_conf
592                ),
593                'max' => array(
594                    (int) $max_input,
595                    (int) $max_conf
596                )
597            );
598            $bounds = array(
599                'top' => $conf['toptoclevel'],
600                'max' => $conf['maxtoclevel']
601
602            );
603            foreach($bounds_input as $bound => $values) {
604                foreach($values as $value) {
605                    if($value > 0 && $value <= 5) {
606                        //stop at valid value and store
607                        $bounds[$bound] = $value;
608                        break;
609                    }
610                }
611            }
612
613            if($bounds['max'] < $bounds['top']) {
614                $bounds['max'] = $bounds['top'];
615            }
616
617            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
618                $levels["H$level"] = $level - 1;
619            }
620        }
621        $this->exportConfig['hasToC'] = $hasToC;
622        $this->exportConfig['levels'] = $levels;
623
624        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
625
626        $tplconf = $this->getConf('template');
627        $tpl = $INPUT->str('template', $tplconf, true);
628        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
629            $tpl = $tplconf;
630        }
631        if(!$tpl){
632            $tpl = 'default';
633        }
634        $this->exportConfig['template'] = $tpl;
635
636        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
637    }
638
639    /**
640     * Returns requested config
641     *
642     * @param string $name
643     * @param mixed  $notset
644     * @return mixed|bool
645     */
646    public function getExportConfig($name, $notset = false) {
647        if ($this->exportConfig === null){
648            $this->loadExportConfig();
649        }
650
651        if(isset($this->exportConfig[$name])){
652            return $this->exportConfig[$name];
653        }else{
654            return $notset;
655        }
656    }
657}
658