xref: /plugin/dw2pdf/action.php (revision 260742f7c33a19da6937686d35ed04487ac1356e)
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 $list = array();
28
29    /**
30     * Constructor. Sets the correct template
31     */
32    public function __construct() {
33        $this->tpl = $this->getExportConfig('template');
34    }
35
36    /**
37     * Register the events
38     *
39     * @param Doku_Event_Handler $controller
40     */
41    public function register(Doku_Event_Handler $controller) {
42        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
43        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
44    }
45
46    /**
47     * Do the HTML to PDF conversion work
48     *
49     * @param Doku_Event $event
50     * @return bool
51     */
52    public function convert(Doku_Event $event) {
53        global $ACT;
54        global $ID;
55
56        // our event?
57        if(($ACT != 'export_pdfbook') && ($ACT != 'export_pdf') && ($ACT != 'export_pdfns')) return false;
58
59        // check user's rights
60        if(auth_quickaclcheck($ID) < AUTH_READ) return false;
61
62        if($data = $this->collectExportPages($event)) {
63            list($title, $this->list) = $data;
64        } else {
65            return false;
66        }
67
68        // it's ours, no one else's
69        $event->preventDefault();
70
71        // prepare cache and its dependencies
72        $depends = array();
73        $cache = $this->prepareCache($title, $depends);
74
75        // hard work only when no cache available
76        if(!$this->getConf('usecache') || $this->getExportConfig('isDebug') || !$cache->useCache($depends)) {
77            // generating the pdf may take a long time for larger wikis / namespaces with many pages
78            set_time_limit(0);
79
80            $this->generatePDF($cache->cache, $title);
81        }
82
83        // deliver the file
84        $this->sendPDFFile($cache->cache, $title);
85        return true;
86    }
87
88
89    /**
90     * Obtain list of pages and title, based on url parameters
91     *
92     * @param Doku_Event $event
93     * @return string|bool
94     */
95    protected function collectExportPages(Doku_Event $event) {
96        global $ACT;
97        global $ID;
98        global $INPUT;
99        global $conf;
100
101        // list of one or multiple pages
102        $list = array();
103
104        if($ACT == 'export_pdf') {
105            $list[0] = $ID;
106            $title = $INPUT->str('pdftitle'); //DEPRECATED
107            $title = $INPUT->str('book_title', $title, true);
108            if(empty($title)) {
109                $title = p_get_first_heading($ID);
110            }
111
112        } elseif($ACT == 'export_pdfns') {
113            //check input for title and ns
114            if(!$title = $INPUT->str('book_title')) {
115                $this->showPageWithErrorMsg($event, 'needtitle');
116                return false;
117            }
118            $pdfnamespace = cleanID($INPUT->str('book_ns'));
119            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
120                $this->showPageWithErrorMsg($event, 'needns');
121                return false;
122            }
123
124            //sort order
125            $order = $INPUT->str('book_order', 'natural', true);
126            $sortoptions = array('pagename', 'date', 'natural');
127            if(!in_array($order, $sortoptions)) {
128                $order = 'natural';
129            }
130
131            //search depth
132            $depth = $INPUT->int('book_nsdepth', 0);
133            if($depth < 0) {
134                $depth = 0;
135            }
136
137            //page search
138            $result = array();
139            $opts = array('depth' => $depth); //recursive all levels
140            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
141            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
142
143            //sorting
144            if(count($result) > 0) {
145                if($order == 'date') {
146                    usort($result, array($this, '_datesort'));
147                } elseif($order == 'pagename') {
148                    usort($result, array($this, '_pagenamesort'));
149                }
150            }
151
152            foreach($result as $item) {
153                $list[] = $item['id'];
154            }
155
156            if ($pdfnamespace !== '') {
157                if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
158                    if (file_exists(wikiFN(rtrim($pdfnamespace,':')))) {
159                        array_unshift($list,rtrim($pdfnamespace,':'));
160                    }
161                }
162            }
163
164        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
165            /** @deprecated  April 2016 replaced by localStorage version of Bookcreator*/
166            //is in Bookmanager of bookcreator plugin a title given?
167            $title = $INPUT->str('pdfbook_title'); //DEPRECATED
168            $title = $INPUT->str('book_title', $title, true);
169            if(empty($title)) {
170                $this->showPageWithErrorMsg($event, 'needtitle');
171                return false;
172            } else {
173                $list = explode("|", $_COOKIE['list-pagelist']);
174            }
175
176        } elseif($INPUT->has('selection')) {
177            //handle Bookcreator requests based at localStorage
178//            if(!checkSecurityToken()) {
179//                http_status(403);
180//                print $this->getLang('empty');
181//                exit();
182//            }
183
184            $json = new JSON(JSON_LOOSE_TYPE);
185            $list = $json->decode($INPUT->post->str('selection', '', true));
186            if(!is_array($list) || empty($list)) {
187                http_status(400);
188                print $this->getLang('empty');
189                exit();
190            }
191
192            $title = $INPUT->str('pdfbook_title'); //DEPRECATED
193            $title = $INPUT->str('book_title', $title, true);
194            if(empty($title)) {
195                http_status(400);
196                print $this->getLang('needtitle');
197                exit();
198            }
199
200        } else {
201            //show empty bookcreator message
202            $this->showPageWithErrorMsg($event, 'empty');
203            return false;
204        }
205
206        $list = array_map('cleanID', $list);
207
208        $skippedpages = array();
209        foreach($list as $index => $pageid) {
210            if(auth_quickaclcheck($pageid) < AUTH_READ) {
211                $skippedpages[] = $pageid;
212                unset($list[$index]);
213            }
214        }
215        $list = array_filter($list); //removes also pages mentioned '0'
216
217        //if selection contains forbidden pages throw (overridable) warning
218        if(!$INPUT->bool('book_skipforbiddenpages') && !empty($skippedpages)) {
219            $msg = hsc(join(', ', $skippedpages));
220            if($INPUT->has('selection')) {
221                http_status(400);
222                print sprintf($this->getLang('forbidden'), $msg);
223                exit();
224            } else {
225                $this->showPageWithErrorMsg($event, 'forbidden', $msg);
226                return false;
227            }
228
229        }
230
231        return array($title, $list);
232    }
233
234    /**
235     * Prepare cache
236     *
237     * @param string $title
238     * @param array  $depends (reference) array with dependencies
239     * @return cache
240     */
241    protected function prepareCache($title, &$depends) {
242        global $REV;
243
244        $cachekey = join(',', $this->list)
245            . $REV
246            . $this->getExportConfig('template')
247            . $this->getExportConfig('pagesize')
248            . $this->getExportConfig('orientation')
249            . $this->getExportConfig('font-size')
250            . $this->getExportConfig('doublesided')
251            . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0')
252            . $title;
253        $cache = new cache($cachekey, '.dw2.pdf');
254
255        $dependencies = array();
256        foreach($this->list as $pageid) {
257            $relations = p_get_metadata($pageid, 'relation');
258
259            if(is_array($relations)) {
260                if(array_key_exists('media', $relations) && is_array($relations['media'])) {
261                    foreach($relations['media'] as $mediaid => $exists) {
262                        if($exists) {
263                            $dependencies[] = mediaFN($mediaid);
264                        }
265                    }
266                }
267
268                if(array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
269                    foreach($relations['haspart'] as $part_pageid => $exists) {
270                        if($exists) {
271                            $dependencies[] = wikiFN($part_pageid);
272                        }
273                    }
274                }
275            }
276
277            $dependencies[] = metaFN($pageid, '.meta');
278        }
279
280        $depends['files'] = array_map('wikiFN', $this->list);
281        $depends['files'][] = __FILE__;
282        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
283        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
284        $depends['files'] = array_merge(
285            $depends['files'],
286            $dependencies,
287            getConfigFiles('main')
288        );
289        return $cache;
290    }
291
292    /**
293     * Set error notification and reload page again
294     *
295     * @param Doku_Event $event
296     * @param string $msglangkey key of translation key
297     * @param string $replacement
298     */
299    private function showPageWithErrorMsg(Doku_Event $event, $msglangkey, $replacement=null) {
300        if(empty($replacement)) {
301            $msg = $this->getLang($msglangkey);
302        } else {
303            $msg = sprintf($this->getLang($msglangkey), $replacement);
304        }
305        msg($msg, -1);
306
307        $event->data = 'show';
308        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
309    }
310
311    /**
312     * Build a pdf from the html
313     *
314     * @param string $cachefile
315     * @param string $title
316     */
317    protected function generatePDF($cachefile, $title) {
318        global $ID;
319        global $REV;
320        global $INPUT;
321
322        //some shortcuts to export settings
323        $hasToC = $this->getExportConfig('hasToC');
324        $levels = $this->getExportConfig('levels');
325        $isDebug = $this->getExportConfig('isDebug');
326
327        // initialize PDF library
328        require_once(dirname(__FILE__) . "/DokuPDF.class.php");
329
330        $mpdf = new DokuPDF($this->getExportConfig('pagesize'),
331                            $this->getExportConfig('orientation'),
332                            $this->getExportConfig('font-size'));
333
334        // let mpdf fix local links
335        $self = parse_url(DOKU_URL);
336        $url = $self['scheme'] . '://' . $self['host'];
337        if($self['port']) {
338            $url .= ':' . $self['port'];
339        }
340        $mpdf->setBasePath($url);
341
342        // Set the title
343        $mpdf->SetTitle($title);
344
345        // some default document settings
346        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
347        //      single-side document has only odd pages
348        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
349        $mpdf->setAutoTopMargin = 'stretch';
350        $mpdf->setAutoBottomMargin = 'stretch';
351//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
352        if($hasToC) {
353            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off'); //use italic pageno until ToC
354            $mpdf->h2toc = $levels;
355        } else {
356            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
357        }
358
359        // load the template
360        $template = $this->load_template($title);
361
362        // prepare HTML header styles
363        $html = '';
364        if($isDebug) {
365            $html .= '<html><head>';
366            $html .= '<style type="text/css">';
367        }
368        $styles = $this->load_css();
369        $styles .= '@page { size:auto; ' . $template['page'] . '}';
370        $styles .= '@page :first {' . $template['first'] . '}';
371
372        $styles .= '@page landscape-page { size:landscape }';
373        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
374        $styles .= '@page portrait-page { size:portrait }';
375        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
376
377        $mpdf->WriteHTML($styles, 1);
378
379        if($isDebug) {
380            $html .= $styles;
381            $html .= '</style>';
382            $html .= '</head><body>';
383        }
384
385        $body_start = $template['html'];
386        $body_start .= '<div class="dokuwiki">';
387
388        // insert the cover page
389        $body_start .= $template['cover'];
390
391        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
392        if($isDebug) {
393            $html .= $body_start;
394        }
395        if($hasToC) {
396            //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
397            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
398            //      - there is no page numbering at the pages of the ToC
399            $mpdf->TOCpagebreakByArray(
400                array(
401                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
402                    'toc-bookmarkText' => $this->getLang('tocheader'),
403                    'links' => true,
404                    'outdent' => '1em',
405                    'resetpagenum' => true, //start pagenumbering after ToC
406                    'pagenumstyle' => '1'
407                )
408            );
409            $html .= '<tocpagebreak>';
410        }
411
412        // store original pageid
413        $keep = $ID;
414
415        // loop over all pages
416        $counter = 0;
417        $no_pages = count($this->list);
418        foreach($this->list as $page) {
419            $counter++;
420            $filename = wikiFN($page, $REV);
421
422            if(!file_exists($filename)) {
423                continue;
424            }
425
426            // set global pageid to the rendered page
427            $ID = $page;
428
429            $pagehtml = p_cached_output($filename, 'dw2pdf', $page);
430            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
431            if($counter < $no_pages) {
432                $pagehtml .= '<pagebreak />';
433            }
434
435            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
436            if($isDebug) {
437                $html .= $pagehtml;
438            }
439        }
440        //restore ID
441        $ID = $keep;
442
443        // insert the back page
444        $body_end = $template['back'];
445
446        $body_end .= '</div>';
447
448        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
449        if($isDebug) {
450            $html .= $body_end;
451            $html .= '</body>';
452            $html .= '</html>';
453        }
454
455        //Return html for debugging
456        if($isDebug) {
457            if($INPUT->str('debughtml', 'text', true) == 'html') {
458                echo $html;
459            } else {
460                header('Content-Type: text/plain; charset=utf-8');
461                echo $html;
462            }
463            exit();
464        };
465
466        // write to cache file
467        $mpdf->Output($cachefile, 'F');
468    }
469
470    /**
471     * @param string $cachefile
472     * @param string $title
473     */
474    protected function sendPDFFile($cachefile, $title) {
475        header('Content-Type: application/pdf');
476        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
477        header('Pragma: public');
478        http_conditionalRequest(filemtime($cachefile));
479
480        $filename = rawurlencode(cleanID(strtr($title, ':/;"', '    ')));
481        if($this->getConf('output') == 'file') {
482            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
483        } else {
484            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
485        }
486
487        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
488        header('Set-Cookie: fileDownload=true; path=/');
489
490        //try to send file, and exit if done
491        http_sendfile($cachefile);
492
493        $fp = @fopen($cachefile, "rb");
494        if($fp) {
495            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
496        } else {
497            header("HTTP/1.0 500 Internal Server Error");
498            print "Could not read file - bad permissions?";
499        }
500        exit();
501    }
502
503    /**
504     * Load the various template files and prepare the HTML/CSS for insertion
505     *
506     * @param string $title
507     * @return array
508     */
509    protected function load_template($title) {
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($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