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