xref: /plugin/dw2pdf/action.php (revision d0f0c5347e305d0ae4537dbd6b9b8402347ce12b)
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
100639157eSGerrit Uitslag/**
110639157eSGerrit Uitslag * Class action_plugin_dw2pdf
120639157eSGerrit Uitslag *
130639157eSGerrit Uitslag * Export hmtl content to pdf, for different url parameter configurations
140639157eSGerrit Uitslag * DokuPDF which extends mPDF is used for generating the pdf from html.
150639157eSGerrit Uitslag */
161ef68647SAndreas Gohrclass action_plugin_dw2pdf extends DokuWiki_Action_Plugin {
1702f9a447SGerrit Uitslag    /**
1802f9a447SGerrit Uitslag     * Settings for current export, collected from url param, plugin config, global config
1902f9a447SGerrit Uitslag     *
2002f9a447SGerrit Uitslag     * @var array
2102f9a447SGerrit Uitslag     */
22213fdb75SGerrit Uitslag    protected $exportConfig = null;
2360e59de7SGerrit Uitslag    protected $tpl;
2403352761SKirsten Roschanski    protected $title;
2560e59de7SGerrit Uitslag    protected $list = array();
269b288b2aSGerrit Uitslag    protected $onetimefile = false;
271c14c879SAndreas Gohr
281c14c879SAndreas Gohr    /**
291c14c879SAndreas Gohr     * Constructor. Sets the correct template
3003352761SKirsten Roschanski     *
3103352761SKirsten Roschanski     * @param string $title
321c14c879SAndreas Gohr     */
3303352761SKirsten Roschanski    public function __construct($title=null) {
3402f9a447SGerrit Uitslag        $this->tpl   = $this->getExportConfig('template');
3503352761SKirsten Roschanski        $this->title = $title ? $title : '';
361c14c879SAndreas Gohr    }
371c14c879SAndreas Gohr
38ee19bac3SLuigi Micco    /**
399b288b2aSGerrit Uitslag     * Delete cached files that were for one-time use
409b288b2aSGerrit Uitslag     */
419b288b2aSGerrit Uitslag    public function __destruct() {
429b288b2aSGerrit Uitslag        if($this->onetimefile) {
439b288b2aSGerrit Uitslag            unlink($this->onetimefile);
449b288b2aSGerrit Uitslag        }
459b288b2aSGerrit Uitslag    }
469b288b2aSGerrit Uitslag
479b288b2aSGerrit Uitslag    /**
48ee19bac3SLuigi Micco     * Register the events
49177a7d30SGerrit Uitslag     *
50177a7d30SGerrit Uitslag     * @param Doku_Event_Handler $controller
51ee19bac3SLuigi Micco     */
526be736bfSGerrit Uitslag    public function register(Doku_Event_Handler $controller) {
53ee19bac3SLuigi Micco        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
546be736bfSGerrit Uitslag        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
55026b594bSAndreas Gohr        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton', array());
56ee19bac3SLuigi Micco    }
57ee19bac3SLuigi Micco
581c14c879SAndreas Gohr    /**
591c14c879SAndreas Gohr     * Do the HTML to PDF conversion work
60737417c6SKlap-in     *
61737417c6SKlap-in     * @param Doku_Event $event
621c14c879SAndreas Gohr     */
6344e8e8fbSGerrit Uitslag    public function convert(Doku_Event $event) {
642d9cd424SGerrit Uitslag        global $ID, $REV, $DATE_AT;
652d9cd424SGerrit Uitslag        global $conf, $INPUT;
66ee19bac3SLuigi Micco
671ef68647SAndreas Gohr        // our event?
68d9c13ec7SGerrit Uitslag        if(($event->data != 'export_pdfbook') && ($event->data != 'export_pdf') && ($event->data != 'export_pdfns')) return;
69ee19bac3SLuigi Micco
701ef68647SAndreas Gohr        // check user's rights
71d9c13ec7SGerrit Uitslag        if(auth_quickaclcheck($ID) < AUTH_READ) return;
721ef68647SAndreas Gohr
73d63e7fe7SGerrit Uitslag        if($data = $this->collectExportPages($event)) {
7403352761SKirsten Roschanski            list($this->title, $this->list) = $data;
75d63e7fe7SGerrit Uitslag        } else {
76d9c13ec7SGerrit Uitslag            return;
77d63e7fe7SGerrit Uitslag        }
78d63e7fe7SGerrit Uitslag
792d9cd424SGerrit Uitslag        if($event->data === 'export_pdf' && ($REV || $DATE_AT)) {
809b288b2aSGerrit Uitslag            $cachefile = tempnam($conf['tmpdir'] . '/dwpdf', 'dw2pdf_');
819b288b2aSGerrit Uitslag            $this->onetimefile = $cachefile;
82f00df45eSMichael Große            $generateNewPdf = true;
83f00df45eSMichael Große        } else {
84a58f45f0SGerrit Uitslag            // prepare cache and its dependencies
85a58f45f0SGerrit Uitslag            $depends = array();
8603352761SKirsten Roschanski            $cache = $this->prepareCache($depends);
879b288b2aSGerrit Uitslag            $cachefile = $cache->cache;
8827195d5bSMichael Große            $generateNewPdf = !$this->getConf('usecache')
8927195d5bSMichael Große                || $this->getExportConfig('isDebug')
9027195d5bSMichael Große                || !$cache->useCache($depends);
91f00df45eSMichael Große        }
92d63e7fe7SGerrit Uitslag
93bd977188SGerrit Uitslag        // hard work only when no cache available or needed for debugging
94f00df45eSMichael Große        if($generateNewPdf) {
95e5f6c2cbSMichael Große            // generating the pdf may take a long time for larger wikis / namespaces with many pages
96e5f6c2cbSMichael Große            set_time_limit(0);
97b34cb34eSSzymon Olewniczak            try {
989b288b2aSGerrit Uitslag                $this->generatePDF($cachefile, $event);
99b34cb34eSSzymon Olewniczak            } catch(Mpdf\MpdfException $e) {
1002d9cd424SGerrit Uitslag                if($INPUT->has('selection')) {
1012d9cd424SGerrit Uitslag                    http_status(400);
1022d9cd424SGerrit Uitslag                    print $e->getMessage();
1032d9cd424SGerrit Uitslag                    exit();
1042d9cd424SGerrit Uitslag                } else {
105b34cb34eSSzymon Olewniczak                    //prevent act_export()
1062d9cd424SGerrit Uitslag                    $event->data = 'show';
107b34cb34eSSzymon Olewniczak                    msg($e->getMessage(), -1);
1082d9cd424SGerrit Uitslag                    $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
109d9c13ec7SGerrit Uitslag                    return;
110b34cb34eSSzymon Olewniczak                }
111d63e7fe7SGerrit Uitslag            }
1122d9cd424SGerrit Uitslag        }
1132d9cd424SGerrit Uitslag
1142d9cd424SGerrit Uitslag        $event->preventDefault(); // after prevent, $event->data cannot be changed
115d63e7fe7SGerrit Uitslag
116d63e7fe7SGerrit Uitslag        // deliver the file
1179b288b2aSGerrit Uitslag        $this->sendPDFFile($cachefile);  //exits
118d63e7fe7SGerrit Uitslag    }
119d63e7fe7SGerrit Uitslag
120d63e7fe7SGerrit Uitslag    /**
121d63e7fe7SGerrit Uitslag     * Obtain list of pages and title, based on url parameters
122d63e7fe7SGerrit Uitslag     *
123d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
1247c79bc79SGerrit Uitslag     * @return array|false
125d63e7fe7SGerrit Uitslag     */
126d63e7fe7SGerrit Uitslag    protected function collectExportPages(Doku_Event $event) {
12736a7917dSGerrit Uitslag        global $ID, $REV;
128d63e7fe7SGerrit Uitslag        global $INPUT;
129d63e7fe7SGerrit Uitslag        global $conf;
130d63e7fe7SGerrit Uitslag
131d63e7fe7SGerrit Uitslag        // list of one or multiple pages
132d63e7fe7SGerrit Uitslag        $list = array();
13328e636eaSGerrit Uitslag
1344b4cebc2SLarsDW223        if($event->data == 'export_pdf') {
135d63e7fe7SGerrit Uitslag            $list[0] = $ID;
13603352761SKirsten Roschanski            $this->title = $INPUT->str('pdftitle'); //DEPRECATED
13703352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
13803352761SKirsten Roschanski            if(empty($this->title)) {
13903352761SKirsten Roschanski                $this->title = p_get_first_heading($ID);
14015923cb9SGerrit Uitslag            }
141ce8af5d0SHativ            // use page name if title is still empty
142ce8af5d0SHativ            if(empty($this->title)) {
143ce8af5d0SHativ                $this->title = noNS($ID);
144ce8af5d0SHativ            }
145ad18f4e1SGerrit Uitslag
14636a7917dSGerrit Uitslag            $filename = wikiFN($ID, $REV);
14736a7917dSGerrit Uitslag            if(!file_exists($filename)) {
14836a7917dSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'notexist');
14936a7917dSGerrit Uitslag                return false;
15036a7917dSGerrit Uitslag            }
15136a7917dSGerrit Uitslag
1524b4cebc2SLarsDW223        } elseif($event->data == 'export_pdfns') {
153ad18f4e1SGerrit Uitslag            //check input for title and ns
15403352761SKirsten Roschanski            if(!$this->title = $INPUT->str('book_title')) {
15526be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
156ad18f4e1SGerrit Uitslag                return false;
157ad18f4e1SGerrit Uitslag            }
158177a7d30SGerrit Uitslag            $pdfnamespace = cleanID($INPUT->str('book_ns'));
159ad18f4e1SGerrit Uitslag            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
16026be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needns');
161ad18f4e1SGerrit Uitslag                return false;
162ad18f4e1SGerrit Uitslag            }
163ad18f4e1SGerrit Uitslag
16426be4eceSGerrit Uitslag            //sort order
165177a7d30SGerrit Uitslag            $order = $INPUT->str('book_order', 'natural', true);
166ad18f4e1SGerrit Uitslag            $sortoptions = array('pagename', 'date', 'natural');
167ad18f4e1SGerrit Uitslag            if(!in_array($order, $sortoptions)) {
168ad18f4e1SGerrit Uitslag                $order = 'natural';
169ad18f4e1SGerrit Uitslag            }
170ad18f4e1SGerrit Uitslag
17126be4eceSGerrit Uitslag            //search depth
172177a7d30SGerrit Uitslag            $depth = $INPUT->int('book_nsdepth', 0);
173ad18f4e1SGerrit Uitslag            if($depth < 0) {
174ad18f4e1SGerrit Uitslag                $depth = 0;
175ad18f4e1SGerrit Uitslag            }
17626be4eceSGerrit Uitslag
177ad18f4e1SGerrit Uitslag            //page search
178ad18f4e1SGerrit Uitslag            $result = array();
179ad18f4e1SGerrit Uitslag            $opts = array('depth' => $depth); //recursive all levels
180ad18f4e1SGerrit Uitslag            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
181ad18f4e1SGerrit Uitslag            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
182ad18f4e1SGerrit Uitslag
18364541781SAnna Dabrowska            // exclude ids
18464541781SAnna Dabrowska            $excludes = $INPUT->arr('excludes');
18564541781SAnna Dabrowska            if (!empty($excludes)) {
186d31b75d5SAnna Dabrowska                $result = array_filter($result, function ($item) use ($excludes) {
187d31b75d5SAnna Dabrowska                    return array_search($item['id'], $excludes) === false;
188d31b75d5SAnna Dabrowska                });
18964541781SAnna Dabrowska            }
19064541781SAnna Dabrowska
19126be4eceSGerrit Uitslag            //sorting
192ad18f4e1SGerrit Uitslag            if(count($result) > 0) {
193ad18f4e1SGerrit Uitslag                if($order == 'date') {
194ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_datesort'));
19541e5d4e2SAndreas Gohr                } elseif ($order == 'pagename' || $order == 'natural') {
196ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_pagenamesort'));
197ad18f4e1SGerrit Uitslag                }
198ad18f4e1SGerrit Uitslag            }
199ad18f4e1SGerrit Uitslag
200ad18f4e1SGerrit Uitslag            foreach($result as $item) {
201d63e7fe7SGerrit Uitslag                $list[] = $item['id'];
202ad18f4e1SGerrit Uitslag            }
203ad18f4e1SGerrit Uitslag
204baa31dc5SGerrit Uitslag            if ($pdfnamespace !== '') {
205baa31dc5SGerrit Uitslag                if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
206baa31dc5SGerrit Uitslag                    if (file_exists(wikiFN(rtrim($pdfnamespace,':')))) {
207baa31dc5SGerrit Uitslag                        array_unshift($list,rtrim($pdfnamespace,':'));
208baa31dc5SGerrit Uitslag                    }
209baa31dc5SGerrit Uitslag                }
210baa31dc5SGerrit Uitslag            }
211baa31dc5SGerrit Uitslag
212737417c6SKlap-in        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
213b3eed6e3SGerrit Uitslag            /** @deprecated  April 2016 replaced by localStorage version of Bookcreator*/
21426be4eceSGerrit Uitslag            //is in Bookmanager of bookcreator plugin a title given?
21503352761SKirsten Roschanski            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
21603352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
21703352761SKirsten Roschanski            if(empty($this->title)) {
21826be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
219737417c6SKlap-in                return false;
22026be4eceSGerrit Uitslag            } else {
221d63e7fe7SGerrit Uitslag                $list = explode("|", $_COOKIE['list-pagelist']);
22226be4eceSGerrit Uitslag            }
223ad18f4e1SGerrit Uitslag
224b3eed6e3SGerrit Uitslag        } elseif($INPUT->has('selection')) {
225b3eed6e3SGerrit Uitslag            //handle Bookcreator requests based at localStorage
226b3eed6e3SGerrit Uitslag//            if(!checkSecurityToken()) {
227b3eed6e3SGerrit Uitslag//                http_status(403);
228b3eed6e3SGerrit Uitslag//                print $this->getLang('empty');
229b3eed6e3SGerrit Uitslag//                exit();
230b3eed6e3SGerrit Uitslag//            }
231b3eed6e3SGerrit Uitslag
2327c79bc79SGerrit Uitslag            $list = json_decode($INPUT->str('selection', '', true), true);
233b3eed6e3SGerrit Uitslag            if(!is_array($list) || empty($list)) {
234b3eed6e3SGerrit Uitslag                http_status(400);
235b3eed6e3SGerrit Uitslag                print $this->getLang('empty');
236b3eed6e3SGerrit Uitslag                exit();
237b3eed6e3SGerrit Uitslag            }
238b3eed6e3SGerrit Uitslag
23903352761SKirsten Roschanski            $this->title = $INPUT->str('pdfbook_title'); //DEPRECATED
24003352761SKirsten Roschanski            $this->title = $INPUT->str('book_title', $this->title, true);
24103352761SKirsten Roschanski            if(empty($this->title)) {
242b3eed6e3SGerrit Uitslag                http_status(400);
243b3eed6e3SGerrit Uitslag                print $this->getLang('needtitle');
244b3eed6e3SGerrit Uitslag                exit();
245b3eed6e3SGerrit Uitslag            }
246b3eed6e3SGerrit Uitslag
247737417c6SKlap-in        } else {
24826be4eceSGerrit Uitslag            //show empty bookcreator message
24926be4eceSGerrit Uitslag            $this->showPageWithErrorMsg($event, 'empty');
250737417c6SKlap-in            return false;
251737417c6SKlap-in        }
252737417c6SKlap-in
253719256adSGerrit Uitslag        $list = array_map('cleanID', $list);
254c7138b3fSGerrit Uitslag
255c7138b3fSGerrit Uitslag        $skippedpages = array();
256c7138b3fSGerrit Uitslag        foreach($list as $index => $pageid) {
257c7138b3fSGerrit Uitslag            if(auth_quickaclcheck($pageid) < AUTH_READ) {
258c7138b3fSGerrit Uitslag                $skippedpages[] = $pageid;
259c7138b3fSGerrit Uitslag                unset($list[$index]);
260c7138b3fSGerrit Uitslag            }
261c7138b3fSGerrit Uitslag        }
262c7138b3fSGerrit Uitslag        $list = array_filter($list); //removes also pages mentioned '0'
263c7138b3fSGerrit Uitslag
264c7138b3fSGerrit Uitslag        //if selection contains forbidden pages throw (overridable) warning
265c7138b3fSGerrit Uitslag        if(!$INPUT->bool('book_skipforbiddenpages') && !empty($skippedpages)) {
266c7138b3fSGerrit Uitslag            $msg = hsc(join(', ', $skippedpages));
267c7138b3fSGerrit Uitslag            if($INPUT->has('selection')) {
268c7138b3fSGerrit Uitslag                http_status(400);
269c7138b3fSGerrit Uitslag                print sprintf($this->getLang('forbidden'), $msg);
270c7138b3fSGerrit Uitslag                exit();
271c7138b3fSGerrit Uitslag            } else {
272c7138b3fSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'forbidden', $msg);
273c7138b3fSGerrit Uitslag                return false;
274c7138b3fSGerrit Uitslag            }
275c7138b3fSGerrit Uitslag
276c7138b3fSGerrit Uitslag        }
277c7138b3fSGerrit Uitslag
27803352761SKirsten Roschanski        return array($this->title, $list);
279d63e7fe7SGerrit Uitslag    }
280d63e7fe7SGerrit Uitslag
281a58f45f0SGerrit Uitslag    /**
282a58f45f0SGerrit Uitslag     * Prepare cache
283a58f45f0SGerrit Uitslag     *
284a58f45f0SGerrit Uitslag     * @param array  $depends (reference) array with dependencies
285a58f45f0SGerrit Uitslag     * @return cache
286a58f45f0SGerrit Uitslag     */
28703352761SKirsten Roschanski    protected function prepareCache(&$depends) {
288a58f45f0SGerrit Uitslag        global $REV;
289a58f45f0SGerrit Uitslag
290ee19bac3SLuigi Micco        $cachekey = join(',', $this->list)
291ee19bac3SLuigi Micco            . $REV
292ee19bac3SLuigi Micco            . $this->getExportConfig('template')
293ee19bac3SLuigi Micco            . $this->getExportConfig('pagesize')
294ee19bac3SLuigi Micco            . $this->getExportConfig('orientation')
295d83760efSGerrit Uitslag            . $this->getExportConfig('font-size')
296ee19bac3SLuigi Micco            . $this->getExportConfig('doublesided')
297ee19bac3SLuigi Micco            . ($this->getExportConfig('hasToC') ? join('-', $this->getExportConfig('levels')) : '0')
29803352761SKirsten Roschanski            . $this->title;
299ee19bac3SLuigi Micco        $cache = new cache($cachekey, '.dw2.pdf');
300ee19bac3SLuigi Micco
301ee19bac3SLuigi Micco        $dependencies = array();
302ee19bac3SLuigi Micco        foreach($this->list as $pageid) {
303ee19bac3SLuigi Micco            $relations = p_get_metadata($pageid, 'relation');
304ee19bac3SLuigi Micco
305ee19bac3SLuigi Micco            if(is_array($relations)) {
306ee19bac3SLuigi Micco                if(array_key_exists('media', $relations) && is_array($relations['media'])) {
307ee19bac3SLuigi Micco                    foreach($relations['media'] as $mediaid => $exists) {
308ee19bac3SLuigi Micco                        if($exists) {
309ee19bac3SLuigi Micco                            $dependencies[] = mediaFN($mediaid);
310ee19bac3SLuigi Micco                        }
311ee19bac3SLuigi Micco                    }
312ee19bac3SLuigi Micco                }
313ee19bac3SLuigi Micco
314ee19bac3SLuigi Micco                if(array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
315ee19bac3SLuigi Micco                    foreach($relations['haspart'] as $part_pageid => $exists) {
316ee19bac3SLuigi Micco                        if($exists) {
317ee19bac3SLuigi Micco                            $dependencies[] = wikiFN($part_pageid);
318ee19bac3SLuigi Micco                        }
319ee19bac3SLuigi Micco                    }
320ee19bac3SLuigi Micco                }
321ee19bac3SLuigi Micco            }
322ee19bac3SLuigi Micco
323ee19bac3SLuigi Micco            $dependencies[] = metaFN($pageid, '.meta');
324ee19bac3SLuigi Micco        }
325ee19bac3SLuigi Micco
326ee19bac3SLuigi Micco        $depends['files'] = array_map('wikiFN', $this->list);
327ee19bac3SLuigi Micco        $depends['files'][] = __FILE__;
328ee19bac3SLuigi Micco        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
329ee19bac3SLuigi Micco        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
330ee19bac3SLuigi Micco        $depends['files'] = array_merge(
331ee19bac3SLuigi Micco            $depends['files'],
332ee19bac3SLuigi Micco            $dependencies,
333ee19bac3SLuigi Micco            getConfigFiles('main')
334ee19bac3SLuigi Micco        );
335a58f45f0SGerrit Uitslag        return $cache;
336ee19bac3SLuigi Micco    }
337ee19bac3SLuigi Micco
338d63e7fe7SGerrit Uitslag    /**
339d63e7fe7SGerrit Uitslag     * Set error notification and reload page again
340d63e7fe7SGerrit Uitslag     *
341d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
342d63e7fe7SGerrit Uitslag     * @param string $msglangkey key of translation key
343c7138b3fSGerrit Uitslag     * @param string $replacement
344d63e7fe7SGerrit Uitslag     */
345c7138b3fSGerrit Uitslag    private function showPageWithErrorMsg(Doku_Event $event, $msglangkey, $replacement=null) {
346c7138b3fSGerrit Uitslag        if(empty($replacement)) {
347c7138b3fSGerrit Uitslag            $msg = $this->getLang($msglangkey);
348c7138b3fSGerrit Uitslag        } else {
349c7138b3fSGerrit Uitslag            $msg = sprintf($this->getLang($msglangkey), $replacement);
350c7138b3fSGerrit Uitslag        }
351c7138b3fSGerrit Uitslag        msg($msg, -1);
352d63e7fe7SGerrit Uitslag
353d63e7fe7SGerrit Uitslag        $event->data = 'show';
354d63e7fe7SGerrit Uitslag        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
355d63e7fe7SGerrit Uitslag    }
356d63e7fe7SGerrit Uitslag
357d63e7fe7SGerrit Uitslag    /**
358e53f1ec0SSzymon Olewniczak     * Returns the parsed Wikitext in dw2pdf for the given id and revision
359e53f1ec0SSzymon Olewniczak     *
360e53f1ec0SSzymon Olewniczak     * @param string     $id  page id
361e53f1ec0SSzymon Olewniczak     * @param string|int $rev revision timestamp or empty string
362e53f1ec0SSzymon Olewniczak     * @param string     $date_at
363e53f1ec0SSzymon Olewniczak     * @return null|string
364e53f1ec0SSzymon Olewniczak     */
365e53f1ec0SSzymon Olewniczak    protected function p_wiki_dw2pdf($id, $rev = '', $date_at = '') {
366e53f1ec0SSzymon Olewniczak        $file = wikiFN($id, $rev);
367e53f1ec0SSzymon Olewniczak
368e53f1ec0SSzymon Olewniczak        if(!file_exists($file)) return '';
369e53f1ec0SSzymon Olewniczak
370e53f1ec0SSzymon Olewniczak        //ensure $id is in global $ID (needed for parsing)
371e53f1ec0SSzymon Olewniczak        global $ID;
372e53f1ec0SSzymon Olewniczak        $keep = $ID;
373e53f1ec0SSzymon Olewniczak        $ID   = $id;
374e53f1ec0SSzymon Olewniczak
375e53f1ec0SSzymon Olewniczak        if($rev || $date_at) {
376e53f1ec0SSzymon Olewniczak            $ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at); //no caching on old revisions
377e53f1ec0SSzymon Olewniczak        } else {
378e53f1ec0SSzymon Olewniczak            $ret = p_cached_output($file, 'dw2pdf', $id);
379e53f1ec0SSzymon Olewniczak        }
380e53f1ec0SSzymon Olewniczak
381e53f1ec0SSzymon Olewniczak        //restore ID (just in case)
382e53f1ec0SSzymon Olewniczak        $ID = $keep;
383e53f1ec0SSzymon Olewniczak
384e53f1ec0SSzymon Olewniczak        return $ret;
385e53f1ec0SSzymon Olewniczak    }
386e53f1ec0SSzymon Olewniczak
387e53f1ec0SSzymon Olewniczak    /**
388d63e7fe7SGerrit Uitslag     * Build a pdf from the html
389d63e7fe7SGerrit Uitslag     *
390d63e7fe7SGerrit Uitslag     * @param string $cachefile
391d9c13ec7SGerrit Uitslag     * @param Doku_Event $event
3927c79bc79SGerrit Uitslag     * @throws \Mpdf\MpdfException
393d63e7fe7SGerrit Uitslag     */
3942d9cd424SGerrit Uitslag    protected function generatePDF($cachefile, $event) {
3952d9cd424SGerrit Uitslag        global $REV, $INPUT, $DATE_AT;
396e53f1ec0SSzymon Olewniczak
3972d9cd424SGerrit Uitslag        if ($event->data == 'export_pdf') { //only one page is exported
398e53f1ec0SSzymon Olewniczak            $rev = $REV;
399e53f1ec0SSzymon Olewniczak            $date_at = $DATE_AT;
400e53f1ec0SSzymon Olewniczak        } else { //we are exporting entre namespace, ommit revisions
401e53f1ec0SSzymon Olewniczak            $rev = $date_at = '';
402e53f1ec0SSzymon Olewniczak        }
40387c86ddaSAndreas Gohr
40402f9a447SGerrit Uitslag        //some shortcuts to export settings
40502f9a447SGerrit Uitslag        $hasToC = $this->getExportConfig('hasToC');
40602f9a447SGerrit Uitslag        $levels = $this->getExportConfig('levels');
40702f9a447SGerrit Uitslag        $isDebug = $this->getExportConfig('isDebug');
408b80f709fSNicolas        $watermark = $this->getExportConfig('watermark');
4096ea88a05SAndreas Gohr
4101ef68647SAndreas Gohr        // initialize PDF library
411cde5a1b3SAndreas Gohr        require_once(dirname(__FILE__) . "/DokuPDF.class.php");
4126ea88a05SAndreas Gohr
4134870b378SLarsDW223        $mpdf = new DokuPDF($this->getExportConfig('pagesize'),
4144870b378SLarsDW223                            $this->getExportConfig('orientation'),
4154870b378SLarsDW223                            $this->getExportConfig('font-size'));
416ee19bac3SLuigi Micco
417d62df65bSAndreas Gohr        // let mpdf fix local links
418d62df65bSAndreas Gohr        $self = parse_url(DOKU_URL);
419d62df65bSAndreas Gohr        $url = $self['scheme'] . '://' . $self['host'];
42002f9a447SGerrit Uitslag        if($self['port']) {
42102f9a447SGerrit Uitslag            $url .= ':' . $self['port'];
42202f9a447SGerrit Uitslag        }
423d9c13ec7SGerrit Uitslag        $mpdf->SetBasePath($url);
424d62df65bSAndreas Gohr
42556d13144SAndreas Gohr        // Set the title
42603352761SKirsten Roschanski        $mpdf->SetTitle($this->title);
42756d13144SAndreas Gohr
428d63e7fe7SGerrit Uitslag        // some default document settings
429d63e7fe7SGerrit Uitslag        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
430213fdb75SGerrit Uitslag        //      single-side document has only odd pages
431213fdb75SGerrit Uitslag        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
432daa70883SAndreas Gohr        $mpdf->setAutoTopMargin = 'stretch';
433daa70883SAndreas Gohr        $mpdf->setAutoBottomMargin = 'stretch';
43402f9a447SGerrit Uitslag//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
43502f9a447SGerrit Uitslag        if($hasToC) {
43602f9a447SGerrit Uitslag            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off'); //use italic pageno until ToC
43702f9a447SGerrit Uitslag            $mpdf->h2toc = $levels;
43802f9a447SGerrit Uitslag        } else {
43902f9a447SGerrit Uitslag            $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
44002f9a447SGerrit Uitslag        }
4412eedf77dSAndreas Gohr
442b80f709fSNicolas        // Watermarker
443b80f709fSNicolas        if($watermark) {
444b80f709fSNicolas            $mpdf->SetWatermarkText($watermark);
445b80f709fSNicolas            $mpdf->showWatermarkText = true;
446b80f709fSNicolas        }
447b80f709fSNicolas
44856d13144SAndreas Gohr        // load the template
44903352761SKirsten Roschanski        $template = $this->load_template();
450ee19bac3SLuigi Micco
4511ef68647SAndreas Gohr        // prepare HTML header styles
452a2c33768SGerrit Uitslag        $html = '';
45302f9a447SGerrit Uitslag        if($isDebug) {
454a2c33768SGerrit Uitslag            $html .= '<html><head>';
455737417c6SKlap-in            $html .= '<style type="text/css">';
456a2c33768SGerrit Uitslag        }
457db1aa1bfSKirsten Roschanski
458db1aa1bfSKirsten Roschanski        $styles = '@page { size:auto; ' . $template['page'] . '}';
459a2c33768SGerrit Uitslag        $styles .= '@page :first {' . $template['first'] . '}';
460254467c4SGerrit Uitslag
461254467c4SGerrit Uitslag        $styles .= '@page landscape-page { size:landscape }';
462254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
463254467c4SGerrit Uitslag        $styles .= '@page portrait-page { size:portrait }';
464254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
465db1aa1bfSKirsten Roschanski        $styles .= $this->load_css();
466254467c4SGerrit Uitslag
467a2c33768SGerrit Uitslag        $mpdf->WriteHTML($styles, 1);
468a2c33768SGerrit Uitslag
46902f9a447SGerrit Uitslag        if($isDebug) {
470a2c33768SGerrit Uitslag            $html .= $styles;
4711ef68647SAndreas Gohr            $html .= '</style>';
4721ef68647SAndreas Gohr            $html .= '</head><body>';
473a2c33768SGerrit Uitslag        }
474a2c33768SGerrit Uitslag
475a2c33768SGerrit Uitslag        $body_start = $template['html'];
476a2c33768SGerrit Uitslag        $body_start .= '<div class="dokuwiki">';
4772eedf77dSAndreas Gohr
4781e45476bSmnapp        // insert the cover page
479a2c33768SGerrit Uitslag        $body_start .= $template['cover'];
480a2c33768SGerrit Uitslag
481a2c33768SGerrit Uitslag        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
48202f9a447SGerrit Uitslag        if($isDebug) {
483a2c33768SGerrit Uitslag            $html .= $body_start;
484a2c33768SGerrit Uitslag        }
48502f9a447SGerrit Uitslag        if($hasToC) {
48602f9a447SGerrit 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
48702f9a447SGerrit Uitslag            //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
48802f9a447SGerrit Uitslag            //      - there is no page numbering at the pages of the ToC
48902f9a447SGerrit Uitslag            $mpdf->TOCpagebreakByArray(
49002f9a447SGerrit Uitslag                array(
491230b098dSGerrit Uitslag                    'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
492230b098dSGerrit Uitslag                    'toc-bookmarkText' => $this->getLang('tocheader'),
49302f9a447SGerrit Uitslag                    'links' => true,
49402f9a447SGerrit Uitslag                    'outdent' => '1em',
49502f9a447SGerrit Uitslag                    'resetpagenum' => true, //start pagenumbering after ToC
49602f9a447SGerrit Uitslag                    'pagenumstyle' => '1'
49702f9a447SGerrit Uitslag                )
49802f9a447SGerrit Uitslag            );
49902f9a447SGerrit Uitslag            $html .= '<tocpagebreak>';
50002f9a447SGerrit Uitslag        }
50102f9a447SGerrit Uitslag
5021ef68647SAndreas Gohr        // loop over all pages
503c7138b3fSGerrit Uitslag        $counter = 0;
504c7138b3fSGerrit Uitslag        $no_pages = count($this->list);
505c7138b3fSGerrit Uitslag        foreach($this->list as $page) {
506c7138b3fSGerrit Uitslag            $counter++;
507b3eed6e3SGerrit Uitslag
50879be256fSMichael Große            $pagehtml = $this->p_wiki_dw2pdf($page, $rev, $date_at);
509e53f1ec0SSzymon Olewniczak            //file doesn't exists
510e53f1ec0SSzymon Olewniczak            if($pagehtml == '') {
511b3eed6e3SGerrit Uitslag                continue;
512b3eed6e3SGerrit Uitslag            }
513719256adSGerrit Uitslag            $pagehtml .= $this->page_depend_replacements($template['cite'], $page);
514c7138b3fSGerrit Uitslag            if($counter < $no_pages) {
515a2c33768SGerrit Uitslag                $pagehtml .= '<pagebreak />';
516a2c33768SGerrit Uitslag            }
517a2c33768SGerrit Uitslag
518a2c33768SGerrit Uitslag            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
51902f9a447SGerrit Uitslag            if($isDebug) {
520a2c33768SGerrit Uitslag                $html .= $pagehtml;
5211ef68647SAndreas Gohr            }
522ee19bac3SLuigi Micco        }
523ee19bac3SLuigi Micco
52433c15297SGerrit Uitslag        // insert the back page
525a2c33768SGerrit Uitslag        $body_end = $template['back'];
52633c15297SGerrit Uitslag
527a2c33768SGerrit Uitslag        $body_end .= '</div>';
528a2c33768SGerrit Uitslag
529d63e7fe7SGerrit Uitslag        $mpdf->WriteHTML($body_end, 2, false, true); // finish body html
53002f9a447SGerrit Uitslag        if($isDebug) {
531a2c33768SGerrit Uitslag            $html .= $body_end;
532eeb17e15SAndreas Gohr            $html .= '</body>';
533eeb17e15SAndreas Gohr            $html .= '</html>';
534a2c33768SGerrit Uitslag        }
535f765508eSGerrit Uitslag
536f765508eSGerrit Uitslag        //Return html for debugging
53702f9a447SGerrit Uitslag        if($isDebug) {
53802f9a447SGerrit Uitslag            if($INPUT->str('debughtml', 'text', true) == 'html') {
53926be4eceSGerrit Uitslag                echo $html;
540a2c33768SGerrit Uitslag            } else {
541a2c33768SGerrit Uitslag                header('Content-Type: text/plain; charset=utf-8');
542a2c33768SGerrit Uitslag                echo $html;
543a2c33768SGerrit Uitslag            }
54426be4eceSGerrit Uitslag            exit();
5457c79bc79SGerrit Uitslag        }
546f765508eSGerrit Uitslag
54787c86ddaSAndreas Gohr        // write to cache file
548d63e7fe7SGerrit Uitslag        $mpdf->Output($cachefile, 'F');
54987c86ddaSAndreas Gohr    }
55087c86ddaSAndreas Gohr
551d63e7fe7SGerrit Uitslag    /**
552d63e7fe7SGerrit Uitslag     * @param string $cachefile
553d63e7fe7SGerrit Uitslag     */
55403352761SKirsten Roschanski    protected function sendPDFFile($cachefile) {
55587c86ddaSAndreas Gohr        header('Content-Type: application/pdf');
556b853b723SAndreas Gohr        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
55787c86ddaSAndreas Gohr        header('Pragma: public');
558d63e7fe7SGerrit Uitslag        http_conditionalRequest(filemtime($cachefile));
559c0956f69SMichael Große        global $INPUT;
560f7b24f48SMichael Große        $outputTarget = $INPUT->str('outputTarget', $this->getConf('output'));
56187c86ddaSAndreas Gohr
56203352761SKirsten Roschanski        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
563c0956f69SMichael Große        if($outputTarget === 'file') {
5649a3c8d9fSAndreas Gohr            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
56587c86ddaSAndreas Gohr        } else {
5669a3c8d9fSAndreas Gohr            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
56787c86ddaSAndreas Gohr        }
568ee19bac3SLuigi Micco
569b3eed6e3SGerrit Uitslag        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
570b3eed6e3SGerrit Uitslag        header('Set-Cookie: fileDownload=true; path=/');
571b3eed6e3SGerrit Uitslag
572e993da11SGerrit Uitslag        //try to send file, and exit if done
573d63e7fe7SGerrit Uitslag        http_sendfile($cachefile);
57487c86ddaSAndreas Gohr
575d63e7fe7SGerrit Uitslag        $fp = @fopen($cachefile, "rb");
57687c86ddaSAndreas Gohr        if($fp) {
577d63e7fe7SGerrit Uitslag            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
57887c86ddaSAndreas Gohr        } else {
57987c86ddaSAndreas Gohr            header("HTTP/1.0 500 Internal Server Error");
58087c86ddaSAndreas Gohr            print "Could not read file - bad permissions?";
58187c86ddaSAndreas Gohr        }
5821ef68647SAndreas Gohr        exit();
5831ef68647SAndreas Gohr    }
5841ef68647SAndreas Gohr
5856be736bfSGerrit Uitslag    /**
5862eedf77dSAndreas Gohr     * Load the various template files and prepare the HTML/CSS for insertion
58744e8e8fbSGerrit Uitslag     *
58844e8e8fbSGerrit Uitslag     * @return array
5891ef68647SAndreas Gohr     */
59003352761SKirsten Roschanski    protected function load_template() {
5911ef68647SAndreas Gohr        global $ID;
5921ef68647SAndreas Gohr        global $conf;
5931ef68647SAndreas Gohr
5942eedf77dSAndreas Gohr        // this is what we'll return
5952eedf77dSAndreas Gohr        $output = array(
5961e45476bSmnapp            'cover' => '',
5972eedf77dSAndreas Gohr            'html'  => '',
5982eedf77dSAndreas Gohr            'page'  => '',
5992eedf77dSAndreas Gohr            'first' => '',
6002eedf77dSAndreas Gohr            'cite'  => '',
6012eedf77dSAndreas Gohr        );
6022eedf77dSAndreas Gohr
6032eedf77dSAndreas Gohr        // prepare header/footer elements
6042eedf77dSAndreas Gohr        $html = '';
60533c15297SGerrit Uitslag        foreach(array('header', 'footer') as $section) {
60633c15297SGerrit Uitslag            foreach(array('', '_odd', '_even', '_first') as $order) {
60702f9a447SGerrit Uitslag                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
60833c15297SGerrit Uitslag                if(file_exists($file)) {
60933c15297SGerrit Uitslag                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
61033c15297SGerrit Uitslag                    $html .= file_get_contents($file) . DOKU_LF;
61133c15297SGerrit Uitslag                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
6122eedf77dSAndreas Gohr
6132eedf77dSAndreas Gohr                    // register the needed pseudo CSS
61433c15297SGerrit Uitslag                    if($order == '_first') {
61533c15297SGerrit Uitslag                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
61633c15297SGerrit Uitslag                    } elseif($order == '_even') {
61733c15297SGerrit Uitslag                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
61833c15297SGerrit Uitslag                    } elseif($order == '_odd') {
61933c15297SGerrit Uitslag                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
620daa70883SAndreas Gohr                    } else {
62133c15297SGerrit Uitslag                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
6222eedf77dSAndreas Gohr                    }
6232eedf77dSAndreas Gohr                }
6242eedf77dSAndreas Gohr            }
6252eedf77dSAndreas Gohr        }
6262eedf77dSAndreas Gohr
6271ef68647SAndreas Gohr        // prepare replacements
6281ef68647SAndreas Gohr        $replace = array(
6291ef68647SAndreas Gohr            '@PAGE@'    => '{PAGENO}',
63002f9a447SGerrit Uitslag            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
63103352761SKirsten Roschanski            '@TITLE@'   => hsc($this->title),
6321ef68647SAndreas Gohr            '@WIKI@'    => $conf['title'],
6331ef68647SAndreas Gohr            '@WIKIURL@' => DOKU_URL,
6341ef68647SAndreas Gohr            '@DATE@'    => dformat(time()),
6355d6fbaeaSAndreas Gohr            '@BASE@'    => DOKU_BASE,
636893987a2SAndreas Gohr            '@INC@'     => DOKU_INC,
637893987a2SAndreas Gohr            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
638893987a2SAndreas Gohr            '@TPLINC@'  => DOKU_INC . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
6391ef68647SAndreas Gohr        );
6401ef68647SAndreas Gohr
6412eedf77dSAndreas Gohr        // set HTML element
642a180c973SKlap-in        $html = str_replace(array_keys($replace), array_values($replace), $html);
643a180c973SKlap-in        //TODO For bookcreator $ID (= bookmanager page) makes no sense
644a180c973SKlap-in        $output['html'] = $this->page_depend_replacements($html, $ID);
6451ef68647SAndreas Gohr
6461e45476bSmnapp        // cover page
64702f9a447SGerrit Uitslag        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
64833c15297SGerrit Uitslag        if(file_exists($coverfile)) {
64933c15297SGerrit Uitslag            $output['cover'] = file_get_contents($coverfile);
6501e45476bSmnapp            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
6519b071da5SMichael            $output['cover'] = $this->page_depend_replacements($output['cover'], $ID);
6526e2ec302SGerrit Uitslag            $output['cover'] .= '<pagebreak />';
6531e45476bSmnapp        }
6541e45476bSmnapp
65533c15297SGerrit Uitslag        // cover page
65602f9a447SGerrit Uitslag        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
65733c15297SGerrit Uitslag        if(file_exists($backfile)) {
65833c15297SGerrit Uitslag            $output['back'] = '<pagebreak />';
65933c15297SGerrit Uitslag            $output['back'] .= file_get_contents($backfile);
66033c15297SGerrit Uitslag            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
6619b071da5SMichael            $output['back'] = $this->page_depend_replacements($output['back'], $ID);
66233c15297SGerrit Uitslag        }
66333c15297SGerrit Uitslag
6642eedf77dSAndreas Gohr        // citation box
66502f9a447SGerrit Uitslag        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
66633c15297SGerrit Uitslag        if(file_exists($citationfile)) {
66733c15297SGerrit Uitslag            $output['cite'] = file_get_contents($citationfile);
6682eedf77dSAndreas Gohr            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
6692eedf77dSAndreas Gohr        }
6701ef68647SAndreas Gohr
6712eedf77dSAndreas Gohr        return $output;
6721ef68647SAndreas Gohr    }
6731ef68647SAndreas Gohr
6741ef68647SAndreas Gohr    /**
675a180c973SKlap-in     * @param string $raw code with placeholders
676a180c973SKlap-in     * @param string $id  pageid
677a180c973SKlap-in     * @return string
678a180c973SKlap-in     */
679a180c973SKlap-in    protected function page_depend_replacements($raw, $id) {
680e53f1ec0SSzymon Olewniczak        global $REV, $DATE_AT;
681a180c973SKlap-in
6829b2636c8SDiego Belmar        // generate qr code for this page using quickchart.io (Google infographics api was deprecated in March 14, 2019)
683a180c973SKlap-in        $qr_code = '';
684a180c973SKlap-in        if($this->getConf('qrcodesize')) {
685a180c973SKlap-in            $url = urlencode(wl($id, '', '&', true));
6869b2636c8SDiego Belmar            $qr_code = '<img src="https://quickchart.io/qr?size=' .
6879b2636c8SDiego Belmar                $this->getConf('qrcodesize') . '&text=' . $url . '&margin=1&ecLevel=Q" />';
688a180c973SKlap-in        }
689a180c973SKlap-in        // prepare replacements
690a180c973SKlap-in        $replace['@ID@']      = $id;
691a180c973SKlap-in        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
692e53f1ec0SSzymon Olewniczak
693e53f1ec0SSzymon Olewniczak        $params = array();
694e53f1ec0SSzymon Olewniczak        if($DATE_AT) {
695e53f1ec0SSzymon Olewniczak            $params['at'] = $DATE_AT;
696e53f1ec0SSzymon Olewniczak        } elseif($REV) {
697e53f1ec0SSzymon Olewniczak            $params['rev'] = $REV;
698e53f1ec0SSzymon Olewniczak        }
699e53f1ec0SSzymon Olewniczak        $replace['@PAGEURL@'] = wl($id, $params, true, "&");
700a180c973SKlap-in        $replace['@QRCODE@']  = $qr_code;
701a180c973SKlap-in
702d824d23dSAnna Dabrowska        $content = $raw;
703a12c41c3SAnna Dabrowska
704a12c41c3SAnna Dabrowska        // let other plugins define their own replacements
705d824d23dSAnna Dabrowska        $evdata = ['id' => $id, 'replace' => &$replace, 'content' => &$content];
706a12c41c3SAnna Dabrowska        $event = new Doku_Event('PLUGIN_DW2PDF_REPLACE', $evdata);
707d824d23dSAnna Dabrowska        if ($event->advise_before()) {
708e3d68265SGerrit Uitslag            $content = str_replace(array_keys($replace), array_values($replace), $raw);
709d824d23dSAnna Dabrowska        }
710e3d68265SGerrit Uitslag
711a12c41c3SAnna Dabrowska        // plugins may post-process HTML, e.g to clean up unused replacements
712a12c41c3SAnna Dabrowska        $event->advise_after();
713a12c41c3SAnna Dabrowska
714e3d68265SGerrit Uitslag        // @DATE(<date>[, <format>])@
715e3d68265SGerrit Uitslag        $content = preg_replace_callback(
716e3d68265SGerrit Uitslag            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
717e3d68265SGerrit Uitslag            array($this, 'replacedate'),
718e3d68265SGerrit Uitslag            $content
719e3d68265SGerrit Uitslag        );
720e3d68265SGerrit Uitslag
721e3d68265SGerrit Uitslag        return $content;
722a180c973SKlap-in    }
723a180c973SKlap-in
724e3d68265SGerrit Uitslag
725e3d68265SGerrit Uitslag    /**
726e3d68265SGerrit Uitslag     * (callback) Replace date by request datestring
727e3d68265SGerrit Uitslag     * e.g. '%m(30-11-1975)' is replaced by '11'
728e3d68265SGerrit Uitslag     *
729e3d68265SGerrit Uitslag     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
730e3d68265SGerrit Uitslag     * @return string
731e3d68265SGerrit Uitslag     */
732e3d68265SGerrit Uitslag    function replacedate($match) {
733e3d68265SGerrit Uitslag        global $conf;
734e3d68265SGerrit Uitslag        //no 2nd argument for default date format
735e3d68265SGerrit Uitslag        if($match[2] == null) {
736e3d68265SGerrit Uitslag            $match[2] = $conf['dformat'];
737e3d68265SGerrit Uitslag        }
738e3d68265SGerrit Uitslag        return strftime($match[2], strtotime($match[1]));
739e3d68265SGerrit Uitslag    }
740e3d68265SGerrit Uitslag
741a180c973SKlap-in    /**
7421c14c879SAndreas Gohr     * Load all the style sheets and apply the needed replacements
7431ef68647SAndreas Gohr     */
7441c14c879SAndreas Gohr    protected function load_css() {
745737417c6SKlap-in        global $conf;
7467c79bc79SGerrit Uitslag        //reuse the CSS dispatcher functions without triggering the main function
7471c14c879SAndreas Gohr        define('SIMPLE_TEST', 1);
7481c14c879SAndreas Gohr        require_once(DOKU_INC . 'lib/exe/css.php');
749ee19bac3SLuigi Micco
7501c14c879SAndreas Gohr        // prepare CSS files
7511c14c879SAndreas Gohr        $files = array_merge(
7521c14c879SAndreas Gohr            array(
7531c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/screen.css'
7541c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
7551c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/print.css'
7561c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
7571c14c879SAndreas Gohr            ),
75858e6409eSAndreas Gohr            $this->css_pluginPDFstyles(),
7591c14c879SAndreas Gohr            array(
7601c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
7611c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
7621c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
7631c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
7641c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
7651c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
7661c14c879SAndreas Gohr            )
7671c14c879SAndreas Gohr        );
7681c14c879SAndreas Gohr        $css = '';
7691c14c879SAndreas Gohr        foreach($files as $file => $location) {
77028e636eaSGerrit Uitslag            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
77128e636eaSGerrit Uitslag            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
7721c14c879SAndreas Gohr            $css .= css_loadfile($file, $location);
7731ef68647SAndreas Gohr        }
7741ef68647SAndreas Gohr
77528e636eaSGerrit Uitslag        if(function_exists('css_parseless')) {
7761c14c879SAndreas Gohr            // apply pattern replacements
7777c6ca3bcSMichael Große            if (function_exists('css_styleini')) {
7787c6ca3bcSMichael Große                // compatiblity layer for pre-Greebo releases of DokuWiki
77928e636eaSGerrit Uitslag                $styleini = css_styleini($conf['template']);
7807c6ca3bcSMichael Große            } else {
7817c6ca3bcSMichael Große                // Greebo functionality
7827c6ca3bcSMichael Große                $styleUtils = new \dokuwiki\StyleUtils();
783*d0f0c534SGerrit Uitslag                $styleini = $styleUtils->cssStyleini($conf['template']); // older versions need still the template
7847c6ca3bcSMichael Große            }
78528e636eaSGerrit Uitslag            $css = css_applystyle($css, $styleini['replacements']);
78628e636eaSGerrit Uitslag
78728e636eaSGerrit Uitslag            // parse less
78828e636eaSGerrit Uitslag            $css = css_parseless($css);
78928e636eaSGerrit Uitslag        } else {
79028e636eaSGerrit Uitslag            // @deprecated 2013-12-19: fix backward compatibility
7911c14c879SAndreas Gohr            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
79228e636eaSGerrit Uitslag        }
7931ef68647SAndreas Gohr
7941c14c879SAndreas Gohr        return $css;
795ee19bac3SLuigi Micco    }
7961c14c879SAndreas Gohr
79758e6409eSAndreas Gohr    /**
79858e6409eSAndreas Gohr     * Returns a list of possible Plugin PDF Styles
79958e6409eSAndreas Gohr     *
80058e6409eSAndreas Gohr     * Checks for a pdf.css, falls back to print.css
80158e6409eSAndreas Gohr     *
80258e6409eSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
80358e6409eSAndreas Gohr     */
8046be736bfSGerrit Uitslag    protected function css_pluginPDFstyles() {
80558e6409eSAndreas Gohr        $list = array();
80658e6409eSAndreas Gohr        $plugins = plugin_list();
807f54b51f7SAndreas Gohr
808f54b51f7SAndreas Gohr        $usestyle = explode(',', $this->getConf('usestyles'));
80958e6409eSAndreas Gohr        foreach($plugins as $p) {
810f54b51f7SAndreas Gohr            if(in_array($p, $usestyle)) {
811f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
8128003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/";
8138003b493SGerrit Uitslag
814f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
8158003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
816f54b51f7SAndreas Gohr            }
817f54b51f7SAndreas Gohr
8188003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/";
8198003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/";
8208003b493SGerrit Uitslag
821ab96d816SMichael Große            if(file_exists(DOKU_PLUGIN . "$p/pdf.css") || file_exists(DOKU_PLUGIN . "$p/pdf.less")) {
82258e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
8238003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/";
82458e6409eSAndreas Gohr            } else {
82558e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
8268003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/";
82758e6409eSAndreas Gohr            }
82858e6409eSAndreas Gohr        }
82958e6409eSAndreas Gohr        return $list;
83058e6409eSAndreas Gohr    }
831ad18f4e1SGerrit Uitslag
832ad18f4e1SGerrit Uitslag    /**
83360e59de7SGerrit Uitslag     * Returns array of pages which will be included in the exported pdf
83460e59de7SGerrit Uitslag     *
83560e59de7SGerrit Uitslag     * @return array
83660e59de7SGerrit Uitslag     */
83760e59de7SGerrit Uitslag    public function getExportedPages() {
83860e59de7SGerrit Uitslag        return $this->list;
83960e59de7SGerrit Uitslag    }
84060e59de7SGerrit Uitslag
84160e59de7SGerrit Uitslag    /**
842ad18f4e1SGerrit Uitslag     * usort callback to sort by file lastmodified time
84344e8e8fbSGerrit Uitslag     *
84444e8e8fbSGerrit Uitslag     * @param array $a
84544e8e8fbSGerrit Uitslag     * @param array $b
84644e8e8fbSGerrit Uitslag     * @return int
847ad18f4e1SGerrit Uitslag     */
848ad18f4e1SGerrit Uitslag    public function _datesort($a, $b) {
849ad18f4e1SGerrit Uitslag        if($b['rev'] < $a['rev']) return -1;
850ad18f4e1SGerrit Uitslag        if($b['rev'] > $a['rev']) return 1;
851ad18f4e1SGerrit Uitslag        return strcmp($b['id'], $a['id']);
852ad18f4e1SGerrit Uitslag    }
853ad18f4e1SGerrit Uitslag
854ad18f4e1SGerrit Uitslag    /**
855ad18f4e1SGerrit Uitslag     * usort callback to sort by page id
85644e8e8fbSGerrit Uitslag     * @param array $a
85744e8e8fbSGerrit Uitslag     * @param array $b
85844e8e8fbSGerrit Uitslag     * @return int
859ad18f4e1SGerrit Uitslag     */
860ad18f4e1SGerrit Uitslag    public function _pagenamesort($a, $b) {
86120025b90SAndreas Gohr        global $conf;
86220025b90SAndreas Gohr
86320025b90SAndreas Gohr        $partsA = explode(':', $a['id']);
86420025b90SAndreas Gohr        $countA = count($partsA);
86520025b90SAndreas Gohr        $partsB = explode(':', $b['id']);
86620025b90SAndreas Gohr        $countB = count($partsB);
867e00f6071SAndreas Gohr        $max = max($countA, $countB);
86820025b90SAndreas Gohr
86920025b90SAndreas Gohr
87020025b90SAndreas Gohr        // compare namepsace by namespace
871e00f6071SAndreas Gohr        for ($i = 0; $i < $max; $i++) {
872e00f6071SAndreas Gohr            $partA = $partsA[$i] ?: null;
873e00f6071SAndreas Gohr            $partB = $partsB[$i] ?: null;
87420025b90SAndreas Gohr
87520025b90SAndreas Gohr            // have we reached the page level?
876e00f6071SAndreas Gohr            if ($i === ($countA - 1) || $i === ($countB - 1)) {
87720025b90SAndreas Gohr                // start page first
87820025b90SAndreas Gohr                if ($partA == $conf['start']) return -1;
87920025b90SAndreas Gohr                if ($partB == $conf['start']) return 1;
88020025b90SAndreas Gohr            }
88120025b90SAndreas Gohr
882e00f6071SAndreas Gohr            // prefer page over namespace
883e00f6071SAndreas Gohr            if($partA === $partB) {
884e00f6071SAndreas Gohr                if (!isset($partsA[$i + 1])) return -1;
885e00f6071SAndreas Gohr                if (!isset($partsB[$i + 1])) return 1;
886e00f6071SAndreas Gohr                continue;
887e00f6071SAndreas Gohr            }
888e00f6071SAndreas Gohr
889e00f6071SAndreas Gohr
89020025b90SAndreas Gohr            // simply compare
89141e5d4e2SAndreas Gohr            return strnatcmp($partA, $partB);
89220025b90SAndreas Gohr        }
89320025b90SAndreas Gohr
89441e5d4e2SAndreas Gohr        return strnatcmp($a['id'], $b['id']);
895ad18f4e1SGerrit Uitslag    }
89626be4eceSGerrit Uitslag
89726be4eceSGerrit Uitslag    /**
8987c79bc79SGerrit Uitslag     * Collects settings from:
89902f9a447SGerrit Uitslag     *   1. url parameters
90002f9a447SGerrit Uitslag     *   2. plugin config
90102f9a447SGerrit Uitslag     *   3. global config
90202f9a447SGerrit Uitslag     */
90302f9a447SGerrit Uitslag    protected function loadExportConfig() {
90402f9a447SGerrit Uitslag        global $INPUT;
90502f9a447SGerrit Uitslag        global $conf;
90602f9a447SGerrit Uitslag
90702f9a447SGerrit Uitslag        $this->exportConfig = array();
90802f9a447SGerrit Uitslag
90902f9a447SGerrit Uitslag        // decide on the paper setup from param or config
91002f9a447SGerrit Uitslag        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
91102f9a447SGerrit Uitslag        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
91202f9a447SGerrit Uitslag
9134870b378SLarsDW223        // decide on the font-size from param or config
9144870b378SLarsDW223        $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
9154870b378SLarsDW223
916213fdb75SGerrit Uitslag        $doublesided = $INPUT->bool('doublesided', (bool) $this->getConf('doublesided'));
917213fdb75SGerrit Uitslag        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
918213fdb75SGerrit Uitslag
919b80f709fSNicolas        $this->exportConfig['watermark'] = $INPUT->str('watermark', '');
920b80f709fSNicolas
921213fdb75SGerrit Uitslag        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'));
92202f9a447SGerrit Uitslag        $levels = array();
92302f9a447SGerrit Uitslag        if($hasToC) {
92402f9a447SGerrit Uitslag            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
92502f9a447SGerrit Uitslag            list($top_input, $max_input) = explode('-', $toclevels, 2);
92602f9a447SGerrit Uitslag            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
92702f9a447SGerrit Uitslag            $bounds_input = array(
92802f9a447SGerrit Uitslag                'top' => array(
92902f9a447SGerrit Uitslag                    (int) $top_input,
93002f9a447SGerrit Uitslag                    (int) $top_conf
93102f9a447SGerrit Uitslag                ),
93202f9a447SGerrit Uitslag                'max' => array(
93302f9a447SGerrit Uitslag                    (int) $max_input,
93402f9a447SGerrit Uitslag                    (int) $max_conf
93502f9a447SGerrit Uitslag                )
93602f9a447SGerrit Uitslag            );
93702f9a447SGerrit Uitslag            $bounds = array(
93802f9a447SGerrit Uitslag                'top' => $conf['toptoclevel'],
93902f9a447SGerrit Uitslag                'max' => $conf['maxtoclevel']
94002f9a447SGerrit Uitslag
94102f9a447SGerrit Uitslag            );
94202f9a447SGerrit Uitslag            foreach($bounds_input as $bound => $values) {
94302f9a447SGerrit Uitslag                foreach($values as $value) {
94402f9a447SGerrit Uitslag                    if($value > 0 && $value <= 5) {
94502f9a447SGerrit Uitslag                        //stop at valid value and store
94602f9a447SGerrit Uitslag                        $bounds[$bound] = $value;
94702f9a447SGerrit Uitslag                        break;
94802f9a447SGerrit Uitslag                    }
94902f9a447SGerrit Uitslag                }
95002f9a447SGerrit Uitslag            }
95102f9a447SGerrit Uitslag
95202f9a447SGerrit Uitslag            if($bounds['max'] < $bounds['top']) {
95302f9a447SGerrit Uitslag                $bounds['max'] = $bounds['top'];
95402f9a447SGerrit Uitslag            }
95502f9a447SGerrit Uitslag
95602f9a447SGerrit Uitslag            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
95702f9a447SGerrit Uitslag                $levels["H$level"] = $level - 1;
95802f9a447SGerrit Uitslag            }
95902f9a447SGerrit Uitslag        }
96002f9a447SGerrit Uitslag        $this->exportConfig['hasToC'] = $hasToC;
96102f9a447SGerrit Uitslag        $this->exportConfig['levels'] = $levels;
96202f9a447SGerrit Uitslag
96302f9a447SGerrit Uitslag        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
96402f9a447SGerrit Uitslag
96502f9a447SGerrit Uitslag        $tplconf = $this->getConf('template');
96605d2b507SGerrit Uitslag        $tpl = $INPUT->str('tpl', $tplconf, true);
96702f9a447SGerrit Uitslag        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
96802f9a447SGerrit Uitslag            $tpl = $tplconf;
96902f9a447SGerrit Uitslag        }
97002f9a447SGerrit Uitslag        if(!$tpl){
97102f9a447SGerrit Uitslag            $tpl = 'default';
97202f9a447SGerrit Uitslag        }
97302f9a447SGerrit Uitslag        $this->exportConfig['template'] = $tpl;
97402f9a447SGerrit Uitslag
97502f9a447SGerrit Uitslag        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
97602f9a447SGerrit Uitslag    }
97702f9a447SGerrit Uitslag
97802f9a447SGerrit Uitslag    /**
97902f9a447SGerrit Uitslag     * Returns requested config
98002f9a447SGerrit Uitslag     *
98102f9a447SGerrit Uitslag     * @param string $name
98202f9a447SGerrit Uitslag     * @param mixed  $notset
98302f9a447SGerrit Uitslag     * @return mixed|bool
98402f9a447SGerrit Uitslag     */
98502f9a447SGerrit Uitslag    public function getExportConfig($name, $notset = false) {
98602f9a447SGerrit Uitslag        if ($this->exportConfig === null){
98702f9a447SGerrit Uitslag            $this->loadExportConfig();
98802f9a447SGerrit Uitslag        }
98902f9a447SGerrit Uitslag
99002f9a447SGerrit Uitslag        if(isset($this->exportConfig[$name])){
99102f9a447SGerrit Uitslag            return $this->exportConfig[$name];
99202f9a447SGerrit Uitslag        }else{
99302f9a447SGerrit Uitslag            return $notset;
99402f9a447SGerrit Uitslag        }
99502f9a447SGerrit Uitslag    }
996d63e7fe7SGerrit Uitslag
997d63e7fe7SGerrit Uitslag    /**
998d63e7fe7SGerrit Uitslag     * Add 'export pdf'-button to pagetools
999d63e7fe7SGerrit Uitslag     *
1000d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
1001d63e7fe7SGerrit Uitslag     */
100244e8e8fbSGerrit Uitslag    public function addbutton(Doku_Event $event) {
1003e53f1ec0SSzymon Olewniczak        global $ID, $REV, $DATE_AT;
1004d63e7fe7SGerrit Uitslag
1005d63e7fe7SGerrit Uitslag        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
1006d63e7fe7SGerrit Uitslag            $params = array('do' => 'export_pdf');
1007e53f1ec0SSzymon Olewniczak            if($DATE_AT) {
1008e53f1ec0SSzymon Olewniczak                $params['at'] = $DATE_AT;
1009e53f1ec0SSzymon Olewniczak            } elseif($REV) {
1010d63e7fe7SGerrit Uitslag                $params['rev'] = $REV;
1011d63e7fe7SGerrit Uitslag            }
1012d63e7fe7SGerrit Uitslag
1013d63e7fe7SGerrit Uitslag            // insert button at position before last (up to top)
1014d63e7fe7SGerrit Uitslag            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
1015d63e7fe7SGerrit Uitslag                array('export_pdf' =>
1016d63e7fe7SGerrit Uitslag                          '<li>'
101772cadc31SChristian Paul                          . '<a href="' . wl($ID, $params) . '"  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
1018d63e7fe7SGerrit Uitslag                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
1019d63e7fe7SGerrit Uitslag                          . '</a>'
1020d63e7fe7SGerrit Uitslag                          . '</li>'
1021d63e7fe7SGerrit Uitslag                ) +
1022d63e7fe7SGerrit Uitslag                array_slice($event->data['items'], -1, 1, true);
1023d63e7fe7SGerrit Uitslag        }
1024d63e7fe7SGerrit Uitslag    }
1025026b594bSAndreas Gohr
1026026b594bSAndreas Gohr    /**
1027026b594bSAndreas Gohr     * Add 'export pdf' button to page tools, new SVG based mechanism
1028026b594bSAndreas Gohr     *
1029026b594bSAndreas Gohr     * @param Doku_Event $event
1030026b594bSAndreas Gohr     */
1031026b594bSAndreas Gohr    public function addsvgbutton(Doku_Event $event) {
10324c493e44SGerrit Uitslag        global $INFO;
10334c493e44SGerrit Uitslag        if($event->data['view'] != 'page' || !$this->getConf('showexportbutton')) {
10344c493e44SGerrit Uitslag            return;
10354c493e44SGerrit Uitslag        }
10364c493e44SGerrit Uitslag
10374c493e44SGerrit Uitslag        if(!$INFO['exists']) {
10384c493e44SGerrit Uitslag            return;
10394c493e44SGerrit Uitslag        }
10404c493e44SGerrit Uitslag
1041026b594bSAndreas Gohr        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dw2pdf\MenuItem()]);
1042026b594bSAndreas Gohr    }
1043ee19bac3SLuigi Micco}
1044