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