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