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