xref: /plugin/dw2pdf/action.php (revision 4e67f3a2e29c4c7724449ed69c70a1330fb96b8a)
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 .= '</style>';
127            $html .= '</head><body>';
128            $html .= $template['html'];
129            $html .= '<div class="dokuwiki">';
130
131            // loop over all pages
132            $cnt = count($list);
133            for($n=0; $n<$cnt; $n++){
134                $page = $list[$n];
135
136                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
137                $html .= $this->page_depend_replacements($template['cite'], cleanID($page));
138                if ($n < ($cnt - 1)){
139                    $html .= '<pagebreak />';
140                }
141            }
142
143            $html .= '</div>';
144            $mpdf->WriteHTML($html);
145
146            // write to cache file
147            $mpdf->Output($cache->cache, 'F');
148        }
149
150        // deliver the file
151        header('Content-Type: application/pdf');
152        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
153        header('Pragma: public');
154        http_conditionalRequest(filemtime($cache->cache));
155
156        $filename = rawurlencode(cleanID(strtr($title, ':/;"','    ')));
157        if($this->getConf('output') == 'file'){
158            header('Content-Disposition: attachment; filename="'.$filename.'.pdf";');
159        }else{
160            header('Content-Disposition: inline; filename="'.$filename.'.pdf";');
161        }
162
163        if (http_sendfile($cache->cache)) exit;
164
165        $fp = @fopen($cache->cache,"rb");
166        if($fp){
167            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
168        }else{
169            header("HTTP/1.0 500 Internal Server Error");
170            print "Could not read file - bad permissions?";
171        }
172        exit();
173    }
174
175
176    /**
177     * Load the various template files and prepare the HTML/CSS for insertion
178     */
179    protected function load_template($title){
180        global $ID;
181        global $conf;
182        $tpl = $this->tpl;
183
184        // this is what we'll return
185        $output = array(
186            'html'  => '',
187            'page'  => '',
188            'first' => '',
189            'cite'  => '',
190        );
191
192        // prepare header/footer elements
193        $html = '';
194        foreach(array('header','footer') as $t){
195            foreach(array('','_odd','_even','_first') as $h){
196                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
197                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
198                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
199                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
200
201                    // register the needed pseudo CSS
202                    if($h == '_first'){
203                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
204                    }elseif($h == '_even'){
205                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
206                    }elseif($h == '_odd'){
207                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
208                    }else{
209                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
210                    }
211                }
212            }
213        }
214
215        // prepare replacements
216        $replace = array(
217                '@PAGE@'    => '{PAGENO}',
218                '@PAGES@'   => '{nb}',
219                '@TITLE@'   => hsc($title),
220                '@WIKI@'    => $conf['title'],
221                '@WIKIURL@' => DOKU_URL,
222                '@DATE@'    => dformat(time()),
223                '@BASE@'    => DOKU_BASE,
224                '@TPLBASE@' => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$tpl.'/'
225        );
226
227        // set HTML element
228        $html = str_replace(array_keys($replace), array_values($replace), $html);
229        //TODO For bookcreator $ID (= bookmanager page) makes no sense
230        $output['html'] = $this->page_depend_replacements($html, $ID);
231
232        // citation box
233        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
234            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
235            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
236        }
237
238        return $output;
239    }
240
241    /**
242     * @param string $raw code with placeholders
243     * @param string $id  pageid
244     * @return string
245     */
246    protected function page_depend_replacements($raw, $id){
247        global $REV;
248
249        // generate qr code for this page using google infographics api
250        $qr_code = '';
251        if ($this->getConf('qrcodesize')) {
252            $url = urlencode(wl($id,'','&',true));
253            $qr_code = '<img src="https://chart.googleapis.com/chart?chs='.
254                $this->getConf('qrcodesize').'&cht=qr&chl='.$url.'" />';
255        }
256        // prepare replacements
257        $replace['@ID@']      = $id;
258        $replace['@UPDATE@']  = dformat(filemtime(wikiFN($id, $REV)));
259        $replace['@PAGEURL@'] = wl($id, ($REV) ? array('rev'=> $REV) : false, true, "&");
260        $replace['@QRCODE@']  = $qr_code;
261
262        return str_replace(array_keys($replace), array_values($replace), $raw);
263    }
264
265    /**
266     * Load all the style sheets and apply the needed replacements
267     */
268    protected function load_css(){
269        global $conf;
270        //reusue the CSS dispatcher functions without triggering the main function
271        define('SIMPLE_TEST',1);
272        require_once(DOKU_INC.'lib/exe/css.php');
273
274        // prepare CSS files
275        $files = array_merge(
276                    array(
277                        DOKU_INC.'lib/styles/screen.css'
278                            => DOKU_BASE.'lib/styles/',
279                        DOKU_INC.'lib/styles/print.css'
280                            => DOKU_BASE.'lib/styles/',
281                    ),
282                    css_pluginstyles('all'),
283                    $this->css_pluginPDFstyles(),
284                    array(
285                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
286                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
287                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
288                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
289                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
290                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
291                    )
292                 );
293        $css = '';
294        foreach($files as $file => $location){
295            $css .= css_loadfile($file, $location);
296        }
297
298        // apply pattern replacements
299        $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
300
301        return $css;
302    }
303
304
305    /**
306     * Returns a list of possible Plugin PDF Styles
307     *
308     * Checks for a pdf.css, falls back to print.css
309     *
310     * @author Andreas Gohr <andi@splitbrain.org>
311     */
312    function css_pluginPDFstyles(){
313        $list = array();
314        $plugins = plugin_list();
315
316        $usestyle = explode(',',$this->getConf('usestyles'));
317        foreach ($plugins as $p){
318            if(in_array($p,$usestyle)){
319                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
320                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
321            }
322
323            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
324                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
325            }else{
326                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
327            }
328        }
329        return $list;
330    }
331
332}
333