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