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