xref: /plugin/dw2pdf/action.php (revision 02f9a447ac91ae961961e8bb8f6ca67bb3d2bcd5)
1ee19bac3SLuigi Micco<?php
2ee19bac3SLuigi Micco/**
3ee19bac3SLuigi Micco * dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
4ee19bac3SLuigi Micco *
5ee19bac3SLuigi Micco * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6ee19bac3SLuigi Micco * @author     Luigi Micco <l.micco@tiscali.it>
75db42babSAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
8ee19bac3SLuigi Micco */
9ee19bac3SLuigi Micco
10ee19bac3SLuigi Micco// must be run within Dokuwiki
11ee19bac3SLuigi Miccoif(!defined('DOKU_INC')) die();
12ee19bac3SLuigi Micco
130639157eSGerrit Uitslag/**
140639157eSGerrit Uitslag * Class action_plugin_dw2pdf
150639157eSGerrit Uitslag *
160639157eSGerrit Uitslag * Export hmtl content to pdf, for different url parameter configurations
170639157eSGerrit Uitslag * DokuPDF which extends mPDF is used for generating the pdf from html.
180639157eSGerrit Uitslag */
191ef68647SAndreas Gohrclass action_plugin_dw2pdf extends DokuWiki_Action_Plugin {
20*02f9a447SGerrit Uitslag    /**
21*02f9a447SGerrit Uitslag     * Settings for current export, collected from url param, plugin config, global config
22*02f9a447SGerrit Uitslag     *
23*02f9a447SGerrit Uitslag     * @var array
24*02f9a447SGerrit Uitslag     */
25*02f9a447SGerrit Uitslag    public $exportConfig = null;
2660e59de7SGerrit Uitslag    protected $tpl;
2760e59de7SGerrit Uitslag    protected $list = array();
281c14c879SAndreas Gohr
291c14c879SAndreas Gohr    /**
301c14c879SAndreas Gohr     * Constructor. Sets the correct template
311c14c879SAndreas Gohr     */
326be736bfSGerrit Uitslag    public function __construct() {
33*02f9a447SGerrit Uitslag        $this->tpl = $this->getExportConfig('template');
341c14c879SAndreas Gohr    }
351c14c879SAndreas Gohr
36ee19bac3SLuigi Micco    /**
37ee19bac3SLuigi Micco     * Register the events
38ee19bac3SLuigi Micco     */
396be736bfSGerrit Uitslag    public function register(Doku_Event_Handler $controller) {
40ee19bac3SLuigi Micco        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
416be736bfSGerrit Uitslag        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
42ee19bac3SLuigi Micco    }
43ee19bac3SLuigi Micco
441c14c879SAndreas Gohr    /**
451c14c879SAndreas Gohr     * Do the HTML to PDF conversion work
46737417c6SKlap-in     *
47737417c6SKlap-in     * @param Doku_Event $event
48737417c6SKlap-in     * @param array      $param
49737417c6SKlap-in     * @return bool
501c14c879SAndreas Gohr     */
516be736bfSGerrit Uitslag    public function convert(&$event, $param) {
52ee19bac3SLuigi Micco        global $ACT;
53ee19bac3SLuigi Micco        global $REV;
54ee19bac3SLuigi Micco        global $ID;
55ad18f4e1SGerrit Uitslag        global $INPUT, $conf;
56ee19bac3SLuigi Micco
571ef68647SAndreas Gohr        // our event?
58ad18f4e1SGerrit Uitslag        if(($ACT != 'export_pdfbook') && ($ACT != 'export_pdf') && ($ACT != 'export_pdfns')) return false;
59ee19bac3SLuigi Micco
601ef68647SAndreas Gohr        // check user's rights
611ef68647SAndreas Gohr        if(auth_quickaclcheck($ID) < AUTH_READ) return false;
621ef68647SAndreas Gohr
6387c86ddaSAndreas Gohr        // one or multiple pages?
6460e59de7SGerrit Uitslag        $this->list = array();
6528e636eaSGerrit Uitslag
6687c86ddaSAndreas Gohr        if($ACT == 'export_pdf') {
6760e59de7SGerrit Uitslag            $this->list[0] = $ID;
68737417c6SKlap-in            $title = p_get_first_heading($ID);
69ad18f4e1SGerrit Uitslag
70ad18f4e1SGerrit Uitslag        } elseif($ACT == 'export_pdfns') {
71ad18f4e1SGerrit Uitslag            //check input for title and ns
7226be4eceSGerrit Uitslag            if(!$title = $INPUT->str('pdfns_title')) {
7326be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
74ad18f4e1SGerrit Uitslag                return false;
75ad18f4e1SGerrit Uitslag            }
7626be4eceSGerrit Uitslag            $pdfnamespace = cleanID($INPUT->str('pdfns_ns'));
77ad18f4e1SGerrit Uitslag            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
7826be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needns');
79ad18f4e1SGerrit Uitslag                return false;
80ad18f4e1SGerrit Uitslag            }
81ad18f4e1SGerrit Uitslag
8226be4eceSGerrit Uitslag            //sort order
83ad18f4e1SGerrit Uitslag            $order = $INPUT->str('pdfns_order', 'natural', true);
84ad18f4e1SGerrit Uitslag            $sortoptions = array('pagename', 'date', 'natural');
85ad18f4e1SGerrit Uitslag            if(!in_array($order, $sortoptions)) {
86ad18f4e1SGerrit Uitslag                $order = 'natural';
87ad18f4e1SGerrit Uitslag            }
88ad18f4e1SGerrit Uitslag
8926be4eceSGerrit Uitslag            //search depth
90ad18f4e1SGerrit Uitslag            $depth = $INPUT->int('pdfns_depth', 0);
91ad18f4e1SGerrit Uitslag            if($depth < 0) {
92ad18f4e1SGerrit Uitslag                $depth = 0;
93ad18f4e1SGerrit Uitslag            }
9426be4eceSGerrit Uitslag
95ad18f4e1SGerrit Uitslag            //page search
96ad18f4e1SGerrit Uitslag            $result = array();
97ad18f4e1SGerrit Uitslag            $opts = array('depth' => $depth); //recursive all levels
98ad18f4e1SGerrit Uitslag            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
99ad18f4e1SGerrit Uitslag            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
100ad18f4e1SGerrit Uitslag
10126be4eceSGerrit Uitslag            //sorting
102ad18f4e1SGerrit Uitslag            if(count($result) > 0) {
103ad18f4e1SGerrit Uitslag                if($order == 'date') {
104ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_datesort'));
105ad18f4e1SGerrit Uitslag                } elseif($order == 'pagename') {
106ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_pagenamesort'));
107ad18f4e1SGerrit Uitslag                }
108ad18f4e1SGerrit Uitslag            }
109ad18f4e1SGerrit Uitslag
110ad18f4e1SGerrit Uitslag            foreach($result as $item) {
11160e59de7SGerrit Uitslag                $this->list[] = $item['id'];
112ad18f4e1SGerrit Uitslag            }
113ad18f4e1SGerrit Uitslag
114737417c6SKlap-in        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
11526be4eceSGerrit Uitslag            //is in Bookmanager of bookcreator plugin a title given?
11626be4eceSGerrit Uitslag            if(!$title = $INPUT->str('pdfbook_title')) { //TODO when title is changed, the cached file contains the old title
11726be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
118737417c6SKlap-in                return false;
11926be4eceSGerrit Uitslag            } else {
12060e59de7SGerrit Uitslag                $this->list = explode("|", $_COOKIE['list-pagelist']);
12126be4eceSGerrit Uitslag            }
122ad18f4e1SGerrit Uitslag
123737417c6SKlap-in        } else {
12426be4eceSGerrit Uitslag            //show empty bookcreator message
12526be4eceSGerrit Uitslag            $this->showPageWithErrorMsg($event, 'empty');
126737417c6SKlap-in            return false;
127737417c6SKlap-in        }
128737417c6SKlap-in
129737417c6SKlap-in        // it's ours, no one else's
130737417c6SKlap-in        $event->preventDefault();
13187c86ddaSAndreas Gohr
132*02f9a447SGerrit Uitslag        //some shortcuts to export settings
133*02f9a447SGerrit Uitslag        $hasToC = $this->getExportConfig('hasToC');
134*02f9a447SGerrit Uitslag        $levels = $this->getExportConfig('levels');
135*02f9a447SGerrit Uitslag        $isDebug = $this->getExportConfig('isDebug');
1366ea88a05SAndreas Gohr
13787c86ddaSAndreas Gohr        // prepare cache
138*02f9a447SGerrit Uitslag        $cachekey = join(',', $this->list)
139*02f9a447SGerrit Uitslag                    . $REV
140*02f9a447SGerrit Uitslag                    . $this->getExportConfig('template')
141*02f9a447SGerrit Uitslag                    . $this->getExportConfig('pagesize')
142*02f9a447SGerrit Uitslag                    . $this->getExportConfig('orientation')
143*02f9a447SGerrit Uitslag                    . ($hasToC ? join('-', $levels) : '0')
144*02f9a447SGerrit Uitslag                    . $title;
145*02f9a447SGerrit Uitslag        $cache = new cache($cachekey, '.dw2.pdf');
146*02f9a447SGerrit Uitslag
14760e59de7SGerrit Uitslag        $depends['files']   = array_map('wikiFN', $this->list);
14887c86ddaSAndreas Gohr        $depends['files'][] = __FILE__;
14987c86ddaSAndreas Gohr        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
15087c86ddaSAndreas Gohr        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
151df59f400SAndreas Gohr        $depends['files']   = array_merge($depends['files'], getConfigFiles('main'));
15287c86ddaSAndreas Gohr
153d01d2a42SAndreas Gohr        // hard work only when no cache available
15487c86ddaSAndreas Gohr        if(!$this->getConf('usecache') || !$cache->useCache($depends)) {
155a2c33768SGerrit Uitslag            // debug enabled?
156a2c33768SGerrit Uitslag
1571ef68647SAndreas Gohr            // initialize PDF library
158cde5a1b3SAndreas Gohr            require_once(dirname(__FILE__) . "/DokuPDF.class.php");
1596ea88a05SAndreas Gohr
160*02f9a447SGerrit Uitslag            $mpdf = new DokuPDF($this->getExportConfig('pagesize'), $this->getExportConfig('orientation'));
161ee19bac3SLuigi Micco
162d62df65bSAndreas Gohr            // let mpdf fix local links
163d62df65bSAndreas Gohr            $self = parse_url(DOKU_URL);
164d62df65bSAndreas Gohr            $url = $self['scheme'] . '://' . $self['host'];
165*02f9a447SGerrit Uitslag            if($self['port']) {
166*02f9a447SGerrit Uitslag                $url .= ':' . $self['port'];
167*02f9a447SGerrit Uitslag            }
168d62df65bSAndreas Gohr            $mpdf->setBasePath($url);
169d62df65bSAndreas Gohr
17056d13144SAndreas Gohr            // Set the title
17156d13144SAndreas Gohr            $mpdf->SetTitle($title);
17256d13144SAndreas Gohr
1731ef68647SAndreas Gohr            // some default settings
174*02f9a447SGerrit Uitslag            $mpdf->mirrorMargins = 1; //double-sided document, starts at an odd page (first page is a right-hand side page)
175*02f9a447SGerrit Uitslag            $mpdf->useOddEven    = 1; //duplicate of mirrorMargins
176daa70883SAndreas Gohr            $mpdf->setAutoTopMargin = 'stretch';
177daa70883SAndreas Gohr            $mpdf->setAutoBottomMargin = 'stretch';
178*02f9a447SGerrit Uitslag//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
179*02f9a447SGerrit Uitslag            if($hasToC) {
180*02f9a447SGerrit Uitslag                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off');//use italic pageno until ToC
181*02f9a447SGerrit Uitslag                $mpdf->h2toc = $levels;
182*02f9a447SGerrit Uitslag            } else {
183*02f9a447SGerrit Uitslag                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
184*02f9a447SGerrit Uitslag            }
1852eedf77dSAndreas Gohr
18656d13144SAndreas Gohr            // load the template
1871c14c879SAndreas Gohr            $template = $this->load_template($title);
188ee19bac3SLuigi Micco
1891ef68647SAndreas Gohr            // prepare HTML header styles
190a2c33768SGerrit Uitslag            $html = '';
191*02f9a447SGerrit Uitslag            if($isDebug) {
192a2c33768SGerrit Uitslag                $html .= '<html><head>';
193737417c6SKlap-in                $html .= '<style type="text/css">';
194a2c33768SGerrit Uitslag            }
195a2c33768SGerrit Uitslag            $styles = $this->load_css();
196a2c33768SGerrit Uitslag            $styles .= '@page { size:auto; ' . $template['page'] . '}';
197a2c33768SGerrit Uitslag            $styles .= '@page :first {' . $template['first'] . '}';
198a2c33768SGerrit Uitslag            $mpdf->WriteHTML($styles, 1);
199a2c33768SGerrit Uitslag
200*02f9a447SGerrit Uitslag            if($isDebug) {
201a2c33768SGerrit Uitslag                $html .= $styles;
2021ef68647SAndreas Gohr                $html .= '</style>';
2031ef68647SAndreas Gohr                $html .= '</head><body>';
204a2c33768SGerrit Uitslag            }
205a2c33768SGerrit Uitslag
206a2c33768SGerrit Uitslag            $body_start = $template['html'];
207a2c33768SGerrit Uitslag            $body_start .= '<div class="dokuwiki">';
2082eedf77dSAndreas Gohr
2091e45476bSmnapp            // insert the cover page
210a2c33768SGerrit Uitslag            $body_start .= $template['cover'];
211a2c33768SGerrit Uitslag
212a2c33768SGerrit Uitslag            $mpdf->WriteHTML($body_start, 2, true, false); //start body html
213*02f9a447SGerrit Uitslag            if($isDebug) {
214a2c33768SGerrit Uitslag                $html .= $body_start;
215a2c33768SGerrit Uitslag            }
216*02f9a447SGerrit Uitslag            if($hasToC) {
217*02f9a447SGerrit 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
218*02f9a447SGerrit Uitslag                //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
219*02f9a447SGerrit Uitslag                //      - there is no page numbering at the pages of the ToC
220*02f9a447SGerrit Uitslag                $mpdf->TOCpagebreakByArray(
221*02f9a447SGerrit Uitslag                    array(
222*02f9a447SGerrit Uitslag                        'toc-preHTML' => '<h2>Table of contents</h2>',
223*02f9a447SGerrit Uitslag                        'toc-bookmarkText'=> 'Table of Content',
224*02f9a447SGerrit Uitslag                        'links' => true,
225*02f9a447SGerrit Uitslag                        'outdent' => '1em',
226*02f9a447SGerrit Uitslag                        'resetpagenum' => true, //start pagenumbering after ToC
227*02f9a447SGerrit Uitslag                        'pagenumstyle' => '1'
228*02f9a447SGerrit Uitslag                    )
229*02f9a447SGerrit Uitslag                );
230*02f9a447SGerrit Uitslag                $html .= '<tocpagebreak>';
231*02f9a447SGerrit Uitslag            }
232*02f9a447SGerrit Uitslag
233ed9f9952Smnapp
234c00eb13bSGerrit Uitslag            // store original pageid
235c00eb13bSGerrit Uitslag            $keep = $ID;
236c00eb13bSGerrit Uitslag
2371ef68647SAndreas Gohr            // loop over all pages
238a2c33768SGerrit Uitslag            $cnt = count($this->list);
2391ef68647SAndreas Gohr            for($n = 0; $n < $cnt; $n++) {
240a2c33768SGerrit Uitslag                $page = $this->list[$n];
241ee19bac3SLuigi Micco
242c00eb13bSGerrit Uitslag                // set global pageid to the rendered page
243c00eb13bSGerrit Uitslag                $ID   = $page;
244c00eb13bSGerrit Uitslag
245a2c33768SGerrit Uitslag                $pagehtml = p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page);
246a2c33768SGerrit Uitslag                $pagehtml .= $this->page_depend_replacements($template['cite'], cleanID($page));
2471ef68647SAndreas Gohr                if($n < ($cnt - 1)) {
248a2c33768SGerrit Uitslag                    $pagehtml .= '<pagebreak />';
249a2c33768SGerrit Uitslag                }
250a2c33768SGerrit Uitslag
251a2c33768SGerrit Uitslag                $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
252*02f9a447SGerrit Uitslag                if($isDebug) {
253a2c33768SGerrit Uitslag                    $html .= $pagehtml;
2541ef68647SAndreas Gohr                }
255ee19bac3SLuigi Micco            }
256c00eb13bSGerrit Uitslag            //restore ID
257c00eb13bSGerrit Uitslag            $ID = $keep;
258ee19bac3SLuigi Micco
25933c15297SGerrit Uitslag            // insert the back page
260a2c33768SGerrit Uitslag            $body_end = $template['back'];
26133c15297SGerrit Uitslag
262a2c33768SGerrit Uitslag            $body_end .= '</div>';
263a2c33768SGerrit Uitslag
264a2c33768SGerrit Uitslag            $mpdf->WriteHTML($body_end, 2, false, true); // end body html
265*02f9a447SGerrit Uitslag            if($isDebug) {
266a2c33768SGerrit Uitslag                $html .= $body_end;
267eeb17e15SAndreas Gohr                $html .= '</body>';
268eeb17e15SAndreas Gohr                $html .= '</html>';
269a2c33768SGerrit Uitslag            }
270f765508eSGerrit Uitslag
271f765508eSGerrit Uitslag            //Return html for debugging
272*02f9a447SGerrit Uitslag            if($isDebug) {
273*02f9a447SGerrit Uitslag                if($INPUT->str('debughtml', 'text', true) == 'html') {
27426be4eceSGerrit Uitslag                    echo $html;
275a2c33768SGerrit Uitslag                } else {
276a2c33768SGerrit Uitslag                    header('Content-Type: text/plain; charset=utf-8');
277a2c33768SGerrit Uitslag                    echo $html;
278a2c33768SGerrit Uitslag                }
27926be4eceSGerrit Uitslag                exit();
28026be4eceSGerrit Uitslag            };
281f765508eSGerrit Uitslag
28287c86ddaSAndreas Gohr            // write to cache file
28387c86ddaSAndreas Gohr            $mpdf->Output($cache->cache, 'F');
28487c86ddaSAndreas Gohr        }
28587c86ddaSAndreas Gohr
28687c86ddaSAndreas Gohr        // deliver the file
28787c86ddaSAndreas Gohr        header('Content-Type: application/pdf');
288b853b723SAndreas Gohr        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
28987c86ddaSAndreas Gohr        header('Pragma: public');
29087c86ddaSAndreas Gohr        http_conditionalRequest(filemtime($cache->cache));
29187c86ddaSAndreas Gohr
2929a3c8d9fSAndreas Gohr        $filename = rawurlencode(cleanID(strtr($title, ':/;"', '    ')));
29387c86ddaSAndreas Gohr        if($this->getConf('output') == 'file') {
2949a3c8d9fSAndreas Gohr            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
29587c86ddaSAndreas Gohr        } else {
2969a3c8d9fSAndreas Gohr            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
29787c86ddaSAndreas Gohr        }
298ee19bac3SLuigi Micco
299e993da11SGerrit Uitslag        //try to send file, and exit if done
300e993da11SGerrit Uitslag        http_sendfile($cache->cache);
30187c86ddaSAndreas Gohr
30287c86ddaSAndreas Gohr        $fp = @fopen($cache->cache, "rb");
30387c86ddaSAndreas Gohr        if($fp) {
30487c86ddaSAndreas Gohr            http_rangeRequest($fp, filesize($cache->cache), 'application/pdf');
30587c86ddaSAndreas Gohr        } else {
30687c86ddaSAndreas Gohr            header("HTTP/1.0 500 Internal Server Error");
30787c86ddaSAndreas Gohr            print "Could not read file - bad permissions?";
30887c86ddaSAndreas Gohr        }
3091ef68647SAndreas Gohr        exit();
3101ef68647SAndreas Gohr    }
3111ef68647SAndreas Gohr
3126be736bfSGerrit Uitslag    /**
3136be736bfSGerrit Uitslag     * Add 'export pdf'-button to pagetools
3146be736bfSGerrit Uitslag     *
3156be736bfSGerrit Uitslag     * @param Doku_Event $event
3166be736bfSGerrit Uitslag     * @param mixed      $param not defined
3176be736bfSGerrit Uitslag     */
318*02f9a447SGerrit Uitslag    public function addbutton(Doku_Event $event, $param) {
3192c53f619SAndreas Gohr        global $ID, $REV;
3206be736bfSGerrit Uitslag
3216be736bfSGerrit Uitslag        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
3226be736bfSGerrit Uitslag            $params = array('do' => 'export_pdf');
323*02f9a447SGerrit Uitslag            if($REV) {
324*02f9a447SGerrit Uitslag                $params['rev'] = $REV;
325*02f9a447SGerrit Uitslag            }
3266be736bfSGerrit Uitslag
3271e02f86cSAndreas Gohr            // insert button at position before last (up to top)
3281e02f86cSAndreas Gohr            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
3291e02f86cSAndreas Gohr                                    array('export_pdf' =>
3306be736bfSGerrit Uitslag                                          '<li>'
3316be736bfSGerrit Uitslag                                          . '<a href=' . wl($ID, $params) . '  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
3326be736bfSGerrit Uitslag                                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
3336be736bfSGerrit Uitslag                                          . '</a>'
3341e02f86cSAndreas Gohr                                          . '</li>'
3351e02f86cSAndreas Gohr                                    ) +
3361e02f86cSAndreas Gohr                                    array_slice($event->data['items'], -1, 1, true);
3376be736bfSGerrit Uitslag        }
3386be736bfSGerrit Uitslag    }
339d01d2a42SAndreas Gohr
340d01d2a42SAndreas Gohr    /**
3412eedf77dSAndreas Gohr     * Load the various template files and prepare the HTML/CSS for insertion
3421ef68647SAndreas Gohr     */
3431c14c879SAndreas Gohr    protected function load_template($title) {
3441ef68647SAndreas Gohr        global $ID;
3451ef68647SAndreas Gohr        global $conf;
3461ef68647SAndreas Gohr
3472eedf77dSAndreas Gohr        // this is what we'll return
3482eedf77dSAndreas Gohr        $output = array(
3491e45476bSmnapp            'cover' => '',
3502eedf77dSAndreas Gohr            'html'  => '',
3512eedf77dSAndreas Gohr            'page'  => '',
3522eedf77dSAndreas Gohr            'first' => '',
3532eedf77dSAndreas Gohr            'cite'  => '',
3542eedf77dSAndreas Gohr        );
3552eedf77dSAndreas Gohr
3562eedf77dSAndreas Gohr        // prepare header/footer elements
3572eedf77dSAndreas Gohr        $html = '';
35833c15297SGerrit Uitslag        foreach(array('header', 'footer') as $section) {
35933c15297SGerrit Uitslag            foreach(array('', '_odd', '_even', '_first') as $order) {
360*02f9a447SGerrit Uitslag                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
36133c15297SGerrit Uitslag                if(file_exists($file)) {
36233c15297SGerrit Uitslag                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
36333c15297SGerrit Uitslag                    $html .= file_get_contents($file) . DOKU_LF;
36433c15297SGerrit Uitslag                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
3652eedf77dSAndreas Gohr
3662eedf77dSAndreas Gohr                    // register the needed pseudo CSS
36733c15297SGerrit Uitslag                    if($order == '_first') {
36833c15297SGerrit Uitslag                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
36933c15297SGerrit Uitslag                    } elseif($order == '_even') {
37033c15297SGerrit Uitslag                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
37133c15297SGerrit Uitslag                    } elseif($order == '_odd') {
37233c15297SGerrit Uitslag                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
373daa70883SAndreas Gohr                    } else {
37433c15297SGerrit Uitslag                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
3752eedf77dSAndreas Gohr                    }
3762eedf77dSAndreas Gohr                }
3772eedf77dSAndreas Gohr            }
3782eedf77dSAndreas Gohr        }
3792eedf77dSAndreas Gohr
3801ef68647SAndreas Gohr        // prepare replacements
3811ef68647SAndreas Gohr        $replace = array(
3821ef68647SAndreas Gohr            '@PAGE@'    => '{PAGENO}',
383*02f9a447SGerrit Uitslag            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
3842eedf77dSAndreas Gohr            '@TITLE@'   => hsc($title),
3851ef68647SAndreas Gohr            '@WIKI@'    => $conf['title'],
3861ef68647SAndreas Gohr            '@WIKIURL@' => DOKU_URL,
3871ef68647SAndreas Gohr            '@DATE@'    => dformat(time()),
3885d6fbaeaSAndreas Gohr            '@BASE@'    => DOKU_BASE,
389*02f9a447SGerrit Uitslag            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
3901ef68647SAndreas Gohr        );
3911ef68647SAndreas Gohr
3922eedf77dSAndreas Gohr        // set HTML element
393a180c973SKlap-in        $html = str_replace(array_keys($replace), array_values($replace), $html);
394a180c973SKlap-in        //TODO For bookcreator $ID (= bookmanager page) makes no sense
395a180c973SKlap-in        $output['html'] = $this->page_depend_replacements($html, $ID);
3961ef68647SAndreas Gohr
3971e45476bSmnapp        // cover page
398*02f9a447SGerrit Uitslag        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
39933c15297SGerrit Uitslag        if(file_exists($coverfile)) {
40033c15297SGerrit Uitslag            $output['cover'] = file_get_contents($coverfile);
4011e45476bSmnapp            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
4026e2ec302SGerrit Uitslag            $output['cover'] .= '<pagebreak />';
4031e45476bSmnapp        }
4041e45476bSmnapp
40533c15297SGerrit Uitslag        // cover page
406*02f9a447SGerrit Uitslag        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
40733c15297SGerrit Uitslag        if(file_exists($backfile)) {
40833c15297SGerrit Uitslag            $output['back'] = '<pagebreak />';
40933c15297SGerrit Uitslag            $output['back'] .= file_get_contents($backfile);
41033c15297SGerrit Uitslag            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
41133c15297SGerrit Uitslag        }
41233c15297SGerrit Uitslag
4132eedf77dSAndreas Gohr        // citation box
414*02f9a447SGerrit Uitslag        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
41533c15297SGerrit Uitslag        if(file_exists($citationfile)) {
41633c15297SGerrit Uitslag            $output['cite'] = file_get_contents($citationfile);
4172eedf77dSAndreas Gohr            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
4182eedf77dSAndreas Gohr        }
4191ef68647SAndreas Gohr
4202eedf77dSAndreas Gohr        return $output;
4211ef68647SAndreas Gohr    }
4221ef68647SAndreas Gohr
4231ef68647SAndreas Gohr    /**
424a180c973SKlap-in     * @param string $raw code with placeholders
425a180c973SKlap-in     * @param string $id  pageid
426a180c973SKlap-in     * @return string
427a180c973SKlap-in     */
428a180c973SKlap-in    protected function page_depend_replacements($raw, $id) {
429a180c973SKlap-in        global $REV;
430a180c973SKlap-in
431a180c973SKlap-in        // generate qr code for this page using google infographics api
432a180c973SKlap-in        $qr_code = '';
433a180c973SKlap-in        if($this->getConf('qrcodesize')) {
434a180c973SKlap-in            $url = urlencode(wl($id, '', '&', true));
435a180c973SKlap-in            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
436a180c973SKlap-in                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
437a180c973SKlap-in        }
438a180c973SKlap-in        // prepare replacements
439a180c973SKlap-in        $replace['@ID@']      = $id;
440a180c973SKlap-in        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
441a180c973SKlap-in        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&");
442a180c973SKlap-in        $replace['@QRCODE@']  = $qr_code;
443a180c973SKlap-in
444a180c973SKlap-in        return str_replace(array_keys($replace), array_values($replace), $raw);
445a180c973SKlap-in    }
446a180c973SKlap-in
447a180c973SKlap-in    /**
4481c14c879SAndreas Gohr     * Load all the style sheets and apply the needed replacements
4491ef68647SAndreas Gohr     */
4501c14c879SAndreas Gohr    protected function load_css() {
451737417c6SKlap-in        global $conf;
4521c14c879SAndreas Gohr        //reusue the CSS dispatcher functions without triggering the main function
4531c14c879SAndreas Gohr        define('SIMPLE_TEST', 1);
4541c14c879SAndreas Gohr        require_once(DOKU_INC . 'lib/exe/css.php');
455ee19bac3SLuigi Micco
4561c14c879SAndreas Gohr        // prepare CSS files
4571c14c879SAndreas Gohr        $files = array_merge(
4581c14c879SAndreas Gohr            array(
4591c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/screen.css'
4601c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
4611c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/print.css'
4621c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
4631c14c879SAndreas Gohr            ),
4641c14c879SAndreas Gohr            css_pluginstyles('all'),
46558e6409eSAndreas Gohr            $this->css_pluginPDFstyles(),
4661c14c879SAndreas Gohr            array(
4671c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
4681c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
4691c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
4701c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
4711c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
4721c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
4731c14c879SAndreas Gohr            )
4741c14c879SAndreas Gohr        );
4751c14c879SAndreas Gohr        $css = '';
4761c14c879SAndreas Gohr        foreach($files as $file => $location) {
47728e636eaSGerrit Uitslag            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
47828e636eaSGerrit Uitslag            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
4791c14c879SAndreas Gohr            $css .= css_loadfile($file, $location);
4801ef68647SAndreas Gohr        }
4811ef68647SAndreas Gohr
48228e636eaSGerrit Uitslag        if(function_exists('css_parseless')) {
4831c14c879SAndreas Gohr            // apply pattern replacements
48428e636eaSGerrit Uitslag            $styleini = css_styleini($conf['template']);
48528e636eaSGerrit Uitslag            $css = css_applystyle($css, $styleini['replacements']);
48628e636eaSGerrit Uitslag
48728e636eaSGerrit Uitslag            // parse less
48828e636eaSGerrit Uitslag            $css = css_parseless($css);
48928e636eaSGerrit Uitslag        } else {
49028e636eaSGerrit Uitslag            // @deprecated 2013-12-19: fix backward compatibility
4911c14c879SAndreas Gohr            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
49228e636eaSGerrit Uitslag        }
4931ef68647SAndreas Gohr
4941c14c879SAndreas Gohr        return $css;
495ee19bac3SLuigi Micco    }
4961c14c879SAndreas Gohr
49758e6409eSAndreas Gohr    /**
49858e6409eSAndreas Gohr     * Returns a list of possible Plugin PDF Styles
49958e6409eSAndreas Gohr     *
50058e6409eSAndreas Gohr     * Checks for a pdf.css, falls back to print.css
50158e6409eSAndreas Gohr     *
50258e6409eSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
50358e6409eSAndreas Gohr     */
5046be736bfSGerrit Uitslag    protected function css_pluginPDFstyles() {
50558e6409eSAndreas Gohr        $list = array();
50658e6409eSAndreas Gohr        $plugins = plugin_list();
507f54b51f7SAndreas Gohr
508f54b51f7SAndreas Gohr        $usestyle = explode(',', $this->getConf('usestyles'));
50958e6409eSAndreas Gohr        foreach($plugins as $p) {
510f54b51f7SAndreas Gohr            if(in_array($p, $usestyle)) {
511f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
512f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
513f54b51f7SAndreas Gohr            }
514f54b51f7SAndreas Gohr
51558e6409eSAndreas Gohr            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
51658e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
51758e6409eSAndreas Gohr            } else {
51858e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
51958e6409eSAndreas Gohr            }
52058e6409eSAndreas Gohr        }
52158e6409eSAndreas Gohr        return $list;
52258e6409eSAndreas Gohr    }
523ad18f4e1SGerrit Uitslag
524ad18f4e1SGerrit Uitslag    /**
52560e59de7SGerrit Uitslag     * Returns array of pages which will be included in the exported pdf
52660e59de7SGerrit Uitslag     *
52760e59de7SGerrit Uitslag     * @return array
52860e59de7SGerrit Uitslag     */
52960e59de7SGerrit Uitslag    public function getExportedPages() {
53060e59de7SGerrit Uitslag        return $this->list;
53160e59de7SGerrit Uitslag    }
53260e59de7SGerrit Uitslag
53360e59de7SGerrit Uitslag    /**
534ad18f4e1SGerrit Uitslag     * usort callback to sort by file lastmodified time
535ad18f4e1SGerrit Uitslag     */
536ad18f4e1SGerrit Uitslag    public function _datesort($a, $b) {
537ad18f4e1SGerrit Uitslag        if($b['rev'] < $a['rev']) return -1;
538ad18f4e1SGerrit Uitslag        if($b['rev'] > $a['rev']) return 1;
539ad18f4e1SGerrit Uitslag        return strcmp($b['id'], $a['id']);
540ad18f4e1SGerrit Uitslag    }
541ad18f4e1SGerrit Uitslag
542ad18f4e1SGerrit Uitslag    /**
543ad18f4e1SGerrit Uitslag     * usort callback to sort by page id
544ad18f4e1SGerrit Uitslag     */
545ad18f4e1SGerrit Uitslag    public function _pagenamesort($a, $b) {
546ad18f4e1SGerrit Uitslag        if($a['id'] <= $b['id']) return -1;
547ad18f4e1SGerrit Uitslag        if($a['id'] > $b['id']) return 1;
548ad18f4e1SGerrit Uitslag        return 0;
549ad18f4e1SGerrit Uitslag    }
55026be4eceSGerrit Uitslag
55126be4eceSGerrit Uitslag    /**
55226be4eceSGerrit Uitslag     * Set error notification and reload page again
55326be4eceSGerrit Uitslag     *
55426be4eceSGerrit Uitslag     * @param Doku_Event $event
55526be4eceSGerrit Uitslag     * @param string     $msglangkey key of translation key
55626be4eceSGerrit Uitslag     */
55726be4eceSGerrit Uitslag    private function showPageWithErrorMsg(&$event, $msglangkey) {
55826be4eceSGerrit Uitslag        msg($this->getLang($msglangkey), -1);
55926be4eceSGerrit Uitslag
56026be4eceSGerrit Uitslag        $event->data = 'show';
56126be4eceSGerrit Uitslag        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
56226be4eceSGerrit Uitslag    }
563*02f9a447SGerrit Uitslag
564*02f9a447SGerrit Uitslag    /**
565*02f9a447SGerrit Uitslag     * Return settings read from:
566*02f9a447SGerrit Uitslag     *   1. url parameters
567*02f9a447SGerrit Uitslag     *   2. plugin config
568*02f9a447SGerrit Uitslag     *   3. global config
569*02f9a447SGerrit Uitslag     *
570*02f9a447SGerrit Uitslag     * @return array
571*02f9a447SGerrit Uitslag     */
572*02f9a447SGerrit Uitslag    protected function loadExportConfig() {
573*02f9a447SGerrit Uitslag        global $INPUT;
574*02f9a447SGerrit Uitslag        global $conf;
575*02f9a447SGerrit Uitslag
576*02f9a447SGerrit Uitslag        $this->exportConfig = array();
577*02f9a447SGerrit Uitslag
578*02f9a447SGerrit Uitslag        // decide on the paper setup from param or config
579*02f9a447SGerrit Uitslag        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
580*02f9a447SGerrit Uitslag        $this->exportConfig['orientation']  = $INPUT->str('orientation', $this->getConf('orientation'), true);
581*02f9a447SGerrit Uitslag
582*02f9a447SGerrit Uitslag        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'), true);
583*02f9a447SGerrit Uitslag        $levels = array();
584*02f9a447SGerrit Uitslag        if($hasToC) {
585*02f9a447SGerrit Uitslag            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
586*02f9a447SGerrit Uitslag            list($top_input, $max_input) = explode('-', $toclevels, 2);
587*02f9a447SGerrit Uitslag            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
588*02f9a447SGerrit Uitslag            $bounds_input = array(
589*02f9a447SGerrit Uitslag                'top' => array(
590*02f9a447SGerrit Uitslag                    (int) $top_input,
591*02f9a447SGerrit Uitslag                    (int) $top_conf
592*02f9a447SGerrit Uitslag                ),
593*02f9a447SGerrit Uitslag                'max' => array(
594*02f9a447SGerrit Uitslag                    (int) $max_input,
595*02f9a447SGerrit Uitslag                    (int) $max_conf
596*02f9a447SGerrit Uitslag                )
597*02f9a447SGerrit Uitslag            );
598*02f9a447SGerrit Uitslag            $bounds = array(
599*02f9a447SGerrit Uitslag                'top' => $conf['toptoclevel'],
600*02f9a447SGerrit Uitslag                'max' => $conf['maxtoclevel']
601*02f9a447SGerrit Uitslag
602*02f9a447SGerrit Uitslag            );
603*02f9a447SGerrit Uitslag            foreach($bounds_input as $bound => $values) {
604*02f9a447SGerrit Uitslag                foreach($values as $value) {
605*02f9a447SGerrit Uitslag                    if($value > 0 && $value <= 5) {
606*02f9a447SGerrit Uitslag                        //stop at valid value and store
607*02f9a447SGerrit Uitslag                        $bounds[$bound] = $value;
608*02f9a447SGerrit Uitslag                        break;
609*02f9a447SGerrit Uitslag                    }
610*02f9a447SGerrit Uitslag                }
611*02f9a447SGerrit Uitslag            }
612*02f9a447SGerrit Uitslag
613*02f9a447SGerrit Uitslag            if($bounds['max'] < $bounds['top']) {
614*02f9a447SGerrit Uitslag                $bounds['max'] = $bounds['top'];
615*02f9a447SGerrit Uitslag            }
616*02f9a447SGerrit Uitslag
617*02f9a447SGerrit Uitslag            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
618*02f9a447SGerrit Uitslag                $levels["H$level"] = $level - 1;
619*02f9a447SGerrit Uitslag            }
620*02f9a447SGerrit Uitslag        }
621*02f9a447SGerrit Uitslag        $this->exportConfig['hasToC'] = $hasToC;
622*02f9a447SGerrit Uitslag        $this->exportConfig['levels'] = $levels;
623*02f9a447SGerrit Uitslag
624*02f9a447SGerrit Uitslag        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
625*02f9a447SGerrit Uitslag
626*02f9a447SGerrit Uitslag        $tplconf = $this->getConf('template');
627*02f9a447SGerrit Uitslag        $tpl = $INPUT->str('template', $tplconf, true);
628*02f9a447SGerrit Uitslag        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
629*02f9a447SGerrit Uitslag            $tpl = $tplconf;
630*02f9a447SGerrit Uitslag        }
631*02f9a447SGerrit Uitslag        if(!$tpl){
632*02f9a447SGerrit Uitslag            $tpl = 'default';
633*02f9a447SGerrit Uitslag        }
634*02f9a447SGerrit Uitslag        $this->exportConfig['template'] = $tpl;
635*02f9a447SGerrit Uitslag
636*02f9a447SGerrit Uitslag        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
637*02f9a447SGerrit Uitslag    }
638*02f9a447SGerrit Uitslag
639*02f9a447SGerrit Uitslag    /**
640*02f9a447SGerrit Uitslag     * Returns requested config
641*02f9a447SGerrit Uitslag     *
642*02f9a447SGerrit Uitslag     * @param string $name
643*02f9a447SGerrit Uitslag     * @param mixed  $notset
644*02f9a447SGerrit Uitslag     * @return mixed|bool
645*02f9a447SGerrit Uitslag     */
646*02f9a447SGerrit Uitslag    public function getExportConfig($name, $notset = false) {
647*02f9a447SGerrit Uitslag        if ($this->exportConfig === null){
648*02f9a447SGerrit Uitslag            $this->loadExportConfig();
649*02f9a447SGerrit Uitslag        }
650*02f9a447SGerrit Uitslag
651*02f9a447SGerrit Uitslag        if(isset($this->exportConfig[$name])){
652*02f9a447SGerrit Uitslag            return $this->exportConfig[$name];
653*02f9a447SGerrit Uitslag        }else{
654*02f9a447SGerrit Uitslag            return $notset;
655*02f9a447SGerrit Uitslag        }
656*02f9a447SGerrit Uitslag    }
657ee19bac3SLuigi Micco}
658