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