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