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