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