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