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