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