xref: /plugin/dw2pdf/action.php (revision 269f7bbd74179db3949542ea6864be02fed352d0)
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        $template['cover'] = $this->page_depend_replacements($template['cover'], $ID);
329        $body_start .= $template['cover'];
330
331        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
332        if($isDebug) {
333            $html .= $body_start;
334        }
335        if($hasToC) {
336            //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
337            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
338            //      - there is no page numbering at the pages of the ToC
339            $mpdf->TOCpagebreakByArray(
340                array(
341                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
342                    'toc-bookmarkText' => $this->getLang('tocheader'),
343                    'links' => true,
344                    'outdent' => '1em',
345                    'resetpagenum' => true, //start pagenumbering after ToC
346                    'pagenumstyle' => '1'
347                )
348            );
349            $html .= '<tocpagebreak>';
350        }
351
352        // store original pageid
353        $keep = $ID;
354
355        // loop over all pages
356        $cnt = count($this->list);
357        for($n = 0; $n < $cnt; $n++) {
358            $page = $this->list[$n];
359
360            // set global pageid to the rendered page
361            $ID = $page;
362
363            $pagehtml = p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page);
364            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
365            if($n < ($cnt - 1)) {
366                $pagehtml .= '<pagebreak />';
367            }
368
369            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
370            if($isDebug) {
371                $html .= $pagehtml;
372            }
373        }
374        //restore ID
375        $ID = $keep;
376
377        // insert the back page
378        $body_end = $template['back'];
379
380        $body_end .= '</div>';
381
382        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
383        if($isDebug) {
384            $html .= $body_end;
385            $html .= '</body>';
386            $html .= '</html>';
387        }
388
389        //Return html for debugging
390        if($isDebug) {
391            if($INPUT->str('debughtml', 'text', true) == 'html') {
392                echo $html;
393            } else {
394                header('Content-Type: text/plain; charset=utf-8');
395                echo $html;
396            }
397            exit();
398        };
399
400        // write to cache file
401        $mpdf->Output($cachefile, 'F');
402    }
403
404    /**
405     * @param string $cachefile
406     * @param string $title
407     */
408    protected function sendPDFFile($cachefile, $title) {
409        header('Content-Type: application/pdf');
410        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
411        header('Pragma: public');
412        http_conditionalRequest(filemtime($cachefile));
413
414        $filename = rawurlencode(cleanID(strtr($title, ':/;"', '    ')));
415        if($this->getConf('output') == 'file') {
416            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
417        } else {
418            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
419        }
420
421        //try to send file, and exit if done
422        http_sendfile($cachefile);
423
424        $fp = @fopen($cachefile, "rb");
425        if($fp) {
426            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
427        } else {
428            header("HTTP/1.0 500 Internal Server Error");
429            print "Could not read file - bad permissions?";
430        }
431        exit();
432    }
433
434    /**
435     * Load the various template files and prepare the HTML/CSS for insertion
436     *
437     * @param string $title
438     * @return array
439     */
440    protected function load_template($title) {
441        global $ID;
442        global $conf;
443
444        // this is what we'll return
445        $output = array(
446            'cover' => '',
447            'html'  => '',
448            'page'  => '',
449            'first' => '',
450            'cite'  => '',
451        );
452
453        // prepare header/footer elements
454        $html = '';
455        foreach(array('header', 'footer') as $section) {
456            foreach(array('', '_odd', '_even', '_first') as $order) {
457                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
458                if(file_exists($file)) {
459                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
460                    $html .= file_get_contents($file) . DOKU_LF;
461                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
462
463                    // register the needed pseudo CSS
464                    if($order == '_first') {
465                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
466                    } elseif($order == '_even') {
467                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
468                    } elseif($order == '_odd') {
469                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
470                    } else {
471                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
472                    }
473                }
474            }
475        }
476
477        // prepare replacements
478        $replace = array(
479            '@PAGE@'    => '{PAGENO}',
480            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
481            '@TITLE@'   => hsc($title),
482            '@WIKI@'    => $conf['title'],
483            '@WIKIURL@' => DOKU_URL,
484            '@DATE@'    => dformat(time()),
485            '@BASE@'    => DOKU_BASE,
486            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
487        );
488
489        // set HTML element
490        $html = str_replace(array_keys($replace), array_values($replace), $html);
491        //TODO For bookcreator $ID (= bookmanager page) makes no sense
492        $output['html'] = $this->page_depend_replacements($html, $ID);
493
494        // cover page
495        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
496        if(file_exists($coverfile)) {
497            $output['cover'] = file_get_contents($coverfile);
498            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
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        }
509
510        // citation box
511        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
512        if(file_exists($citationfile)) {
513            $output['cite'] = file_get_contents($citationfile);
514            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
515        }
516
517        return $output;
518    }
519
520    /**
521     * @param string $raw code with placeholders
522     * @param string $id  pageid
523     * @return string
524     */
525    protected function page_depend_replacements($raw, $id) {
526        global $REV;
527
528        // generate qr code for this page using google infographics api
529        $qr_code = '';
530        if($this->getConf('qrcodesize')) {
531            $url = urlencode(wl($id, '', '&', true));
532            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
533                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
534        }
535        // prepare replacements
536        $replace['@ID@']      = $id;
537        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
538        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&");
539        $replace['@QRCODE@']  = $qr_code;
540
541        $content = str_replace(array_keys($replace), array_values($replace), $raw);
542
543        // @DATE(<date>[, <format>])@
544        $content = preg_replace_callback(
545            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
546            array($this, 'replacedate'),
547            $content
548        );
549
550        return $content;
551    }
552
553
554    /**
555     * (callback) Replace date by request datestring
556     * e.g. '%m(30-11-1975)' is replaced by '11'
557     *
558     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
559     * @return string
560     */
561    function replacedate($match) {
562        global $conf;
563        //no 2nd argument for default date format
564        if($match[2] == null) {
565            $match[2] = $conf['dformat'];
566        }
567        return strftime($match[2], strtotime($match[1]));
568    }
569
570
571    /**
572     * Load all the style sheets and apply the needed replacements
573     */
574    protected function load_css() {
575        global $conf;
576        //reusue the CSS dispatcher functions without triggering the main function
577        define('SIMPLE_TEST', 1);
578        require_once(DOKU_INC . 'lib/exe/css.php');
579
580        // prepare CSS files
581        $files = array_merge(
582            array(
583                DOKU_INC . 'lib/styles/screen.css'
584                    => DOKU_BASE . 'lib/styles/',
585                DOKU_INC . 'lib/styles/print.css'
586                    => DOKU_BASE . 'lib/styles/',
587            ),
588            css_pluginstyles('all'),
589            $this->css_pluginPDFstyles(),
590            array(
591                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
592                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
593                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
594                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
595                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
596                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
597            )
598        );
599        $css = '';
600        foreach($files as $file => $location) {
601            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
602            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
603            $css .= css_loadfile($file, $location);
604        }
605
606        if(function_exists('css_parseless')) {
607            // apply pattern replacements
608            $styleini = css_styleini($conf['template']);
609            $css = css_applystyle($css, $styleini['replacements']);
610
611            // parse less
612            $css = css_parseless($css);
613        } else {
614            // @deprecated 2013-12-19: fix backward compatibility
615            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
616        }
617
618        return $css;
619    }
620
621    /**
622     * Returns a list of possible Plugin PDF Styles
623     *
624     * Checks for a pdf.css, falls back to print.css
625     *
626     * @author Andreas Gohr <andi@splitbrain.org>
627     */
628    protected function css_pluginPDFstyles() {
629        $list = array();
630        $plugins = plugin_list();
631
632        $usestyle = explode(',', $this->getConf('usestyles'));
633        foreach($plugins as $p) {
634            if(in_array($p, $usestyle)) {
635                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
636                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
637            }
638
639            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
640                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
641            } else {
642                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
643            }
644        }
645        return $list;
646    }
647
648    /**
649     * Returns array of pages which will be included in the exported pdf
650     *
651     * @return array
652     */
653    public function getExportedPages() {
654        return $this->list;
655    }
656
657    /**
658     * usort callback to sort by file lastmodified time
659     *
660     * @param array $a
661     * @param array $b
662     * @return int
663     */
664    public function _datesort($a, $b) {
665        if($b['rev'] < $a['rev']) return -1;
666        if($b['rev'] > $a['rev']) return 1;
667        return strcmp($b['id'], $a['id']);
668    }
669
670    /**
671     * usort callback to sort by page id
672     * @param array $a
673     * @param array $b
674     * @return int
675     */
676    public function _pagenamesort($a, $b) {
677        if($a['id'] <= $b['id']) return -1;
678        if($a['id'] > $b['id']) return 1;
679        return 0;
680    }
681
682    /**
683     * Return settings read from:
684     *   1. url parameters
685     *   2. plugin config
686     *   3. global config
687     *
688     * @return array
689     */
690    protected function loadExportConfig() {
691        global $INPUT;
692        global $conf;
693
694        $this->exportConfig = array();
695
696        // decide on the paper setup from param or config
697        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
698        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
699
700        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
701        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
702
703        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
704        $levels = array();
705        if($hasToC) {
706            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
707            list($top_input, $max_input) = explode('-', $toclevels, 2);
708            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
709            $bounds_input = array(
710                'top' => array(
711                    (int) $top_input,
712                    (int) $top_conf
713                ),
714                'max' => array(
715                    (int) $max_input,
716                    (int) $max_conf
717                )
718            );
719            $bounds = array(
720                'top' => $conf['toptoclevel'],
721                'max' => $conf['maxtoclevel']
722
723            );
724            foreach($bounds_input as $bound => $values) {
725                foreach($values as $value) {
726                    if($value > 0 && $value <= 5) {
727                        //stop at valid value and store
728                        $bounds[$bound] = $value;
729                        break;
730                    }
731                }
732            }
733
734            if($bounds['max'] < $bounds['top']) {
735                $bounds['max'] = $bounds['top'];
736            }
737
738            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
739                $levels["H$level"] = $level - 1;
740            }
741        }
742        $this->exportConfig['hasToC'] = $hasToC;
743        $this->exportConfig['levels'] = $levels;
744
745        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
746
747        $tplconf = $this->getConf('template');
748        $tpl = $INPUT->str('tpl', $tplconf, true);
749        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
750            $tpl = $tplconf;
751        }
752        if(!$tpl){
753            $tpl = 'default';
754        }
755        $this->exportConfig['template'] = $tpl;
756
757        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
758    }
759
760    /**
761     * Returns requested config
762     *
763     * @param string $name
764     * @param mixed  $notset
765     * @return mixed|bool
766     */
767    public function getExportConfig($name, $notset = false) {
768        if ($this->exportConfig === null){
769            $this->loadExportConfig();
770        }
771
772        if(isset($this->exportConfig[$name])){
773            return $this->exportConfig[$name];
774        }else{
775            return $notset;
776        }
777    }
778
779    /**
780     * Add 'export pdf'-button to pagetools
781     *
782     * @param Doku_Event $event
783     */
784    public function addbutton(Doku_Event $event) {
785        global $ID, $REV;
786
787        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
788            $params = array('do' => 'export_pdf');
789            if($REV) {
790                $params['rev'] = $REV;
791            }
792
793            // insert button at position before last (up to top)
794            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
795                array('export_pdf' =>
796                          '<li>'
797                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
798                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
799                          . '</a>'
800                          . '</li>'
801                ) +
802                array_slice($event->data['items'], -1, 1, true);
803        }
804    }
805}
806