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