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