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