xref: /plugin/dw2pdf/action.php (revision ad18f4e1047f87e7d65311de94c571d10022bf2e)
1<?php
2 /**
3  * dw2Pdf Plugin: Conversion from dokuwiki content to pdf.
4  *
5  * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6  * @author     Luigi Micco <l.micco@tiscali.it>
7  * @author     Andreas Gohr <andi@splitbrain.org>
8  */
9
10// must be run within Dokuwiki
11if (!defined('DOKU_INC')) die();
12
13class action_plugin_dw2pdf extends DokuWiki_Action_Plugin {
14
15    private $tpl;
16
17    /**
18     * Constructor. Sets the correct template
19     */
20    public function __construct(){
21        $tpl = false;
22        if(isset($_REQUEST['tpl'])){
23            $tpl = trim(preg_replace('/[^A-Za-z0-9_\-]+/','',$_REQUEST['tpl']));
24        }
25        if(!$tpl) $tpl = $this->getConf('template');
26        if(!$tpl) $tpl = 'default';
27        if(!is_dir(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl)) $tpl = 'default';
28
29        $this->tpl = $tpl;
30    }
31
32    /**
33     * Register the events
34     */
35    public function register(Doku_Event_Handler $controller) {
36        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert', array());
37        $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'addbutton', array());
38    }
39
40    /**
41     * Do the HTML to PDF conversion work
42     *
43     * @param Doku_Event $event
44     * @param array      $param
45     * @return bool
46     */
47    public function convert(&$event, $param) {
48        global $ACT;
49        global $REV;
50        global $ID;
51        global $INPUT, $conf;
52
53        // our event?
54        if (( $ACT != 'export_pdfbook' ) && ( $ACT != 'export_pdf' ) && ( $ACT != 'export_pdfns' )) return false;
55
56        // check user's rights
57        if ( auth_quickaclcheck($ID) < AUTH_READ ) return false;
58
59        // one or multiple pages?
60        $list  = array();
61
62        if($ACT == 'export_pdf') {
63            $list[0] = $ID;
64            $title = p_get_first_heading($ID);
65
66        } elseif($ACT == 'export_pdfns') {
67            //check input for title and ns
68            if(!$title = $INPUT->str('pdfns_title', '')) {
69                $bookcreator = plugin_load('action', 'bookcreator');
70                msg($bookcreator->getLang('needtitle'), -1);
71                $event->data               = 'show';
72                $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
73                return false;
74            }
75
76            $pdfnamespace = cleanID($INPUT->str('pdfns_ns', ''));
77            if(!@is_dir(dirname(wikiFN($pdfnamespace . ':dummy')))) {
78                $bookcreator = plugin_load('action', 'bookcreator');
79                msg($bookcreator->getLang('needtitle').' missing ns', -1);
80                $event->data               = 'show';
81                $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
82                return false;
83            }
84
85            $order = $INPUT->str('pdfns_order', 'natural', true);
86            $sortoptions = array('pagename', 'date', 'natural');
87            if(!in_array($order, $sortoptions)) {
88                $order = 'natural';
89            }
90
91            $depth = $INPUT->int('pdfns_depth', 0);
92            if($depth < 0) {
93                $depth = 0;
94            }
95            //page search
96            $result = array();
97            $opts = array('depth' => $depth); //recursive all levels
98            $dir = utf8_encodeFN(str_replace(':', '/', $pdfnamespace));
99            search($result, $conf['datadir'], 'search_allpages', $opts, $dir);
100
101            //sort
102            if(count($result) > 0) {
103                if($order == 'date') {
104                    usort($result, array($this, '_datesort'));
105                } elseif($order == 'pagename') {
106                    usort($result, array($this, '_pagenamesort'));
107                }
108            }
109
110            foreach($result as $item) {
111                $list[] = $item['id'];
112            }
113
114        } elseif(isset($_COOKIE['list-pagelist']) && !empty($_COOKIE['list-pagelist'])) {
115            //is in Bookmanager of bookcreator plugin title given
116            if(!$title = $_GET['pdfbook_title']) {  //TODO when title is changed, the cached file contains the old title
117                /** @var $bookcreator action_plugin_bookcreator */
118                $bookcreator = plugin_load('action', 'bookcreator');
119                msg($bookcreator->getLang('needtitle'), -1);
120
121                $event->data               = 'show';
122                $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
123                return false;
124            }
125            $list = explode("|", $_COOKIE['list-pagelist']);
126
127        } else {
128            /** @var $bookcreator action_plugin_bookcreator */
129            $bookcreator = plugin_load('action', 'bookcreator');
130            msg($bookcreator->getLang('empty'), -1);
131
132            $event->data               = 'show';
133            $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
134            return false;
135        }
136
137        // it's ours, no one else's
138        $event->preventDefault();
139
140        // decide on the paper setup from param or config
141        $pagesize    = $INPUT->str('pagesize', $this->getConf('pagesize'), true);
142        $orientation = $INPUT->str('orientation', $this->getConf('orientation'), true);
143
144        // prepare cache
145        $cache = new cache(join(',',$list).$REV.$this->tpl.$pagesize.$orientation,'.dw2.pdf');
146        $depends['files']   = array_map('wikiFN',$list);
147        $depends['files'][] = __FILE__;
148        $depends['files'][] = dirname(__FILE__).'/renderer.php';
149        $depends['files'][] = dirname(__FILE__).'/mpdf/mpdf.php';
150        $depends['files']   = array_merge($depends['files'], getConfigFiles('main'));
151
152        // hard work only when no cache available
153        if(!$this->getConf('usecache') || !$cache->useCache($depends)){
154            // initialize PDF library
155            require_once(dirname(__FILE__)."/DokuPDF.class.php");
156
157            $mpdf = new DokuPDF($pagesize, $orientation);
158
159            // let mpdf fix local links
160            $self = parse_url(DOKU_URL);
161            $url  = $self['scheme'].'://'.$self['host'];
162            if($self['port']) $url .= ':'.$self['port'];
163            $mpdf->setBasePath($url);
164
165            // Set the title
166            $mpdf->SetTitle($title);
167
168            // some default settings
169            $mpdf->mirrorMargins = 1;
170            $mpdf->useOddEven    = 1;
171            $mpdf->setAutoTopMargin = 'stretch';
172            $mpdf->setAutoBottomMargin = 'stretch';
173
174            // load the template
175            $template = $this->load_template($title);
176
177            // prepare HTML header styles
178            $html  = '<html><head>';
179            $html .= '<style type="text/css">';
180            $html .= $this->load_css();
181            $html .= '@page { size:auto; '.$template['page'].'}';
182            $html .= '@page :first {'.$template['first'].'}';
183            $html .= '</style>';
184            $html .= '</head><body>';
185            $html .= $template['html'];
186            $html .= '<div class="dokuwiki">';
187
188            // loop over all pages
189            $cnt = count($list);
190            for($n=0; $n<$cnt; $n++){
191                $page = $list[$n];
192
193                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
194                $html .= $this->page_depend_replacements($template['cite'], cleanID($page));
195                if ($n < ($cnt - 1)){
196                    $html .= '<pagebreak />';
197                }
198            }
199
200            $html .= '</div>';
201
202            //Return html for debugging
203            if($_GET['debughtml'] == 'html') die($html);
204
205            $mpdf->WriteHTML($html);
206
207            // write to cache file
208            $mpdf->Output($cache->cache, 'F');
209        }
210
211        // deliver the file
212        header('Content-Type: application/pdf');
213        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
214        header('Pragma: public');
215        http_conditionalRequest(filemtime($cache->cache));
216
217        $filename = rawurlencode(cleanID(strtr($title, ':/;"','    ')));
218        if($this->getConf('output') == 'file'){
219            header('Content-Disposition: attachment; filename="'.$filename.'.pdf";');
220        }else{
221            header('Content-Disposition: inline; filename="'.$filename.'.pdf";');
222        }
223
224        //try to send file, and exit if done
225        http_sendfile($cache->cache);
226
227        $fp = @fopen($cache->cache,"rb");
228        if($fp){
229            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
230        }else{
231            header("HTTP/1.0 500 Internal Server Error");
232            print "Could not read file - bad permissions?";
233        }
234        exit();
235    }
236
237    /**
238     * Add 'export pdf'-button to pagetools
239     *
240     * @param Doku_Event $event
241     * @param mixed      $param not defined
242     */
243    public function addbutton(&$event, $param) {
244        global $ID, $REV, $conf;
245
246        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
247            $params = array('do' => 'export_pdf');
248            if($REV) $params['rev'] = $REV;
249
250            switch($conf['template']) {
251                case 'dokuwiki':
252                case 'arago':
253                case 'wikilu': // a private template
254                    $event->data['items']['export_pdf'] =
255                        '<li>'
256                        .'<a href='.wl($ID, $params).'  class="action export_pdf" rel="nofollow" title="'.$this->getLang('export_pdf_button').'">'
257                        .'<span>'.$this->getLang('export_pdf_button').'</span>'
258                        .'</a>'
259                        .'</li>';
260                    break;
261            }
262        }
263    }
264
265    /**
266     * Load the various template files and prepare the HTML/CSS for insertion
267     */
268    protected function load_template($title){
269        global $ID;
270        global $conf;
271        $tpl = $this->tpl;
272
273        // this is what we'll return
274        $output = array(
275            'html'  => '',
276            'page'  => '',
277            'first' => '',
278            'cite'  => '',
279        );
280
281        // prepare header/footer elements
282        $html = '';
283        foreach(array('header','footer') as $t){
284            foreach(array('','_odd','_even','_first') as $h){
285                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
286                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
287                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
288                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
289
290                    // register the needed pseudo CSS
291                    if($h == '_first'){
292                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
293                    }elseif($h == '_even'){
294                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
295                    }elseif($h == '_odd'){
296                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
297                    }else{
298                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
299                    }
300                }
301            }
302        }
303
304        // prepare replacements
305        $replace = array(
306                '@PAGE@'    => '{PAGENO}',
307                '@PAGES@'   => '{nb}',
308                '@TITLE@'   => hsc($title),
309                '@WIKI@'    => $conf['title'],
310                '@WIKIURL@' => DOKU_URL,
311                '@DATE@'    => dformat(time()),
312                '@BASE@'    => DOKU_BASE,
313                '@TPLBASE@' => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$tpl.'/'
314        );
315
316        // set HTML element
317        $html = str_replace(array_keys($replace), array_values($replace), $html);
318        //TODO For bookcreator $ID (= bookmanager page) makes no sense
319        $output['html'] = $this->page_depend_replacements($html, $ID);
320
321        // citation box
322        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
323            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
324            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
325        }
326
327        return $output;
328    }
329
330    /**
331     * @param string $raw code with placeholders
332     * @param string $id  pageid
333     * @return string
334     */
335    protected function page_depend_replacements($raw, $id){
336        global $REV;
337
338        // generate qr code for this page using google infographics api
339        $qr_code = '';
340        if ($this->getConf('qrcodesize')) {
341            $url = urlencode(wl($id,'','&',true));
342            $qr_code = '<img src="https://chart.googleapis.com/chart?chs='.
343                $this->getConf('qrcodesize').'&cht=qr&chl='.$url.'" />';
344        }
345        // prepare replacements
346        $replace['@ID@']      = $id;
347        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
348        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev'=> $REV) : false, true, "&");
349        $replace['@QRCODE@']  = $qr_code;
350
351        return str_replace(array_keys($replace), array_values($replace), $raw);
352    }
353
354    /**
355     * Load all the style sheets and apply the needed replacements
356     */
357    protected function load_css(){
358        global $conf;
359        //reusue the CSS dispatcher functions without triggering the main function
360        define('SIMPLE_TEST',1);
361        require_once(DOKU_INC.'lib/exe/css.php');
362
363        // prepare CSS files
364        $files = array_merge(
365                    array(
366                        DOKU_INC.'lib/styles/screen.css'
367                            => DOKU_BASE.'lib/styles/',
368                        DOKU_INC.'lib/styles/print.css'
369                            => DOKU_BASE.'lib/styles/',
370                    ),
371                    css_pluginstyles('all'),
372                    $this->css_pluginPDFstyles(),
373                    array(
374                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
375                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
376                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
377                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
378                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
379                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
380                    )
381                 );
382        $css = '';
383        foreach($files as $file => $location){
384            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
385            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
386            $css .= css_loadfile($file, $location);
387        }
388
389        if(function_exists('css_parseless')) {
390            // apply pattern replacements
391            $styleini = css_styleini($conf['template']);
392            $css = css_applystyle($css, $styleini['replacements']);
393
394            // parse less
395            $css = css_parseless($css);
396        } else {
397            // @deprecated 2013-12-19: fix backward compatibility
398            $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
399        }
400
401        return $css;
402    }
403
404    /**
405     * Returns a list of possible Plugin PDF Styles
406     *
407     * Checks for a pdf.css, falls back to print.css
408     *
409     * @author Andreas Gohr <andi@splitbrain.org>
410     */
411    protected function css_pluginPDFstyles(){
412        $list = array();
413        $plugins = plugin_list();
414
415        $usestyle = explode(',',$this->getConf('usestyles'));
416        foreach ($plugins as $p){
417            if(in_array($p,$usestyle)){
418                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
419                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
420            }
421
422            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
423                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
424            }else{
425                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
426            }
427        }
428        return $list;
429    }
430
431    /**
432     * usort callback to sort by file lastmodified time
433     */
434    public function _datesort($a, $b) {
435        if($b['rev'] < $a['rev']) return -1;
436        if($b['rev'] > $a['rev']) return 1;
437        return strcmp($b['id'], $a['id']);
438    }
439
440    /**
441     * usort callback to sort by page id
442     */
443    public function _pagenamesort($a, $b) {
444        if($a['id'] <= $b['id']) return -1;
445        if($a['id'] > $b['id']) return 1;
446        return 0;
447    }
448}
449