xref: /plugin/dw2pdf/action.php (revision d9ff9cfac32cb94f0e8565e03120dc17665c0359)
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;
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    function convert(&$event, $param) {
44        global $ACT;
45        global $REV;
46        global $ID;
47        global $conf;
48
49        // our event?
50        if (( $ACT != 'export_pdfbook' ) && ( $ACT != 'export_pdf' )) return false;
51
52        // check user's rights
53        if ( auth_quickaclcheck($ID) < AUTH_READ ) return false;
54
55        // it's ours, no one else's
56        $event->preventDefault();
57
58        // one or multiple pages?
59        $list = array();
60        if ( $ACT == 'export_pdf' ) {
61            $list[0] = $ID;
62        } elseif (isset($_COOKIE['list-pagelist'])) {
63            $list = explode("|", $_COOKIE['list-pagelist']);
64        }
65
66        // prepare cache
67        $cache = new cache(join(',',$list).$REV.$this->tpl,'.dw2.pdf');
68        $depends['files']   = array_map('wikiFN',$list);
69        $depends['files'][] = __FILE__;
70        $depends['files'][] = dirname(__FILE__).'/renderer.php';
71        $depends['files'][] = dirname(__FILE__).'/mpdf/mpdf.php';
72        $depends['files']   = array_merge($depends['files'], getConfigFiles('main'));
73
74        // hard work only when no cache available
75        if(!$this->getConf('usecache') || !$cache->useCache($depends)){
76            // initialize PDF library
77            require_once(dirname(__FILE__)."/DokuPDF.class.php");
78            $mpdf = new DokuPDF();
79
80            // let mpdf fix local links
81            $self = parse_url(DOKU_URL);
82            $url  = $self['scheme'].'://'.$self['host'];
83            if($self['port']) $url .= ':'.$port;
84            $mpdf->setBasePath($url);
85
86            // Set the title
87            $title = $_GET['pdfbook_title'];
88            if(!$title) $title = p_get_first_heading($ID);
89            $mpdf->SetTitle($title);
90
91            // some default settings
92            $mpdf->mirrorMargins = 1;
93            $mpdf->useOddEven    = 1;
94            $mpdf->setAutoTopMargin = 'stretch';
95            $mpdf->setAutoBottomMargin = 'stretch';
96
97            // load the template
98            $template = $this->load_template($title);
99
100            // prepare HTML header styles
101            $html  = '<html><head>';
102            $html .= '<style>';
103            $html .= $this->load_css();
104            $html .= '@page { size:auto; '.$template['page'].'}';
105            $html .= '@page :first {'.$template['first'].'}';
106            $html .= $template['css'];
107            $html .= '</style>';
108            $html .= '</head><body>';
109            $html .= $template['html'];
110            $html .= '<div class="dokuwiki">';
111
112            // loop over all pages
113            $cnt = count($list);
114            for($n=0; $n<$cnt; $n++){
115                $page = $list[$n];
116
117                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
118                $html .= $template['cite'];
119                if ($n < ($cnt - 1)){
120                    $html .= '<pagebreak />';
121                }
122            }
123
124            $html .= '</div>';
125            $mpdf->WriteHTML($html);
126
127            // write to cache file
128            $mpdf->Output($cache->cache, 'F');
129        }
130
131        // deliver the file
132        header('Content-Type: application/pdf');
133        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
134        header('Pragma: public');
135        http_conditionalRequest(filemtime($cache->cache));
136
137        if($this->getConf('output') == 'file'){
138            header('Content-Disposition: attachment; filename="'.rawurlencode($title).'.pdf";');
139        }else{
140            header('Content-Disposition: inline; filename="'.rawurlencode($title).'.pdf";');
141        }
142
143        if (http_sendfile($cache->cache)) exit;
144
145        $fp = @fopen($cache->cache,"rb");
146        if($fp){
147            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
148        }else{
149            header("HTTP/1.0 500 Internal Server Error");
150            print "Could not read file - bad permissions?";
151        }
152        exit();
153    }
154
155
156    /**
157     * Load the various template files and prepare the HTML/CSS for insertion
158     */
159    protected function load_template($title){
160        global $ID;
161        global $REV;
162        global $conf;
163        $tpl = $this->tpl;
164
165        // this is what we'll return
166        $output = array(
167            'html'  => '',
168            'css'   => '',
169            'page'  => '',
170            'first' => '',
171            'cite'  => '',
172        );
173
174        // prepare header/footer elements
175        $html = '';
176        foreach(array('header','footer') as $t){
177            foreach(array('','_odd','_even','_first') as $h){
178                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
179                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
180                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
181                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
182
183                    // register the needed pseudo CSS
184                    if($h == '_first'){
185                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
186                    }elseif($h == '_even'){
187                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
188                    }elseif($h == '_odd'){
189                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
190                    }else{
191                        $output['page'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
192                    }
193                }
194            }
195        }
196
197        // generate qr code for this page using kaywa.com
198        $protocol = ($_SERVER['HTTPS']) ? 'https://' : 'http://';
199        $url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
200        $url = str_replace("?do=export_pdf", "", $url);
201        $qr_code = '<img src="http://qrcode.kaywa.com/img.php?s=3&d='.$url.'">';
202
203        // prepare replacements
204        $replace = array(
205                '@ID@'      => $ID,
206                '@PAGE@'    => '{PAGENO}',
207                '@PAGES@'   => '{nb}',
208                '@TITLE@'   => hsc($title),
209                '@WIKI@'    => $conf['title'],
210                '@WIKIURL@' => DOKU_URL,
211                '@UPDATE@'  => dformat(filemtime(wikiFN($ID,$REV))),
212                '@PAGEURL@' => wl($ID,($REV)?array('rev'=>$REV):false, true, "&"),
213                '@DATE@'    => dformat(time()),
214                '@BASE@'    => DOKU_BASE,
215                '@TPLBASE@' => DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/',
216                '@QRCODE@'  => $qr_code,
217        );
218
219        // set HTML element
220        $output['html'] = str_replace(array_keys($replace), array_values($replace), $html);
221
222        // citation box
223        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
224            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
225            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
226        }
227
228        // set custom styles
229        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css')){
230            $output['css'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css');
231        }
232
233        return $output;
234    }
235
236    /**
237     * Load all the style sheets and apply the needed replacements
238     */
239    protected function load_css(){
240        //reusue the CSS dispatcher functions without triggering the main function
241        define('SIMPLE_TEST',1);
242        require_once(DOKU_INC.'lib/exe/css.php');
243
244        // prepare CSS files
245        $files = array_merge(
246                    array(
247                        DOKU_INC.'lib/styles/screen.css'
248                            => DOKU_BASE.'lib/styles/',
249                        DOKU_INC.'lib/styles/print.css'
250                            => DOKU_BASE.'lib/styles/',
251                    ),
252                    css_pluginstyles('all'),
253                    $this->css_pluginPDFstyles(),
254                    array(
255                        DOKU_PLUGIN.'dw2pdf/conf/style.css'
256                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
257                        DOKU_PLUGIN.'dw2pdf/tpl/'.$this->tpl.'/style.css'
258                            => DOKU_BASE.'lib/plugins/dw2pdf/tpl/'.$this->tpl.'/',
259                        DOKU_PLUGIN.'dw2pdf/conf/style.local.css'
260                            => DOKU_BASE.'lib/plugins/dw2pdf/conf/',
261                    )
262                 );
263        $css = '';
264        foreach($files as $file => $location){
265            $css .= css_loadfile($file, $location);
266        }
267
268        // apply pattern replacements
269        $css = css_applystyle($css,DOKU_INC.'lib/tpl/'.$conf['template'].'/');
270
271        return $css;
272    }
273
274
275    /**
276     * Returns a list of possible Plugin PDF Styles
277     *
278     * Checks for a pdf.css, falls back to print.css
279     *
280     * @author Andreas Gohr <andi@splitbrain.org>
281     */
282    function css_pluginPDFstyles(){
283        global $lang;
284        $list = array();
285        $plugins = plugin_list();
286
287        $usestyle = explode(',',$this->getConf('usestyles'));
288        foreach ($plugins as $p){
289            if(in_array($p,$usestyle)){
290                $list[DOKU_PLUGIN."$p/screen.css"] = DOKU_BASE."lib/plugins/$p/";
291                $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/";
292            }
293
294            if(file_exists(DOKU_PLUGIN."$p/pdf.css")){
295                $list[DOKU_PLUGIN."$p/pdf.css"] = DOKU_BASE."lib/plugins/$p/";
296            }else{
297                $list[DOKU_PLUGIN."$p/print.css"] = DOKU_BASE."lib/plugins/$p/";
298            }
299        }
300        return $list;
301    }
302
303}
304