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