xref: /plugin/dw2pdf/action.php (revision e993da11b118de2786fa3e64461ff6f6ad004ad6)
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        //try to send file, and exit if done
171        http_sendfile($cache->cache);
172
173        $fp = @fopen($cache->cache,"rb");
174        if($fp){
175            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
176        }else{
177            header("HTTP/1.0 500 Internal Server Error");
178            print "Could not read file - bad permissions?";
179        }
180        exit();
181    }
182
183    /**
184     * Add 'export pdf'-button to pagetools
185     *
186     * @param Doku_Event $event
187     * @param mixed      $param not defined
188     */
189    public function addbutton(&$event, $param) {
190        global $ID, $REV, $conf;
191
192        if($this->getConf('showexportbutton') && $event->data['view'] == 'main') {
193            $params = array('do' => 'export_pdf');
194            if($REV) $params['rev'] = $REV;
195
196            switch($conf['template']) {
197                case 'dokuwiki':
198                case 'arago':
199                case 'wikilu': // a private template
200                    $event->data['items']['export_pdf'] =
201                        '<li>'
202                        .'<a href='.wl($ID, $params).'  class="action export_pdf" rel="nofollow" title="'.$this->getLang('export_pdf_button').'">'
203                        .'<span>'.$this->getLang('export_pdf_button').'</span>'
204                        .'</a>'
205                        .'</li>';
206                    break;
207            }
208        }
209    }
210
211    /**
212     * Load the various template files and prepare the HTML/CSS for insertion
213     */
214    protected function load_template($title){
215        global $ID;
216        global $conf;
217        $tpl = $this->tpl;
218
219        // this is what we'll return
220        $output = array(
221            'html'  => '',
222            'page'  => '',
223            'first' => '',
224            'cite'  => '',
225        );
226
227        // prepare header/footer elements
228        $html = '';
229        foreach(array('header','footer') as $t){
230            foreach(array('','_odd','_even','_first') as $h){
231                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
232                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
233                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
234                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
235
236                    // register the needed pseudo CSS
237                    if($h == '_first'){
238                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
239                    }elseif($h == '_even'){
240                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
241                    }elseif($h == '_odd'){
242                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
243                    }else{
244                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
245                    }
246                }
247            }
248        }
249
250        // prepare replacements
251        $replace = array(
252                '@PAGE@'    => '{PAGENO}',
253                '@PAGES@'   => '{nb}',
254                '@TITLE@'   => hsc($title),
255                '@WIKI@'    => $conf['title'],
256                '@WIKIURL@' => DOKU_URL,
257                '@DATE@'    => dformat(time()),
258                '@BASE@'    => DOKU_BASE,
259                '@TPLBASE@' => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$tpl.'/'
260        );
261
262        // set HTML element
263        $html = str_replace(array_keys($replace), array_values($replace), $html);
264        //TODO For bookcreator $ID (= bookmanager page) makes no sense
265        $output['html'] = $this->page_depend_replacements($html, $ID);
266
267        // citation box
268        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
269            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
270            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
271        }
272
273        return $output;
274    }
275
276    /**
277     * @param string $raw code with placeholders
278     * @param string $id  pageid
279     * @return string
280     */
281    protected function page_depend_replacements($raw, $id){
282        global $REV;
283
284        // generate qr code for this page using google infographics api
285        $qr_code = '';
286        if ($this->getConf('qrcodesize')) {
287            $url = urlencode(wl($id,'','&',true));
288            $qr_code = '<img src="https://chart.googleapis.com/chart?chs='.
289                $this->getConf('qrcodesize').'&cht=qr&chl='.$url.'" />';
290        }
291        // prepare replacements
292        $replace['@ID@']      = $id;
293        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
294        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev'=> $REV) : false, true, "&");
295        $replace['@QRCODE@']  = $qr_code;
296
297        return str_replace(array_keys($replace), array_values($replace), $raw);
298    }
299
300    /**
301     * Load all the style sheets and apply the needed replacements
302     */
303    protected function load_css(){
304        global $conf;
305        //reusue the CSS dispatcher functions without triggering the main function
306        define('SIMPLE_TEST',1);
307        require_once(DOKU_INC.'lib/exe/css.php');
308
309        // prepare CSS files
310        $files = array_merge(
311                    array(
312                        DOKU_INC.'lib/styles/screen.css'
313                            => DOKU_BASE.'lib/styles/',
314                        DOKU_INC.'lib/styles/print.css'
315                            => DOKU_BASE.'lib/styles/',
316                    ),
317                    css_pluginstyles('all'),
318                    $this->css_pluginPDFstyles(),
319                    array(
320                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
321                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
322                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
323                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
324                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
325                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
326                    )
327                 );
328        $css = '';
329        foreach($files as $file => $location){
330            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
331            $css .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
332            $css .= css_loadfile($file, $location);
333        }
334
335        if(function_exists('css_parseless')) {
336            // apply pattern replacements
337            $styleini = css_styleini($conf['template']);
338            $css = css_applystyle($css, $styleini['replacements']);
339
340            // parse less
341            $css = css_parseless($css);
342        } else {
343            // @deprecated 2013-12-19: fix backward compatibility
344            $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
345        }
346
347        return $css;
348    }
349
350    /**
351     * Returns a list of possible Plugin PDF Styles
352     *
353     * Checks for a pdf.css, falls back to print.css
354     *
355     * @author Andreas Gohr <andi@splitbrain.org>
356     */
357    protected function css_pluginPDFstyles(){
358        $list = array();
359        $plugins = plugin_list();
360
361        $usestyle = explode(',',$this->getConf('usestyles'));
362        foreach ($plugins as $p){
363            if(in_array($p,$usestyle)){
364                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
365                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
366            }
367
368            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
369                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
370            }else{
371                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
372            }
373        }
374        return $list;
375    }
376}
377