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