xref: /plugin/dw2pdf/action.php (revision 15923cb9cc4cd6db9135acd7da9f35384df71d73)
1ee19bac3SLuigi Micco<?php
2ee19bac3SLuigi Micco/**
3ee19bac3SLuigi Micco * dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
4ee19bac3SLuigi Micco *
5ee19bac3SLuigi Micco * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6ee19bac3SLuigi Micco * @author     Luigi Micco <l.micco@tiscali.it>
75db42babSAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
8ee19bac3SLuigi Micco */
9ee19bac3SLuigi Micco
10ee19bac3SLuigi Micco// must be run within Dokuwiki
11ee19bac3SLuigi Miccoif(!defined('DOKU_INC')) die();
12ee19bac3SLuigi Micco
130639157eSGerrit Uitslag/**
140639157eSGerrit Uitslag * Class action_plugin_dw2pdf
150639157eSGerrit Uitslag *
160639157eSGerrit Uitslag * Export hmtl content to pdf, for different url parameter configurations
170639157eSGerrit Uitslag * DokuPDF which extends mPDF is used for generating the pdf from html.
180639157eSGerrit Uitslag */
191ef68647SAndreas Gohrclass action_plugin_dw2pdf extends DokuWiki_Action_Plugin {
2002f9a447SGerrit Uitslag    /**
2102f9a447SGerrit Uitslag     * Settings for current export, collected from url param, plugin config, global config
2202f9a447SGerrit Uitslag     *
2302f9a447SGerrit Uitslag     * @var array
2402f9a447SGerrit Uitslag     */
2502f9a447SGerrit 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() {
3302f9a447SGerrit 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;
68*15923cb9SGerrit Uitslag            $title = $INPUT->str('pdftitle');
69*15923cb9SGerrit Uitslag            if(!$title) {
70737417c6SKlap-in                $title = p_get_first_heading($ID);
71*15923cb9SGerrit Uitslag            }
72ad18f4e1SGerrit Uitslag
73ad18f4e1SGerrit Uitslag        } elseif($ACT == 'export_pdfns') {
74ad18f4e1SGerrit Uitslag            //check input for title and ns
7526be4eceSGerrit Uitslag            if(!$title = $INPUT->str('pdfns_title')) {
7626be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
77ad18f4e1SGerrit Uitslag                return false;
78ad18f4e1SGerrit Uitslag            }
7926be4eceSGerrit Uitslag            $pdfnamespace = cleanID($INPUT->str('pdfns_ns'));
80ad18f4e1SGerrit Uitslag            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
8126be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needns');
82ad18f4e1SGerrit Uitslag                return false;
83ad18f4e1SGerrit Uitslag            }
84ad18f4e1SGerrit Uitslag
8526be4eceSGerrit Uitslag            //sort order
86ad18f4e1SGerrit Uitslag            $order = $INPUT->str('pdfns_order', 'natural', true);
87ad18f4e1SGerrit Uitslag            $sortoptions = array('pagename', 'date', 'natural');
88ad18f4e1SGerrit Uitslag            if(!in_array($order, $sortoptions)) {
89ad18f4e1SGerrit Uitslag                $order = 'natural';
90ad18f4e1SGerrit Uitslag            }
91ad18f4e1SGerrit Uitslag
9226be4eceSGerrit Uitslag            //search depth
93ad18f4e1SGerrit Uitslag            $depth = $INPUT->int('pdfns_depth', 0);
94ad18f4e1SGerrit Uitslag            if($depth < 0) {
95ad18f4e1SGerrit Uitslag                $depth = 0;
96ad18f4e1SGerrit Uitslag            }
9726be4eceSGerrit Uitslag
98ad18f4e1SGerrit Uitslag            //page search
99ad18f4e1SGerrit Uitslag            $result = array();
100ad18f4e1SGerrit Uitslag            $opts = array('depth' => $depth); //recursive all levels
101ad18f4e1SGerrit Uitslag            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
102ad18f4e1SGerrit Uitslag            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
103ad18f4e1SGerrit Uitslag
10426be4eceSGerrit Uitslag            //sorting
105ad18f4e1SGerrit Uitslag            if(count($result) > 0) {
106ad18f4e1SGerrit Uitslag                if($order == 'date') {
107ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_datesort'));
108ad18f4e1SGerrit Uitslag                } elseif($order == 'pagename') {
109ad18f4e1SGerrit Uitslag                    usort($result, array($this, '_pagenamesort'));
110ad18f4e1SGerrit Uitslag                }
111ad18f4e1SGerrit Uitslag            }
112ad18f4e1SGerrit Uitslag
113ad18f4e1SGerrit Uitslag            foreach($result as $item) {
11460e59de7SGerrit Uitslag                $this->list[] = $item['id'];
115ad18f4e1SGerrit Uitslag            }
116ad18f4e1SGerrit Uitslag
117737417c6SKlap-in        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
11826be4eceSGerrit Uitslag            //is in Bookmanager of bookcreator plugin a title given?
11926be4eceSGerrit Uitslag            if(!$title = $INPUT->str('pdfbook_title')) { //TODO when title is changed, the cached file contains the old title
12026be4eceSGerrit Uitslag                $this->showPageWithErrorMsg($event, 'needtitle');
121737417c6SKlap-in                return false;
12226be4eceSGerrit Uitslag            } else {
12360e59de7SGerrit Uitslag                $this->list = explode("|", $_COOKIE['list-pagelist']);
12426be4eceSGerrit Uitslag            }
125ad18f4e1SGerrit Uitslag
126737417c6SKlap-in        } else {
12726be4eceSGerrit Uitslag            //show empty bookcreator message
12826be4eceSGerrit Uitslag            $this->showPageWithErrorMsg($event, 'empty');
129737417c6SKlap-in            return false;
130737417c6SKlap-in        }
131737417c6SKlap-in
132737417c6SKlap-in        // it's ours, no one else's
133737417c6SKlap-in        $event->preventDefault();
13487c86ddaSAndreas Gohr
13502f9a447SGerrit Uitslag        //some shortcuts to export settings
13602f9a447SGerrit Uitslag        $hasToC = $this->getExportConfig('hasToC');
13702f9a447SGerrit Uitslag        $levels = $this->getExportConfig('levels');
13802f9a447SGerrit Uitslag        $isDebug = $this->getExportConfig('isDebug');
1396ea88a05SAndreas Gohr
14087c86ddaSAndreas Gohr        // prepare cache
14102f9a447SGerrit Uitslag        $cachekey = join(',', $this->list)
14202f9a447SGerrit Uitslag                    . $REV
14302f9a447SGerrit Uitslag                    . $this->getExportConfig('template')
14402f9a447SGerrit Uitslag                    . $this->getExportConfig('pagesize')
14502f9a447SGerrit Uitslag                    . $this->getExportConfig('orientation')
14602f9a447SGerrit Uitslag                    . ($hasToC ? join('-', $levels) : '0')
14702f9a447SGerrit Uitslag                    . $title;
14802f9a447SGerrit Uitslag        $cache = new cache($cachekey, '.dw2.pdf');
14902f9a447SGerrit Uitslag
15060e59de7SGerrit Uitslag        $depends['files']   = array_map('wikiFN', $this->list);
15187c86ddaSAndreas Gohr        $depends['files'][] = __FILE__;
15287c86ddaSAndreas Gohr        $depends['files'][] = dirname(__FILE__) . '/renderer.php';
15387c86ddaSAndreas Gohr        $depends['files'][] = dirname(__FILE__) . '/mpdf/mpdf.php';
154df59f400SAndreas Gohr        $depends['files']   = array_merge($depends['files'], getConfigFiles('main'));
15587c86ddaSAndreas Gohr
156d01d2a42SAndreas Gohr        // hard work only when no cache available
15787c86ddaSAndreas Gohr        if(!$this->getConf('usecache') || !$cache->useCache($depends)) {
158a2c33768SGerrit Uitslag            // debug enabled?
159a2c33768SGerrit Uitslag
1601ef68647SAndreas Gohr            // initialize PDF library
161cde5a1b3SAndreas Gohr            require_once(dirname(__FILE__) . "/DokuPDF.class.php");
1626ea88a05SAndreas Gohr
16302f9a447SGerrit Uitslag            $mpdf = new DokuPDF($this->getExportConfig('pagesize'), $this->getExportConfig('orientation'));
164ee19bac3SLuigi Micco
165d62df65bSAndreas Gohr            // let mpdf fix local links
166d62df65bSAndreas Gohr            $self = parse_url(DOKU_URL);
167d62df65bSAndreas Gohr            $url = $self['scheme'] . '://' . $self['host'];
16802f9a447SGerrit Uitslag            if($self['port']) {
16902f9a447SGerrit Uitslag                $url .= ':' . $self['port'];
17002f9a447SGerrit Uitslag            }
171d62df65bSAndreas Gohr            $mpdf->setBasePath($url);
172d62df65bSAndreas Gohr
17356d13144SAndreas Gohr            // Set the title
17456d13144SAndreas Gohr            $mpdf->SetTitle($title);
17556d13144SAndreas Gohr
1761ef68647SAndreas Gohr            // some default settings
17702f9a447SGerrit Uitslag            $mpdf->mirrorMargins = 1; //double-sided document, starts at an odd page (first page is a right-hand side page)
17802f9a447SGerrit Uitslag            $mpdf->useOddEven    = 1; //duplicate of mirrorMargins
179daa70883SAndreas Gohr            $mpdf->setAutoTopMargin = 'stretch';
180daa70883SAndreas Gohr            $mpdf->setAutoBottomMargin = 'stretch';
18102f9a447SGerrit Uitslag//            $mpdf->pagenumSuffix = '/'; //prefix for {nbpg}
18202f9a447SGerrit Uitslag            if($hasToC) {
18302f9a447SGerrit Uitslag                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => 'i', 'suppress' => 'off');//use italic pageno until ToC
18402f9a447SGerrit Uitslag                $mpdf->h2toc = $levels;
18502f9a447SGerrit Uitslag            } else {
18602f9a447SGerrit Uitslag                $mpdf->PageNumSubstitutions[] = array('from' => 1, 'reset' => 0, 'type' => '1', 'suppress' => 'off');
18702f9a447SGerrit Uitslag            }
1882eedf77dSAndreas Gohr
18956d13144SAndreas Gohr            // load the template
1901c14c879SAndreas Gohr            $template = $this->load_template($title);
191ee19bac3SLuigi Micco
1921ef68647SAndreas Gohr            // prepare HTML header styles
193a2c33768SGerrit Uitslag            $html = '';
19402f9a447SGerrit Uitslag            if($isDebug) {
195a2c33768SGerrit Uitslag                $html .= '<html><head>';
196737417c6SKlap-in                $html .= '<style type="text/css">';
197a2c33768SGerrit Uitslag            }
198a2c33768SGerrit Uitslag            $styles = $this->load_css();
199a2c33768SGerrit Uitslag            $styles .= '@page { size:auto; ' . $template['page'] . '}';
200a2c33768SGerrit Uitslag            $styles .= '@page :first {' . $template['first'] . '}';
201a2c33768SGerrit Uitslag            $mpdf->WriteHTML($styles, 1);
202a2c33768SGerrit Uitslag
20302f9a447SGerrit Uitslag            if($isDebug) {
204a2c33768SGerrit Uitslag                $html .= $styles;
2051ef68647SAndreas Gohr                $html .= '</style>';
2061ef68647SAndreas Gohr                $html .= '</head><body>';
207a2c33768SGerrit Uitslag            }
208a2c33768SGerrit Uitslag
209a2c33768SGerrit Uitslag            $body_start = $template['html'];
210a2c33768SGerrit Uitslag            $body_start .= '<div class="dokuwiki">';
2112eedf77dSAndreas Gohr
2121e45476bSmnapp            // insert the cover page
213a2c33768SGerrit Uitslag            $body_start .= $template['cover'];
214a2c33768SGerrit Uitslag
215a2c33768SGerrit Uitslag            $mpdf->WriteHTML($body_start, 2, true, false); //start body html
21602f9a447SGerrit Uitslag            if($isDebug) {
217a2c33768SGerrit Uitslag                $html .= $body_start;
218a2c33768SGerrit Uitslag            }
21902f9a447SGerrit Uitslag            if($hasToC) {
22002f9a447SGerrit 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
22102f9a447SGerrit Uitslag                //      - first page of ToC starts always at odd page (so eventually an additional blank page is included before)
22202f9a447SGerrit Uitslag                //      - there is no page numbering at the pages of the ToC
22302f9a447SGerrit Uitslag                $mpdf->TOCpagebreakByArray(
22402f9a447SGerrit Uitslag                    array(
22502f9a447SGerrit Uitslag                        'toc-preHTML' => '<h2>Table of contents</h2>',
22602f9a447SGerrit Uitslag                        'toc-bookmarkText'=> 'Table of Content',
22702f9a447SGerrit Uitslag                        'links' => true,
22802f9a447SGerrit Uitslag                        'outdent' => '1em',
22902f9a447SGerrit Uitslag                        'resetpagenum' => true, //start pagenumbering after ToC
23002f9a447SGerrit Uitslag                        'pagenumstyle' => '1'
23102f9a447SGerrit Uitslag                    )
23202f9a447SGerrit Uitslag                );
23302f9a447SGerrit Uitslag                $html .= '<tocpagebreak>';
23402f9a447SGerrit Uitslag            }
23502f9a447SGerrit Uitslag
236ed9f9952Smnapp
237c00eb13bSGerrit Uitslag            // store original pageid
238c00eb13bSGerrit Uitslag            $keep = $ID;
239c00eb13bSGerrit Uitslag
2401ef68647SAndreas Gohr            // loop over all pages
241a2c33768SGerrit Uitslag            $cnt = count($this->list);
2421ef68647SAndreas Gohr            for($n = 0; $n < $cnt; $n++) {
243a2c33768SGerrit Uitslag                $page = $this->list[$n];
244ee19bac3SLuigi Micco
245c00eb13bSGerrit Uitslag                // set global pageid to the rendered page
246c00eb13bSGerrit Uitslag                $ID   = $page;
247c00eb13bSGerrit Uitslag
248a2c33768SGerrit Uitslag                $pagehtml = p_cached_output(wikiFN($page, $REV), 'dw2pdf', $page);
249a2c33768SGerrit Uitslag                $pagehtml .= $this->page_depend_replacements($template['cite'], cleanID($page));
2501ef68647SAndreas Gohr                if($n < ($cnt - 1)) {
251a2c33768SGerrit Uitslag                    $pagehtml .= '<pagebreak />';
252a2c33768SGerrit Uitslag                }
253a2c33768SGerrit Uitslag
254a2c33768SGerrit Uitslag                $mpdf->WriteHTML($pagehtml, 2, false, false); //intermediate body html
25502f9a447SGerrit Uitslag                if($isDebug) {
256a2c33768SGerrit Uitslag                    $html .= $pagehtml;
2571ef68647SAndreas Gohr                }
258ee19bac3SLuigi Micco            }
259c00eb13bSGerrit Uitslag            //restore ID
260c00eb13bSGerrit Uitslag            $ID = $keep;
261ee19bac3SLuigi Micco
26233c15297SGerrit Uitslag            // insert the back page
263a2c33768SGerrit Uitslag            $body_end = $template['back'];
26433c15297SGerrit Uitslag
265a2c33768SGerrit Uitslag            $body_end .= '</div>';
266a2c33768SGerrit Uitslag
267a2c33768SGerrit Uitslag            $mpdf->WriteHTML($body_end, 2, false, true); // end body html
26802f9a447SGerrit Uitslag            if($isDebug) {
269a2c33768SGerrit Uitslag                $html .= $body_end;
270eeb17e15SAndreas Gohr                $html .= '</body>';
271eeb17e15SAndreas Gohr                $html .= '</html>';
272a2c33768SGerrit Uitslag            }
273f765508eSGerrit Uitslag
274f765508eSGerrit Uitslag            //Return html for debugging
27502f9a447SGerrit Uitslag            if($isDebug) {
27602f9a447SGerrit Uitslag                if($INPUT->str('debughtml', 'text', true) == 'html') {
27726be4eceSGerrit Uitslag                    echo $html;
278a2c33768SGerrit Uitslag                } else {
279a2c33768SGerrit Uitslag                    header('Content-Type: text/plain; charset=utf-8');
280a2c33768SGerrit Uitslag                    echo $html;
281a2c33768SGerrit Uitslag                }
28226be4eceSGerrit Uitslag                exit();
28326be4eceSGerrit Uitslag            };
284f765508eSGerrit Uitslag
28587c86ddaSAndreas Gohr            // write to cache file
28687c86ddaSAndreas Gohr            $mpdf->Output($cache->cache, 'F');
28787c86ddaSAndreas Gohr        }
28887c86ddaSAndreas Gohr
28987c86ddaSAndreas Gohr        // deliver the file
29087c86ddaSAndreas Gohr        header('Content-Type: application/pdf');
291b853b723SAndreas Gohr        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
29287c86ddaSAndreas Gohr        header('Pragma: public');
29387c86ddaSAndreas Gohr        http_conditionalRequest(filemtime($cache->cache));
29487c86ddaSAndreas Gohr
2959a3c8d9fSAndreas Gohr        $filename = rawurlencode(cleanID(strtr($title, ':/;"', '    ')));
29687c86ddaSAndreas Gohr        if($this->getConf('output') == 'file') {
2979a3c8d9fSAndreas Gohr            header('Content-Disposition: attachment; filename="' . $filename . '.pdf";');
29887c86ddaSAndreas Gohr        } else {
2999a3c8d9fSAndreas Gohr            header('Content-Disposition: inline; filename="' . $filename . '.pdf";');
30087c86ddaSAndreas Gohr        }
301ee19bac3SLuigi Micco
302e993da11SGerrit Uitslag        //try to send file, and exit if done
303e993da11SGerrit Uitslag        http_sendfile($cache->cache);
30487c86ddaSAndreas Gohr
30587c86ddaSAndreas Gohr        $fp = @fopen($cache->cache, "rb");
30687c86ddaSAndreas Gohr        if($fp) {
30787c86ddaSAndreas Gohr            http_rangeRequest($fp, filesize($cache->cache), 'application/pdf');
30887c86ddaSAndreas Gohr        } else {
30987c86ddaSAndreas Gohr            header("HTTP/1.0 500 Internal Server Error");
31087c86ddaSAndreas Gohr            print "Could not read file - bad permissions?";
31187c86ddaSAndreas Gohr        }
3121ef68647SAndreas Gohr        exit();
3131ef68647SAndreas Gohr    }
3141ef68647SAndreas Gohr
3156be736bfSGerrit Uitslag    /**
3166be736bfSGerrit Uitslag     * Add 'export pdf'-button to pagetools
3176be736bfSGerrit Uitslag     *
3186be736bfSGerrit Uitslag     * @param Doku_Event $event
3196be736bfSGerrit Uitslag     * @param mixed      $param not defined
3206be736bfSGerrit Uitslag     */
32102f9a447SGerrit Uitslag    public function addbutton(Doku_Event $event, $param) {
3222c53f619SAndreas Gohr        global $ID, $REV;
3236be736bfSGerrit Uitslag
3246be736bfSGerrit Uitslag        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
3256be736bfSGerrit Uitslag            $params = array('do' => 'export_pdf');
32602f9a447SGerrit Uitslag            if($REV) {
32702f9a447SGerrit Uitslag                $params['rev'] = $REV;
32802f9a447SGerrit Uitslag            }
3296be736bfSGerrit Uitslag
3301e02f86cSAndreas Gohr            // insert button at position before last (up to top)
3311e02f86cSAndreas Gohr            $event->data['items'] = array_slice($event->data['items'], 0, -1, true) +
3321e02f86cSAndreas Gohr                                    array('export_pdf' =>
3336be736bfSGerrit Uitslag                                          '<li>'
3346be736bfSGerrit Uitslag                                          . '<a href=' . wl($ID, $params) . '  class="action export_pdf" rel="nofollow" title="' . $this->getLang('export_pdf_button') . '">'
3356be736bfSGerrit Uitslag                                          . '<span>' . $this->getLang('export_pdf_button') . '</span>'
3366be736bfSGerrit Uitslag                                          . '</a>'
3371e02f86cSAndreas Gohr                                          . '</li>'
3381e02f86cSAndreas Gohr                                    ) +
3391e02f86cSAndreas Gohr                                    array_slice($event->data['items'], -1, 1, true);
3406be736bfSGerrit Uitslag        }
3416be736bfSGerrit Uitslag    }
342d01d2a42SAndreas Gohr
343d01d2a42SAndreas Gohr    /**
3442eedf77dSAndreas Gohr     * Load the various template files and prepare the HTML/CSS for insertion
3451ef68647SAndreas Gohr     */
3461c14c879SAndreas Gohr    protected function load_template($title) {
3471ef68647SAndreas Gohr        global $ID;
3481ef68647SAndreas Gohr        global $conf;
3491ef68647SAndreas Gohr
3502eedf77dSAndreas Gohr        // this is what we'll return
3512eedf77dSAndreas Gohr        $output = array(
3521e45476bSmnapp            'cover' => '',
3532eedf77dSAndreas Gohr            'html'  => '',
3542eedf77dSAndreas Gohr            'page'  => '',
3552eedf77dSAndreas Gohr            'first' => '',
3562eedf77dSAndreas Gohr            'cite'  => '',
3572eedf77dSAndreas Gohr        );
3582eedf77dSAndreas Gohr
3592eedf77dSAndreas Gohr        // prepare header/footer elements
3602eedf77dSAndreas Gohr        $html = '';
36133c15297SGerrit Uitslag        foreach(array('header', 'footer') as $section) {
36233c15297SGerrit Uitslag            foreach(array('', '_odd', '_even', '_first') as $order) {
36302f9a447SGerrit Uitslag                $file = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/' . $section . $order . '.html';
36433c15297SGerrit Uitslag                if(file_exists($file)) {
36533c15297SGerrit Uitslag                    $html .= '<htmlpage' . $section . ' name="' . $section . $order . '">' . DOKU_LF;
36633c15297SGerrit Uitslag                    $html .= file_get_contents($file) . DOKU_LF;
36733c15297SGerrit Uitslag                    $html .= '</htmlpage' . $section . '>' . DOKU_LF;
3682eedf77dSAndreas Gohr
3692eedf77dSAndreas Gohr                    // register the needed pseudo CSS
37033c15297SGerrit Uitslag                    if($order == '_first') {
37133c15297SGerrit Uitslag                        $output['first'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
37233c15297SGerrit Uitslag                    } elseif($order == '_even') {
37333c15297SGerrit Uitslag                        $output['page'] .= 'even-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
37433c15297SGerrit Uitslag                    } elseif($order == '_odd') {
37533c15297SGerrit Uitslag                        $output['page'] .= 'odd-' . $section . '-name: html_' . $section . $order . ';' . DOKU_LF;
376daa70883SAndreas Gohr                    } else {
37733c15297SGerrit Uitslag                        $output['page'] .= $section . ': html_' . $section . $order . ';' . DOKU_LF;
3782eedf77dSAndreas Gohr                    }
3792eedf77dSAndreas Gohr                }
3802eedf77dSAndreas Gohr            }
3812eedf77dSAndreas Gohr        }
3822eedf77dSAndreas Gohr
3831ef68647SAndreas Gohr        // prepare replacements
3841ef68647SAndreas Gohr        $replace = array(
3851ef68647SAndreas Gohr            '@PAGE@'    => '{PAGENO}',
38602f9a447SGerrit Uitslag            '@PAGES@'   => '{nbpg}', //see also $mpdf->pagenumSuffix = ' / '
3872eedf77dSAndreas Gohr            '@TITLE@'   => hsc($title),
3881ef68647SAndreas Gohr            '@WIKI@'    => $conf['title'],
3891ef68647SAndreas Gohr            '@WIKIURL@' => DOKU_URL,
3901ef68647SAndreas Gohr            '@DATE@'    => dformat(time()),
3915d6fbaeaSAndreas Gohr            '@BASE@'    => DOKU_BASE,
39202f9a447SGerrit Uitslag            '@TPLBASE@' => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/'
3931ef68647SAndreas Gohr        );
3941ef68647SAndreas Gohr
3952eedf77dSAndreas Gohr        // set HTML element
396a180c973SKlap-in        $html = str_replace(array_keys($replace), array_values($replace), $html);
397a180c973SKlap-in        //TODO For bookcreator $ID (= bookmanager page) makes no sense
398a180c973SKlap-in        $output['html'] = $this->page_depend_replacements($html, $ID);
3991ef68647SAndreas Gohr
4001e45476bSmnapp        // cover page
40102f9a447SGerrit Uitslag        $coverfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/cover.html';
40233c15297SGerrit Uitslag        if(file_exists($coverfile)) {
40333c15297SGerrit Uitslag            $output['cover'] = file_get_contents($coverfile);
4041e45476bSmnapp            $output['cover'] = str_replace(array_keys($replace), array_values($replace), $output['cover']);
4056e2ec302SGerrit Uitslag            $output['cover'] .= '<pagebreak />';
4061e45476bSmnapp        }
4071e45476bSmnapp
40833c15297SGerrit Uitslag        // cover page
40902f9a447SGerrit Uitslag        $backfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/back.html';
41033c15297SGerrit Uitslag        if(file_exists($backfile)) {
41133c15297SGerrit Uitslag            $output['back'] = '<pagebreak />';
41233c15297SGerrit Uitslag            $output['back'] .= file_get_contents($backfile);
41333c15297SGerrit Uitslag            $output['back'] = str_replace(array_keys($replace), array_values($replace), $output['back']);
41433c15297SGerrit Uitslag        }
41533c15297SGerrit Uitslag
4162eedf77dSAndreas Gohr        // citation box
41702f9a447SGerrit Uitslag        $citationfile = DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/citation.html';
41833c15297SGerrit Uitslag        if(file_exists($citationfile)) {
41933c15297SGerrit Uitslag            $output['cite'] = file_get_contents($citationfile);
4202eedf77dSAndreas Gohr            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
4212eedf77dSAndreas Gohr        }
4221ef68647SAndreas Gohr
4232eedf77dSAndreas Gohr        return $output;
4241ef68647SAndreas Gohr    }
4251ef68647SAndreas Gohr
4261ef68647SAndreas Gohr    /**
427a180c973SKlap-in     * @param string $raw code with placeholders
428a180c973SKlap-in     * @param string $id  pageid
429a180c973SKlap-in     * @return string
430a180c973SKlap-in     */
431a180c973SKlap-in    protected function page_depend_replacements($raw, $id) {
432a180c973SKlap-in        global $REV;
433a180c973SKlap-in
434a180c973SKlap-in        // generate qr code for this page using google infographics api
435a180c973SKlap-in        $qr_code = '';
436a180c973SKlap-in        if($this->getConf('qrcodesize')) {
437a180c973SKlap-in            $url = urlencode(wl($id, '', '&', true));
438a180c973SKlap-in            $qr_code = '<img src="https://chart.googleapis.com/chart?chs=' .
439a180c973SKlap-in                $this->getConf('qrcodesize') . '&cht=qr&chl=' . $url . '" />';
440a180c973SKlap-in        }
441a180c973SKlap-in        // prepare replacements
442a180c973SKlap-in        $replace['@ID@']      = $id;
443a180c973SKlap-in        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
444a180c973SKlap-in        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev' => $REV) : false, true, "&");
445a180c973SKlap-in        $replace['@QRCODE@']  = $qr_code;
446a180c973SKlap-in
447a180c973SKlap-in        return str_replace(array_keys($replace), array_values($replace), $raw);
448a180c973SKlap-in    }
449a180c973SKlap-in
450a180c973SKlap-in    /**
4511c14c879SAndreas Gohr     * Load all the style sheets and apply the needed replacements
4521ef68647SAndreas Gohr     */
4531c14c879SAndreas Gohr    protected function load_css() {
454737417c6SKlap-in        global $conf;
4551c14c879SAndreas Gohr        //reusue the CSS dispatcher functions without triggering the main function
4561c14c879SAndreas Gohr        define('SIMPLE_TEST', 1);
4571c14c879SAndreas Gohr        require_once(DOKU_INC . 'lib/exe/css.php');
458ee19bac3SLuigi Micco
4591c14c879SAndreas Gohr        // prepare CSS files
4601c14c879SAndreas Gohr        $files = array_merge(
4611c14c879SAndreas Gohr            array(
4621c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/screen.css'
4631c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
4641c14c879SAndreas Gohr                DOKU_INC . 'lib/styles/print.css'
4651c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/styles/',
4661c14c879SAndreas Gohr            ),
4671c14c879SAndreas Gohr            css_pluginstyles('all'),
46858e6409eSAndreas Gohr            $this->css_pluginPDFstyles(),
4691c14c879SAndreas Gohr            array(
4701c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.css'
4711c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
4721c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/tpl/' . $this->tpl . '/style.css'
4731c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/tpl/' . $this->tpl . '/',
4741c14c879SAndreas Gohr                DOKU_PLUGIN . 'dw2pdf/conf/style.local.css'
4751c14c879SAndreas Gohr                    => DOKU_BASE . 'lib/plugins/dw2pdf/conf/',
4761c14c879SAndreas Gohr            )
4771c14c879SAndreas Gohr        );
4781c14c879SAndreas Gohr        $css = '';
4791c14c879SAndreas Gohr        foreach($files as $file => $location) {
48028e636eaSGerrit Uitslag            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
48128e636eaSGerrit Uitslag            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
4821c14c879SAndreas Gohr            $css .= css_loadfile($file, $location);
4831ef68647SAndreas Gohr        }
4841ef68647SAndreas Gohr
48528e636eaSGerrit Uitslag        if(function_exists('css_parseless')) {
4861c14c879SAndreas Gohr            // apply pattern replacements
48728e636eaSGerrit Uitslag            $styleini = css_styleini($conf['template']);
48828e636eaSGerrit Uitslag            $css = css_applystyle($css, $styleini['replacements']);
48928e636eaSGerrit Uitslag
49028e636eaSGerrit Uitslag            // parse less
49128e636eaSGerrit Uitslag            $css = css_parseless($css);
49228e636eaSGerrit Uitslag        } else {
49328e636eaSGerrit Uitslag            // @deprecated 2013-12-19: fix backward compatibility
4941c14c879SAndreas Gohr            $css = css_applystyle($css, DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
49528e636eaSGerrit Uitslag        }
4961ef68647SAndreas Gohr
4971c14c879SAndreas Gohr        return $css;
498ee19bac3SLuigi Micco    }
4991c14c879SAndreas Gohr
50058e6409eSAndreas Gohr    /**
50158e6409eSAndreas Gohr     * Returns a list of possible Plugin PDF Styles
50258e6409eSAndreas Gohr     *
50358e6409eSAndreas Gohr     * Checks for a pdf.css, falls back to print.css
50458e6409eSAndreas Gohr     *
50558e6409eSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
50658e6409eSAndreas Gohr     */
5076be736bfSGerrit Uitslag    protected function css_pluginPDFstyles() {
50858e6409eSAndreas Gohr        $list = array();
50958e6409eSAndreas Gohr        $plugins = plugin_list();
510f54b51f7SAndreas Gohr
511f54b51f7SAndreas Gohr        $usestyle = explode(',', $this->getConf('usestyles'));
51258e6409eSAndreas Gohr        foreach($plugins as $p) {
513f54b51f7SAndreas Gohr            if(in_array($p, $usestyle)) {
514f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/screen.css"] = DOKU_BASE . "lib/plugins/$p/";
515f54b51f7SAndreas Gohr                $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
516f54b51f7SAndreas Gohr            }
517f54b51f7SAndreas Gohr
51858e6409eSAndreas Gohr            if(file_exists(DOKU_PLUGIN . "$p/pdf.css")) {
51958e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/pdf.css"] = DOKU_BASE . "lib/plugins/$p/";
52058e6409eSAndreas Gohr            } else {
52158e6409eSAndreas Gohr                $list[DOKU_PLUGIN . "$p/print.css"] = DOKU_BASE . "lib/plugins/$p/";
52258e6409eSAndreas Gohr            }
52358e6409eSAndreas Gohr        }
52458e6409eSAndreas Gohr        return $list;
52558e6409eSAndreas Gohr    }
526ad18f4e1SGerrit Uitslag
527ad18f4e1SGerrit Uitslag    /**
52860e59de7SGerrit Uitslag     * Returns array of pages which will be included in the exported pdf
52960e59de7SGerrit Uitslag     *
53060e59de7SGerrit Uitslag     * @return array
53160e59de7SGerrit Uitslag     */
53260e59de7SGerrit Uitslag    public function getExportedPages() {
53360e59de7SGerrit Uitslag        return $this->list;
53460e59de7SGerrit Uitslag    }
53560e59de7SGerrit Uitslag
53660e59de7SGerrit Uitslag    /**
537ad18f4e1SGerrit Uitslag     * usort callback to sort by file lastmodified time
538ad18f4e1SGerrit Uitslag     */
539ad18f4e1SGerrit Uitslag    public function _datesort($a, $b) {
540ad18f4e1SGerrit Uitslag        if($b['rev'] < $a['rev']) return -1;
541ad18f4e1SGerrit Uitslag        if($b['rev'] > $a['rev']) return 1;
542ad18f4e1SGerrit Uitslag        return strcmp($b['id'], $a['id']);
543ad18f4e1SGerrit Uitslag    }
544ad18f4e1SGerrit Uitslag
545ad18f4e1SGerrit Uitslag    /**
546ad18f4e1SGerrit Uitslag     * usort callback to sort by page id
547ad18f4e1SGerrit Uitslag     */
548ad18f4e1SGerrit Uitslag    public function _pagenamesort($a, $b) {
549ad18f4e1SGerrit Uitslag        if($a['id'] <= $b['id']) return -1;
550ad18f4e1SGerrit Uitslag        if($a['id'] > $b['id']) return 1;
551ad18f4e1SGerrit Uitslag        return 0;
552ad18f4e1SGerrit Uitslag    }
55326be4eceSGerrit Uitslag
55426be4eceSGerrit Uitslag    /**
55526be4eceSGerrit Uitslag     * Set error notification and reload page again
55626be4eceSGerrit Uitslag     *
55726be4eceSGerrit Uitslag     * @param Doku_Event $event
55826be4eceSGerrit Uitslag     * @param string     $msglangkey key of translation key
55926be4eceSGerrit Uitslag     */
56026be4eceSGerrit Uitslag    private function showPageWithErrorMsg(&$event, $msglangkey) {
56126be4eceSGerrit Uitslag        msg($this->getLang($msglangkey), -1);
56226be4eceSGerrit Uitslag
56326be4eceSGerrit Uitslag        $event->data = 'show';
56426be4eceSGerrit Uitslag        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
56526be4eceSGerrit Uitslag    }
56602f9a447SGerrit Uitslag
56702f9a447SGerrit Uitslag    /**
56802f9a447SGerrit Uitslag     * Return settings read from:
56902f9a447SGerrit Uitslag     *   1. url parameters
57002f9a447SGerrit Uitslag     *   2. plugin config
57102f9a447SGerrit Uitslag     *   3. global config
57202f9a447SGerrit Uitslag     *
57302f9a447SGerrit Uitslag     * @return array
57402f9a447SGerrit Uitslag     */
57502f9a447SGerrit Uitslag    protected function loadExportConfig() {
57602f9a447SGerrit Uitslag        global $INPUT;
57702f9a447SGerrit Uitslag        global $conf;
57802f9a447SGerrit Uitslag
57902f9a447SGerrit Uitslag        $this->exportConfig = array();
58002f9a447SGerrit Uitslag
58102f9a447SGerrit Uitslag        // decide on the paper setup from param or config
58202f9a447SGerrit Uitslag        $this->exportConfig['pagesize'] = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
58302f9a447SGerrit Uitslag        $this->exportConfig['orientation']  = $INPUT->str('orientation', $this->getConf('orientation'), true);
58402f9a447SGerrit Uitslag
58502f9a447SGerrit Uitslag        $hasToC = $INPUT->bool('toc', (bool) $this->getConf('toc'), true);
58602f9a447SGerrit Uitslag        $levels = array();
58702f9a447SGerrit Uitslag        if($hasToC) {
58802f9a447SGerrit Uitslag            $toclevels = $INPUT->str('toclevels', $this->getConf('toclevels'), true);
58902f9a447SGerrit Uitslag            list($top_input, $max_input) = explode('-', $toclevels, 2);
59002f9a447SGerrit Uitslag            list($top_conf, $max_conf) = explode('-', $this->getConf('toclevels'), 2);
59102f9a447SGerrit Uitslag            $bounds_input = array(
59202f9a447SGerrit Uitslag                'top' => array(
59302f9a447SGerrit Uitslag                    (int) $top_input,
59402f9a447SGerrit Uitslag                    (int) $top_conf
59502f9a447SGerrit Uitslag                ),
59602f9a447SGerrit Uitslag                'max' => array(
59702f9a447SGerrit Uitslag                    (int) $max_input,
59802f9a447SGerrit Uitslag                    (int) $max_conf
59902f9a447SGerrit Uitslag                )
60002f9a447SGerrit Uitslag            );
60102f9a447SGerrit Uitslag            $bounds = array(
60202f9a447SGerrit Uitslag                'top' => $conf['toptoclevel'],
60302f9a447SGerrit Uitslag                'max' => $conf['maxtoclevel']
60402f9a447SGerrit Uitslag
60502f9a447SGerrit Uitslag            );
60602f9a447SGerrit Uitslag            foreach($bounds_input as $bound => $values) {
60702f9a447SGerrit Uitslag                foreach($values as $value) {
60802f9a447SGerrit Uitslag                    if($value > 0 && $value <= 5) {
60902f9a447SGerrit Uitslag                        //stop at valid value and store
61002f9a447SGerrit Uitslag                        $bounds[$bound] = $value;
61102f9a447SGerrit Uitslag                        break;
61202f9a447SGerrit Uitslag                    }
61302f9a447SGerrit Uitslag                }
61402f9a447SGerrit Uitslag            }
61502f9a447SGerrit Uitslag
61602f9a447SGerrit Uitslag            if($bounds['max'] < $bounds['top']) {
61702f9a447SGerrit Uitslag                $bounds['max'] = $bounds['top'];
61802f9a447SGerrit Uitslag            }
61902f9a447SGerrit Uitslag
62002f9a447SGerrit Uitslag            for($level = $bounds['top']; $level <= $bounds['max']; $level++) {
62102f9a447SGerrit Uitslag                $levels["H$level"] = $level - 1;
62202f9a447SGerrit Uitslag            }
62302f9a447SGerrit Uitslag        }
62402f9a447SGerrit Uitslag        $this->exportConfig['hasToC'] = $hasToC;
62502f9a447SGerrit Uitslag        $this->exportConfig['levels'] = $levels;
62602f9a447SGerrit Uitslag
62702f9a447SGerrit Uitslag        $this->exportConfig['maxbookmarks'] = $INPUT->int('maxbookmarks', $this->getConf('maxbookmarks'), true);
62802f9a447SGerrit Uitslag
62902f9a447SGerrit Uitslag        $tplconf = $this->getConf('template');
63002f9a447SGerrit Uitslag        $tpl = $INPUT->str('template', $tplconf, true);
63102f9a447SGerrit Uitslag        if(!is_dir(DOKU_PLUGIN . 'dw2pdf/tpl/' . $tpl)) {
63202f9a447SGerrit Uitslag            $tpl = $tplconf;
63302f9a447SGerrit Uitslag        }
63402f9a447SGerrit Uitslag        if(!$tpl){
63502f9a447SGerrit Uitslag            $tpl = 'default';
63602f9a447SGerrit Uitslag        }
63702f9a447SGerrit Uitslag        $this->exportConfig['template'] = $tpl;
63802f9a447SGerrit Uitslag
63902f9a447SGerrit Uitslag        $this->exportConfig['isDebug'] = $conf['allowdebug'] && $INPUT->has('debughtml');
64002f9a447SGerrit Uitslag    }
64102f9a447SGerrit Uitslag
64202f9a447SGerrit Uitslag    /**
64302f9a447SGerrit Uitslag     * Returns requested config
64402f9a447SGerrit Uitslag     *
64502f9a447SGerrit Uitslag     * @param string $name
64602f9a447SGerrit Uitslag     * @param mixed  $notset
64702f9a447SGerrit Uitslag     * @return mixed|bool
64802f9a447SGerrit Uitslag     */
64902f9a447SGerrit Uitslag    public function getExportConfig($name, $notset = false) {
65002f9a447SGerrit Uitslag        if ($this->exportConfig === null){
65102f9a447SGerrit Uitslag            $this->loadExportConfig();
65202f9a447SGerrit Uitslag        }
65302f9a447SGerrit Uitslag
65402f9a447SGerrit Uitslag        if(isset($this->exportConfig[$name])){
65502f9a447SGerrit Uitslag            return $this->exportConfig[$name];
65602f9a447SGerrit Uitslag        }else{
65702f9a447SGerrit Uitslag            return $notset;
65802f9a447SGerrit Uitslag        }
65902f9a447SGerrit Uitslag    }
660ee19bac3SLuigi Micco}
661