xref: /plugin/dw2pdf/action.php (revision 36a7917d5bd8f0bdf6263781a5393efefd4d9362)
1ee19bac3SLuigi Micco<?php
2ee19bac3SLuigi Micco/**
3ee19bac3SLuigi Micco * dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
4ee19bac3SLuigi Micco *
5ee19bac3SLuigi Micco * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6ee19bac3SLuigi Micco * @author     Luigi Micco <l.micco@tiscali.it>
75db42babSAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
8ee19bac3SLuigi Micco */
9ee19bac3SLuigi Micco
10ee19bac3SLuigi Micco// must be run within Dokuwiki
11ee19bac3SLuigi Miccoif(!defined('DOKU_INC')) die();
12ee19bac3SLuigi Micco
130639157eSGerrit Uitslag/**
140639157eSGerrit Uitslag * Class action_plugin_dw2pdf
150639157eSGerrit Uitslag *
160639157eSGerrit Uitslag * Export hmtl content to pdf, for different url parameter configurations
170639157eSGerrit Uitslag * DokuPDF which extends mPDF is used for generating the pdf from html.
180639157eSGerrit Uitslag */
191ef68647SAndreas Gohrclass action_plugin_dw2pdf extends DokuWiki_Action_Plugin {
2002f9a447SGerrit Uitslag    /**
2102f9a447SGerrit Uitslag     * Settings for current export, collected from url param, plugin config, global config
2202f9a447SGerrit Uitslag     *
2302f9a447SGerrit Uitslag     * @var array
2402f9a447SGerrit Uitslag     */
25213fdb75SGerrit Uitslag    protected $exportConfig = null;
2660e59de7SGerrit Uitslag    protected $tpl;
2703352761SKirsten Roschanski    protected $title;
2860e59de7SGerrit Uitslag    protected $list = array();
291c14c879SAndreas Gohr
301c14c879SAndreas Gohr    /**
311c14c879SAndreas Gohr     * Constructor. Sets the correct template
3203352761SKirsten Roschanski     *
3303352761SKirsten Roschanski     * @param string $title
341c14c879SAndreas Gohr     */
3503352761SKirsten Roschanski    public function __construct($title=null) {
3602f9a447SGerrit Uitslag        $this->tpl   = $this->getExportConfig('template');
3703352761SKirsten Roschanski        $this->title = $title ? $title : '';
381c14c879SAndreas Gohr    }
391c14c879SAndreas Gohr
40ee19bac3SLuigi Micco    /**
41ee19bac3SLuigi Micco     * Register the events
42177a7d30SGerrit Uitslag     *
43177a7d30SGerrit Uitslag     * @param Doku_Event_Handler $controller
44ee19bac3SLuigi Micco     */
456be736bfSGerrit Uitslag    public function register(Doku_Event_Handler $controller) {
46ee19bac3SLuigi Micco        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
476be736bfSGerrit Uitslag        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
48026b594bSAndreas Gohr        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton', array());
49ee19bac3SLuigi Micco    }
50ee19bac3SLuigi Micco
511c14c879SAndreas Gohr    /**
521c14c879SAndreas Gohr     * Do the HTML to PDF conversion work
53737417c6SKlap-in     *
54737417c6SKlap-in     * @param Doku_Event $event
55737417c6SKlap-in     * @return bool
561c14c879SAndreas Gohr     */
5744e8e8fbSGerrit Uitslag    public function convert(Doku_Event $event) {
58ee19bac3SLuigi Micco        global $ID;
5927195d5bSMichael Große        global $REV, $DATE_AT, $conf;
60ee19bac3SLuigi Micco
611ef68647SAndreas Gohr        // our event?
6252738244SLarsDW223        if(($event->data != 'export_pdfbook') && ($event->data != 'export_pdf') && ($event->data != 'export_pdfns')) return false;
63ee19bac3SLuigi Micco
641ef68647SAndreas Gohr        // check user's rights
651ef68647SAndreas Gohr        if(auth_quickaclcheck($ID) < AUTH_READ) return false;
661ef68647SAndreas Gohr
67d63e7fe7SGerrit Uitslag        if($data = $this->collectExportPages($event)) {
6803352761SKirsten Roschanski            list($this->title, $this->list) = $data;
69d63e7fe7SGerrit Uitslag        } else {
70d63e7fe7SGerrit Uitslag            return false;
71d63e7fe7SGerrit Uitslag        }
72d63e7fe7SGerrit Uitslag
73d63e7fe7SGerrit Uitslag        // it's ours, no one else's
74d63e7fe7SGerrit Uitslag        $event->preventDefault();
75d63e7fe7SGerrit Uitslag
7627195d5bSMichael Große        if ($ACT === 'export_pdf' && ($REV || $DATE_AT)) {
7727195d5bSMichael Große            $tempFilename = tempnam($conf['tmpdir'], 'dw2pdf_');
78f00df45eSMichael Große            $generateNewPdf = true;
7927d48100SMichael Große            $isTempFile = true;
80f00df45eSMichael Große        } else {
81a58f45f0SGerrit Uitslag            // prepare cache and its dependencies
82a58f45f0SGerrit Uitslag            $depends = array();
8303352761SKirsten Roschanski            $cache = $this->prepareCache($depends);
84f00df45eSMichael Große            $tempFilename = $cache->cache;
8527195d5bSMichael Große            $generateNewPdf = !$this->getConf('usecache')
8627195d5bSMichael Große                || $this->getExportConfig('isDebug')
8727195d5bSMichael Große                || !$cache->useCache($depends);
8827d48100SMichael Große            $isTempFile = false;
89f00df45eSMichael Große        }
90d63e7fe7SGerrit Uitslag
91bd977188SGerrit Uitslag        // hard work only when no cache available or needed for debugging
92f00df45eSMichael Große        if($generateNewPdf) {
93e5f6c2cbSMichael Große            // generating the pdf may take a long time for larger wikis / namespaces with many pages
94e5f6c2cbSMichael Große            set_time_limit(0);
95b34cb34eSSzymon Olewniczak            try {
96f00df45eSMichael Große                $this->generatePDF($tempFilename);
97b34cb34eSSzymon Olewniczak            } catch (Mpdf\MpdfException $e) {
98b34cb34eSSzymon Olewniczak                //prevent act_export()
99b34cb34eSSzymon Olewniczak                $ACT = 'show';
100b34cb34eSSzymon Olewniczak                msg($e->getMessage(), -1);
101b34cb34eSSzymon Olewniczak                return false;
102b34cb34eSSzymon Olewniczak            }
103e5f6c2cbSMichael Große
104d63e7fe7SGerrit Uitslag        }
105d63e7fe7SGerrit Uitslag
106d63e7fe7SGerrit Uitslag        // deliver the file
107f00df45eSMichael Große        $this->sendPDFFile($tempFilename);
10827d48100SMichael Große        if ($isTempFile) {
10927d48100SMichael Große            unlink($tempFilename);
11027d48100SMichael Große        }
111d63e7fe7SGerrit Uitslag        return true;
112d63e7fe7SGerrit Uitslag    }
113d63e7fe7SGerrit Uitslag
114d63e7fe7SGerrit Uitslag    /**
115d63e7fe7SGerrit Uitslag     * Obtain list of pages and title, based on url parameters
116d63e7fe7SGerrit Uitslag     *
117d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
118d63e7fe7SGerrit Uitslag     * @return string|bool
119d63e7fe7SGerrit Uitslag     */
120d63e7fe7SGerrit Uitslag    protected function collectExportPages(Doku_Event $event) {
121*36a7917dSGerrit Uitslag        global $ID, $REV;
122d63e7fe7SGerrit Uitslag        global $INPUT;
123d63e7fe7SGerrit Uitslag        global $conf;
124d63e7fe7SGerrit Uitslag
125d63e7fe7SGerrit Uitslag        // list of one or multiple pages
126d63e7fe7SGerrit Uitslag        $list = array();
12728e636eaSGerrit Uitslag
1284b4cebc2SLarsDW223        if($event->data == 'export_pdf') {
129d63e7fe7SGerrit Uitslag            $list[0] = $ID;
13003352761SKirsten Roschanski            $this->title = $INPUT->str('pdftitle'); //DEPRECATED
13103352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
13203352761SKirsten Roschanski            if(empty($this->title)) {
13303352761SKirsten Roschanski                $this->title = p_get_first_heading($ID);
13415923cb9SGerrit Uitslag            }
135ad18f4e1SGerrit Uitslag
136*36a7917dSGerrit Uitslag            $filename = wikiFN($ID, $REV);
137*36a7917dSGerrit Uitslag            if(!file_exists($filename)) {
138*36a7917dSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'notexist');
139*36a7917dSGerrit Uitslag                return false;
140*36a7917dSGerrit Uitslag            }
141*36a7917dSGerrit Uitslag
1424b4cebc2SLarsDW223        } elseif($event->data == 'export_pdfns') {
143ad18f4e1SGerrit Uitslag            //check input for title and ns
14403352761SKirsten Roschanski            if(!$this->title = $INPUT->str('book_title')) {
14526be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
146ad18f4e1SGerrit Uitslag                return false;
147ad18f4e1SGerrit Uitslag            }
148177a7d30SGerrit Uitslag            $pdfnamespace = cleanID($INPUT->str('book_ns'));
149ad18f4e1SGerrit Uitslag            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
15026be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needns');
151ad18f4e1SGerrit Uitslag                return false;
152ad18f4e1SGerrit Uitslag            }
153ad18f4e1SGerrit Uitslag
15426be4eceSGerrit Uitslag            //sort order
155177a7d30SGerrit Uitslag            $order = $INPUT->str('book_order', 'natural', true);
156ad18f4e1SGerrit Uitslag            $sortoptions = array('pagename', 'date', 'natural');
157ad18f4e1SGerrit Uitslag            if(!in_array($order, $sortoptions)) {
158ad18f4e1SGerrit Uitslag                $order = 'natural';
159ad18f4e1SGerrit Uitslag            }
160ad18f4e1SGerrit Uitslag
16126be4eceSGerrit Uitslag            //search depth
162177a7d30SGerrit Uitslag            $depth = $INPUT->int('book_nsdepth', 0);
163ad18f4e1SGerrit Uitslag            if($depth < 0) {
164ad18f4e1SGerrit Uitslag                $depth = 0;
165ad18f4e1SGerrit Uitslag            }
16626be4eceSGerrit Uitslag
167ad18f4e1SGerrit Uitslag            //page search
168ad18f4e1SGerrit Uitslag            $result = array();
169ad18f4e1SGerrit Uitslag            $opts = array('depth' => $depth); //recursive all levels
170ad18f4e1SGerrit Uitslag            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
171ad18f4e1SGerrit Uitslag            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
172ad18f4e1SGerrit Uitslag
17326be4eceSGerrit Uitslag            //sorting
174ad18f4e1SGerrit Uitslag            if(count($result) > 0) {
175ad18f4e1SGerrit Uitslag                if($order == 'date') {
176ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_datesort'));
177ad18f4e1SGerrit Uitslag                } elseif($order == 'pagename') {
178ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_pagenamesort'));
179ad18f4e1SGerrit Uitslag                }
180ad18f4e1SGerrit Uitslag            }
181ad18f4e1SGerrit Uitslag
182ad18f4e1SGerrit Uitslag            foreach($result as $item) {
183d63e7fe7SGerrit Uitslag                $list[] = $item['id'];
184ad18f4e1SGerrit Uitslag            }
185ad18f4e1SGerrit Uitslag
186baa31dc5SGerrit Uitslag            if ($pdfnamespace !== '') {
187baa31dc5SGerrit Uitslag                if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
188baa31dc5SGerrit Uitslag                    if (file_exists(wikiFN(rtrim($pdfnamespace,':')))) {
189baa31dc5SGerrit Uitslag                        array_unshift($list,rtrim($pdfnamespace,':'));
190baa31dc5SGerrit Uitslag                    }
191baa31dc5SGerrit Uitslag                }
192baa31dc5SGerrit Uitslag            }
193baa31dc5SGerrit Uitslag
194737417c6SKlap-in        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
195b3eed6e3SGerrit Uitslag            /** @deprecated  April 2016 replaced by localStorage version of Bookcreator*/
19626be4eceSGerrit Uitslag            //is in Bookmanager of bookcreator plugin a title given?
19703352761SKirsten Roschanski            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
19803352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
19903352761SKirsten Roschanski            if(empty($this->title)) {
20026be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
201737417c6SKlap-in                return false;
20226be4eceSGerrit Uitslag            } else {
203d63e7fe7SGerrit Uitslag                $list = explode("|", $_COOKIE['list-pagelist']);
20426be4eceSGerrit Uitslag            }
205ad18f4e1SGerrit Uitslag
206b3eed6e3SGerrit Uitslag        } elseif($INPUT->has('selection')) {
207b3eed6e3SGerrit Uitslag            //handle Bookcreator requests based at localStorage
208b3eed6e3SGerrit Uitslag//            if(!checkSecurityToken()) {
209b3eed6e3SGerrit Uitslag//                http_status(403);
210b3eed6e3SGerrit Uitslag//                print $this->getLang('empty');
211b3eed6e3SGerrit Uitslag//                exit();
212b3eed6e3SGerrit Uitslag//            }
213b3eed6e3SGerrit Uitslag
214b3eed6e3SGerrit Uitslag            $json = new JSON(JSON_LOOSE_TYPE);
215b3eed6e3SGerrit Uitslag            $list = $json->decode($INPUT->post->str('selection', '', true));
216b3eed6e3SGerrit Uitslag            if(!is_array($list) || empty($list)) {
217b3eed6e3SGerrit Uitslag                http_status(400);
218b3eed6e3SGerrit Uitslag                print $this->getLang('empty');
219b3eed6e3SGerrit Uitslag                exit();
220b3eed6e3SGerrit Uitslag            }
221b3eed6e3SGerrit Uitslag
22203352761SKirsten Roschanski            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
22303352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
22403352761SKirsten Roschanski            if(empty($this->title)) {
225b3eed6e3SGerrit Uitslag                http_status(400);
226b3eed6e3SGerrit Uitslag                print $this->getLang('needtitle');
227b3eed6e3SGerrit Uitslag                exit();
228b3eed6e3SGerrit Uitslag            }
229b3eed6e3SGerrit Uitslag
230737417c6SKlap-in        } else {
23126be4eceSGerrit Uitslag            //show empty bookcreator message
23226be4eceSGerrit Uitslag            $this->showPageWithErrorMsg($event, 'empty');
233737417c6SKlap-in            return false;
234737417c6SKlap-in        }
235737417c6SKlap-in
236719256adSGerrit Uitslag        $list = array_map('cleanID', $list);
237c7138b3fSGerrit Uitslag
238c7138b3fSGerrit Uitslag        $skippedpages = array();
239c7138b3fSGerrit Uitslag        foreach($list as $index => $pageid) {
240c7138b3fSGerrit Uitslag            if(auth_quickaclcheck($pageid) < AUTH_READ) {
241c7138b3fSGerrit Uitslag                $skippedpages[] = $pageid;
242c7138b3fSGerrit Uitslag                unset($list[$index]);
243c7138b3fSGerrit Uitslag            }
244c7138b3fSGerrit Uitslag        }
245c7138b3fSGerrit Uitslag        $list = array_filter($list); //removes also pages mentioned '0'
246c7138b3fSGerrit Uitslag
247c7138b3fSGerrit Uitslag        //if selection contains forbidden pages throw (overridable) warning
248c7138b3fSGerrit Uitslag        if(!$INPUT->bool('book_skipforbiddenpages') && !empty($skippedpages)) {
249c7138b3fSGerrit Uitslag            $msg = hsc(join(', ', $skippedpages));
250c7138b3fSGerrit Uitslag            if($INPUT->has('selection')) {
251c7138b3fSGerrit Uitslag                http_status(400);
252c7138b3fSGerrit Uitslag                print sprintf($this->getLang('forbidden'), $msg);
253c7138b3fSGerrit Uitslag                exit();
254c7138b3fSGerrit Uitslag            } else {
255c7138b3fSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'forbidden', $msg);
256c7138b3fSGerrit Uitslag                return false;
257c7138b3fSGerrit Uitslag            }
258c7138b3fSGerrit Uitslag
259c7138b3fSGerrit Uitslag        }
260c7138b3fSGerrit Uitslag
26103352761SKirsten Roschanski        return array($this->title, $list);
262d63e7fe7SGerrit Uitslag    }
263d63e7fe7SGerrit Uitslag
264a58f45f0SGerrit Uitslag    /**
265a58f45f0SGerrit Uitslag     * Prepare cache
266a58f45f0SGerrit Uitslag     *
267a58f45f0SGerrit Uitslag     * @param array  $depends (reference) array with dependencies
268a58f45f0SGerrit Uitslag     * @return cache
269a58f45f0SGerrit Uitslag     */
27003352761SKirsten Roschanski    protected function prepareCache(&$depends) {
271a58f45f0SGerrit Uitslag        global $REV;
272a58f45f0SGerrit Uitslag
273ee19bac3SLuigi Micco        $cachekey = join(',', $this->list)
274ee19bac3SLuigi Micco            . $REV
275ee19bac3SLuigi Micco            . $this->getExportConfig('template')
276ee19bac3SLuigi Micco            . $this->getExportConfig('pagesize')
277ee19bac3SLuigi Micco            . $this->getExportConfig('orientation')
278d83760efSGerrit Uitslag            . $this->getExportConfig('font-size')
279ee19bac3SLuigi Micco            . $this->getExportConfig('doublesided')
280ee19bac3SLuigi Micco            . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0')
28103352761SKirsten Roschanski            . $this->title;
282ee19bac3SLuigi Micco        $cache = new cache($cachekey, '.dw2.pdf');
283ee19bac3SLuigi Micco
284ee19bac3SLuigi Micco        $dependencies = array();
285ee19bac3SLuigi Micco        foreach($this->list as $pageid) {
286ee19bac3SLuigi Micco            $relations = p_get_metadata($pageid, 'relation');
287ee19bac3SLuigi Micco
288ee19bac3SLuigi Micco            if(is_array($relations)) {
289ee19bac3SLuigi Micco                if(array_key_exists('media', $relations) && is_array($relations['media'])) {
290ee19bac3SLuigi Micco                    foreach($relations['media'] as $mediaid => $exists) {
291ee19bac3SLuigi Micco                        if($exists) {
292ee19bac3SLuigi Micco                            $dependencies[] = mediaFN($mediaid);
293ee19bac3SLuigi Micco                        }
294ee19bac3SLuigi Micco                    }
295ee19bac3SLuigi Micco                }
296ee19bac3SLuigi Micco
297ee19bac3SLuigi Micco                if(array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
298ee19bac3SLuigi Micco                    foreach($relations['haspart'] as $part_pageid => $exists) {
299ee19bac3SLuigi Micco                        if($exists) {
300ee19bac3SLuigi Micco                            $dependencies[] = wikiFN($part_pageid);
301ee19bac3SLuigi Micco                        }
302ee19bac3SLuigi Micco                    }
303ee19bac3SLuigi Micco                }
304ee19bac3SLuigi Micco            }
305ee19bac3SLuigi Micco
306ee19bac3SLuigi Micco            $dependencies[] = metaFN($pageid, '.meta');
307ee19bac3SLuigi Micco        }
308ee19bac3SLuigi Micco
309ee19bac3SLuigi Micco        $depends['files'] = array_map('wikiFN', $this->list);
310ee19bac3SLuigi Micco        $depends['files'][] = __FILE__;
311ee19bac3SLuigi Micco        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
312ee19bac3SLuigi Micco        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
313ee19bac3SLuigi Micco        $depends['files'] = array_merge(
314ee19bac3SLuigi Micco            $depends['files'],
315ee19bac3SLuigi Micco            $dependencies,
316ee19bac3SLuigi Micco            getConfigFiles('main')
317ee19bac3SLuigi Micco        );
318a58f45f0SGerrit Uitslag        return $cache;
319ee19bac3SLuigi Micco    }
320ee19bac3SLuigi Micco
321d63e7fe7SGerrit Uitslag    /**
322d63e7fe7SGerrit Uitslag     * Set error notification and reload page again
323d63e7fe7SGerrit Uitslag     *
324d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
325d63e7fe7SGerrit Uitslag     * @param string $msglangkey key of translation key
326c7138b3fSGerrit Uitslag     * @param string $replacement
327d63e7fe7SGerrit Uitslag     */
328c7138b3fSGerrit Uitslag    private function showPageWithErrorMsg(Doku_Event $event, $msglangkey, $replacement=null) {
329c7138b3fSGerrit Uitslag        if(empty($replacement)) {
330c7138b3fSGerrit Uitslag            $msg = $this->getLang($msglangkey);
331c7138b3fSGerrit Uitslag        } else {
332c7138b3fSGerrit Uitslag            $msg = sprintf($this->getLang($msglangkey), $replacement);
333c7138b3fSGerrit Uitslag        }
334c7138b3fSGerrit Uitslag        msg($msg, -1);
335d63e7fe7SGerrit Uitslag
336d63e7fe7SGerrit Uitslag        $event->data = 'show';
337d63e7fe7SGerrit Uitslag        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
338d63e7fe7SGerrit Uitslag    }
339d63e7fe7SGerrit Uitslag
340d63e7fe7SGerrit Uitslag    /**
341e53f1ec0SSzymon Olewniczak     * Returns the parsed Wikitext in dw2pdf for the given id and revision
342e53f1ec0SSzymon Olewniczak     *
343e53f1ec0SSzymon Olewniczak     * @param string     $id  page id
344e53f1ec0SSzymon Olewniczak     * @param string|int $rev revision timestamp or empty string
345e53f1ec0SSzymon Olewniczak     * @param string     $date_at
346e53f1ec0SSzymon Olewniczak     * @return null|string
347e53f1ec0SSzymon Olewniczak     */
348e53f1ec0SSzymon Olewniczak    protected function p_wiki_dw2pdf($id, $rev = '', $date_at = '') {
349e53f1ec0SSzymon Olewniczak        $file = wikiFN($id, $rev);
350e53f1ec0SSzymon Olewniczak
351e53f1ec0SSzymon Olewniczak        if(!file_exists($file)) return '';
352e53f1ec0SSzymon Olewniczak
353e53f1ec0SSzymon Olewniczak        //ensure $id is in global $ID (needed for parsing)
354e53f1ec0SSzymon Olewniczak        global $ID;
355e53f1ec0SSzymon Olewniczak        $keep = $ID;
356e53f1ec0SSzymon Olewniczak        $ID   = $id;
357e53f1ec0SSzymon Olewniczak
358e53f1ec0SSzymon Olewniczak        $ret  = '';
359e53f1ec0SSzymon Olewniczak
360e53f1ec0SSzymon Olewniczak        if($rev || $date_at) {
361e53f1ec0SSzymon Olewniczak            $ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at); //no caching on old revisions
362e53f1ec0SSzymon Olewniczak        } else {
363e53f1ec0SSzymon Olewniczak            $ret = p_cached_output($file, 'dw2pdf', $id);
364e53f1ec0SSzymon Olewniczak        }
365e53f1ec0SSzymon Olewniczak
366e53f1ec0SSzymon Olewniczak        //restore ID (just in case)
367e53f1ec0SSzymon Olewniczak        $ID = $keep;
368e53f1ec0SSzymon Olewniczak
369e53f1ec0SSzymon Olewniczak        return $ret;
370e53f1ec0SSzymon Olewniczak    }
371e53f1ec0SSzymon Olewniczak
372e53f1ec0SSzymon Olewniczak    /**
373d63e7fe7SGerrit Uitslag     * Build a pdf from the html
374d63e7fe7SGerrit Uitslag     *
375d63e7fe7SGerrit Uitslag     * @param string $cachefile
376d63e7fe7SGerrit Uitslag     */
37703352761SKirsten Roschanski    protected function generatePDF($cachefile) {
378e53f1ec0SSzymon Olewniczak        global $ID, $REV, $INPUT, $DATE_AT, $ACT;
379e53f1ec0SSzymon Olewniczak
380e53f1ec0SSzymon Olewniczak        if ($ACT == 'export_pdf') { //only one page is exported
381e53f1ec0SSzymon Olewniczak            $rev = $REV;
382e53f1ec0SSzymon Olewniczak            $date_at = $DATE_AT;
383e53f1ec0SSzymon Olewniczak        } else { //we are exporting entre namespace, ommit revisions
384e53f1ec0SSzymon Olewniczak            $rev = $date_at = '';
385e53f1ec0SSzymon Olewniczak        }
38687c86ddaSAndreas Gohr
38702f9a447SGerrit Uitslag        //some shortcuts to export settings
38802f9a447SGerrit Uitslag        $hasToC = $this->getExportConfig('hasToC');
38902f9a447SGerrit Uitslag        $levels = $this->getExportConfig('levels');
39002f9a447SGerrit Uitslag        $isDebug = $this->getExportConfig('isDebug');
3916ea88a05SAndreas Gohr
3921ef68647SAndreas Gohr        // initialize PDF library
393cde5a1b3SAndreas Gohr        require_once(dirname(__FILE__) . "/DokuPDF.class.php");
3946ea88a05SAndreas Gohr
3954870b378SLarsDW223        $mpdf = new DokuPDF($this->getExportConfig('pagesize'),
3964870b378SLarsDW223                            $this->getExportConfig('orientation'),
3974870b378SLarsDW223                            $this->getExportConfig('font-size'));
398ee19bac3SLuigi Micco
399d62df65bSAndreas Gohr        // let mpdf fix local links
400d62df65bSAndreas Gohr        $self = parse_url(DOKU_URL);
401d62df65bSAndreas Gohr        $url = $self['scheme'] . '://' . $self['host'];
40202f9a447SGerrit Uitslag        if($self['port']) {
40302f9a447SGerrit Uitslag            $url .= ':' . $self['port'];
40402f9a447SGerrit Uitslag        }
405d62df65bSAndreas Gohr        $mpdf->setBasePath($url);
406d62df65bSAndreas Gohr
40756d13144SAndreas Gohr        // Set the title
40803352761SKirsten Roschanski        $mpdf->SetTitle($this->title);
40956d13144SAndreas Gohr
410d63e7fe7SGerrit Uitslag        // some default document settings
411d63e7fe7SGerrit Uitslag        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
412213fdb75SGerrit Uitslag        //      single-side document has only odd pages
413213fdb75SGerrit Uitslag        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
414daa70883SAndreas Gohr        $mpdf->setAutoTopMargin = 'stretch';
415daa70883SAndreas Gohr        $mpdf->setAutoBottomMargin = 'stretch';
41602f9a447SGerrit Uitslag//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
41702f9a447SGerrit Uitslag        if($hasToC) {
41802f9a447SGerrit Uitslag            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off'); //use italic pageno until ToC
41902f9a447SGerrit Uitslag            $mpdf->h2toc = $levels;
42002f9a447SGerrit Uitslag        } else {
42102f9a447SGerrit Uitslag            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
42202f9a447SGerrit Uitslag        }
4232eedf77dSAndreas Gohr
42456d13144SAndreas Gohr        // load the template
42503352761SKirsten Roschanski        $template = $this->load_template();
426ee19bac3SLuigi Micco
4271ef68647SAndreas Gohr        // prepare HTML header styles
428a2c33768SGerrit Uitslag        $html = '';
42902f9a447SGerrit Uitslag        if($isDebug) {
430a2c33768SGerrit Uitslag            $html .= '<html><head>';
431737417c6SKlap-in            $html .= '<style type="text/css">';
432a2c33768SGerrit Uitslag        }
433db1aa1bfSKirsten Roschanski
434db1aa1bfSKirsten Roschanski        $styles = '@page { size:auto; ' . $template['page'] . '}';
435a2c33768SGerrit Uitslag        $styles .= '@page :first {' . $template['first'] . '}';
436254467c4SGerrit Uitslag
437254467c4SGerrit Uitslag        $styles .= '@page landscape-page { size:landscape }';
438254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
439254467c4SGerrit Uitslag        $styles .= '@page portrait-page { size:portrait }';
440254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
441db1aa1bfSKirsten Roschanski        $styles .= $this->load_css();
442254467c4SGerrit Uitslag
443a2c33768SGerrit Uitslag        $mpdf->WriteHTML($styles, 1);
444a2c33768SGerrit Uitslag
44502f9a447SGerrit Uitslag        if($isDebug) {
446a2c33768SGerrit Uitslag            $html .= $styles;
4471ef68647SAndreas Gohr            $html .= '</style>';
4481ef68647SAndreas Gohr            $html .= '</head><body>';
449a2c33768SGerrit Uitslag        }
450a2c33768SGerrit Uitslag
451a2c33768SGerrit Uitslag        $body_start = $template['html'];
452a2c33768SGerrit Uitslag        $body_start .= '<div class="dokuwiki">';
4532eedf77dSAndreas Gohr
4541e45476bSmnapp        // insert the cover page
455a2c33768SGerrit Uitslag        $body_start .= $template['cover'];
456a2c33768SGerrit Uitslag
457a2c33768SGerrit Uitslag        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
45802f9a447SGerrit Uitslag        if($isDebug) {
459a2c33768SGerrit Uitslag            $html .= $body_start;
460a2c33768SGerrit Uitslag        }
46102f9a447SGerrit Uitslag        if($hasToC) {
46202f9a447SGerrit Uitslag            //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
46302f9a447SGerrit Uitslag            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
46402f9a447SGerrit Uitslag            //      - there is no page numbering at the pages of the ToC
46502f9a447SGerrit Uitslag            $mpdf->TOCpagebreakByArray(
46602f9a447SGerrit Uitslag                array(
467230b098dSGerrit Uitslag                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
468230b098dSGerrit Uitslag                    'toc-bookmarkText' => $this->getLang('tocheader'),
46902f9a447SGerrit Uitslag                    'links' => true,
47002f9a447SGerrit Uitslag                    'outdent' => '1em',
47102f9a447SGerrit Uitslag                    'resetpagenum' => true, //start pagenumbering after ToC
47202f9a447SGerrit Uitslag                    'pagenumstyle' => '1'
47302f9a447SGerrit Uitslag                )
47402f9a447SGerrit Uitslag            );
47502f9a447SGerrit Uitslag            $html .= '<tocpagebreak>';
47602f9a447SGerrit Uitslag        }
47702f9a447SGerrit Uitslag
4781ef68647SAndreas Gohr        // loop over all pages
479c7138b3fSGerrit Uitslag        $counter = 0;
480c7138b3fSGerrit Uitslag        $no_pages = count($this->list);
481c7138b3fSGerrit Uitslag        foreach($this->list as $page) {
482c7138b3fSGerrit Uitslag            $counter++;
483b3eed6e3SGerrit Uitslag
48479be256fSMichael Große            $pagehtml = $this->p_wiki_dw2pdf($page, $rev, $date_at);
485e53f1ec0SSzymon Olewniczak            //file doesn't exists
486e53f1ec0SSzymon Olewniczak            if($pagehtml == '') {
487b3eed6e3SGerrit Uitslag                continue;
488b3eed6e3SGerrit Uitslag            }
489719256adSGerrit Uitslag            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
490c7138b3fSGerrit Uitslag            if($counter < $no_pages) {
491a2c33768SGerrit Uitslag                $pagehtml .= '<pagebreak />';
492a2c33768SGerrit Uitslag            }
493a2c33768SGerrit Uitslag
494a2c33768SGerrit Uitslag            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
49502f9a447SGerrit Uitslag            if($isDebug) {
496a2c33768SGerrit Uitslag                $html .= $pagehtml;
4971ef68647SAndreas Gohr            }
498ee19bac3SLuigi Micco        }
499ee19bac3SLuigi Micco
50033c15297SGerrit Uitslag        // insert the back page
501a2c33768SGerrit Uitslag        $body_end = $template['back'];
50233c15297SGerrit Uitslag
503a2c33768SGerrit Uitslag        $body_end .= '</div>';
504a2c33768SGerrit Uitslag
505d63e7fe7SGerrit Uitslag        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
50602f9a447SGerrit Uitslag        if($isDebug) {
507a2c33768SGerrit Uitslag            $html .= $body_end;
508eeb17e15SAndreas Gohr            $html .= '</body>';
509eeb17e15SAndreas Gohr            $html .= '</html>';
510a2c33768SGerrit Uitslag        }
511f765508eSGerrit Uitslag
512f765508eSGerrit Uitslag        //Return html for debugging
51302f9a447SGerrit Uitslag        if($isDebug) {
51402f9a447SGerrit Uitslag            if($INPUT->str('debughtml', 'text', true) == 'html') {
51526be4eceSGerrit Uitslag                echo $html;
516a2c33768SGerrit Uitslag            } else {
517a2c33768SGerrit Uitslag                header('Content-Type: text/plain; charset=utf-8');
518a2c33768SGerrit Uitslag                echo $html;
519a2c33768SGerrit Uitslag            }
52026be4eceSGerrit Uitslag            exit();
52126be4eceSGerrit Uitslag        };
522f765508eSGerrit Uitslag
52387c86ddaSAndreas Gohr        // write to cache file
524d63e7fe7SGerrit Uitslag        $mpdf->Output($cachefile, 'F');
52587c86ddaSAndreas Gohr    }
52687c86ddaSAndreas Gohr
527d63e7fe7SGerrit Uitslag    /**
528d63e7fe7SGerrit Uitslag     * @param string $cachefile
529d63e7fe7SGerrit Uitslag     */
53003352761SKirsten Roschanski    protected function sendPDFFile($cachefile) {
53187c86ddaSAndreas Gohr        header('Content-Type: application/pdf');
532b853b723SAndreas Gohr        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
53387c86ddaSAndreas Gohr        header('Pragma: public');
534d63e7fe7SGerrit Uitslag        http_conditionalRequest(filemtime($cachefile));
535c0956f69SMichael Große        global $INPUT;
536f7b24f48SMichael Große        $outputTarget = $INPUT->str('outputTarget', $this->getConf('output'));
53787c86ddaSAndreas Gohr
53803352761SKirsten Roschanski        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
539c0956f69SMichael Große        if($outputTarget === 'file') {
5409a3c8d9fSAndreas Gohr            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
54187c86ddaSAndreas Gohr        } else {
5429a3c8d9fSAndreas Gohr            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
54387c86ddaSAndreas Gohr        }
544ee19bac3SLuigi Micco
545b3eed6e3SGerrit Uitslag        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
546b3eed6e3SGerrit Uitslag        header('Set-Cookie: fileDownload=true; path=/');
547b3eed6e3SGerrit Uitslag
548e993da11SGerrit Uitslag        //try to send file, and exit if done
549d63e7fe7SGerrit Uitslag        http_sendfile($cachefile);
55087c86ddaSAndreas Gohr
551d63e7fe7SGerrit Uitslag        $fp = @fopen($cachefile, "rb");
55287c86ddaSAndreas Gohr        if($fp) {
553d63e7fe7SGerrit Uitslag            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
55487c86ddaSAndreas Gohr        } else {
55587c86ddaSAndreas Gohr            header("HTTP/1.0 500 Internal Server Error");
55687c86ddaSAndreas Gohr            print "Could not read file - bad permissions?";
55787c86ddaSAndreas Gohr        }
5581ef68647SAndreas Gohr        exit();
5591ef68647SAndreas Gohr    }
5601ef68647SAndreas Gohr
5616be736bfSGerrit Uitslag    /**
5622eedf77dSAndreas Gohr     * Load the various template files and prepare the HTML/CSS for insertion
56344e8e8fbSGerrit Uitslag     *
56444e8e8fbSGerrit Uitslag     * @return array
5651ef68647SAndreas Gohr     */
56603352761SKirsten Roschanski    protected function load_template() {
5671ef68647SAndreas Gohr        global $ID;
5681ef68647SAndreas Gohr        global $conf;
5691ef68647SAndreas Gohr
5702eedf77dSAndreas Gohr        // this is what we'll return
5712eedf77dSAndreas Gohr        $output = array(
5721e45476bSmnapp            'cover' => '',
5732eedf77dSAndreas Gohr            'html'  => '',
5742eedf77dSAndreas Gohr            'page'  => '',
5752eedf77dSAndreas Gohr            'first' => '',
5762eedf77dSAndreas Gohr            'cite'  => '',
5772eedf77dSAndreas Gohr        );
5782eedf77dSAndreas Gohr
5792eedf77dSAndreas Gohr        // prepare header/footer elements
5802eedf77dSAndreas Gohr        $html = '';
58133c15297SGerrit Uitslag        foreach(array('header', 'footer') as $section) {
58233c15297SGerrit Uitslag            foreach(array('', '_odd', '_even', '_first') as $order) {
58302f9a447SGerrit Uitslag                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
58433c15297SGerrit Uitslag                if(file_exists($file)) {
58533c15297SGerrit Uitslag                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
58633c15297SGerrit Uitslag                    $html .= file_get_contents($file) . DOKU_LF;
58733c15297SGerrit Uitslag                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
5882eedf77dSAndreas Gohr
5892eedf77dSAndreas Gohr                    // register the needed pseudo CSS
59033c15297SGerrit Uitslag                    if($order == '_first') {
59133c15297SGerrit Uitslag                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
59233c15297SGerrit Uitslag                    } elseif($order == '_even') {
59333c15297SGerrit Uitslag                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
59433c15297SGerrit Uitslag                    } elseif($order == '_odd') {
59533c15297SGerrit Uitslag                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
596daa70883SAndreas Gohr                    } else {
59733c15297SGerrit Uitslag                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
5982eedf77dSAndreas Gohr                    }
5992eedf77dSAndreas Gohr                }
6002eedf77dSAndreas Gohr            }
6012eedf77dSAndreas Gohr        }
6022eedf77dSAndreas Gohr
6031ef68647SAndreas Gohr        // prepare replacements
6041ef68647SAndreas Gohr        $replace = array(
6051ef68647SAndreas Gohr            '@PAGE@'    => '{PAGENO}',
60602f9a447SGerrit Uitslag            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
60703352761SKirsten Roschanski            '@TITLE@'   => hsc($this->title),
6081ef68647SAndreas Gohr            '@WIKI@'    => $conf['title'],
6091ef68647SAndreas Gohr            '@WIKIURL@' => DOKU_URL,
6101ef68647SAndreas Gohr            '@DATE@'    => dformat(time()),
6115d6fbaeaSAndreas Gohr            '@BASE@'    => DOKU_BASE,
612893987a2SAndreas Gohr            '@INC@'     => DOKU_INC,
613893987a2SAndreas Gohr            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
614893987a2SAndreas Gohr            '@TPLINC@'  => DOKU_INC . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
6151ef68647SAndreas Gohr        );
6161ef68647SAndreas Gohr
6172eedf77dSAndreas Gohr        // set HTML element
618a180c973SKlap-in        $html = str_replace(array_keys($replace), array_values($replace), $html);
619a180c973SKlap-in        //TODO For bookcreator $ID (= bookmanager page) makes no sense
620a180c973SKlap-in        $output['html'] = $this->page_depend_replacements($html, $ID);
6211ef68647SAndreas Gohr
6221e45476bSmnapp        // cover page
62302f9a447SGerrit Uitslag        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
62433c15297SGerrit Uitslag        if(file_exists($coverfile)) {
62533c15297SGerrit Uitslag            $output['cover'] = file_get_contents($coverfile);
6261e45476bSmnapp            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
6279b071da5SMichael            $output['cover'] = $this->page_depend_replacements($output['cover'], $ID);
6286e2ec302SGerrit Uitslag            $output['cover'] .= '<pagebreak />';
6291e45476bSmnapp        }
6301e45476bSmnapp
63133c15297SGerrit Uitslag        // cover page
63202f9a447SGerrit Uitslag        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
63333c15297SGerrit Uitslag        if(file_exists($backfile)) {
63433c15297SGerrit Uitslag            $output['back'] = '<pagebreak />';
63533c15297SGerrit Uitslag            $output['back'] .= file_get_contents($backfile);
63633c15297SGerrit Uitslag            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
6379b071da5SMichael            $output['back'] = $this->page_depend_replacements($output['back'], $ID);
63833c15297SGerrit Uitslag        }
63933c15297SGerrit Uitslag
6402eedf77dSAndreas Gohr        // citation box
64102f9a447SGerrit Uitslag        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
64233c15297SGerrit Uitslag        if(file_exists($citationfile)) {
64333c15297SGerrit Uitslag            $output['cite'] = file_get_contents($citationfile);
6442eedf77dSAndreas Gohr            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
6452eedf77dSAndreas Gohr        }
6461ef68647SAndreas Gohr
6472eedf77dSAndreas Gohr        return $output;
6481ef68647SAndreas Gohr    }
6491ef68647SAndreas Gohr
6501ef68647SAndreas Gohr    /**
651a180c973SKlap-in     * @param string $raw code with placeholders
652a180c973SKlap-in     * @param string $id  pageid
653a180c973SKlap-in     * @return string
654a180c973SKlap-in     */
655a180c973SKlap-in    protected function page_depend_replacements($raw, $id) {
656e53f1ec0SSzymon Olewniczak        global $REV, $DATE_AT;
657a180c973SKlap-in
658a180c973SKlap-in        // generate qr code for this page using google infographics api
659a180c973SKlap-in        $qr_code = '';
660a180c973SKlap-in        if($this->getConf('qrcodesize')) {
661a180c973SKlap-in            $url = urlencode(wl($id, '', '&', true));
662a180c973SKlap-in            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
663a180c973SKlap-in                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
664a180c973SKlap-in        }
665a180c973SKlap-in        // prepare replacements
666a180c973SKlap-in        $replace['@ID@']      = $id;
667a180c973SKlap-in        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
668e53f1ec0SSzymon Olewniczak
669e53f1ec0SSzymon Olewniczak        $params = array();
670e53f1ec0SSzymon Olewniczak        if($DATE_AT) {
671e53f1ec0SSzymon Olewniczak            $params['at'] = $DATE_AT;
672e53f1ec0SSzymon Olewniczak        } elseif($REV) {
673e53f1ec0SSzymon Olewniczak            $params['rev'] = $REV;
674e53f1ec0SSzymon Olewniczak        }
675e53f1ec0SSzymon Olewniczak        $replace['@PAGEURL@'] = wl($id, $params, true, "&");
676a180c973SKlap-in        $replace['@QRCODE@']  = $qr_code;
677a180c973SKlap-in
678e3d68265SGerrit Uitslag        $content = str_replace(array_keys($replace), array_values($replace), $raw);
679e3d68265SGerrit Uitslag
680e3d68265SGerrit Uitslag        // @DATE(<date>[, <format>])@
681e3d68265SGerrit Uitslag        $content = preg_replace_callback(
682e3d68265SGerrit Uitslag            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
683e3d68265SGerrit Uitslag            array($this, 'replacedate'),
684e3d68265SGerrit Uitslag            $content
685e3d68265SGerrit Uitslag        );
686e3d68265SGerrit Uitslag
687e3d68265SGerrit Uitslag        return $content;
688a180c973SKlap-in    }
689a180c973SKlap-in
690e3d68265SGerrit Uitslag
691e3d68265SGerrit Uitslag    /**
692e3d68265SGerrit Uitslag     * (callback) Replace date by request datestring
693e3d68265SGerrit Uitslag     * e.g. '%m(30-11-1975)' is replaced by '11'
694e3d68265SGerrit Uitslag     *
695e3d68265SGerrit Uitslag     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
696e3d68265SGerrit Uitslag     * @return string
697e3d68265SGerrit Uitslag     */
698e3d68265SGerrit Uitslag    function replacedate($match) {
699e3d68265SGerrit Uitslag        global $conf;
700e3d68265SGerrit Uitslag        //no 2nd argument for default date format
701e3d68265SGerrit Uitslag        if($match[2] == null) {
702e3d68265SGerrit Uitslag            $match[2] = $conf['dformat'];
703e3d68265SGerrit Uitslag        }
704e3d68265SGerrit Uitslag        return strftime($match[2], strtotime($match[1]));
705e3d68265SGerrit Uitslag    }
706e3d68265SGerrit Uitslag
707a180c973SKlap-in    /**
7081c14c879SAndreas Gohr     * Load all the style sheets and apply the needed replacements
7091ef68647SAndreas Gohr     */
7101c14c879SAndreas Gohr    protected function load_css() {
711737417c6SKlap-in        global $conf;
7121c14c879SAndreas Gohr        //reusue the CSS dispatcher functions without triggering the main function
7131c14c879SAndreas Gohr        define('SIMPLE_TEST', 1);
7141c14c879SAndreas Gohr        require_once(DOKU_INC . 'lib/exe/css.php');
715ee19bac3SLuigi Micco
7161c14c879SAndreas Gohr        // prepare CSS files
7171c14c879SAndreas Gohr        $files = array_merge(
7181c14c879SAndreas Gohr            array(
7191c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/screen.css'
7201c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
7211c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/print.css'
7221c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
7231c14c879SAndreas Gohr            ),
72458e6409eSAndreas Gohr            $this->css_pluginPDFstyles(),
7251c14c879SAndreas Gohr            array(
7261c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
7271c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
7281c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
7291c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
7301c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
7311c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
7321c14c879SAndreas Gohr            )
7331c14c879SAndreas Gohr        );
7341c14c879SAndreas Gohr        $css = '';
7351c14c879SAndreas Gohr        foreach($files as $file => $location) {
73628e636eaSGerrit Uitslag            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
73728e636eaSGerrit Uitslag            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
7381c14c879SAndreas Gohr            $css .= css_loadfile($file, $location);
7391ef68647SAndreas Gohr        }
7401ef68647SAndreas Gohr
74128e636eaSGerrit Uitslag        if(function_exists('css_parseless')) {
7421c14c879SAndreas Gohr            // apply pattern replacements
74328e636eaSGerrit Uitslag            $styleini = css_styleini($conf['template']);
74428e636eaSGerrit Uitslag            $css = css_applystyle($css, $styleini['replacements']);
74528e636eaSGerrit Uitslag
74628e636eaSGerrit Uitslag            // parse less
74728e636eaSGerrit Uitslag            $css = css_parseless($css);
74828e636eaSGerrit Uitslag        } else {
74928e636eaSGerrit Uitslag            // @deprecated 2013-12-19: fix backward compatibility
7501c14c879SAndreas Gohr            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
75128e636eaSGerrit Uitslag        }
7521ef68647SAndreas Gohr
7531c14c879SAndreas Gohr        return $css;
754ee19bac3SLuigi Micco    }
7551c14c879SAndreas Gohr
75658e6409eSAndreas Gohr    /**
75758e6409eSAndreas Gohr     * Returns a list of possible Plugin PDF Styles
75858e6409eSAndreas Gohr     *
75958e6409eSAndreas Gohr     * Checks for a pdf.css, falls back to print.css
76058e6409eSAndreas Gohr     *
76158e6409eSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
76258e6409eSAndreas Gohr     */
7636be736bfSGerrit Uitslag    protected function css_pluginPDFstyles() {
76458e6409eSAndreas Gohr        $list = array();
76558e6409eSAndreas Gohr        $plugins = plugin_list();
766f54b51f7SAndreas Gohr
767f54b51f7SAndreas Gohr        $usestyle = explode(',', $this->getConf('usestyles'));
76858e6409eSAndreas Gohr        foreach($plugins as $p) {
769f54b51f7SAndreas Gohr            if(in_array($p, $usestyle)) {
770f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
7718003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/";
7728003b493SGerrit Uitslag
773f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
7748003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
775f54b51f7SAndreas Gohr            }
776f54b51f7SAndreas Gohr
7778003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/";
7788003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/";
7798003b493SGerrit Uitslag
78058e6409eSAndreas Gohr            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
78158e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
7828003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/";
78358e6409eSAndreas Gohr            } else {
78458e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
7858003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/";
78658e6409eSAndreas Gohr            }
78758e6409eSAndreas Gohr        }
78858e6409eSAndreas Gohr        return $list;
78958e6409eSAndreas Gohr    }
790ad18f4e1SGerrit Uitslag
791ad18f4e1SGerrit Uitslag    /**
79260e59de7SGerrit Uitslag     * Returns array of pages which will be included in the exported pdf
79360e59de7SGerrit Uitslag     *
79460e59de7SGerrit Uitslag     * @return array
79560e59de7SGerrit Uitslag     */
79660e59de7SGerrit Uitslag    public function getExportedPages() {
79760e59de7SGerrit Uitslag        return $this->list;
79860e59de7SGerrit Uitslag    }
79960e59de7SGerrit Uitslag
80060e59de7SGerrit Uitslag    /**
801ad18f4e1SGerrit Uitslag     * usort callback to sort by file lastmodified time
80244e8e8fbSGerrit Uitslag     *
80344e8e8fbSGerrit Uitslag     * @param array $a
80444e8e8fbSGerrit Uitslag     * @param array $b
80544e8e8fbSGerrit Uitslag     * @return int
806ad18f4e1SGerrit Uitslag     */
807ad18f4e1SGerrit Uitslag    public function _datesort($a, $b) {
808ad18f4e1SGerrit Uitslag        if($b['rev'] < $a['rev']) return -1;
809ad18f4e1SGerrit Uitslag        if($b['rev'] > $a['rev']) return 1;
810ad18f4e1SGerrit Uitslag        return strcmp($b['id'], $a['id']);
811ad18f4e1SGerrit Uitslag    }
812ad18f4e1SGerrit Uitslag
813ad18f4e1SGerrit Uitslag    /**
814ad18f4e1SGerrit Uitslag     * usort callback to sort by page id
81544e8e8fbSGerrit Uitslag     * @param array $a
81644e8e8fbSGerrit Uitslag     * @param array $b
81744e8e8fbSGerrit Uitslag     * @return int
818ad18f4e1SGerrit Uitslag     */
819ad18f4e1SGerrit Uitslag    public function _pagenamesort($a, $b) {
820eea6fd2cSMichael Große        // do not sort numbers before namespace separators
821eea6fd2cSMichael Große        $aID = str_replace(':', '/', $a['id']);
822eea6fd2cSMichael Große        $bID = str_replace(':', '/', $b['id']);
823eea6fd2cSMichael Große        if($aID <= $bID) return -1;
824eea6fd2cSMichael Große        if($aID > $bID) return 1;
825ad18f4e1SGerrit Uitslag        return 0;
826ad18f4e1SGerrit Uitslag    }
82726be4eceSGerrit Uitslag
82826be4eceSGerrit Uitslag    /**
82902f9a447SGerrit Uitslag     * Return settings read from:
83002f9a447SGerrit Uitslag     *   1. url parameters
83102f9a447SGerrit Uitslag     *   2. plugin config
83202f9a447SGerrit Uitslag     *   3. global config
83302f9a447SGerrit Uitslag     *
83402f9a447SGerrit Uitslag     * @return array
83502f9a447SGerrit Uitslag     */
83602f9a447SGerrit Uitslag    protected function loadExportConfig() {
83702f9a447SGerrit Uitslag        global $INPUT;
83802f9a447SGerrit Uitslag        global $conf;
83902f9a447SGerrit Uitslag
84002f9a447SGerrit Uitslag        $this->exportConfig = array();
84102f9a447SGerrit Uitslag
84202f9a447SGerrit Uitslag        // decide on the paper setup from param or config
84302f9a447SGerrit Uitslag        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
84402f9a447SGerrit Uitslag        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
84502f9a447SGerrit Uitslag
8464870b378SLarsDW223        // decide on the font-size from param or config
8474870b378SLarsDW223        $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
8484870b378SLarsDW223
849213fdb75SGerrit Uitslag        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
850213fdb75SGerrit Uitslag        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
851213fdb75SGerrit Uitslag
852213fdb75SGerrit Uitslag        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
85302f9a447SGerrit Uitslag        $levels = array();
85402f9a447SGerrit Uitslag        if($hasToC) {
85502f9a447SGerrit Uitslag            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
85602f9a447SGerrit Uitslag            list($top_input, $max_input) = explode('-', $toclevels, 2);
85702f9a447SGerrit Uitslag            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
85802f9a447SGerrit Uitslag            $bounds_input = array(
85902f9a447SGerrit Uitslag                'top' => array(
86002f9a447SGerrit Uitslag                    (int) $top_input,
86102f9a447SGerrit Uitslag                    (int) $top_conf
86202f9a447SGerrit Uitslag                ),
86302f9a447SGerrit Uitslag                'max' => array(
86402f9a447SGerrit Uitslag                    (int) $max_input,
86502f9a447SGerrit Uitslag                    (int) $max_conf
86602f9a447SGerrit Uitslag                )
86702f9a447SGerrit Uitslag            );
86802f9a447SGerrit Uitslag            $bounds = array(
86902f9a447SGerrit Uitslag                'top' => $conf['toptoclevel'],
87002f9a447SGerrit Uitslag                'max' => $conf['maxtoclevel']
87102f9a447SGerrit Uitslag
87202f9a447SGerrit Uitslag            );
87302f9a447SGerrit Uitslag            foreach($bounds_input as $bound => $values) {
87402f9a447SGerrit Uitslag                foreach($values as $value) {
87502f9a447SGerrit Uitslag                    if($value > 0 && $value <= 5) {
87602f9a447SGerrit Uitslag                        //stop at valid value and store
87702f9a447SGerrit Uitslag                        $bounds[$bound] = $value;
87802f9a447SGerrit Uitslag                        break;
87902f9a447SGerrit Uitslag                    }
88002f9a447SGerrit Uitslag                }
88102f9a447SGerrit Uitslag            }
88202f9a447SGerrit Uitslag
88302f9a447SGerrit Uitslag            if($bounds['max'] < $bounds['top']) {
88402f9a447SGerrit Uitslag                $bounds['max'] = $bounds['top'];
88502f9a447SGerrit Uitslag            }
88602f9a447SGerrit Uitslag
88702f9a447SGerrit Uitslag            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
88802f9a447SGerrit Uitslag                $levels["H$level"] = $level - 1;
88902f9a447SGerrit Uitslag            }
89002f9a447SGerrit Uitslag        }
89102f9a447SGerrit Uitslag        $this->exportConfig['hasToC'] = $hasToC;
89202f9a447SGerrit Uitslag        $this->exportConfig['levels'] = $levels;
89302f9a447SGerrit Uitslag
89402f9a447SGerrit Uitslag        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
89502f9a447SGerrit Uitslag
89602f9a447SGerrit Uitslag        $tplconf = $this->getConf('template');
89705d2b507SGerrit Uitslag        $tpl = $INPUT->str('tpl', $tplconf, true);
89802f9a447SGerrit Uitslag        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
89902f9a447SGerrit Uitslag            $tpl = $tplconf;
90002f9a447SGerrit Uitslag        }
90102f9a447SGerrit Uitslag        if(!$tpl){
90202f9a447SGerrit Uitslag            $tpl = 'default';
90302f9a447SGerrit Uitslag        }
90402f9a447SGerrit Uitslag        $this->exportConfig['template'] = $tpl;
90502f9a447SGerrit Uitslag
90602f9a447SGerrit Uitslag        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
90702f9a447SGerrit Uitslag    }
90802f9a447SGerrit Uitslag
90902f9a447SGerrit Uitslag    /**
91002f9a447SGerrit Uitslag     * Returns requested config
91102f9a447SGerrit Uitslag     *
91202f9a447SGerrit Uitslag     * @param string $name
91302f9a447SGerrit Uitslag     * @param mixed  $notset
91402f9a447SGerrit Uitslag     * @return mixed|bool
91502f9a447SGerrit Uitslag     */
91602f9a447SGerrit Uitslag    public function getExportConfig($name, $notset = false) {
91702f9a447SGerrit Uitslag        if ($this->exportConfig === null){
91802f9a447SGerrit Uitslag            $this->loadExportConfig();
91902f9a447SGerrit Uitslag        }
92002f9a447SGerrit Uitslag
92102f9a447SGerrit Uitslag        if(isset($this->exportConfig[$name])){
92202f9a447SGerrit Uitslag            return $this->exportConfig[$name];
92302f9a447SGerrit Uitslag        }else{
92402f9a447SGerrit Uitslag            return $notset;
92502f9a447SGerrit Uitslag        }
92602f9a447SGerrit Uitslag    }
927d63e7fe7SGerrit Uitslag
928d63e7fe7SGerrit Uitslag    /**
929d63e7fe7SGerrit Uitslag     * Add 'export pdf'-button to pagetools
930d63e7fe7SGerrit Uitslag     *
931d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
932d63e7fe7SGerrit Uitslag     */
93344e8e8fbSGerrit Uitslag    public function addbutton(Doku_Event $event) {
934e53f1ec0SSzymon Olewniczak        global $ID, $REV, $DATE_AT;
935d63e7fe7SGerrit Uitslag
936d63e7fe7SGerrit Uitslag        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
937d63e7fe7SGerrit Uitslag            $params = array('do' => 'export_pdf');
938e53f1ec0SSzymon Olewniczak            if($DATE_AT) {
939e53f1ec0SSzymon Olewniczak                $params['at'] = $DATE_AT;
940e53f1ec0SSzymon Olewniczak            } elseif($REV) {
941d63e7fe7SGerrit Uitslag                $params['rev'] = $REV;
942d63e7fe7SGerrit Uitslag            }
943d63e7fe7SGerrit Uitslag
944d63e7fe7SGerrit Uitslag            // insert button at position before last (up to top)
945d63e7fe7SGerrit Uitslag            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
946d63e7fe7SGerrit Uitslag                array('export_pdf' =>
947d63e7fe7SGerrit Uitslag                          '<li>'
94872cadc31SChristian Paul                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
949d63e7fe7SGerrit Uitslag                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
950d63e7fe7SGerrit Uitslag                          . '</a>'
951d63e7fe7SGerrit Uitslag                          . '</li>'
952d63e7fe7SGerrit Uitslag                ) +
953d63e7fe7SGerrit Uitslag                array_slice($event->data['items'], -1, 1, true);
954d63e7fe7SGerrit Uitslag        }
955d63e7fe7SGerrit Uitslag    }
956026b594bSAndreas Gohr
957026b594bSAndreas Gohr    /**
958026b594bSAndreas Gohr     * Add 'export pdf' button to page tools, new SVG based mechanism
959026b594bSAndreas Gohr     *
960026b594bSAndreas Gohr     * @param Doku_Event $event
961026b594bSAndreas Gohr     */
962026b594bSAndreas Gohr    public function addsvgbutton(Doku_Event $event) {
9634c493e44SGerrit Uitslag        global $INFO;
9644c493e44SGerrit Uitslag        if($event->data['view'] != 'page' || !$this->getConf('showexportbutton')) {
9654c493e44SGerrit Uitslag            return;
9664c493e44SGerrit Uitslag        }
9674c493e44SGerrit Uitslag
9684c493e44SGerrit Uitslag        if(!$INFO['exists']) {
9694c493e44SGerrit Uitslag            return;
9704c493e44SGerrit Uitslag        }
9714c493e44SGerrit Uitslag
972026b594bSAndreas Gohr        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dw2pdf\MenuItem()]);
973026b594bSAndreas Gohr    }
974ee19bac3SLuigi Micco}
975