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