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