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