xref: /plugin/dw2pdf/action.php (revision 2c53f619c72428fd39c97befc9b195dc537fd568)
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            // loop over all pages
177            $cnt = count($list);
178            for($n=0; $n<$cnt; $n++){
179                $page = $list[$n];
180
181                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
182                $html .= $this->page_depend_replacements($template['cite'], cleanID($page));
183                if ($n < ($cnt - 1)){
184                    $html .= '<pagebreak />';
185                }
186            }
187
188            $html .= '</div>';
189
190            //Return html for debugging
191            if($conf['allowdebug'] && $_GET['debughtml'] == 'html') {
192                echo $html;
193                exit();
194            };
195
196            $mpdf->WriteHTML($html);
197
198            // write to cache file
199            $mpdf->Output($cache->cache, 'F');
200        }
201
202        // deliver the file
203        header('Content-Type: application/pdf');
204        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
205        header('Pragma: public');
206        http_conditionalRequest(filemtime($cache->cache));
207
208        $filename = rawurlencode(cleanID(strtr($title, ':/;"','    ')));
209        if($this->getConf('output') == 'file'){
210            header('Content-Disposition: attachment; filename="'.$filename.'.pdf";');
211        }else{
212            header('Content-Disposition: inline; filename="'.$filename.'.pdf";');
213        }
214
215        //try to send file, and exit if done
216        http_sendfile($cache->cache);
217
218        $fp = @fopen($cache->cache,"rb");
219        if($fp){
220            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
221        }else{
222            header("HTTP/1.0 500 Internal Server Error");
223            print "Could not read file - bad permissions?";
224        }
225        exit();
226    }
227
228    /**
229     * Add 'export pdf'-button to pagetools
230     *
231     * @param Doku_Event $event
232     * @param mixed      $param not defined
233     */
234    public function addbutton(&$event, $param) {
235        global $ID, $REV;
236
237        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
238            $params = array('do' => 'export_pdf');
239            if($REV) $params['rev'] = $REV;
240
241            $event->data['items']['export_pdf'] =
242                '<li>'
243                .'<a href='.wl($ID, $params).'  class="action export_pdf" rel="nofollow" title="'.$this->getLang('export_pdf_button').'">'
244                .'<span>'.$this->getLang('export_pdf_button').'</span>'
245                .'</a>'
246                .'</li>';
247        }
248    }
249
250    /**
251     * Load the various template files and prepare the HTML/CSS for insertion
252     */
253    protected function load_template($title){
254        global $ID;
255        global $conf;
256        $tpl = $this->tpl;
257
258        // this is what we'll return
259        $output = array(
260            'html'  => '',
261            'page'  => '',
262            'first' => '',
263            'cite'  => '',
264        );
265
266        // prepare header/footer elements
267        $html = '';
268        foreach(array('header','footer') as $t){
269            foreach(array('','_odd','_even','_first') as $h){
270                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
271                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
272                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
273                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
274
275                    // register the needed pseudo CSS
276                    if($h == '_first'){
277                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
278                    }elseif($h == '_even'){
279                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
280                    }elseif($h == '_odd'){
281                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
282                    }else{
283                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
284                    }
285                }
286            }
287        }
288
289        // prepare replacements
290        $replace = array(
291                '@PAGE@'    => '{PAGENO}',
292                '@PAGES@'   => '{nb}',
293                '@TITLE@'   => hsc($title),
294                '@WIKI@'    => $conf['title'],
295                '@WIKIURL@' => DOKU_URL,
296                '@DATE@'    => dformat(time()),
297                '@BASE@'    => DOKU_BASE,
298                '@TPLBASE@' => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$tpl.'/'
299        );
300
301        // set HTML element
302        $html = str_replace(array_keys($replace), array_values($replace), $html);
303        //TODO For bookcreator $ID (= bookmanager page) makes no sense
304        $output['html'] = $this->page_depend_replacements($html, $ID);
305
306        // citation box
307        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
308            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
309            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
310        }
311
312        return $output;
313    }
314
315    /**
316     * @param string $raw code with placeholders
317     * @param string $id  pageid
318     * @return string
319     */
320    protected function page_depend_replacements($raw, $id){
321        global $REV;
322
323        // generate qr code for this page using google infographics api
324        $qr_code = '';
325        if ($this->getConf('qrcodesize')) {
326            $url = urlencode(wl($id,'','&',true));
327            $qr_code = '<img src="https://chart.googleapis.com/chart?chs='.
328                $this->getConf('qrcodesize').'&cht=qr&chl='.$url.'" />';
329        }
330        // prepare replacements
331        $replace['@ID@']      = $id;
332        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
333        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev'=> $REV) : false, true, "&");
334        $replace['@QRCODE@']  = $qr_code;
335
336        return str_replace(array_keys($replace), array_values($replace), $raw);
337    }
338
339    /**
340     * Load all the style sheets and apply the needed replacements
341     */
342    protected function load_css(){
343        global $conf;
344        //reusue the CSS dispatcher functions without triggering the main function
345        define('SIMPLE_TEST',1);
346        require_once(DOKU_INC.'lib/exe/css.php');
347
348        // prepare CSS files
349        $files = array_merge(
350                    array(
351                        DOKU_INC.'lib/styles/screen.css'
352                            => DOKU_BASE.'lib/styles/',
353                        DOKU_INC.'lib/styles/print.css'
354                            => DOKU_BASE.'lib/styles/',
355                    ),
356                    css_pluginstyles('all'),
357                    $this->css_pluginPDFstyles(),
358                    array(
359                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
360                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
361                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
362                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
363                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
364                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
365                    )
366                 );
367        $css = '';
368        foreach($files as $file => $location){
369            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
370            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
371            $css .= css_loadfile($file, $location);
372        }
373
374        if(function_exists('css_parseless')) {
375            // apply pattern replacements
376            $styleini = css_styleini($conf['template']);
377            $css = css_applystyle($css, $styleini['replacements']);
378
379            // parse less
380            $css = css_parseless($css);
381        } else {
382            // @deprecated 2013-12-19: fix backward compatibility
383            $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
384        }
385
386        return $css;
387    }
388
389    /**
390     * Returns a list of possible Plugin PDF Styles
391     *
392     * Checks for a pdf.css, falls back to print.css
393     *
394     * @author Andreas Gohr <andi@splitbrain.org>
395     */
396    protected function css_pluginPDFstyles(){
397        $list = array();
398        $plugins = plugin_list();
399
400        $usestyle = explode(',',$this->getConf('usestyles'));
401        foreach ($plugins as $p){
402            if(in_array($p,$usestyle)){
403                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
404                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
405            }
406
407            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
408                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
409            }else{
410                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
411            }
412        }
413        return $list;
414    }
415
416    /**
417     * usort callback to sort by file lastmodified time
418     */
419    public function _datesort($a, $b) {
420        if($b['rev'] < $a['rev']) return -1;
421        if($b['rev'] > $a['rev']) return 1;
422        return strcmp($b['id'], $a['id']);
423    }
424
425    /**
426     * usort callback to sort by page id
427     */
428    public function _pagenamesort($a, $b) {
429        if($a['id'] <= $b['id']) return -1;
430        if($a['id'] > $b['id']) return 1;
431        return 0;
432    }
433
434    /**
435     * Set error notification and reload page again
436     *
437     * @param Doku_Event $event
438     * @param string     $msglangkey key of translation key
439     */
440    private function showPageWithErrorMsg(&$event, $msglangkey) {
441        msg($this->getLang($msglangkey), -1);
442
443        $event->data = 'show';
444        $_SERVER['REQUEST_METHOD'] = 'POST'; //clears url
445    }
446}
447