xref: /plugin/dw2pdf/action.php (revision 893987a24582311038ed9e719e73ecc819c486b5)
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 $ACT;
59        global $ID;
60
61        // our event?
62        if(($ACT != 'export_pdfbook') && ($ACT != 'export_pdf') && ($ACT != 'export_pdfns')) return false;
63
64        // check user's rights
65        if(auth_quickaclcheck($ID) < AUTH_READ) return false;
66
67        if($data = $this->collectExportPages($event)) {
68            list($this->title, $this->list) = $data;
69        } else {
70            return false;
71        }
72
73        // it's ours, no one else's
74        $event->preventDefault();
75
76        // prepare cache and its dependencies
77        $depends = array();
78        $cache = $this->prepareCache($depends);
79
80        // hard work only when no cache available or needed for debugging
81        if(!$this->getConf('usecache') || $this->getExportConfig('isDebug') || !$cache->useCache($depends)) {
82            // generating the pdf may take a long time for larger wikis / namespaces with many pages
83            set_time_limit(0);
84
85            $this->generatePDF($cache->cache);
86        }
87
88        // deliver the file
89        $this->sendPDFFile($cache->cache);
90        return true;
91    }
92
93
94    /**
95     * Obtain list of pages and title, based on url parameters
96     *
97     * @param Doku_Event $event
98     * @return string|bool
99     */
100    protected function collectExportPages(Doku_Event $event) {
101        global $ACT;
102        global $ID;
103        global $INPUT;
104        global $conf;
105
106        // list of one or multiple pages
107        $list = array();
108
109        if($ACT == 'export_pdf') {
110            $list[0] = $ID;
111            $this->title = $INPUT->str('pdftitle'); //DEPRECATED
112            $this->title = $INPUT->str('book_title', $this->title, true);
113            if(empty($this->title)) {
114                $this->title = p_get_first_heading($ID);
115            }
116
117        } elseif($ACT == 'export_pdfns') {
118            //check input for title and ns
119            if(!$this->title = $INPUT->str('book_title')) {
120                $this->showPageWithErrorMsg($event, 'needtitle');
121                return false;
122            }
123            $pdfnamespace = cleanID($INPUT->str('book_ns'));
124            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
125                $this->showPageWithErrorMsg($event, 'needns');
126                return false;
127            }
128
129            //sort order
130            $order = $INPUT->str('book_order', 'natural', true);
131            $sortoptions = array('pagename', 'date', 'natural');
132            if(!in_array($order, $sortoptions)) {
133                $order = 'natural';
134            }
135
136            //search depth
137            $depth = $INPUT->int('book_nsdepth', 0);
138            if($depth < 0) {
139                $depth = 0;
140            }
141
142            //page search
143            $result = array();
144            $opts = array('depth' => $depth); //recursive all levels
145            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
146            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
147
148            //sorting
149            if(count($result) > 0) {
150                if($order == 'date') {
151                    usort($result, array($this, '_datesort'));
152                } elseif($order == 'pagename') {
153                    usort($result, array($this, '_pagenamesort'));
154                }
155            }
156
157            foreach($result as $item) {
158                $list[] = $item['id'];
159            }
160
161            if ($pdfnamespace !== '') {
162                if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
163                    if (file_exists(wikiFN(rtrim($pdfnamespace,':')))) {
164                        array_unshift($list,rtrim($pdfnamespace,':'));
165                    }
166                }
167            }
168
169        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
170            /** @deprecated  April 2016 replaced by localStorage version of Bookcreator*/
171            //is in Bookmanager of bookcreator plugin a title given?
172            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
173            $this->title = $INPUT->str('book_title', $this->title, true);
174            if(empty($this->title)) {
175                $this->showPageWithErrorMsg($event, 'needtitle');
176                return false;
177            } else {
178                $list = explode("|", $_COOKIE['list-pagelist']);
179            }
180
181        } elseif($INPUT->has('selection')) {
182            //handle Bookcreator requests based at localStorage
183//            if(!checkSecurityToken()) {
184//                http_status(403);
185//                print $this->getLang('empty');
186//                exit();
187//            }
188
189            $json = new JSON(JSON_LOOSE_TYPE);
190            $list = $json->decode($INPUT->post->str('selection', '', true));
191            if(!is_array($list) || empty($list)) {
192                http_status(400);
193                print $this->getLang('empty');
194                exit();
195            }
196
197            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
198            $this->title = $INPUT->str('book_title', $this->title, true);
199            if(empty($this->title)) {
200                http_status(400);
201                print $this->getLang('needtitle');
202                exit();
203            }
204
205        } else {
206            //show empty bookcreator message
207            $this->showPageWithErrorMsg($event, 'empty');
208            return false;
209        }
210
211        $list = array_map('cleanID', $list);
212
213        $skippedpages = array();
214        foreach($list as $index => $pageid) {
215            if(auth_quickaclcheck($pageid) < AUTH_READ) {
216                $skippedpages[] = $pageid;
217                unset($list[$index]);
218            }
219        }
220        $list = array_filter($list); //removes also pages mentioned '0'
221
222        //if selection contains forbidden pages throw (overridable) warning
223        if(!$INPUT->bool('book_skipforbiddenpages') && !empty($skippedpages)) {
224            $msg = hsc(join(', ', $skippedpages));
225            if($INPUT->has('selection')) {
226                http_status(400);
227                print sprintf($this->getLang('forbidden'), $msg);
228                exit();
229            } else {
230                $this->showPageWithErrorMsg($event, 'forbidden', $msg);
231                return false;
232            }
233
234        }
235
236        return array($this->title, $list);
237    }
238
239    /**
240     * Prepare cache
241     *
242     * @param array  $depends (reference) array with dependencies
243     * @return cache
244     */
245    protected function prepareCache(&$depends) {
246        global $REV;
247
248        $cachekey = join(',', $this->list)
249            . $REV
250            . $this->getExportConfig('template')
251            . $this->getExportConfig('pagesize')
252            . $this->getExportConfig('orientation')
253            . $this->getExportConfig('font-size')
254            . $this->getExportConfig('doublesided')
255            . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0')
256            . $this->title;
257        $cache = new cache($cachekey, '.dw2.pdf');
258
259        $dependencies = array();
260        foreach($this->list as $pageid) {
261            $relations = p_get_metadata($pageid, 'relation');
262
263            if(is_array($relations)) {
264                if(array_key_exists('media', $relations) && is_array($relations['media'])) {
265                    foreach($relations['media'] as $mediaid => $exists) {
266                        if($exists) {
267                            $dependencies[] = mediaFN($mediaid);
268                        }
269                    }
270                }
271
272                if(array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
273                    foreach($relations['haspart'] as $part_pageid => $exists) {
274                        if($exists) {
275                            $dependencies[] = wikiFN($part_pageid);
276                        }
277                    }
278                }
279            }
280
281            $dependencies[] = metaFN($pageid, '.meta');
282        }
283
284        $depends['files'] = array_map('wikiFN', $this->list);
285        $depends['files'][] = __FILE__;
286        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
287        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
288        $depends['files'] = array_merge(
289            $depends['files'],
290            $dependencies,
291            getConfigFiles('main')
292        );
293        return $cache;
294    }
295
296    /**
297     * Set error notification and reload page again
298     *
299     * @param Doku_Event $event
300     * @param string $msglangkey key of translation key
301     * @param string $replacement
302     */
303    private function showPageWithErrorMsg(Doku_Event $event, $msglangkey, $replacement=null) {
304        if(empty($replacement)) {
305            $msg = $this->getLang($msglangkey);
306        } else {
307            $msg = sprintf($this->getLang($msglangkey), $replacement);
308        }
309        msg($msg, -1);
310
311        $event->data = 'show';
312        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
313    }
314
315    /**
316     * Build a pdf from the html
317     *
318     * @param string $cachefile
319     */
320    protected function generatePDF($cachefile) {
321        global $ID;
322        global $REV;
323        global $INPUT;
324
325        //some shortcuts to export settings
326        $hasToC = $this->getExportConfig('hasToC');
327        $levels = $this->getExportConfig('levels');
328        $isDebug = $this->getExportConfig('isDebug');
329
330        // initialize PDF library
331        require_once(dirname(__FILE__) . "/DokuPDF.class.php");
332
333        $mpdf = new DokuPDF($this->getExportConfig('pagesize'),
334                            $this->getExportConfig('orientation'),
335                            $this->getExportConfig('font-size'));
336
337        // let mpdf fix local links
338        $self = parse_url(DOKU_URL);
339        $url = $self['scheme'] . '://' . $self['host'];
340        if($self['port']) {
341            $url .= ':' . $self['port'];
342        }
343        $mpdf->setBasePath($url);
344
345        // Set the title
346        $mpdf->SetTitle($this->title);
347
348        // some default document settings
349        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
350        //      single-side document has only odd pages
351        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
352        $mpdf->setAutoTopMargin = 'stretch';
353        $mpdf->setAutoBottomMargin = 'stretch';
354//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
355        if($hasToC) {
356            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off'); //use italic pageno until ToC
357            $mpdf->h2toc = $levels;
358        } else {
359            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
360        }
361
362        // load the template
363        $template = $this->load_template();
364
365        // prepare HTML header styles
366        $html = '';
367        if($isDebug) {
368            $html .= '<html><head>';
369            $html .= '<style type="text/css">';
370        }
371
372        $styles = '@page { size:auto; ' . $template['page'] . '}';
373        $styles .= '@page :first {' . $template['first'] . '}';
374
375        $styles .= '@page landscape-page { size:landscape }';
376        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
377        $styles .= '@page portrait-page { size:portrait }';
378        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
379        $styles .= $this->load_css();
380
381        $mpdf->WriteHTML($styles, 1);
382
383        if($isDebug) {
384            $html .= $styles;
385            $html .= '</style>';
386            $html .= '</head><body>';
387        }
388
389        $body_start = $template['html'];
390        $body_start .= '<div class="dokuwiki">';
391
392        // insert the cover page
393        $body_start .= $template['cover'];
394
395        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
396        if($isDebug) {
397            $html .= $body_start;
398        }
399        if($hasToC) {
400            //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
401            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
402            //      - there is no page numbering at the pages of the ToC
403            $mpdf->TOCpagebreakByArray(
404                array(
405                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
406                    'toc-bookmarkText' => $this->getLang('tocheader'),
407                    'links' => true,
408                    'outdent' => '1em',
409                    'resetpagenum' => true, //start pagenumbering after ToC
410                    'pagenumstyle' => '1'
411                )
412            );
413            $html .= '<tocpagebreak>';
414        }
415
416        // store original pageid
417        $keep = $ID;
418
419        // loop over all pages
420        $counter = 0;
421        $no_pages = count($this->list);
422        foreach($this->list as $page) {
423            $counter++;
424            $filename = wikiFN($page, $REV);
425
426            if(!file_exists($filename)) {
427                continue;
428            }
429
430            // set global pageid to the rendered page
431            $ID = $page;
432
433            $pagehtml = p_cached_output($filename, 'dw2pdf', $page);
434            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
435            if($counter < $no_pages) {
436                $pagehtml .= '<pagebreak />';
437            }
438
439            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
440            if($isDebug) {
441                $html .= $pagehtml;
442            }
443        }
444        //restore ID
445        $ID = $keep;
446
447        // insert the back page
448        $body_end = $template['back'];
449
450        $body_end .= '</div>';
451
452        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
453        if($isDebug) {
454            $html .= $body_end;
455            $html .= '</body>';
456            $html .= '</html>';
457        }
458
459        //Return html for debugging
460        if($isDebug) {
461            if($INPUT->str('debughtml', 'text', true) == 'html') {
462                echo $html;
463            } else {
464                header('Content-Type: text/plain; charset=utf-8');
465                echo $html;
466            }
467            exit();
468        };
469
470        // write to cache file
471        $mpdf->Output($cachefile, 'F');
472    }
473
474    /**
475     * @param string $cachefile
476     */
477    protected function sendPDFFile($cachefile) {
478        header('Content-Type: application/pdf');
479        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
480        header('Pragma: public');
481        http_conditionalRequest(filemtime($cachefile));
482
483        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
484        if($this->getConf('output') == '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