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