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