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