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