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