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