xref: /plugin/dw2pdf/action.php (revision 737417c69f280f598d9db0ccda4ef70cdf721e26)
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 .= $template['cite'];
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 $REV;
183        global $conf;
184        $tpl = $this->tpl;
185
186        // this is what we'll return
187        $output = array(
188            'html'  => '',
189            'css'   => '',
190            'page'  => '',
191            'first' => '',
192            'cite'  => '',
193        );
194
195        // prepare header/footer elements
196        $html = '';
197        foreach(array('header','footer') as $t){
198            foreach(array('','_odd','_even','_first') as $h){
199                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
200                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
201                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
202                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
203
204                    // register the needed pseudo CSS
205                    if($h == '_first'){
206                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
207                    }elseif($h == '_even'){
208                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
209                    }elseif($h == '_odd'){
210                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
211                    }else{
212                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
213                    }
214                }
215            }
216        }
217
218        // generate qr code for this page using google infographics api
219        $qr_code = '';
220        if ($this->getConf('qrcodesize')) {
221            $url = urlencode(wl($ID,'','&',true));
222            $qr_code = '<img src="https://chart.googleapis.com/chart?chs='.
223                       $this->getConf('qrcodesize').'&cht=qr&chl='.$url.'" />';
224        }
225
226        // prepare replacements
227        $replace = array(
228                '@ID@'      => $ID,
229                '@PAGE@'    => '{PAGENO}',
230                '@PAGES@'   => '{nb}',
231                '@TITLE@'   => hsc($title),
232                '@WIKI@'    => $conf['title'],
233                '@WIKIURL@' => DOKU_URL,
234                '@UPDATE@'  => dformat(filemtime(wikiFN($ID,$REV))),
235                '@PAGEURL@' => wl($ID,($REV)?array('rev'=>$REV):false, true, "&"),
236                '@DATE@'    => dformat(time()),
237                '@BASE@'    => DOKU_BASE,
238                '@TPLBASE@' => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$tpl.'/',
239                '@QRCODE@'  => $qr_code,
240        );
241
242        // set HTML element
243        $output['html'] = str_replace(array_keys($replace), array_values($replace), $html);
244
245        // citation box
246        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
247            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
248            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
249        }
250
251        // set custom styles
252        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css')){
253            $output['css'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css');
254        }
255
256        return $output;
257    }
258
259    /**
260     * Load all the style sheets and apply the needed replacements
261     */
262    protected function load_css(){
263        global $conf;
264        //reusue the CSS dispatcher functions without triggering the main function
265        define('SIMPLE_TEST',1);
266        require_once(DOKU_INC.'lib/exe/css.php');
267
268        // prepare CSS files
269        $files = array_merge(
270                    array(
271                        DOKU_INC.'lib/styles/screen.css'
272                            => DOKU_BASE.'lib/styles/',
273                        DOKU_INC.'lib/styles/print.css'
274                            => DOKU_BASE.'lib/styles/',
275                    ),
276                    css_pluginstyles('all'),
277                    $this->css_pluginPDFstyles(),
278                    array(
279                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
280                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
281                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
282                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
283                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
284                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
285                    )
286                 );
287        $css = '';
288        foreach($files as $file => $location){
289            $css .= css_loadfile($file, $location);
290        }
291
292        // apply pattern replacements
293        $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
294
295        return $css;
296    }
297
298
299    /**
300     * Returns a list of possible Plugin PDF Styles
301     *
302     * Checks for a pdf.css, falls back to print.css
303     *
304     * @author Andreas Gohr <andi@splitbrain.org>
305     */
306    function css_pluginPDFstyles(){
307        $list = array();
308        $plugins = plugin_list();
309
310        $usestyle = explode(',',$this->getConf('usestyles'));
311        foreach ($plugins as $p){
312            if(in_array($p,$usestyle)){
313                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
314                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
315            }
316
317            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
318                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
319            }else{
320                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
321            }
322        }
323        return $list;
324    }
325
326}
327