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