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