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