xref: /plugin/dw2pdf/action.php (revision c4c95814504bb32ebf3f9b6a0e189c19779325fb)
1ee19bac3SLuigi Micco<?php
2852931daSAndreas Gohr
3852931daSAndreas Gohruse dokuwiki\Cache\Cache;
4852931daSAndreas Gohruse dokuwiki\Extension\ActionPlugin;
5852931daSAndreas Gohruse dokuwiki\Extension\Event;
6852931daSAndreas Gohruse dokuwiki\Extension\EventHandler;
7852931daSAndreas Gohruse dokuwiki\plugin\dw2pdf\MenuItem;
8852931daSAndreas Gohruse dokuwiki\StyleUtils;
9852931daSAndreas Gohruse Mpdf\MpdfException;
10852931daSAndreas Gohr
11ee19bac3SLuigi Micco/**
12ee19bac3SLuigi Micco * dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
13ee19bac3SLuigi Micco *
14852931daSAndreas Gohr * Export html content to pdf, for different url parameter configurations
15852931daSAndreas Gohr * DokuPDF which extends mPDF is used for generating the pdf from html.
16852931daSAndreas Gohr *
17ee19bac3SLuigi Micco * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
18ee19bac3SLuigi Micco * @author     Luigi Micco <l.micco@tiscali.it>
195db42babSAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
20ee19bac3SLuigi Micco */
21852931daSAndreas Gohrclass action_plugin_dw2pdf extends ActionPlugin
2217e88313SGerrit Uitslag{
2302f9a447SGerrit Uitslag    /**
2402f9a447SGerrit Uitslag     * Settings for current export, collected from url param, plugin config, global config
2502f9a447SGerrit Uitslag     *
2602f9a447SGerrit Uitslag     * @var array
2702f9a447SGerrit Uitslag     */
28852931daSAndreas Gohr    protected $exportConfig;
292a127a1dSGerrit Uitslag    /** @var string template name, to use templates from dw2pdf/tpl/<template name> */
3060e59de7SGerrit Uitslag    protected $tpl;
312a127a1dSGerrit Uitslag    /** @var string title of exported pdf */
3203352761SKirsten Roschanski    protected $title;
336a7f9d6cSGerrit Uitslag    /** @var array list of pages included in exported pdf */
3417e88313SGerrit Uitslag    protected $list = [];
352a127a1dSGerrit Uitslag    /** @var bool|string path to temporary cachefile */
369b288b2aSGerrit Uitslag    protected $onetimefile = false;
379c76f78dSVincent GIRARD    protected $currentBookChapter = 0;
381c14c879SAndreas Gohr
391c14c879SAndreas Gohr    /**
401c14c879SAndreas Gohr     * Constructor. Sets the correct template
411c14c879SAndreas Gohr     */
4217e88313SGerrit Uitslag    public function __construct()
4317e88313SGerrit Uitslag    {
44d97a751eSGerrit Uitslag        require_once __DIR__ . '/vendor/autoload.php';
45d97a751eSGerrit Uitslag
4602f9a447SGerrit Uitslag        $this->tpl = $this->getExportConfig('template');
471c14c879SAndreas Gohr    }
481c14c879SAndreas Gohr
49ee19bac3SLuigi Micco    /**
509b288b2aSGerrit Uitslag     * Delete cached files that were for one-time use
519b288b2aSGerrit Uitslag     */
5217e88313SGerrit Uitslag    public function __destruct()
5317e88313SGerrit Uitslag    {
549b288b2aSGerrit Uitslag        if ($this->onetimefile) {
559b288b2aSGerrit Uitslag            unlink($this->onetimefile);
569b288b2aSGerrit Uitslag        }
579b288b2aSGerrit Uitslag    }
589b288b2aSGerrit Uitslag
599b288b2aSGerrit Uitslag    /**
609c76f78dSVincent GIRARD     * Return the value of currentBookChapter, which is the order of the file to be added in a book generation
619c76f78dSVincent GIRARD     */
629c76f78dSVincent GIRARD    public function getCurrentBookChapter()
639c76f78dSVincent GIRARD    {
649c76f78dSVincent GIRARD        return $this->currentBookChapter;
659c76f78dSVincent GIRARD    }
669c76f78dSVincent GIRARD
679c76f78dSVincent GIRARD    /**
68ee19bac3SLuigi Micco     * Register the events
69177a7d30SGerrit Uitslag     *
70177a7d30SGerrit Uitslag     * @param Doku_Event_Handler $controller
71ee19bac3SLuigi Micco     */
72852931daSAndreas Gohr    public function register(EventHandler $controller)
7317e88313SGerrit Uitslag    {
7417e88313SGerrit Uitslag        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert');
7517e88313SGerrit Uitslag        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton');
7617e88313SGerrit Uitslag        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton');
77ee19bac3SLuigi Micco    }
78ee19bac3SLuigi Micco
791c14c879SAndreas Gohr    /**
801c14c879SAndreas Gohr     * Do the HTML to PDF conversion work
81737417c6SKlap-in     *
82737417c6SKlap-in     * @param Doku_Event $event
831c14c879SAndreas Gohr     */
84852931daSAndreas Gohr    public function convert(Event $event)
8517e88313SGerrit Uitslag    {
862a127a1dSGerrit Uitslag        global $REV, $DATE_AT;
872d9cd424SGerrit Uitslag        global $conf, $INPUT;
88ee19bac3SLuigi Micco
891ef68647SAndreas Gohr        // our event?
902a127a1dSGerrit Uitslag        $allowedEvents = ['export_pdfbook', 'export_pdf', 'export_pdfns'];
91*c4c95814SKlap-in        if (!in_array($event->data, $allowedEvents)) {
92*c4c95814SKlap-in            return;
93*c4c95814SKlap-in        }
94ee19bac3SLuigi Micco
952a127a1dSGerrit Uitslag        try {
962a127a1dSGerrit Uitslag            //collect pages and check permissions
97852931daSAndreas Gohr            [$this->title, $this->list] = $this->collectExportablePages($event);
98d63e7fe7SGerrit Uitslag
992d9cd424SGerrit Uitslag            if ($event->data === 'export_pdf' && ($REV || $DATE_AT)) {
1009b288b2aSGerrit Uitslag                $cachefile = tempnam($conf['tmpdir'] . '/dwpdf', 'dw2pdf_');
1019b288b2aSGerrit Uitslag                $this->onetimefile = $cachefile;
102f00df45eSMichael Große                $generateNewPdf = true;
103f00df45eSMichael Große            } else {
104a58f45f0SGerrit Uitslag                // prepare cache and its dependencies
10517e88313SGerrit Uitslag                $depends = [];
10603352761SKirsten Roschanski                $cache = $this->prepareCache($depends);
1079b288b2aSGerrit Uitslag                $cachefile = $cache->cache;
10827195d5bSMichael Große                $generateNewPdf = !$this->getConf('usecache')
10927195d5bSMichael Große                    || $this->getExportConfig('isDebug')
11027195d5bSMichael Große                    || !$cache->useCache($depends);
111f00df45eSMichael Große            }
112d63e7fe7SGerrit Uitslag
113bd977188SGerrit Uitslag            // hard work only when no cache available or needed for debugging
114f00df45eSMichael Große            if ($generateNewPdf) {
115e5f6c2cbSMichael Große                // generating the pdf may take a long time for larger wikis / namespaces with many pages
116e5f6c2cbSMichael Große                set_time_limit(0);
1172a127a1dSGerrit Uitslag                //may throw Mpdf\MpdfException as well
1189b288b2aSGerrit Uitslag                $this->generatePDF($cachefile, $event);
1192a127a1dSGerrit Uitslag            }
1202a127a1dSGerrit Uitslag        } catch (Exception $e) {
1212d9cd424SGerrit Uitslag            if ($INPUT->has('selection')) {
1222d9cd424SGerrit Uitslag                http_status(400);
123852931daSAndreas Gohr                echo $e->getMessage();
1242d9cd424SGerrit Uitslag                exit();
1252d9cd424SGerrit Uitslag            } else {
1262a127a1dSGerrit Uitslag                //prevent Action/Export()
127b34cb34eSSzymon Olewniczak                msg($e->getMessage(), -1);
1282a127a1dSGerrit Uitslag                $event->data = 'redirect';
129d9c13ec7SGerrit Uitslag                return;
130b34cb34eSSzymon Olewniczak            }
131d63e7fe7SGerrit Uitslag        }
1322d9cd424SGerrit Uitslag        $event->preventDefault(); // after prevent, $event->data cannot be changed
133d63e7fe7SGerrit Uitslag
134d63e7fe7SGerrit Uitslag        // deliver the file
1359b288b2aSGerrit Uitslag        $this->sendPDFFile($cachefile);  //exits
136d63e7fe7SGerrit Uitslag    }
137d63e7fe7SGerrit Uitslag
138d63e7fe7SGerrit Uitslag    /**
1392a127a1dSGerrit Uitslag     * Obtain list of pages and title, for different methods of exporting the pdf.
1402a127a1dSGerrit Uitslag     *  - Return a title and selection, throw otherwise an exception
1412a127a1dSGerrit Uitslag     *  - Check permisions
142d63e7fe7SGerrit Uitslag     *
143d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
1448ff32d7bSGerrit Uitslag     * @return array
1452a127a1dSGerrit Uitslag     * @throws Exception
146d63e7fe7SGerrit Uitslag     */
147852931daSAndreas Gohr    protected function collectExportablePages(Event $event)
14817e88313SGerrit Uitslag    {
14936a7917dSGerrit Uitslag        global $ID, $REV;
150d63e7fe7SGerrit Uitslag        global $INPUT;
1512a127a1dSGerrit Uitslag        global $conf, $lang;
152d63e7fe7SGerrit Uitslag
153d63e7fe7SGerrit Uitslag        // list of one or multiple pages
15417e88313SGerrit Uitslag        $list = [];
15528e636eaSGerrit Uitslag
1564b4cebc2SLarsDW223        if ($event->data == 'export_pdf') {
1572a127a1dSGerrit Uitslag            if (auth_quickaclcheck($ID) < AUTH_READ) {  // set more specific denied message
1582a127a1dSGerrit Uitslag                throw new Exception($lang['accessdenied']);
1592a127a1dSGerrit Uitslag            }
160d63e7fe7SGerrit Uitslag            $list[0] = $ID;
1612a127a1dSGerrit Uitslag            $title = $INPUT->str('pdftitle'); //DEPRECATED
1622a127a1dSGerrit Uitslag            $title = $INPUT->str('book_title', $title, true);
1632a127a1dSGerrit Uitslag            if (empty($title)) {
1642a127a1dSGerrit Uitslag                $title = p_get_first_heading($ID);
16515923cb9SGerrit Uitslag            }
166ce8af5d0SHativ            // use page name if title is still empty
1672a127a1dSGerrit Uitslag            if (empty($title)) {
1682a127a1dSGerrit Uitslag                $title = noNS($ID);
169ce8af5d0SHativ            }
170ad18f4e1SGerrit Uitslag
17136a7917dSGerrit Uitslag            $filename = wikiFN($ID, $REV);
17236a7917dSGerrit Uitslag            if (!file_exists($filename)) {
1732a127a1dSGerrit Uitslag                throw new Exception($this->getLang('notexist'));
17436a7917dSGerrit Uitslag            }
1754b4cebc2SLarsDW223        } elseif ($event->data == 'export_pdfns') {
176ad18f4e1SGerrit Uitslag            //check input for title and ns
1772a127a1dSGerrit Uitslag            if (!$title = $INPUT->str('book_title')) {
1782a127a1dSGerrit Uitslag                throw new Exception($this->getLang('needtitle'));
179ad18f4e1SGerrit Uitslag            }
180177a7d30SGerrit Uitslag            $pdfnamespace = cleanID($INPUT->str('book_ns'));
181ad18f4e1SGerrit Uitslag            if (!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
1822a127a1dSGerrit Uitslag                throw new Exception($this->getLang('needns'));
183ad18f4e1SGerrit Uitslag            }
184ad18f4e1SGerrit Uitslag
18526be4eceSGerrit Uitslag            //sort order
186177a7d30SGerrit Uitslag            $order = $INPUT->str('book_order', 'natural', true);
18717e88313SGerrit Uitslag            $sortoptions = ['pagename', 'date', 'natural'];
188ad18f4e1SGerrit Uitslag            if (!in_array($order, $sortoptions)) {
189ad18f4e1SGerrit Uitslag                $order = 'natural';
190ad18f4e1SGerrit Uitslag            }
191ad18f4e1SGerrit Uitslag
19226be4eceSGerrit Uitslag            //search depth
193177a7d30SGerrit Uitslag            $depth = $INPUT->int('book_nsdepth', 0);
194ad18f4e1SGerrit Uitslag            if ($depth < 0) {
195ad18f4e1SGerrit Uitslag                $depth = 0;
196ad18f4e1SGerrit Uitslag            }
19726be4eceSGerrit Uitslag
198ad18f4e1SGerrit Uitslag            //page search
19917e88313SGerrit Uitslag            $result = [];
20017e88313SGerrit Uitslag            $opts = ['depth' => $depth]; //recursive all levels
201ad18f4e1SGerrit Uitslag            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
202ad18f4e1SGerrit Uitslag            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
203ad18f4e1SGerrit Uitslag
20464541781SAnna Dabrowska            // exclude ids
20564541781SAnna Dabrowska            $excludes = $INPUT->arr('excludes');
20664541781SAnna Dabrowska            if (!empty($excludes)) {
207d31b75d5SAnna Dabrowska                $result = array_filter($result, function ($item) use ($excludes) {
2088c25a9b9SGerrit Uitslag                    return !in_array($item['id'], $excludes);
2098c25a9b9SGerrit Uitslag                });
2108c25a9b9SGerrit Uitslag            }
2118c25a9b9SGerrit Uitslag            // exclude namespaces
2128c25a9b9SGerrit Uitslag            $excludesns = $INPUT->arr('excludesns');
2138c25a9b9SGerrit Uitslag            if (!empty($excludesns)) {
2148c25a9b9SGerrit Uitslag                $result = array_filter($result, function ($item) use ($excludesns) {
2158c25a9b9SGerrit Uitslag                    foreach ($excludesns as $ns) {
216*c4c95814SKlap-in                        if (strpos($item['id'], $ns . ':') === 0) {
217*c4c95814SKlap-in                            return false;
218*c4c95814SKlap-in                        }
2198c25a9b9SGerrit Uitslag                    }
2208c25a9b9SGerrit Uitslag                    return true;
221d31b75d5SAnna Dabrowska                });
22264541781SAnna Dabrowska            }
22364541781SAnna Dabrowska
22426be4eceSGerrit Uitslag            //sorting
225ad18f4e1SGerrit Uitslag            if (count($result) > 0) {
226ad18f4e1SGerrit Uitslag                if ($order == 'date') {
227852931daSAndreas Gohr                    usort($result, [$this, 'cbDateSort']);
22841e5d4e2SAndreas Gohr                } elseif ($order == 'pagename' || $order == 'natural') {
229852931daSAndreas Gohr                    usort($result, [$this, 'cbPagenameSort']);
230ad18f4e1SGerrit Uitslag                }
231ad18f4e1SGerrit Uitslag            }
232ad18f4e1SGerrit Uitslag
233ad18f4e1SGerrit Uitslag            foreach ($result as $item) {
234d63e7fe7SGerrit Uitslag                $list[] = $item['id'];
235ad18f4e1SGerrit Uitslag            }
236ad18f4e1SGerrit Uitslag
237baa31dc5SGerrit Uitslag            if ($pdfnamespace !== '') {
238baa31dc5SGerrit Uitslag                if (!in_array($pdfnamespace . ':' . $conf['start'], $list, true)) {
239baa31dc5SGerrit Uitslag                    if (file_exists(wikiFN(rtrim($pdfnamespace, ':')))) {
240baa31dc5SGerrit Uitslag                        array_unshift($list, rtrim($pdfnamespace, ':'));
241baa31dc5SGerrit Uitslag                    }
242baa31dc5SGerrit Uitslag                }
243baa31dc5SGerrit Uitslag            }
24417e88313SGerrit Uitslag        } elseif (!empty($_COOKIE['list-pagelist'])) {
245b3eed6e3SGerrit Uitslag            /** @deprecated  April 2016 replaced by localStorage version of Bookcreator */
24626be4eceSGerrit Uitslag            //is in Bookmanager of bookcreator plugin a title given?
2472a127a1dSGerrit Uitslag            $title = $INPUT->str('pdfbook_title'); //DEPRECATED
2482a127a1dSGerrit Uitslag            $title = $INPUT->str('book_title', $title, true);
2492a127a1dSGerrit Uitslag            if (empty($title)) {
2502a127a1dSGerrit Uitslag                throw new Exception($this->getLang('needtitle'));
25126be4eceSGerrit Uitslag            }
252ad18f4e1SGerrit Uitslag
2532a127a1dSGerrit Uitslag            $list = explode("|", $_COOKIE['list-pagelist']);
254b3eed6e3SGerrit Uitslag        } elseif ($INPUT->has('selection')) {
255b3eed6e3SGerrit Uitslag            //handle Bookcreator requests based at localStorage
256b3eed6e3SGerrit Uitslag//            if(!checkSecurityToken()) {
257b3eed6e3SGerrit Uitslag//                http_status(403);
258b3eed6e3SGerrit Uitslag//                print $this->getLang('empty');
259b3eed6e3SGerrit Uitslag//                exit();
260b3eed6e3SGerrit Uitslag//            }
261b3eed6e3SGerrit Uitslag
2627c79bc79SGerrit Uitslag            $list = json_decode($INPUT->str('selection', '', true), true);
263852931daSAndreas Gohr            if (!is_array($list) || $list === []) {
2642a127a1dSGerrit Uitslag                throw new Exception($this->getLang('empty'));
265b3eed6e3SGerrit Uitslag            }
266b3eed6e3SGerrit Uitslag
2672a127a1dSGerrit Uitslag            $title = $INPUT->str('pdfbook_title'); //DEPRECATED
2682a127a1dSGerrit Uitslag            $title = $INPUT->str('book_title', $title, true);
2692a127a1dSGerrit Uitslag            if (empty($title)) {
2702a127a1dSGerrit Uitslag                throw new Exception($this->getLang('needtitle'));
2712a127a1dSGerrit Uitslag            }
2722a127a1dSGerrit Uitslag        } elseif ($INPUT->has('savedselection')) {
2732a127a1dSGerrit Uitslag            //export a saved selection of the Bookcreator Plugin
2742a127a1dSGerrit Uitslag            if (plugin_isdisabled('bookcreator')) {
2752a127a1dSGerrit Uitslag                throw new Exception($this->getLang('missingbookcreator'));
2762a127a1dSGerrit Uitslag            }
2772a127a1dSGerrit Uitslag            /** @var action_plugin_bookcreator_handleselection $SelectionHandling */
2782a127a1dSGerrit Uitslag            $SelectionHandling = plugin_load('action', 'bookcreator_handleselection');
2792a127a1dSGerrit Uitslag            $savedselection = $SelectionHandling->loadSavedSelection($INPUT->str('savedselection'));
2802a127a1dSGerrit Uitslag            $title = $savedselection['title'];
2812a127a1dSGerrit Uitslag            $title = $INPUT->str('book_title', $title, true);
2822a127a1dSGerrit Uitslag            $list = $savedselection['selection'];
2832a127a1dSGerrit Uitslag
2842a127a1dSGerrit Uitslag            if (empty($title)) {
2852a127a1dSGerrit Uitslag                throw new Exception($this->getLang('needtitle'));
286b3eed6e3SGerrit Uitslag            }
287737417c6SKlap-in        } else {
28826be4eceSGerrit Uitslag            //show empty bookcreator message
2892a127a1dSGerrit Uitslag            throw new Exception($this->getLang('empty'));
290737417c6SKlap-in        }
291737417c6SKlap-in
292719256adSGerrit Uitslag        $list = array_map('cleanID', $list);
293c7138b3fSGerrit Uitslag
29417e88313SGerrit Uitslag        $skippedpages = [];
295c7138b3fSGerrit Uitslag        foreach ($list as $index => $pageid) {
296c7138b3fSGerrit Uitslag            if (auth_quickaclcheck($pageid) < AUTH_READ) {
297c7138b3fSGerrit Uitslag                $skippedpages[] = $pageid;
298c7138b3fSGerrit Uitslag                unset($list[$index]);
299c7138b3fSGerrit Uitslag            }
300c7138b3fSGerrit Uitslag        }
3012a127a1dSGerrit Uitslag        $list = array_filter($list, 'strlen'); //use of strlen() callback prevents removal of pagename '0'
302c7138b3fSGerrit Uitslag
303c7138b3fSGerrit Uitslag        //if selection contains forbidden pages throw (overridable) warning
304852931daSAndreas Gohr        if (!$INPUT->bool('book_skipforbiddenpages') && $skippedpages !== []) {
305852931daSAndreas Gohr            $msg = hsc(implode(', ', $skippedpages));
3062a127a1dSGerrit Uitslag            throw new Exception(sprintf($this->getLang('forbidden'), $msg));
307c7138b3fSGerrit Uitslag        }
308c7138b3fSGerrit Uitslag
30917e88313SGerrit Uitslag        return [$title, $list];
310d63e7fe7SGerrit Uitslag    }
311d63e7fe7SGerrit Uitslag
312a58f45f0SGerrit Uitslag    /**
313a58f45f0SGerrit Uitslag     * Prepare cache
314a58f45f0SGerrit Uitslag     *
315a58f45f0SGerrit Uitslag     * @param array $depends (reference) array with dependencies
316a58f45f0SGerrit Uitslag     * @return cache
317a58f45f0SGerrit Uitslag     */
31817e88313SGerrit Uitslag    protected function prepareCache(&$depends)
31917e88313SGerrit Uitslag    {
320a58f45f0SGerrit Uitslag        global $REV;
321a58f45f0SGerrit Uitslag
322852931daSAndreas Gohr        $cachekey = implode(',', $this->list)
323ee19bac3SLuigi Micco            . $REV
324ee19bac3SLuigi Micco            . $this->getExportConfig('template')
325ee19bac3SLuigi Micco            . $this->getExportConfig('pagesize')
326ee19bac3SLuigi Micco            . $this->getExportConfig('orientation')
327d83760efSGerrit Uitslag            . $this->getExportConfig('font-size')
328ee19bac3SLuigi Micco            . $this->getExportConfig('doublesided')
3299c76f78dSVincent GIRARD            . $this->getExportConfig('headernumber')
330852931daSAndreas Gohr            . ($this->getExportConfig('hasToC') ? implode('-', $this->getExportConfig('levels')) : '0')
33103352761SKirsten Roschanski            . $this->title;
3320833b7cdSStephan Bauer        $cache = new Cache($cachekey, '.dw2.pdf');
333ee19bac3SLuigi Micco
33417e88313SGerrit Uitslag        $dependencies = [];
335ee19bac3SLuigi Micco        foreach ($this->list as $pageid) {
336ee19bac3SLuigi Micco            $relations = p_get_metadata($pageid, 'relation');
337ee19bac3SLuigi Micco
338ee19bac3SLuigi Micco            if (is_array($relations)) {
339ee19bac3SLuigi Micco                if (array_key_exists('media', $relations) && is_array($relations['media'])) {
340ee19bac3SLuigi Micco                    foreach ($relations['media'] as $mediaid => $exists) {
341ee19bac3SLuigi Micco                        if ($exists) {
342ee19bac3SLuigi Micco                            $dependencies[] = mediaFN($mediaid);
343ee19bac3SLuigi Micco                        }
344ee19bac3SLuigi Micco                    }
345ee19bac3SLuigi Micco                }
346ee19bac3SLuigi Micco
347ee19bac3SLuigi Micco                if (array_key_exists('haspart', $relations) && is_array($relations['haspart'])) {
348ee19bac3SLuigi Micco                    foreach ($relations['haspart'] as $part_pageid => $exists) {
349ee19bac3SLuigi Micco                        if ($exists) {
350ee19bac3SLuigi Micco                            $dependencies[] = wikiFN($part_pageid);
351ee19bac3SLuigi Micco                        }
352ee19bac3SLuigi Micco                    }
353ee19bac3SLuigi Micco                }
354ee19bac3SLuigi Micco            }
355ee19bac3SLuigi Micco
356ee19bac3SLuigi Micco            $dependencies[] = metaFN($pageid, '.meta');
357ee19bac3SLuigi Micco        }
358ee19bac3SLuigi Micco
359ee19bac3SLuigi Micco        $depends['files'] = array_map('wikiFN', $this->list);
360ee19bac3SLuigi Micco        $depends['files'][] = __FILE__;
361852931daSAndreas Gohr        $depends['files'][] = __DIR__ . '/renderer.php';
362852931daSAndreas Gohr        $depends['files'][] = __DIR__ . '/mpdf/mpdf.php';
363ee19bac3SLuigi Micco        $depends['files'] = array_merge(
364ee19bac3SLuigi Micco            $depends['files'],
365ee19bac3SLuigi Micco            $dependencies,
366ee19bac3SLuigi Micco            getConfigFiles('main')
367ee19bac3SLuigi Micco        );
368a58f45f0SGerrit Uitslag        return $cache;
369ee19bac3SLuigi Micco    }
370ee19bac3SLuigi Micco
371d63e7fe7SGerrit Uitslag    /**
372e53f1ec0SSzymon Olewniczak     * Returns the parsed Wikitext in dw2pdf for the given id and revision
373e53f1ec0SSzymon Olewniczak     *
374e53f1ec0SSzymon Olewniczak     * @param string $id page id
375e53f1ec0SSzymon Olewniczak     * @param string|int $rev revision timestamp or empty string
376e53f1ec0SSzymon Olewniczak     * @param string $date_at
377e53f1ec0SSzymon Olewniczak     * @return null|string
378e53f1ec0SSzymon Olewniczak     */
379852931daSAndreas Gohr    protected function wikiToDW2PDF($id, $rev = '', $date_at = '')
38017e88313SGerrit Uitslag    {
381e53f1ec0SSzymon Olewniczak        $file = wikiFN($id, $rev);
382e53f1ec0SSzymon Olewniczak
383*c4c95814SKlap-in        if (!file_exists($file)) {
384*c4c95814SKlap-in            return '';
385*c4c95814SKlap-in        }
386e53f1ec0SSzymon Olewniczak
387e53f1ec0SSzymon Olewniczak        //ensure $id is in global $ID (needed for parsing)
388e53f1ec0SSzymon Olewniczak        global $ID;
389e53f1ec0SSzymon Olewniczak        $keep = $ID;
390e53f1ec0SSzymon Olewniczak        $ID = $id;
391e53f1ec0SSzymon Olewniczak
392e53f1ec0SSzymon Olewniczak        if ($rev || $date_at) {
393852931daSAndreas Gohr            //no caching on old revisions
394852931daSAndreas Gohr            $ret = p_render('dw2pdf', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
395e53f1ec0SSzymon Olewniczak        } else {
396e53f1ec0SSzymon Olewniczak            $ret = p_cached_output($file, 'dw2pdf', $id);
397e53f1ec0SSzymon Olewniczak        }
398e53f1ec0SSzymon Olewniczak
399e53f1ec0SSzymon Olewniczak        //restore ID (just in case)
400e53f1ec0SSzymon Olewniczak        $ID = $keep;
401e53f1ec0SSzymon Olewniczak
402e53f1ec0SSzymon Olewniczak        return $ret;
403e53f1ec0SSzymon Olewniczak    }
404e53f1ec0SSzymon Olewniczak
405e53f1ec0SSzymon Olewniczak    /**
406d63e7fe7SGerrit Uitslag     * Build a pdf from the html
407d63e7fe7SGerrit Uitslag     *
408d63e7fe7SGerrit Uitslag     * @param string $cachefile
409d9c13ec7SGerrit Uitslag     * @param Doku_Event $event
41017e88313SGerrit Uitslag     * @throws MpdfException
411d63e7fe7SGerrit Uitslag     */
41217e88313SGerrit Uitslag    protected function generatePDF($cachefile, $event)
41317e88313SGerrit Uitslag    {
4142d9cd424SGerrit Uitslag        global $REV, $INPUT, $DATE_AT;
415e53f1ec0SSzymon Olewniczak
4162d9cd424SGerrit Uitslag        if ($event->data == 'export_pdf') { //only one page is exported
417e53f1ec0SSzymon Olewniczak            $rev = $REV;
418e53f1ec0SSzymon Olewniczak            $date_at = $DATE_AT;
419852931daSAndreas Gohr        } else {
420852931daSAndreas Gohr            //we are exporting entire namespace, ommit revisions
421852931daSAndreas Gohr            $rev = '';
422852931daSAndreas Gohr            $date_at = '';
423e53f1ec0SSzymon Olewniczak        }
42487c86ddaSAndreas Gohr
42502f9a447SGerrit Uitslag        //some shortcuts to export settings
42602f9a447SGerrit Uitslag        $hasToC = $this->getExportConfig('hasToC');
42702f9a447SGerrit Uitslag        $levels = $this->getExportConfig('levels');
42802f9a447SGerrit Uitslag        $isDebug = $this->getExportConfig('isDebug');
429b80f709fSNicolas        $watermark = $this->getExportConfig('watermark');
4306ea88a05SAndreas Gohr
4311ef68647SAndreas Gohr        // initialize PDF library
432852931daSAndreas Gohr        require_once(__DIR__ . "/DokuPDF.class.php");
4336ea88a05SAndreas Gohr
434979c9cf5SAndreas Gohr        $mpdf = new DokuPDF(
435979c9cf5SAndreas Gohr            $this->getExportConfig('pagesize'),
4364870b378SLarsDW223            $this->getExportConfig('orientation'),
437979c9cf5SAndreas Gohr            $this->getExportConfig('font-size'),
438979c9cf5SAndreas Gohr            $this->getDocumentLanguage($this->list[0]) //use language of first page
439979c9cf5SAndreas Gohr        );
440ee19bac3SLuigi Micco
441d62df65bSAndreas Gohr        // let mpdf fix local links
442d62df65bSAndreas Gohr        $self = parse_url(DOKU_URL);
443d62df65bSAndreas Gohr        $url = $self['scheme'] . '://' . $self['host'];
44421a55743SAnna Dabrowska        if (!empty($self['port'])) {
44502f9a447SGerrit Uitslag            $url .= ':' . $self['port'];
44602f9a447SGerrit Uitslag        }
447d9c13ec7SGerrit Uitslag        $mpdf->SetBasePath($url);
448d62df65bSAndreas Gohr
44956d13144SAndreas Gohr        // Set the title
45003352761SKirsten Roschanski        $mpdf->SetTitle($this->title);
45156d13144SAndreas Gohr
452d63e7fe7SGerrit Uitslag        // some default document settings
453d63e7fe7SGerrit Uitslag        //note: double-sided document, starts at an odd page (first page is a right-hand side page)
454213fdb75SGerrit Uitslag        //      single-side document has only odd pages
455213fdb75SGerrit Uitslag        $mpdf->mirrorMargins = $this->getExportConfig('doublesided');
456daa70883SAndreas Gohr        $mpdf->setAutoTopMargin = 'stretch';
457daa70883SAndreas Gohr        $mpdf->setAutoBottomMargin = 'stretch';
45802f9a447SGerrit Uitslag//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
45902f9a447SGerrit Uitslag        if ($hasToC) {
46002f9a447SGerrit Uitslag            $mpdf->h2toc = $levels;
46102f9a447SGerrit Uitslag        }
46217e88313SGerrit Uitslag        $mpdf->PageNumSubstitutions[] = ['from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off'];
4632eedf77dSAndreas Gohr
464b80f709fSNicolas        // Watermarker
465b80f709fSNicolas        if ($watermark) {
466b80f709fSNicolas            $mpdf->SetWatermarkText($watermark);
467b80f709fSNicolas            $mpdf->showWatermarkText = true;
468b80f709fSNicolas        }
469b80f709fSNicolas
47056d13144SAndreas Gohr        // load the template
471852931daSAndreas Gohr        $template = $this->loadTemplate();
472ee19bac3SLuigi Micco
4731ef68647SAndreas Gohr        // prepare HTML header styles
474a2c33768SGerrit Uitslag        $html = '';
47502f9a447SGerrit Uitslag        if ($isDebug) {
476a2c33768SGerrit Uitslag            $html .= '<html><head>';
47717e88313SGerrit Uitslag            $html .= '<style>';
478a2c33768SGerrit Uitslag        }
479db1aa1bfSKirsten Roschanski
480db1aa1bfSKirsten Roschanski        $styles = '@page { size:auto; ' . $template['page'] . '}';
481a2c33768SGerrit Uitslag        $styles .= '@page :first {' . $template['first'] . '}';
482254467c4SGerrit Uitslag
483254467c4SGerrit Uitslag        $styles .= '@page landscape-page { size:landscape }';
484254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-landscape { page:landscape-page }';
485254467c4SGerrit Uitslag        $styles .= '@page portrait-page { size:portrait }';
486254467c4SGerrit Uitslag        $styles .= 'div.dw2pdf-portrait { page:portrait-page }';
487852931daSAndreas Gohr        $styles .= $this->loadCSS();
488254467c4SGerrit Uitslag
489a2c33768SGerrit Uitslag        $mpdf->WriteHTML($styles, 1);
490a2c33768SGerrit Uitslag
49102f9a447SGerrit Uitslag        if ($isDebug) {
492a2c33768SGerrit Uitslag            $html .= $styles;
4931ef68647SAndreas Gohr            $html .= '</style>';
4941ef68647SAndreas Gohr            $html .= '</head><body>';
495a2c33768SGerrit Uitslag        }
496a2c33768SGerrit Uitslag
497a2c33768SGerrit Uitslag        $body_start = $template['html'];
498a2c33768SGerrit Uitslag        $body_start .= '<div class="dokuwiki">';
4992eedf77dSAndreas Gohr
5001e45476bSmnapp        // insert the cover page
501a2c33768SGerrit Uitslag        $body_start .= $template['cover'];
502a2c33768SGerrit Uitslag
503a2c33768SGerrit Uitslag        $mpdf->WriteHTML($body_start, 2, true, false); //start body html
50402f9a447SGerrit Uitslag        if ($isDebug) {
505a2c33768SGerrit Uitslag            $html .= $body_start;
506a2c33768SGerrit Uitslag        }
50702f9a447SGerrit Uitslag        if ($hasToC) {
508852931daSAndreas Gohr            //Note: - for double-sided document the ToC is always on an even number of pages, so that the
509852931daSAndreas Gohr            //        following content is on a correct odd/even page
510852931daSAndreas Gohr            //      - first page of ToC starts always at odd page (so eventually an additional blank page
511852931daSAndreas Gohr            //        is included before)
51202f9a447SGerrit Uitslag            //      - there is no page numbering at the pages of the ToC
51317e88313SGerrit Uitslag            $mpdf->TOCpagebreakByArray([
514230b098dSGerrit Uitslag                'toc-preHTML' => '<h2>' . $this->getLang('tocheader') . '</h2>',
515230b098dSGerrit Uitslag                'toc-bookmarkText' => $this->getLang('tocheader'),
51602f9a447SGerrit Uitslag                'links' => true,
51702f9a447SGerrit Uitslag                'outdent' => '1em',
51802f9a447SGerrit Uitslag                'pagenumstyle' => '1'
51917e88313SGerrit Uitslag            ]);
52002f9a447SGerrit Uitslag            $html .= '<tocpagebreak>';
52102f9a447SGerrit Uitslag        }
52202f9a447SGerrit Uitslag
5231ef68647SAndreas Gohr        // loop over all pages
524c7138b3fSGerrit Uitslag        $counter = 0;
525c7138b3fSGerrit Uitslag        $no_pages = count($this->list);
526c7138b3fSGerrit Uitslag        foreach ($this->list as $page) {
5279c76f78dSVincent GIRARD            $this->currentBookChapter = $counter;
528c7138b3fSGerrit Uitslag            $counter++;
529b3eed6e3SGerrit Uitslag
530852931daSAndreas Gohr            $pagehtml = $this->wikiToDW2PDF($page, $rev, $date_at);
531e53f1ec0SSzymon Olewniczak            //file doesn't exists
532e53f1ec0SSzymon Olewniczak            if ($pagehtml == '') {
533b3eed6e3SGerrit Uitslag                continue;
534b3eed6e3SGerrit Uitslag            }
535852931daSAndreas Gohr            $pagehtml .= $this->pageDependReplacements($template['cite'], $page);
536c7138b3fSGerrit Uitslag            if ($counter < $no_pages) {
537a2c33768SGerrit Uitslag                $pagehtml .= '<pagebreak />';
538a2c33768SGerrit Uitslag            }
539a2c33768SGerrit Uitslag
540a2c33768SGerrit Uitslag            $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
54102f9a447SGerrit Uitslag            if ($isDebug) {
542a2c33768SGerrit Uitslag                $html .= $pagehtml;
5431ef68647SAndreas Gohr            }
544ee19bac3SLuigi Micco        }
545ee19bac3SLuigi Micco
54633c15297SGerrit Uitslag        // insert the back page
547a2c33768SGerrit Uitslag        $body_end = $template['back'];
54833c15297SGerrit Uitslag
549a2c33768SGerrit Uitslag        $body_end .= '</div>';
550a2c33768SGerrit Uitslag
551facf2f2cSGerrit Uitslag        $mpdf->WriteHTML($body_end, 2, false); // finish body html
55202f9a447SGerrit Uitslag        if ($isDebug) {
553a2c33768SGerrit Uitslag            $html .= $body_end;
554eeb17e15SAndreas Gohr            $html .= '</body>';
555eeb17e15SAndreas Gohr            $html .= '</html>';
556a2c33768SGerrit Uitslag        }
557f765508eSGerrit Uitslag
558f765508eSGerrit Uitslag        //Return html for debugging
55902f9a447SGerrit Uitslag        if ($isDebug) {
56017e88313SGerrit Uitslag            if ($INPUT->str('debughtml', 'text', true) == 'text') {
561a2c33768SGerrit Uitslag                header('Content-Type: text/plain; charset=utf-8');
562a2c33768SGerrit Uitslag            }
56317e88313SGerrit Uitslag            echo $html;
56426be4eceSGerrit Uitslag            exit();
5657c79bc79SGerrit Uitslag        }
566f765508eSGerrit Uitslag
56787c86ddaSAndreas Gohr        // write to cache file
568d63e7fe7SGerrit Uitslag        $mpdf->Output($cachefile, 'F');
56987c86ddaSAndreas Gohr    }
57087c86ddaSAndreas Gohr
571d63e7fe7SGerrit Uitslag    /**
572d63e7fe7SGerrit Uitslag     * @param string $cachefile
573d63e7fe7SGerrit Uitslag     */
57417e88313SGerrit Uitslag    protected function sendPDFFile($cachefile)
57517e88313SGerrit Uitslag    {
57687c86ddaSAndreas Gohr        header('Content-Type: application/pdf');
577b853b723SAndreas Gohr        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
57887c86ddaSAndreas Gohr        header('Pragma: public');
579d63e7fe7SGerrit Uitslag        http_conditionalRequest(filemtime($cachefile));
580c0956f69SMichael Große        global $INPUT;
581f7b24f48SMichael Große        $outputTarget = $INPUT->str('outputTarget', $this->getConf('output'));
58287c86ddaSAndreas Gohr
58303352761SKirsten Roschanski        $filename = rawurlencode(cleanID(strtr($this->title, ':/;"', '    ')));
584c0956f69SMichael Große        if ($outputTarget === 'file') {
5859a3c8d9fSAndreas Gohr            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
58687c86ddaSAndreas Gohr        } else {
5879a3c8d9fSAndreas Gohr            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
58887c86ddaSAndreas Gohr        }
589ee19bac3SLuigi Micco
590b3eed6e3SGerrit Uitslag        //Bookcreator uses jQuery.fileDownload.js, which requires a cookie.
591b3eed6e3SGerrit Uitslag        header('Set-Cookie: fileDownload=true; path=/');
592b3eed6e3SGerrit Uitslag
593e993da11SGerrit Uitslag        //try to send file, and exit if done
594d63e7fe7SGerrit Uitslag        http_sendfile($cachefile);
59587c86ddaSAndreas Gohr
596d63e7fe7SGerrit Uitslag        $fp = @fopen($cachefile, "rb");
59787c86ddaSAndreas Gohr        if ($fp) {
598d63e7fe7SGerrit Uitslag            http_rangeRequest($fp, filesize($cachefile), 'application/pdf');
59987c86ddaSAndreas Gohr        } else {
60087c86ddaSAndreas Gohr            header("HTTP/1.0 500 Internal Server Error");
601852931daSAndreas Gohr            echo "Could not read file - bad permissions?";
60287c86ddaSAndreas Gohr        }
6031ef68647SAndreas Gohr        exit();
6041ef68647SAndreas Gohr    }
6051ef68647SAndreas Gohr
6066be736bfSGerrit Uitslag    /**
6072eedf77dSAndreas Gohr     * Load the various template files and prepare the HTML/CSS for insertion
60844e8e8fbSGerrit Uitslag     *
60944e8e8fbSGerrit Uitslag     * @return array
6101ef68647SAndreas Gohr     */
611852931daSAndreas Gohr    protected function loadTemplate()
61217e88313SGerrit Uitslag    {
6131ef68647SAndreas Gohr        global $ID;
6141ef68647SAndreas Gohr        global $conf;
6150a11dabaSChris75forumname        global $INFO;
6161ef68647SAndreas Gohr
6172eedf77dSAndreas Gohr        // this is what we'll return
61821a55743SAnna Dabrowska        $output = [
6191e45476bSmnapp            'cover' => '',
62021a55743SAnna Dabrowska            'back' => '',
6212eedf77dSAndreas Gohr            'html' => '',
6222eedf77dSAndreas Gohr            'page' => '',
6232eedf77dSAndreas Gohr            'first' => '',
6242eedf77dSAndreas Gohr            'cite' => '',
62521a55743SAnna Dabrowska        ];
6262eedf77dSAndreas Gohr
6272eedf77dSAndreas Gohr        // prepare header/footer elements
6282eedf77dSAndreas Gohr        $html = '';
62917e88313SGerrit Uitslag        foreach (['header', 'footer'] as $section) {
63017e88313SGerrit Uitslag            foreach (['', '_odd', '_even', '_first'] as $order) {
63102f9a447SGerrit Uitslag                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
63233c15297SGerrit Uitslag                if (file_exists($file)) {
63333c15297SGerrit Uitslag                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
63433c15297SGerrit Uitslag                    $html .= file_get_contents($file) . DOKU_LF;
63533c15297SGerrit Uitslag                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
6362eedf77dSAndreas Gohr
6372eedf77dSAndreas Gohr                    // register the needed pseudo CSS
63833c15297SGerrit Uitslag                    if ($order == '_first') {
63933c15297SGerrit Uitslag                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
64033c15297SGerrit Uitslag                    } elseif ($order == '_even') {
64133c15297SGerrit Uitslag                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
64233c15297SGerrit Uitslag                    } elseif ($order == '_odd') {
64333c15297SGerrit Uitslag                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
644daa70883SAndreas Gohr                    } else {
64533c15297SGerrit Uitslag                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
6462eedf77dSAndreas Gohr                    }
6472eedf77dSAndreas Gohr                }
6482eedf77dSAndreas Gohr            }
6492eedf77dSAndreas Gohr        }
6502eedf77dSAndreas Gohr
6511ef68647SAndreas Gohr        // prepare replacements
65217e88313SGerrit Uitslag        $replace = [
6531ef68647SAndreas Gohr            '@PAGE@' => '{PAGENO}',
65402f9a447SGerrit Uitslag            '@PAGES@' => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
65503352761SKirsten Roschanski            '@TITLE@' => hsc($this->title),
6561ef68647SAndreas Gohr            '@WIKI@' => $conf['title'],
6571ef68647SAndreas Gohr            '@WIKIURL@' => DOKU_URL,
6581ef68647SAndreas Gohr            '@DATE@' => dformat(time()),
6598b11a0e6SChris75forumname            '@USERNAME@' => $INFO['userinfo']['name'] ?? '',
6605d6fbaeaSAndreas Gohr            '@BASE@' => DOKU_BASE,
661893987a2SAndreas Gohr            '@INC@' => DOKU_INC,
662893987a2SAndreas Gohr            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
663893987a2SAndreas Gohr            '@TPLINC@' => DOKU_INC . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
66417e88313SGerrit Uitslag        ];
6651ef68647SAndreas Gohr
6662eedf77dSAndreas Gohr        // set HTML element
667a180c973SKlap-in        $html = str_replace(array_keys($replace), array_values($replace), $html);
668a180c973SKlap-in        //TODO For bookcreator $ID (= bookmanager page) makes no sense
669852931daSAndreas Gohr        $output['html'] = $this->pageDependReplacements($html, $ID);
6701ef68647SAndreas Gohr
6711e45476bSmnapp        // cover page
67202f9a447SGerrit Uitslag        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
67333c15297SGerrit Uitslag        if (file_exists($coverfile)) {
67433c15297SGerrit Uitslag            $output['cover'] = file_get_contents($coverfile);
6751e45476bSmnapp            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
676852931daSAndreas Gohr            $output['cover'] = $this->pageDependReplacements($output['cover'], $ID);
6776e2ec302SGerrit Uitslag            $output['cover'] .= '<pagebreak />';
6781e45476bSmnapp        }
6791e45476bSmnapp
68033c15297SGerrit Uitslag        // cover page
68102f9a447SGerrit Uitslag        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
68233c15297SGerrit Uitslag        if (file_exists($backfile)) {
68333c15297SGerrit Uitslag            $output['back'] = '<pagebreak />';
68433c15297SGerrit Uitslag            $output['back'] .= file_get_contents($backfile);
68533c15297SGerrit Uitslag            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
686852931daSAndreas Gohr            $output['back'] = $this->pageDependReplacements($output['back'], $ID);
68733c15297SGerrit Uitslag        }
68833c15297SGerrit Uitslag
6892eedf77dSAndreas Gohr        // citation box
69002f9a447SGerrit Uitslag        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
69133c15297SGerrit Uitslag        if (file_exists($citationfile)) {
69233c15297SGerrit Uitslag            $output['cite'] = file_get_contents($citationfile);
6932eedf77dSAndreas Gohr            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
6942eedf77dSAndreas Gohr        }
6951ef68647SAndreas Gohr
6962eedf77dSAndreas Gohr        return $output;
6971ef68647SAndreas Gohr    }
6981ef68647SAndreas Gohr
6991ef68647SAndreas Gohr    /**
700a180c973SKlap-in     * @param string $raw code with placeholders
701a180c973SKlap-in     * @param string $id pageid
702a180c973SKlap-in     * @return string
703a180c973SKlap-in     */
704852931daSAndreas Gohr    protected function pageDependReplacements($raw, $id)
70517e88313SGerrit Uitslag    {
706e53f1ec0SSzymon Olewniczak        global $REV, $DATE_AT;
707a180c973SKlap-in
708fb347f35SAndreas Gohr        // generate qr code for this page
709a180c973SKlap-in        $qr_code = '';
710fb347f35SAndreas Gohr        if ($this->getConf('qrcodescale')) {
711fb347f35SAndreas Gohr            $url = hsc(wl($id, '', '&', true));
712852931daSAndreas Gohr            $size = (float)$this->getConf('qrcodescale');
713852931daSAndreas Gohr            $qr_code = sprintf(
714852931daSAndreas Gohr                '<barcode type="QR" code="%s" error="Q" disableborder="1" class="qrcode" size="%s" />',
715852931daSAndreas Gohr                $url,
716852931daSAndreas Gohr                $size
717852931daSAndreas Gohr            );
718a180c973SKlap-in        }
719a180c973SKlap-in        // prepare replacements
720a180c973SKlap-in        $replace['@ID@'] = $id;
721a180c973SKlap-in        $replace['@UPDATE@'] = dformat(filemtime(wikiFN($id, $REV)));
722e53f1ec0SSzymon Olewniczak
72317e88313SGerrit Uitslag        $params = [];
724e53f1ec0SSzymon Olewniczak        if ($DATE_AT) {
725e53f1ec0SSzymon Olewniczak            $params['at'] = $DATE_AT;
726e53f1ec0SSzymon Olewniczak        } elseif ($REV) {
727e53f1ec0SSzymon Olewniczak            $params['rev'] = $REV;
728e53f1ec0SSzymon Olewniczak        }
729e53f1ec0SSzymon Olewniczak        $replace['@PAGEURL@'] = wl($id, $params, true, "&");
730a180c973SKlap-in        $replace['@QRCODE@'] = $qr_code;
731a180c973SKlap-in
732d824d23dSAnna Dabrowska        $content = $raw;
733a12c41c3SAnna Dabrowska
734a12c41c3SAnna Dabrowska        // let other plugins define their own replacements
735d824d23dSAnna Dabrowska        $evdata = ['id' => $id, 'replace' => &$replace, 'content' => &$content];
736852931daSAndreas Gohr        $event = new Event('PLUGIN_DW2PDF_REPLACE', $evdata);
737d824d23dSAnna Dabrowska        if ($event->advise_before()) {
738e3d68265SGerrit Uitslag            $content = str_replace(array_keys($replace), array_values($replace), $raw);
739d824d23dSAnna Dabrowska        }
740e3d68265SGerrit Uitslag
741a12c41c3SAnna Dabrowska        // plugins may post-process HTML, e.g to clean up unused replacements
742a12c41c3SAnna Dabrowska        $event->advise_after();
743a12c41c3SAnna Dabrowska
744e3d68265SGerrit Uitslag        // @DATE(<date>[, <format>])@
745e3d68265SGerrit Uitslag        $content = preg_replace_callback(
746e3d68265SGerrit Uitslag            '/@DATE\((.*?)(?:,\s*(.*?))?\)@/',
747852931daSAndreas Gohr            [$this, 'replaceDate'],
748e3d68265SGerrit Uitslag            $content
749e3d68265SGerrit Uitslag        );
750e3d68265SGerrit Uitslag
751e3d68265SGerrit Uitslag        return $content;
752a180c973SKlap-in    }
753a180c973SKlap-in
754e3d68265SGerrit Uitslag
755e3d68265SGerrit Uitslag    /**
756e3d68265SGerrit Uitslag     * (callback) Replace date by request datestring
757e3d68265SGerrit Uitslag     * e.g. '%m(30-11-1975)' is replaced by '11'
758e3d68265SGerrit Uitslag     *
759e3d68265SGerrit Uitslag     * @param array $match with [0]=>whole match, [1]=> first subpattern, [2] => second subpattern
760e3d68265SGerrit Uitslag     * @return string
761e3d68265SGerrit Uitslag     */
762852931daSAndreas Gohr    public function replaceDate($match)
76317e88313SGerrit Uitslag    {
764e3d68265SGerrit Uitslag        global $conf;
765e3d68265SGerrit Uitslag        //no 2nd argument for default date format
766e3d68265SGerrit Uitslag        if ($match[2] == null) {
767e3d68265SGerrit Uitslag            $match[2] = $conf['dformat'];
768e3d68265SGerrit Uitslag        }
769e3d68265SGerrit Uitslag        return strftime($match[2], strtotime($match[1]));
770e3d68265SGerrit Uitslag    }
771e3d68265SGerrit Uitslag
772a180c973SKlap-in    /**
7731c14c879SAndreas Gohr     * Load all the style sheets and apply the needed replacements
774facf2f2cSGerrit Uitslag     *
775facf2f2cSGerrit Uitslag     * @return string css styles
7761ef68647SAndreas Gohr     */
777852931daSAndreas Gohr    protected function loadCSS()
77817e88313SGerrit Uitslag    {
779737417c6SKlap-in        global $conf;
7807c79bc79SGerrit Uitslag        //reuse the CSS dispatcher functions without triggering the main function
7811c14c879SAndreas Gohr        define('SIMPLE_TEST', 1);
7821c14c879SAndreas Gohr        require_once(DOKU_INC . 'lib/exe/css.php');
783ee19bac3SLuigi Micco
7841c14c879SAndreas Gohr        // prepare CSS files
7851c14c879SAndreas Gohr        $files = array_merge(
78617e88313SGerrit Uitslag            [
78717e88313SGerrit Uitslag                DOKU_INC . 'lib/styles/screen.css' => DOKU_BASE . 'lib/styles/',
78817e88313SGerrit Uitslag                DOKU_INC . 'lib/styles/print.css' => DOKU_BASE . 'lib/styles/',
78917e88313SGerrit Uitslag            ],
790852931daSAndreas Gohr            $this->cssPluginPDFstyles(),
79117e88313SGerrit Uitslag            [
79217e88313SGerrit Uitslag                DOKU_PLUGIN . 'dw2pdf/conf/style.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
793852931daSAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css' =>
794852931daSAndreas Gohr                    DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
79517e88313SGerrit Uitslag                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css' => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
79617e88313SGerrit Uitslag            ]
7971c14c879SAndreas Gohr        );
7981c14c879SAndreas Gohr        $css = '';
7991c14c879SAndreas Gohr        foreach ($files as $file => $location) {
80028e636eaSGerrit Uitslag            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
80128e636eaSGerrit Uitslag            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
8021c14c879SAndreas Gohr            $css .= css_loadfile($file, $location);
8031ef68647SAndreas Gohr        }
8041ef68647SAndreas Gohr
8051c14c879SAndreas Gohr        // apply pattern replacements
8067c6ca3bcSMichael Große        if (function_exists('css_styleini')) {
8077c6ca3bcSMichael Große            // compatiblity layer for pre-Greebo releases of DokuWiki
80828e636eaSGerrit Uitslag            $styleini = css_styleini($conf['template']);
8097c6ca3bcSMichael Große        } else {
8107c6ca3bcSMichael Große            // Greebo functionality
81117e88313SGerrit Uitslag            $styleUtils = new StyleUtils();
812d0f0c534SGerrit Uitslag            $styleini = $styleUtils->cssStyleini($conf['template']); // older versions need still the template
8137c6ca3bcSMichael Große        }
81428e636eaSGerrit Uitslag        $css = css_applystyle($css, $styleini['replacements']);
81528e636eaSGerrit Uitslag
81628e636eaSGerrit Uitslag        // parse less
817facf2f2cSGerrit Uitslag        return css_parseless($css);
818ee19bac3SLuigi Micco    }
8191c14c879SAndreas Gohr
82058e6409eSAndreas Gohr    /**
82158e6409eSAndreas Gohr     * Returns a list of possible Plugin PDF Styles
82258e6409eSAndreas Gohr     *
82358e6409eSAndreas Gohr     * Checks for a pdf.css, falls back to print.css
82458e6409eSAndreas Gohr     *
82558e6409eSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
82658e6409eSAndreas Gohr     */
827852931daSAndreas Gohr    protected function cssPluginPDFstyles()
82817e88313SGerrit Uitslag    {
82917e88313SGerrit Uitslag        $list = [];
83058e6409eSAndreas Gohr        $plugins = plugin_list();
831f54b51f7SAndreas Gohr
832f54b51f7SAndreas Gohr        $usestyle = explode(',', $this->getConf('usestyles'));
83358e6409eSAndreas Gohr        foreach ($plugins as $p) {
834f54b51f7SAndreas Gohr            if (in_array($p, $usestyle)) {
835f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
8368003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/screen.less"] = DOKU_BASE . "lib/plugins/$p/";
8378003b493SGerrit Uitslag
838f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
8398003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
840f54b51f7SAndreas Gohr            }
841f54b51f7SAndreas Gohr
8428003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.css"] = DOKU_BASE . "lib/plugins/$p/";
8438003b493SGerrit Uitslag            $list[DOKU_PLUGIN . "$p/all.less"] = DOKU_BASE . "lib/plugins/$p/";
8448003b493SGerrit Uitslag
845ab96d816SMichael Große            if (file_exists(DOKU_PLUGIN . "$p/pdf.css") || file_exists(DOKU_PLUGIN . "$p/pdf.less")) {
84658e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
8478003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/pdf.less"] = DOKU_BASE . "lib/plugins/$p/";
84858e6409eSAndreas Gohr            } else {
84958e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
8508003b493SGerrit Uitslag                $list[DOKU_PLUGIN . "$p/print.less"] = DOKU_BASE . "lib/plugins/$p/";
85158e6409eSAndreas Gohr            }
85258e6409eSAndreas Gohr        }
8538b8ac6ecSAndreas Gohr
8548b8ac6ecSAndreas Gohr        // template support
855852931daSAndreas Gohr        foreach (
856852931daSAndreas Gohr            [
857852931daSAndreas Gohr                     'pdf.css',
858852931daSAndreas Gohr                     'pdf.less',
859852931daSAndreas Gohr                     'css/pdf.css',
860852931daSAndreas Gohr                     'css/pdf.less',
861852931daSAndreas Gohr                     'styles/pdf.css',
862852931daSAndreas Gohr                     'styles/pdf.less'
863852931daSAndreas Gohr                 ] as $file
864852931daSAndreas Gohr        ) {
8658b8ac6ecSAndreas Gohr            if (file_exists(tpl_incdir() . $file)) {
8668b8ac6ecSAndreas Gohr                $list[tpl_incdir() . $file] = tpl_basedir() . $file;
8678b8ac6ecSAndreas Gohr            }
8688b8ac6ecSAndreas Gohr        }
8698b8ac6ecSAndreas Gohr
87058e6409eSAndreas Gohr        return $list;
87158e6409eSAndreas Gohr    }
872ad18f4e1SGerrit Uitslag
873ad18f4e1SGerrit Uitslag    /**
87460e59de7SGerrit Uitslag     * Returns array of pages which will be included in the exported pdf
87560e59de7SGerrit Uitslag     *
87660e59de7SGerrit Uitslag     * @return array
87760e59de7SGerrit Uitslag     */
87817e88313SGerrit Uitslag    public function getExportedPages()
87917e88313SGerrit Uitslag    {
88060e59de7SGerrit Uitslag        return $this->list;
88160e59de7SGerrit Uitslag    }
88260e59de7SGerrit Uitslag
88360e59de7SGerrit Uitslag    /**
884ad18f4e1SGerrit Uitslag     * usort callback to sort by file lastmodified time
88544e8e8fbSGerrit Uitslag     *
88644e8e8fbSGerrit Uitslag     * @param array $a
88744e8e8fbSGerrit Uitslag     * @param array $b
88844e8e8fbSGerrit Uitslag     * @return int
889ad18f4e1SGerrit Uitslag     */
890852931daSAndreas Gohr    public function cbDateSort($a, $b)
89117e88313SGerrit Uitslag    {
892*c4c95814SKlap-in        if ($b['rev'] < $a['rev']) {
893*c4c95814SKlap-in            return -1;
894*c4c95814SKlap-in        }
895*c4c95814SKlap-in        if ($b['rev'] > $a['rev']) {
896*c4c95814SKlap-in            return 1;
897*c4c95814SKlap-in        }
898ad18f4e1SGerrit Uitslag        return strcmp($b['id'], $a['id']);
899ad18f4e1SGerrit Uitslag    }
900ad18f4e1SGerrit Uitslag
901ad18f4e1SGerrit Uitslag    /**
902ad18f4e1SGerrit Uitslag     * usort callback to sort by page id
90344e8e8fbSGerrit Uitslag     * @param array $a
90444e8e8fbSGerrit Uitslag     * @param array $b
90544e8e8fbSGerrit Uitslag     * @return int
906ad18f4e1SGerrit Uitslag     */
907852931daSAndreas Gohr    public function cbPagenameSort($a, $b)
90817e88313SGerrit Uitslag    {
90920025b90SAndreas Gohr        global $conf;
91020025b90SAndreas Gohr
91120025b90SAndreas Gohr        $partsA = explode(':', $a['id']);
91220025b90SAndreas Gohr        $countA = count($partsA);
91320025b90SAndreas Gohr        $partsB = explode(':', $b['id']);
91420025b90SAndreas Gohr        $countB = count($partsB);
915e00f6071SAndreas Gohr        $max = max($countA, $countB);
91620025b90SAndreas Gohr
91720025b90SAndreas Gohr
91820025b90SAndreas Gohr        // compare namepsace by namespace
919e00f6071SAndreas Gohr        for ($i = 0; $i < $max; $i++) {
920e00f6071SAndreas Gohr            $partA = $partsA[$i] ?: null;
921e00f6071SAndreas Gohr            $partB = $partsB[$i] ?: null;
92220025b90SAndreas Gohr
92320025b90SAndreas Gohr            // have we reached the page level?
924e00f6071SAndreas Gohr            if ($i === ($countA - 1) || $i === ($countB - 1)) {
92520025b90SAndreas Gohr                // start page first
926*c4c95814SKlap-in                if ($partA == $conf['start']) {
927*c4c95814SKlap-in                    return -1;
928*c4c95814SKlap-in                }
929*c4c95814SKlap-in                if ($partB == $conf['start']) {
930*c4c95814SKlap-in                    return 1;
931*c4c95814SKlap-in                }
93220025b90SAndreas Gohr            }
93320025b90SAndreas Gohr
934e00f6071SAndreas Gohr            // prefer page over namespace
935e00f6071SAndreas Gohr            if ($partA === $partB) {
936*c4c95814SKlap-in                if (!isset($partsA[$i + 1])) {
937*c4c95814SKlap-in                    return -1;
938*c4c95814SKlap-in                }
939*c4c95814SKlap-in                if (!isset($partsB[$i + 1])) {
940*c4c95814SKlap-in                    return 1;
941*c4c95814SKlap-in                }
942e00f6071SAndreas Gohr                continue;
943e00f6071SAndreas Gohr            }
944e00f6071SAndreas Gohr
945e00f6071SAndreas Gohr
94620025b90SAndreas Gohr            // simply compare
94741e5d4e2SAndreas Gohr            return strnatcmp($partA, $partB);
94820025b90SAndreas Gohr        }
94920025b90SAndreas Gohr
95041e5d4e2SAndreas Gohr        return strnatcmp($a['id'], $b['id']);
951ad18f4e1SGerrit Uitslag    }
95226be4eceSGerrit Uitslag
95326be4eceSGerrit Uitslag    /**
9547c79bc79SGerrit Uitslag     * Collects settings from:
95502f9a447SGerrit Uitslag     *   1. url parameters
95602f9a447SGerrit Uitslag     *   2. plugin config
95702f9a447SGerrit Uitslag     *   3. global config
95802f9a447SGerrit Uitslag     */
95917e88313SGerrit Uitslag    protected function loadExportConfig()
96017e88313SGerrit Uitslag    {
96102f9a447SGerrit Uitslag        global $INPUT;
96202f9a447SGerrit Uitslag        global $conf;
96302f9a447SGerrit Uitslag
96417e88313SGerrit Uitslag        $this->exportConfig = [];
96502f9a447SGerrit Uitslag
96602f9a447SGerrit Uitslag        // decide on the paper setup from param or config
96702f9a447SGerrit Uitslag        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
96802f9a447SGerrit Uitslag        $this->exportConfig['orientation'] = $INPUT->str('orientation', $this->getConf('orientation'), true);
96902f9a447SGerrit Uitslag
9704870b378SLarsDW223        // decide on the font-size from param or config
9714870b378SLarsDW223        $this->exportConfig['font-size'] = $INPUT->str('font-size', $this->getConf('font-size'), true);
9724870b378SLarsDW223
973213fdb75SGerrit Uitslag        $doublesided = $INPUT->bool('doublesided', (bool)$this->getConf('doublesided'));
974213fdb75SGerrit Uitslag        $this->exportConfig['doublesided'] = $doublesided ? '1' : '0';
975213fdb75SGerrit Uitslag
976b80f709fSNicolas        $this->exportConfig['watermark'] = $INPUT->str('watermark', '');
977b80f709fSNicolas
978213fdb75SGerrit Uitslag        $hasToC = $INPUT->bool('toc', (bool)$this->getConf('toc'));
97917e88313SGerrit Uitslag        $levels = [];
98002f9a447SGerrit Uitslag        if ($hasToC) {
98102f9a447SGerrit Uitslag            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
982852931daSAndreas Gohr            [$top_input, $max_input] = array_pad(explode('-', $toclevels, 2), 2, '');
983852931daSAndreas Gohr            [$top_conf, $max_conf] = array_pad(explode('-', $this->getConf('toclevels'), 2), 2, '');
98417e88313SGerrit Uitslag            $bounds_input = [
98517e88313SGerrit Uitslag                'top' => [
98602f9a447SGerrit Uitslag                    (int)$top_input,
98702f9a447SGerrit Uitslag                    (int)$top_conf
98817e88313SGerrit Uitslag                ],
98917e88313SGerrit Uitslag                'max' => [
99002f9a447SGerrit Uitslag                    (int)$max_input,
99102f9a447SGerrit Uitslag                    (int)$max_conf
99217e88313SGerrit Uitslag                ]
99317e88313SGerrit Uitslag            ];
99417e88313SGerrit Uitslag            $bounds = [
99502f9a447SGerrit Uitslag                'top' => $conf['toptoclevel'],
99602f9a447SGerrit Uitslag                'max' => $conf['maxtoclevel']
99702f9a447SGerrit Uitslag
99817e88313SGerrit Uitslag            ];
99902f9a447SGerrit Uitslag            foreach ($bounds_input as $bound => $values) {
100002f9a447SGerrit Uitslag                foreach ($values as $value) {
100102f9a447SGerrit Uitslag                    if ($value > 0 && $value <= 5) {
100202f9a447SGerrit Uitslag                        //stop at valid value and store
100302f9a447SGerrit Uitslag                        $bounds[$bound] = $value;
100402f9a447SGerrit Uitslag                        break;
100502f9a447SGerrit Uitslag                    }
100602f9a447SGerrit Uitslag                }
100702f9a447SGerrit Uitslag            }
100802f9a447SGerrit Uitslag
100902f9a447SGerrit Uitslag            if ($bounds['max'] < $bounds['top']) {
101002f9a447SGerrit Uitslag                $bounds['max'] = $bounds['top'];
101102f9a447SGerrit Uitslag            }
101202f9a447SGerrit Uitslag
101302f9a447SGerrit Uitslag            for ($level = $bounds['top']; $level <= $bounds['max']; $level++) {
101402f9a447SGerrit Uitslag                $levels["H$level"] = $level - 1;
101502f9a447SGerrit Uitslag            }
101602f9a447SGerrit Uitslag        }
101702f9a447SGerrit Uitslag        $this->exportConfig['hasToC'] = $hasToC;
101802f9a447SGerrit Uitslag        $this->exportConfig['levels'] = $levels;
101902f9a447SGerrit Uitslag
102002f9a447SGerrit Uitslag        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
102102f9a447SGerrit Uitslag
102202f9a447SGerrit Uitslag        $tplconf = $this->getConf('template');
102305d2b507SGerrit Uitslag        $tpl = $INPUT->str('tpl', $tplconf, true);
102402f9a447SGerrit Uitslag        if (!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
102502f9a447SGerrit Uitslag            $tpl = $tplconf;
102602f9a447SGerrit Uitslag        }
102702f9a447SGerrit Uitslag        if (!$tpl) {
102802f9a447SGerrit Uitslag            $tpl = 'default';
102902f9a447SGerrit Uitslag        }
103002f9a447SGerrit Uitslag        $this->exportConfig['template'] = $tpl;
103102f9a447SGerrit Uitslag
103202f9a447SGerrit Uitslag        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
103302f9a447SGerrit Uitslag    }
103402f9a447SGerrit Uitslag
103502f9a447SGerrit Uitslag    /**
103602f9a447SGerrit Uitslag     * Returns requested config
103702f9a447SGerrit Uitslag     *
103802f9a447SGerrit Uitslag     * @param string $name
103902f9a447SGerrit Uitslag     * @param mixed $notset
104002f9a447SGerrit Uitslag     * @return mixed|bool
104102f9a447SGerrit Uitslag     */
104217e88313SGerrit Uitslag    public function getExportConfig($name, $notset = false)
104317e88313SGerrit Uitslag    {
104402f9a447SGerrit Uitslag        if ($this->exportConfig === null) {
104502f9a447SGerrit Uitslag            $this->loadExportConfig();
104602f9a447SGerrit Uitslag        }
104702f9a447SGerrit Uitslag
104817e88313SGerrit Uitslag        return $this->exportConfig[$name] ?? $notset;
104902f9a447SGerrit Uitslag    }
1050d63e7fe7SGerrit Uitslag
1051d63e7fe7SGerrit Uitslag    /**
1052d63e7fe7SGerrit Uitslag     * Add 'export pdf'-button to pagetools
1053d63e7fe7SGerrit Uitslag     *
1054d63e7fe7SGerrit Uitslag     * @param Doku_Event $event
1055d63e7fe7SGerrit Uitslag     */
1056852931daSAndreas Gohr    public function addbutton(Event $event)
105717e88313SGerrit Uitslag    {
1058e53f1ec0SSzymon Olewniczak        global $ID, $REV, $DATE_AT;
1059d63e7fe7SGerrit Uitslag
1060d63e7fe7SGerrit Uitslag        if ($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
106117e88313SGerrit Uitslag            $params = ['do' => 'export_pdf'];
1062e53f1ec0SSzymon Olewniczak            if ($DATE_AT) {
1063e53f1ec0SSzymon Olewniczak                $params['at'] = $DATE_AT;
1064e53f1ec0SSzymon Olewniczak            } elseif ($REV) {
1065d63e7fe7SGerrit Uitslag                $params['rev'] = $REV;
1066d63e7fe7SGerrit Uitslag            }
1067d63e7fe7SGerrit Uitslag
1068d63e7fe7SGerrit Uitslag            // insert button at position before last (up to top)
1069d63e7fe7SGerrit Uitslag            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
1070852931daSAndreas Gohr                ['export_pdf' => sprintf(
1071852931daSAndreas Gohr                    '<li><a href="%s" class="%s" rel="nofollow" title="%s"><span>%s</span></a></li>',
1072852931daSAndreas Gohr                    wl($ID, $params),
1073852931daSAndreas Gohr                    'action export_pdf',
1074852931daSAndreas Gohr                    $this->getLang('export_pdf_button'),
1075852931daSAndreas Gohr                    $this->getLang('export_pdf_button')
1076852931daSAndreas Gohr                )] +
1077d63e7fe7SGerrit Uitslag                array_slice($event->data['items'], -1, 1, true);
1078d63e7fe7SGerrit Uitslag        }
1079d63e7fe7SGerrit Uitslag    }
1080026b594bSAndreas Gohr
1081026b594bSAndreas Gohr    /**
1082026b594bSAndreas Gohr     * Add 'export pdf' button to page tools, new SVG based mechanism
1083026b594bSAndreas Gohr     *
1084026b594bSAndreas Gohr     * @param Doku_Event $event
1085026b594bSAndreas Gohr     */
1086852931daSAndreas Gohr    public function addsvgbutton(Event $event)
108717e88313SGerrit Uitslag    {
10884c493e44SGerrit Uitslag        global $INFO;
10894c493e44SGerrit Uitslag        if ($event->data['view'] != 'page' || !$this->getConf('showexportbutton')) {
10904c493e44SGerrit Uitslag            return;
10914c493e44SGerrit Uitslag        }
10924c493e44SGerrit Uitslag
10934c493e44SGerrit Uitslag        if (!$INFO['exists']) {
10944c493e44SGerrit Uitslag            return;
10954c493e44SGerrit Uitslag        }
10964c493e44SGerrit Uitslag
109717e88313SGerrit Uitslag        array_splice($event->data['items'], -1, 0, [new MenuItem()]);
1098026b594bSAndreas Gohr    }
1099979c9cf5SAndreas Gohr
1100979c9cf5SAndreas Gohr    /**
1101979c9cf5SAndreas Gohr     * Get the language of the current document
1102979c9cf5SAndreas Gohr     *
1103979c9cf5SAndreas Gohr     * Uses the translation plugin if available
1104979c9cf5SAndreas Gohr     * @return string
1105979c9cf5SAndreas Gohr     */
1106979c9cf5SAndreas Gohr    protected function getDocumentLanguage($pageid)
1107979c9cf5SAndreas Gohr    {
1108979c9cf5SAndreas Gohr        global $conf;
1109979c9cf5SAndreas Gohr
1110979c9cf5SAndreas Gohr        $lang = $conf['lang'];
1111979c9cf5SAndreas Gohr        /** @var helper_plugin_translation $trans */
1112979c9cf5SAndreas Gohr        $trans = plugin_load('helper', 'translation');
1113979c9cf5SAndreas Gohr        if ($trans) {
1114979c9cf5SAndreas Gohr            $tr = $trans->getLangPart($pageid);
1115*c4c95814SKlap-in            if ($tr) {
1116*c4c95814SKlap-in                $lang = $tr;
1117*c4c95814SKlap-in            }
1118979c9cf5SAndreas Gohr        }
1119979c9cf5SAndreas Gohr
1120979c9cf5SAndreas Gohr        return $lang;
1121979c9cf5SAndreas Gohr    }
1122ee19bac3SLuigi Micco}
1123