xref: /plugin/dw2pdf/action.php (revision baa31dc580708adcd82be88cf936e5ceb9a15277)
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'] .= '<pagebreak />';
499        }
500
501        // cover page
502        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
503        if(file_exists($backfile)) {
504            $output['back'] = '<pagebreak />';
505            $output['back'] .= file_get_contents($backfile);
506            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
507        }
508
509        // citation box
510        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
511        if(file_exists($citationfile)) {
512            $output['cite'] = file_get_contents($citationfile);
513            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
514        }
515
516        return $output;
517    }
518
519    /**
520     * @param string $raw code with placeholders
521     * @param string $id  pageid
522     * @return string
523     */
524    protected function page_depend_replacements($raw, $id) {
525        global $REV;
526
527        // generate qr code for this page using google infographics api
528        $qr_code = '';
529        if($this->getConf('qrcodesize')) {
530            $url = urlencode(wl($id, '', '&', true));
531            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
532                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
533        }
534        // prepare replacements
535        $replace['@ID@']      = $id;
536        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
537        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&");
538        $replace['@QRCODE@']  = $qr_code;
539
540        $content = str_replace(array_keys($replace), array_values($replace), $raw);
541
542        // @DATE(<date>[, <format>])@
543        $content = preg_replace_callback(
544            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
545            array($this, 'replacedate'),
546            $content
547        );
548
549        return $content;
550    }
551
552
553    /**
554     * (callback) Replace date by request datestring
555     * e.g. '%m(30-11-1975)' is replaced by '11'
556     *
557     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
558     * @return string
559     */
560    function replacedate($match) {
561        global $conf;
562        //no 2nd argument for default date format
563        if($match[2] == null) {
564            $match[2] = $conf['dformat'];
565        }
566        return strftime($match[2], strtotime($match[1]));
567    }
568
569
570    /**
571     * Load all the style sheets and apply the needed replacements
572     */
573    protected function load_css() {
574        global $conf;
575        //reusue the CSS dispatcher functions without triggering the main function
576        define('SIMPLE_TEST', 1);
577        require_once(DOKU_INC . 'lib/exe/css.php');
578
579        // prepare CSS files
580        $files = array_merge(
581            array(
582                DOKU_INC . 'lib/styles/screen.css'
583                    => DOKU_BASE . 'lib/styles/',
584                DOKU_INC . 'lib/styles/print.css'
585                    => DOKU_BASE . 'lib/styles/',
586            ),
587            css_pluginstyles('all'),
588            $this->css_pluginPDFstyles(),
589            array(
590                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
591                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
592                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
593                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
594                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
595                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
596            )
597        );
598        $css = '';
599        foreach($files as $file => $location) {
600            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
601            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
602            $css .= css_loadfile($file, $location);
603        }
604
605        if(function_exists('css_parseless')) {
606            // apply pattern replacements
607            $styleini = css_styleini($conf['template']);
608            $css = css_applystyle($css, $styleini['replacements']);
609
610            // parse less
611            $css = css_parseless($css);
612        } else {
613            // @deprecated 2013-12-19: fix backward compatibility
614            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
615        }
616
617        return $css;
618    }
619
620    /**
621     * Returns a list of possible Plugin PDF Styles
622     *
623     * Checks for a pdf.css, falls back to print.css
624     *
625     * @author Andreas Gohr <andi@splitbrain.org>
626     */
627    protected function css_pluginPDFstyles() {
628        $list = array();
629        $plugins = plugin_list();
630
631        $usestyle = explode(',', $this->getConf('usestyles'));
632        foreach($plugins as $p) {
633            if(in_array($p, $usestyle)) {
634                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
635                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
636            }
637
638            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
639                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
640            } else {
641                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
642            }
643        }
644        return $list;
645    }
646
647    /**
648     * Returns array of pages which will be included in the exported pdf
649     *
650     * @return array
651     */
652    public function getExportedPages() {
653        return $this->list;
654    }
655
656    /**
657     * usort callback to sort by file lastmodified time
658     *
659     * @param array $a
660     * @param array $b
661     * @return int
662     */
663    public function _datesort($a, $b) {
664        if($b['rev'] < $a['rev']) return -1;
665        if($b['rev'] > $a['rev']) return 1;
666        return strcmp($b['id'], $a['id']);
667    }
668
669    /**
670     * usort callback to sort by page id
671     * @param array $a
672     * @param array $b
673     * @return int
674     */
675    public function _pagenamesort($a, $b) {
676        if($a['id'] <= $b['id']) return -1;
677        if($a['id'] > $b['id']) return 1;
678        return 0;
679    }
680
681    /**
682     * Return settings read from:
683     *   1. url parameters
684     *   2. plugin config
685     *   3. global config
686     *
687     * @return array
688     */
689    protected function loadExportConfig() {
690        global $INPUT;
691        global $conf;
692
693        $this->exportConfig = array();
694
695        // decide on the paper setup from param or config
696        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
697        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
698
699        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
700        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
701
702        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
703        $levels = array();
704        if($hasToC) {
705            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
706            list($top_input, $max_input) = explode('-', $toclevels, 2);
707            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
708            $bounds_input = array(
709                'top' => array(
710                    (int) $top_input,
711                    (int) $top_conf
712                ),
713                'max' => array(
714                    (int) $max_input,
715                    (int) $max_conf
716                )
717            );
718            $bounds = array(
719                'top' => $conf['toptoclevel'],
720                'max' => $conf['maxtoclevel']
721
722            );
723            foreach($bounds_input as $bound => $values) {
724                foreach($values as $value) {
725                    if($value > 0 && $value <= 5) {
726                        //stop at valid value and store
727                        $bounds[$bound] = $value;
728                        break;
729                    }
730                }
731            }
732
733            if($bounds['max'] < $bounds['top']) {
734                $bounds['max'] = $bounds['top'];
735            }
736
737            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
738                $levels["H$level"] = $level - 1;
739            }
740        }
741        $this->exportConfig['hasToC'] = $hasToC;
742        $this->exportConfig['levels'] = $levels;
743
744        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
745
746        $tplconf = $this->getConf('template');
747        $tpl = $INPUT->str('tpl', $tplconf, true);
748        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
749            $tpl = $tplconf;
750        }
751        if(!$tpl){
752            $tpl = 'default';
753        }
754        $this->exportConfig['template'] = $tpl;
755
756        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
757    }
758
759    /**
760     * Returns requested config
761     *
762     * @param string $name
763     * @param mixed  $notset
764     * @return mixed|bool
765     */
766    public function getExportConfig($name, $notset = false) {
767        if ($this->exportConfig === null){
768            $this->loadExportConfig();
769        }
770
771        if(isset($this->exportConfig[$name])){
772            return $this->exportConfig[$name];
773        }else{
774            return $notset;
775        }
776    }
777
778    /**
779     * Add 'export pdf'-button to pagetools
780     *
781     * @param Doku_Event $event
782     */
783    public function addbutton(Doku_Event $event) {
784        global $ID, $REV;
785
786        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
787            $params = array('do' => 'export_pdf');
788            if($REV) {
789                $params['rev'] = $REV;
790            }
791
792            // insert button at position before last (up to top)
793            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
794                array('export_pdf' =>
795                          '<li>'
796                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
797                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
798                          . '</a>'
799                          . '</li>'
800                ) +
801                array_slice($event->data['items'], -1, 1, true);
802        }
803    }
804}
805