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