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