xref: /plugin/dw2pdf/action.php (revision f46889d73edbcef464d4d93f4319a891e53f946b)
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        // store original pageid
474        $keep = $ID;
475
476        // loop over all pages
477        $counter = 0;
478        $no_pages = count($this->list);
479        foreach($this->list as $page) {
480            $counter++;
481
482            // set global pageid to the rendered page
483            $ID = $page;
484
485            //$pagehtml = p_cached_output($filename, 'dw2pdf', $page);
486            $pagehtml = $this->p_wiki_dw2pdf($ID, $rev, $date_at);
487            //file doesn't exists
488            if($pagehtml == '') {
489                continue;
490            }
491            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
492            if($counter < $no_pages) {
493                $pagehtml .= '<pagebreak />';
494            }
495
496            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
497            if($isDebug) {
498                $html .= $pagehtml;
499            }
500        }
501        //restore ID
502        $ID = $keep;
503
504        // insert the back page
505        $body_end = $template['back'];
506
507        $body_end .= '</div>';
508
509        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
510        if($isDebug) {
511            $html .= $body_end;
512            $html .= '</body>';
513            $html .= '</html>';
514        }
515
516        //Return html for debugging
517        if($isDebug) {
518            if($INPUT->str('debughtml', 'text', true) == 'html') {
519                echo $html;
520            } else {
521                header('Content-Type: text/plain; charset=utf-8');
522                echo $html;
523            }
524            exit();
525        };
526
527        // write to cache file
528        $mpdf->Output($cachefile, 'F');
529    }
530
531    /**
532     * @param string $cachefile
533     */
534    protected function sendPDFFile($cachefile) {
535        header('Content-Type: application/pdf');
536        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
537        header('Pragma: public');
538        http_conditionalRequest(filemtime($cachefile));
539
540        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
541        if($this->getConf('output') == 'file') {
542            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
543        } else {
544            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
545        }
546
547        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
548        header('Set-Cookie: fileDownload=true; path=/');
549
550        //try to send file, and exit if done
551        http_sendfile($cachefile);
552
553        $fp = @fopen($cachefile, "rb");
554        if($fp) {
555            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
556        } else {
557            header("HTTP/1.0 500 Internal Server Error");
558            print "Could not read file - bad permissions?";
559        }
560        exit();
561    }
562
563    /**
564     * Load the various template files and prepare the HTML/CSS for insertion
565     *
566     * @return array
567     */
568    protected function load_template() {
569        global $ID;
570        global $conf;
571
572        // this is what we'll return
573        $output = array(
574            'cover' => '',
575            'html'  => '',
576            'page'  => '',
577            'first' => '',
578            'cite'  => '',
579        );
580
581        // prepare header/footer elements
582        $html = '';
583        foreach(array('header', 'footer') as $section) {
584            foreach(array('', '_odd', '_even', '_first') as $order) {
585                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
586                if(file_exists($file)) {
587                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
588                    $html .= file_get_contents($file) . DOKU_LF;
589                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
590
591                    // register the needed pseudo CSS
592                    if($order == '_first') {
593                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
594                    } elseif($order == '_even') {
595                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
596                    } elseif($order == '_odd') {
597                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
598                    } else {
599                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
600                    }
601                }
602            }
603        }
604
605        // prepare replacements
606        $replace = array(
607            '@PAGE@'    => '{PAGENO}',
608            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
609            '@TITLE@'   => hsc($this->title),
610            '@WIKI@'    => $conf['title'],
611            '@WIKIURL@' => DOKU_URL,
612            '@DATE@'    => dformat(time()),
613            '@BASE@'    => DOKU_BASE,
614            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
615        );
616
617        // set HTML element
618        $html = str_replace(array_keys($replace), array_values($replace), $html);
619        //TODO For bookcreator $ID (= bookmanager page) makes no sense
620        $output['html'] = $this->page_depend_replacements($html, $ID);
621
622        // cover page
623        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
624        if(file_exists($coverfile)) {
625            $output['cover'] = file_get_contents($coverfile);
626            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
627            $output['cover'] = $this->page_depend_replacements($output['cover'], $ID);
628            $output['cover'] .= '<pagebreak />';
629        }
630
631        // cover page
632        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
633        if(file_exists($backfile)) {
634            $output['back'] = '<pagebreak />';
635            $output['back'] .= file_get_contents($backfile);
636            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
637            $output['back'] = $this->page_depend_replacements($output['back'], $ID);
638        }
639
640        // citation box
641        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
642        if(file_exists($citationfile)) {
643            $output['cite'] = file_get_contents($citationfile);
644            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
645        }
646
647        return $output;
648    }
649
650    /**
651     * @param string $raw code with placeholders
652     * @param string $id  pageid
653     * @return string
654     */
655    protected function page_depend_replacements($raw, $id) {
656        global $REV, $DATE_AT;
657
658        // generate qr code for this page using google infographics api
659        $qr_code = '';
660        if($this->getConf('qrcodesize')) {
661            $url = urlencode(wl($id, '', '&', true));
662            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
663                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
664        }
665        // prepare replacements
666        $replace['@ID@']      = $id;
667        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
668
669        $params = array();
670        if($DATE_AT) {
671            $params['at'] = $DATE_AT;
672        } elseif($REV) {
673            $params['rev'] = $REV;
674        }
675        $replace['@PAGEURL@'] = wl($id, $params, true, "&");
676        $replace['@QRCODE@']  = $qr_code;
677
678        $content = str_replace(array_keys($replace), array_values($replace), $raw);
679
680        // @DATE(<date>[, <format>])@
681        $content = preg_replace_callback(
682            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
683            array($this, 'replacedate'),
684            $content
685        );
686
687        return $content;
688    }
689
690
691    /**
692     * (callback) Replace date by request datestring
693     * e.g. '%m(30-11-1975)' is replaced by '11'
694     *
695     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
696     * @return string
697     */
698    function replacedate($match) {
699        global $conf;
700        //no 2nd argument for default date format
701        if($match[2] == null) {
702            $match[2] = $conf['dformat'];
703        }
704        return strftime($match[2], strtotime($match[1]));
705    }
706
707    /**
708     * Load all the style sheets and apply the needed replacements
709     */
710    protected function load_css() {
711        global $conf;
712        //reusue the CSS dispatcher functions without triggering the main function
713        define('SIMPLE_TEST', 1);
714        require_once(DOKU_INC . 'lib/exe/css.php');
715
716        // prepare CSS files
717        $files = array_merge(
718            array(
719                DOKU_INC . 'lib/styles/screen.css'
720                    => DOKU_BASE . 'lib/styles/',
721                DOKU_INC . 'lib/styles/print.css'
722                    => DOKU_BASE . 'lib/styles/',
723            ),
724            css_pluginstyles('all'),
725            $this->css_pluginPDFstyles(),
726            array(
727                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
728                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
729                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
730                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
731                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
732                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
733            )
734        );
735        $css = '';
736        foreach($files as $file => $location) {
737            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
738            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
739            $css .= css_loadfile($file, $location);
740        }
741
742        if(function_exists('css_parseless')) {
743            // apply pattern replacements
744            $styleini = css_styleini($conf['template']);
745            $css = css_applystyle($css, $styleini['replacements']);
746
747            // parse less
748            $css = css_parseless($css);
749        } else {
750            // @deprecated 2013-12-19: fix backward compatibility
751            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
752        }
753
754        return $css;
755    }
756
757    /**
758     * Returns a list of possible Plugin PDF Styles
759     *
760     * Checks for a pdf.css, falls back to print.css
761     *
762     * @author Andreas Gohr <andi@splitbrain.org>
763     */
764    protected function css_pluginPDFstyles() {
765        $list = array();
766        $plugins = plugin_list();
767
768        $usestyle = explode(',', $this->getConf('usestyles'));
769        foreach($plugins as $p) {
770            if(in_array($p, $usestyle)) {
771                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
772                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
773            }
774
775            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
776                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
777            } else {
778                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
779            }
780        }
781        return $list;
782    }
783
784    /**
785     * Returns array of pages which will be included in the exported pdf
786     *
787     * @return array
788     */
789    public function getExportedPages() {
790        return $this->list;
791    }
792
793    /**
794     * usort callback to sort by file lastmodified time
795     *
796     * @param array $a
797     * @param array $b
798     * @return int
799     */
800    public function _datesort($a, $b) {
801        if($b['rev'] < $a['rev']) return -1;
802        if($b['rev'] > $a['rev']) return 1;
803        return strcmp($b['id'], $a['id']);
804    }
805
806    /**
807     * usort callback to sort by page id
808     * @param array $a
809     * @param array $b
810     * @return int
811     */
812    public function _pagenamesort($a, $b) {
813        if($a['id'] <= $b['id']) return -1;
814        if($a['id'] > $b['id']) return 1;
815        return 0;
816    }
817
818    /**
819     * Return settings read from:
820     *   1. url parameters
821     *   2. plugin config
822     *   3. global config
823     *
824     * @return array
825     */
826    protected function loadExportConfig() {
827        global $INPUT;
828        global $conf;
829
830        $this->exportConfig = array();
831
832        // decide on the paper setup from param or config
833        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
834        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
835
836        // decide on the font-size from param or config
837        $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
838
839        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
840        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
841
842        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
843        $levels = array();
844        if($hasToC) {
845            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
846            list($top_input, $max_input) = explode('-', $toclevels, 2);
847            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
848            $bounds_input = array(
849                'top' => array(
850                    (int) $top_input,
851                    (int) $top_conf
852                ),
853                'max' => array(
854                    (int) $max_input,
855                    (int) $max_conf
856                )
857            );
858            $bounds = array(
859                'top' => $conf['toptoclevel'],
860                'max' => $conf['maxtoclevel']
861
862            );
863            foreach($bounds_input as $bound => $values) {
864                foreach($values as $value) {
865                    if($value > 0 && $value <= 5) {
866                        //stop at valid value and store
867                        $bounds[$bound] = $value;
868                        break;
869                    }
870                }
871            }
872
873            if($bounds['max'] < $bounds['top']) {
874                $bounds['max'] = $bounds['top'];
875            }
876
877            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
878                $levels["H$level"] = $level - 1;
879            }
880        }
881        $this->exportConfig['hasToC'] = $hasToC;
882        $this->exportConfig['levels'] = $levels;
883
884        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
885
886        $tplconf = $this->getConf('template');
887        $tpl = $INPUT->str('tpl', $tplconf, true);
888        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
889            $tpl = $tplconf;
890        }
891        if(!$tpl){
892            $tpl = 'default';
893        }
894        $this->exportConfig['template'] = $tpl;
895
896        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
897    }
898
899    /**
900     * Returns requested config
901     *
902     * @param string $name
903     * @param mixed  $notset
904     * @return mixed|bool
905     */
906    public function getExportConfig($name, $notset = false) {
907        if ($this->exportConfig === null){
908            $this->loadExportConfig();
909        }
910
911        if(isset($this->exportConfig[$name])){
912            return $this->exportConfig[$name];
913        }else{
914            return $notset;
915        }
916    }
917
918    /**
919     * Add 'export pdf'-button to pagetools
920     *
921     * @param Doku_Event $event
922     */
923    public function addbutton(Doku_Event $event) {
924        global $ID, $REV, $DATE_AT;
925
926        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
927            $params = array('do' => 'export_pdf');
928            if($DATE_AT) {
929                $params['at'] = $DATE_AT;
930            } elseif($REV) {
931                $params['rev'] = $REV;
932            }
933
934            // insert button at position before last (up to top)
935            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
936                array('export_pdf' =>
937                          '<li>'
938                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
939                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
940                          . '</a>'
941                          . '</li>'
942                ) +
943                array_slice($event->data['items'], -1, 1, true);
944        }
945    }
946}
947