xref: /plugin/dw2pdf/action.php (revision 27d481009de64282799143c50099aaa4b8c86ed9)
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     * Get $meta['relations'] for the given page and revision
261     *
262     * @param        $id
263     * @param string $rev
264     * @return mixed
265     */
266    protected function getMetaRelation($id, $rev='') {
267        //current revision
268        if ($rev == '') return p_get_metadata($id, 'relation');
269
270        // get instructions
271        $instructions = p_cached_instructions(wikiFN($id, $rev),false,$id);
272
273        // set up the renderer
274        $renderer = new Doku_Renderer_metadata();
275
276        // loop through the instructions
277        foreach ($instructions as $instruction){
278            //execute only relation['media'] and relation['haspart'] functions
279            if ($instruction[0] != 'locallink' &&
280                $instruction[0] != 'internallink' &&
281                $instruction[0] != 'externallink' &&
282                $instruction[0] != 'interwikilink' &&
283                $instruction[0] != 'windowssharelink' &&
284                $instruction[0] != 'emaillink' &&
285                $instruction[0] != 'internalmedia' &&
286                $instruction[0] != 'rss') continue;
287
288            // execute the callback against the renderer
289            call_user_func_array(array(&$renderer, $instruction[0]), (array) $instruction[1]);
290        }
291
292        return $renderer->meta['relation'];
293    }
294
295    /**
296     * Prepare cache
297     *
298     * @param array  $depends (reference) array with dependencies
299     * @return cache
300     */
301    protected function prepareCache(&$depends) {
302        global $REV;
303
304        $cachekey = join(',', $this->list)
305            . $REV
306            . $this->getExportConfig('template')
307            . $this->getExportConfig('pagesize')
308            . $this->getExportConfig('orientation')
309            . $this->getExportConfig('font-size')
310            . $this->getExportConfig('doublesided')
311            . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0')
312            . $this->title;
313        $cache = new cache($cachekey, '.dw2.pdf');
314
315        $dependencies = array();
316        foreach($this->list as $pageid) {
317            $relations = p_get_metadata($pageid, 'relation');
318
319            if(is_array($relations)) {
320                if(array_key_exists('media', $relations) && is_array($relations['media'])) {
321                    foreach($relations['media'] as $mediaid => $exists) {
322                        if($exists) {
323                            $dependencies[] = mediaFN($mediaid);
324                        }
325                    }
326                }
327
328                if(array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
329                    foreach($relations['haspart'] as $part_pageid => $exists) {
330                        if($exists) {
331                            $dependencies[] = wikiFN($part_pageid);
332                        }
333                    }
334                }
335            }
336
337            $dependencies[] = metaFN($pageid, '.meta');
338        }
339
340        $depends['files'] = array_map('wikiFN', $this->list);
341        $depends['files'][] = __FILE__;
342        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
343        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
344        $depends['files'] = array_merge(
345            $depends['files'],
346            $dependencies,
347            getConfigFiles('main')
348        );
349        return $cache;
350    }
351
352    /**
353     * Set error notification and reload page again
354     *
355     * @param Doku_Event $event
356     * @param string $msglangkey key of translation key
357     * @param string $replacement
358     */
359    private function showPageWithErrorMsg(Doku_Event $event, $msglangkey, $replacement=null) {
360        if(empty($replacement)) {
361            $msg = $this->getLang($msglangkey);
362        } else {
363            $msg = sprintf($this->getLang($msglangkey), $replacement);
364        }
365        msg($msg, -1);
366
367        $event->data = 'show';
368        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
369    }
370
371    /**
372     * Returns the parsed Wikitext in dw2pdf for the given id and revision
373     *
374     * @param string     $id  page id
375     * @param string|int $rev revision timestamp or empty string
376     * @param string     $date_at
377     * @return null|string
378     */
379    protected function p_wiki_dw2pdf($id, $rev = '', $date_at = '') {
380        $file = wikiFN($id, $rev);
381
382        if(!file_exists($file)) return '';
383
384        //ensure $id is in global $ID (needed for parsing)
385        global $ID;
386        $keep = $ID;
387        $ID   = $id;
388
389        $ret  = '';
390
391        if($rev || $date_at) {
392            $ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at); //no caching on old revisions
393        } else {
394            $ret = p_cached_output($file, 'dw2pdf', $id);
395        }
396
397        //restore ID (just in case)
398        $ID = $keep;
399
400        return $ret;
401    }
402
403    /**
404     * Build a pdf from the html
405     *
406     * @param string $cachefile
407     */
408    protected function generatePDF($cachefile) {
409        global $ID, $REV, $INPUT, $DATE_AT, $ACT;
410
411        if ($ACT == 'export_pdf') { //only one page is exported
412            $rev = $REV;
413            $date_at = $DATE_AT;
414        } else { //we are exporting entre namespace, ommit revisions
415            $rev = $date_at = '';
416        }
417
418        //some shortcuts to export settings
419        $hasToC = $this->getExportConfig('hasToC');
420        $levels = $this->getExportConfig('levels');
421        $isDebug = $this->getExportConfig('isDebug');
422
423        // initialize PDF library
424        require_once(dirname(__FILE__) . "/DokuPDF.class.php");
425
426        $mpdf = new DokuPDF($this->getExportConfig('pagesize'),
427                            $this->getExportConfig('orientation'),
428                            $this->getExportConfig('font-size'));
429
430        // let mpdf fix local links
431        $self = parse_url(DOKU_URL);
432        $url = $self['scheme'] . '://' . $self['host'];
433        if($self['port']) {
434            $url .= ':' . $self['port'];
435        }
436        $mpdf->setBasePath($url);
437
438        // Set the title
439        $mpdf->SetTitle($this->title);
440
441        // some default document settings
442        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
443        //      single-side document has only odd pages
444        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
445        $mpdf->setAutoTopMargin = 'stretch';
446        $mpdf->setAutoBottomMargin = 'stretch';
447//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
448        if($hasToC) {
449            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off'); //use italic pageno until ToC
450            $mpdf->h2toc = $levels;
451        } else {
452            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
453        }
454
455        // load the template
456        $template = $this->load_template();
457
458        // prepare HTML header styles
459        $html = '';
460        if($isDebug) {
461            $html .= '<html><head>';
462            $html .= '<style type="text/css">';
463        }
464
465        $styles = '@page { size:auto; ' . $template['page'] . '}';
466        $styles .= '@page :first {' . $template['first'] . '}';
467
468        $styles .= '@page landscape-page { size:landscape }';
469        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
470        $styles .= '@page portrait-page { size:portrait }';
471        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
472        $styles .= $this->load_css();
473
474        $mpdf->WriteHTML($styles, 1);
475
476        if($isDebug) {
477            $html .= $styles;
478            $html .= '</style>';
479            $html .= '</head><body>';
480        }
481
482        $body_start = $template['html'];
483        $body_start .= '<div class="dokuwiki">';
484
485        // insert the cover page
486        $body_start .= $template['cover'];
487
488        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
489        if($isDebug) {
490            $html .= $body_start;
491        }
492        if($hasToC) {
493            //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
494            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
495            //      - there is no page numbering at the pages of the ToC
496            $mpdf->TOCpagebreakByArray(
497                array(
498                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
499                    'toc-bookmarkText' => $this->getLang('tocheader'),
500                    'links' => true,
501                    'outdent' => '1em',
502                    'resetpagenum' => true, //start pagenumbering after ToC
503                    'pagenumstyle' => '1'
504                )
505            );
506            $html .= '<tocpagebreak>';
507        }
508
509        // store original pageid
510        $keep = $ID;
511
512        // loop over all pages
513        $counter = 0;
514        $no_pages = count($this->list);
515        foreach($this->list as $page) {
516            $counter++;
517
518            // set global pageid to the rendered page
519            $ID = $page;
520
521            //$pagehtml = p_cached_output($filename, 'dw2pdf', $page);
522            $pagehtml = $this->p_wiki_dw2pdf($ID, $rev, $date_at);
523            //file doesn't exists
524            if($pagehtml == '') {
525                continue;
526            }
527            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
528            if($counter < $no_pages) {
529                $pagehtml .= '<pagebreak />';
530            }
531
532            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
533            if($isDebug) {
534                $html .= $pagehtml;
535            }
536        }
537        //restore ID
538        $ID = $keep;
539
540        // insert the back page
541        $body_end = $template['back'];
542
543        $body_end .= '</div>';
544
545        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
546        if($isDebug) {
547            $html .= $body_end;
548            $html .= '</body>';
549            $html .= '</html>';
550        }
551
552        //Return html for debugging
553        if($isDebug) {
554            if($INPUT->str('debughtml', 'text', true) == 'html') {
555                echo $html;
556            } else {
557                header('Content-Type: text/plain; charset=utf-8');
558                echo $html;
559            }
560            exit();
561        };
562
563        // write to cache file
564        $mpdf->Output($cachefile, 'F');
565    }
566
567    /**
568     * @param string $cachefile
569     */
570    protected function sendPDFFile($cachefile) {
571        header('Content-Type: application/pdf');
572        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
573        header('Pragma: public');
574        http_conditionalRequest(filemtime($cachefile));
575
576        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
577        if($this->getConf('output') == 'file') {
578            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
579        } else {
580            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
581        }
582
583        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
584        header('Set-Cookie: fileDownload=true; path=/');
585
586        //try to send file, and exit if done
587        http_sendfile($cachefile);
588
589        $fp = @fopen($cachefile, "rb");
590        if($fp) {
591            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
592        } else {
593            header("HTTP/1.0 500 Internal Server Error");
594            print "Could not read file - bad permissions?";
595        }
596        exit();
597    }
598
599    /**
600     * Load the various template files and prepare the HTML/CSS for insertion
601     *
602     * @return array
603     */
604    protected function load_template() {
605        global $ID;
606        global $conf;
607
608        // this is what we'll return
609        $output = array(
610            'cover' => '',
611            'html'  => '',
612            'page'  => '',
613            'first' => '',
614            'cite'  => '',
615        );
616
617        // prepare header/footer elements
618        $html = '';
619        foreach(array('header', 'footer') as $section) {
620            foreach(array('', '_odd', '_even', '_first') as $order) {
621                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
622                if(file_exists($file)) {
623                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
624                    $html .= file_get_contents($file) . DOKU_LF;
625                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
626
627                    // register the needed pseudo CSS
628                    if($order == '_first') {
629                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
630                    } elseif($order == '_even') {
631                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
632                    } elseif($order == '_odd') {
633                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
634                    } else {
635                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
636                    }
637                }
638            }
639        }
640
641        // prepare replacements
642        $replace = array(
643            '@PAGE@'    => '{PAGENO}',
644            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
645            '@TITLE@'   => hsc($this->title),
646            '@WIKI@'    => $conf['title'],
647            '@WIKIURL@' => DOKU_URL,
648            '@DATE@'    => dformat(time()),
649            '@BASE@'    => DOKU_BASE,
650            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
651        );
652
653        // set HTML element
654        $html = str_replace(array_keys($replace), array_values($replace), $html);
655        //TODO For bookcreator $ID (= bookmanager page) makes no sense
656        $output['html'] = $this->page_depend_replacements($html, $ID);
657
658        // cover page
659        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
660        if(file_exists($coverfile)) {
661            $output['cover'] = file_get_contents($coverfile);
662            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
663            $output['cover'] = $this->page_depend_replacements($output['cover'], $ID);
664            $output['cover'] .= '<pagebreak />';
665        }
666
667        // cover page
668        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
669        if(file_exists($backfile)) {
670            $output['back'] = '<pagebreak />';
671            $output['back'] .= file_get_contents($backfile);
672            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
673            $output['back'] = $this->page_depend_replacements($output['back'], $ID);
674        }
675
676        // citation box
677        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
678        if(file_exists($citationfile)) {
679            $output['cite'] = file_get_contents($citationfile);
680            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
681        }
682
683        return $output;
684    }
685
686    /**
687     * @param string $raw code with placeholders
688     * @param string $id  pageid
689     * @return string
690     */
691    protected function page_depend_replacements($raw, $id) {
692        global $REV, $DATE_AT;
693
694        // generate qr code for this page using google infographics api
695        $qr_code = '';
696        if($this->getConf('qrcodesize')) {
697            $url = urlencode(wl($id, '', '&', true));
698            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
699                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
700        }
701        // prepare replacements
702        $replace['@ID@']      = $id;
703        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
704
705        $params = array();
706        if($DATE_AT) {
707            $params['at'] = $DATE_AT;
708        } elseif($REV) {
709            $params['rev'] = $REV;
710        }
711        $replace['@PAGEURL@'] = wl($id, $params, true, "&");
712        $replace['@QRCODE@']  = $qr_code;
713
714        $content = str_replace(array_keys($replace), array_values($replace), $raw);
715
716        // @DATE(<date>[, <format>])@
717        $content = preg_replace_callback(
718            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
719            array($this, 'replacedate'),
720            $content
721        );
722
723        return $content;
724    }
725
726
727    /**
728     * (callback) Replace date by request datestring
729     * e.g. '%m(30-11-1975)' is replaced by '11'
730     *
731     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
732     * @return string
733     */
734    function replacedate($match) {
735        global $conf;
736        //no 2nd argument for default date format
737        if($match[2] == null) {
738            $match[2] = $conf['dformat'];
739        }
740        return strftime($match[2], strtotime($match[1]));
741    }
742
743    /**
744     * Load all the style sheets and apply the needed replacements
745     */
746    protected function load_css() {
747        global $conf;
748        //reusue the CSS dispatcher functions without triggering the main function
749        define('SIMPLE_TEST', 1);
750        require_once(DOKU_INC . 'lib/exe/css.php');
751
752        // prepare CSS files
753        $files = array_merge(
754            array(
755                DOKU_INC . 'lib/styles/screen.css'
756                    => DOKU_BASE . 'lib/styles/',
757                DOKU_INC . 'lib/styles/print.css'
758                    => DOKU_BASE . 'lib/styles/',
759            ),
760            css_pluginstyles('all'),
761            $this->css_pluginPDFstyles(),
762            array(
763                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
764                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
765                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
766                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
767                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
768                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
769            )
770        );
771        $css = '';
772        foreach($files as $file => $location) {
773            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
774            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
775            $css .= css_loadfile($file, $location);
776        }
777
778        if(function_exists('css_parseless')) {
779            // apply pattern replacements
780            $styleini = css_styleini($conf['template']);
781            $css = css_applystyle($css, $styleini['replacements']);
782
783            // parse less
784            $css = css_parseless($css);
785        } else {
786            // @deprecated 2013-12-19: fix backward compatibility
787            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
788        }
789
790        return $css;
791    }
792
793    /**
794     * Returns a list of possible Plugin PDF Styles
795     *
796     * Checks for a pdf.css, falls back to print.css
797     *
798     * @author Andreas Gohr <andi@splitbrain.org>
799     */
800    protected function css_pluginPDFstyles() {
801        $list = array();
802        $plugins = plugin_list();
803
804        $usestyle = explode(',', $this->getConf('usestyles'));
805        foreach($plugins as $p) {
806            if(in_array($p, $usestyle)) {
807                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
808                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
809            }
810
811            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
812                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
813            } else {
814                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
815            }
816        }
817        return $list;
818    }
819
820    /**
821     * Returns array of pages which will be included in the exported pdf
822     *
823     * @return array
824     */
825    public function getExportedPages() {
826        return $this->list;
827    }
828
829    /**
830     * usort callback to sort by file lastmodified time
831     *
832     * @param array $a
833     * @param array $b
834     * @return int
835     */
836    public function _datesort($a, $b) {
837        if($b['rev'] < $a['rev']) return -1;
838        if($b['rev'] > $a['rev']) return 1;
839        return strcmp($b['id'], $a['id']);
840    }
841
842    /**
843     * usort callback to sort by page id
844     * @param array $a
845     * @param array $b
846     * @return int
847     */
848    public function _pagenamesort($a, $b) {
849        if($a['id'] <= $b['id']) return -1;
850        if($a['id'] > $b['id']) return 1;
851        return 0;
852    }
853
854    /**
855     * Return settings read from:
856     *   1. url parameters
857     *   2. plugin config
858     *   3. global config
859     *
860     * @return array
861     */
862    protected function loadExportConfig() {
863        global $INPUT;
864        global $conf;
865
866        $this->exportConfig = array();
867
868        // decide on the paper setup from param or config
869        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
870        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
871
872        // decide on the font-size from param or config
873        $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
874
875        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
876        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
877
878        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
879        $levels = array();
880        if($hasToC) {
881            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
882            list($top_input, $max_input) = explode('-', $toclevels, 2);
883            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
884            $bounds_input = array(
885                'top' => array(
886                    (int) $top_input,
887                    (int) $top_conf
888                ),
889                'max' => array(
890                    (int) $max_input,
891                    (int) $max_conf
892                )
893            );
894            $bounds = array(
895                'top' => $conf['toptoclevel'],
896                'max' => $conf['maxtoclevel']
897
898            );
899            foreach($bounds_input as $bound => $values) {
900                foreach($values as $value) {
901                    if($value > 0 && $value <= 5) {
902                        //stop at valid value and store
903                        $bounds[$bound] = $value;
904                        break;
905                    }
906                }
907            }
908
909            if($bounds['max'] < $bounds['top']) {
910                $bounds['max'] = $bounds['top'];
911            }
912
913            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
914                $levels["H$level"] = $level - 1;
915            }
916        }
917        $this->exportConfig['hasToC'] = $hasToC;
918        $this->exportConfig['levels'] = $levels;
919
920        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
921
922        $tplconf = $this->getConf('template');
923        $tpl = $INPUT->str('tpl', $tplconf, true);
924        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
925            $tpl = $tplconf;
926        }
927        if(!$tpl){
928            $tpl = 'default';
929        }
930        $this->exportConfig['template'] = $tpl;
931
932        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
933    }
934
935    /**
936     * Returns requested config
937     *
938     * @param string $name
939     * @param mixed  $notset
940     * @return mixed|bool
941     */
942    public function getExportConfig($name, $notset = false) {
943        if ($this->exportConfig === null){
944            $this->loadExportConfig();
945        }
946
947        if(isset($this->exportConfig[$name])){
948            return $this->exportConfig[$name];
949        }else{
950            return $notset;
951        }
952    }
953
954    /**
955     * Add 'export pdf'-button to pagetools
956     *
957     * @param Doku_Event $event
958     */
959    public function addbutton(Doku_Event $event) {
960        global $ID, $REV, $DATE_AT;
961
962        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
963            $params = array('do' => 'export_pdf');
964            if($DATE_AT) {
965                $params['at'] = $DATE_AT;
966            } elseif($REV) {
967                $params['rev'] = $REV;
968            }
969
970            // insert button at position before last (up to top)
971            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
972                array('export_pdf' =>
973                          '<li>'
974                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
975                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
976                          . '</a>'
977                          . '</li>'
978                ) +
979                array_slice($event->data['items'], -1, 1, true);
980        }
981    }
982}
983