xref: /plugin/dw2pdf/action.php (revision eee88cbec18777ef50e5573088770612769d2692)
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    /**
17     * Register the events
18     */
19    function register(&$controller) {
20        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'convert',array());
21    }
22
23    function convert(&$event, $param) {
24        global $ACT;
25        global $REV;
26        global $ID;
27        global $conf;
28
29        // our event?
30        if (( $ACT != 'export_pdfbook' ) && ( $ACT != 'export_pdf' )) return false;
31
32        // check user's rights
33        if ( auth_quickaclcheck($ID) < AUTH_READ ) return false;
34
35        // it's ours, no one else's
36        $event->preventDefault();
37
38        // one or multiple pages?
39        $list = array();
40        if ( $ACT == 'export_pdf' ) {
41            $list[0] = $ID;
42        } elseif (isset($_COOKIE['list-pagelist'])) {
43            $list = explode("|", $_COOKIE['list-pagelist']);
44        }
45
46        $tpl = $this->select_template();
47
48        // prepare cache
49        $cache = new cache(join(',',$list).$REV.$tpl,'.dw2.pdf');
50        $depends['files']   = array_map('wikiFN',$list);
51        $depends['files'][] = __FILE__;
52        $depends['files'][] = dirname(__FILE__).'/renderer.php';
53        $depends['files'][] = dirname(__FILE__).'/mpdf/mpdf.php';
54
55        // hard work only when no cache available
56        if(!$this->getConf('usecache') || !$cache->useCache($depends)){
57            // initialize PDF library
58            require_once(dirname(__FILE__)."/DokuPDF.class.php");
59            $mpdf = new DokuPDF();
60
61            // let mpdf fix local links
62            $self = parse_url(DOKU_URL);
63            $url  = $self['scheme'].'://'.$self['host'];
64            if($self['port']) $url .= ':'.$port;
65            $mpdf->setBasePath($url);
66
67            // Set the title
68            $title = $_GET['pdfbook_title'];
69            if(!$title) $title = p_get_first_heading($ID);
70            $mpdf->SetTitle($title);
71
72            // some default settings
73            $mpdf->mirrorMargins          = 1;  // Use different Odd/Even headers and footers and mirror margins
74            $mdpf->useOddEven = 1;
75
76            // load the template
77            $template = $this->load_template($tpl, $title);
78
79            // prepare HTML header styles
80            $html  = '<html><head>';
81            $html .= '<style>';
82            $html .= file_get_contents(DOKU_INC.'lib/styles/screen.css');
83            $html .= file_get_contents(DOKU_INC.'lib/styles/print.css');
84            $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.css');
85            $html .= @file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.local.css');
86            $html .= '@page {'.$template['page'].'}';
87            $html .= '@page :first {'.$template['first'].'}';
88            $html .= '@page :last {'.$template['last'].'}';
89            $html .= $template['css'];
90            $html .= '</style>';
91            $html .= '</head><body>';
92            $html .= $template['html'];
93
94            // loop over all pages
95            $cnt = count($list);
96            for($n=0; $n<$cnt; $n++){
97                $page = $list[$n];
98
99                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
100                $html .= $template['cite'];
101                if ($n < ($cnt - 1)){
102                    $html .= '<pagebreak />';
103                }
104            }
105
106            $this->arrangeHtml($html, $this->getConf("norender"));
107            $mpdf->WriteHTML($html);
108
109            // write to cache file
110            $mpdf->Output($cache->cache, 'F');
111        }
112
113        // deliver the file
114        header('Content-Type: application/pdf');
115        header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
116        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
117        header('Pragma: public');
118        http_conditionalRequest(filemtime($cache->cache));
119
120        if($this->getConf('output') == 'file'){
121            header('Content-Disposition: attachment; filename="'.rawurlencode($title).'.pdf";');
122        }else{
123            header('Content-Disposition: inline; filename="'.rawurlencode($title).'.pdf";');
124        }
125
126        if (http_sendfile($cache->cache)) exit;
127
128        $fp = @fopen($cache->cache,"rb");
129        if($fp){
130            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
131        }else{
132            header("HTTP/1.0 500 Internal Server Error");
133            print "Could not read file - bad permissions?";
134        }
135        exit();
136    }
137
138    /**
139     * Choose the correct template
140     */
141    protected function select_template(){
142        $tpl;
143        if(isset($_REQUEST['tpl'])){
144            $tpl = trim(preg_replace('/[^A-Za-z0-9_\-]+/','',$_REQUEST['tpl']));
145        }
146        if(!$tpl) $tpl = $this->getConf('template');
147        if(!$tpl) $tpl = 'default';
148        if(!is_dir(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl)) $tpl = 'default';
149
150        return $tpl;
151    }
152
153    /**
154     * Load the various template files and prepare the HTML/CSS for insertion
155     */
156    protected function load_template($tpl, $title){
157        global $ID;
158        global $REV;
159        global $conf;
160
161        // this is what we'll return
162        $output = array(
163            'html'  => '',
164            'css'   => '',
165            'page'  => '',
166            'first' => '',
167            'last'  => '',
168            'cite'  => '',
169        );
170
171        // prepare header/footer elements
172        $html = '';
173        foreach(array('header','footer') as $t){
174            foreach(array('','_odd','_even','_first','_last') as $h){
175                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
176                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
177                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
178                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
179
180                    // register the needed pseudo CSS
181                    if($h == '_last'){
182                        $output['last'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
183                    }elseif($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                    }else{
188                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
189                    }
190                }
191            }
192        }
193
194        // prepare replacements
195        $replace = array(
196                '@ID@'      => $ID,
197                '@PAGE@'    => '{PAGENO}',
198                '@PAGES@'   => '{nb}',
199                '@TITLE@'   => hsc($title),
200                '@WIKI@'    => $conf['title'],
201                '@WIKIURL@' => DOKU_URL,
202                '@UPDATE@'  => dformat(filemtime(wikiFN($ID,$REV))),
203                '@PAGEURL@' => wl($ID,($REV)?array('rev'=>$REV):false, true, "&"),
204                '@DATE@'    => dformat(time()),
205                '@BASE@'    => DOKU_BASE,
206                '@TPLBASE@' => DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/',
207        );
208
209        // set HTML element
210        $output['html'] = str_replace(array_keys($replace), array_values($replace), $html);
211
212        // citation box
213        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
214            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
215            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
216        }
217
218        // set custom styles
219        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css')){
220            $output['css'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css');
221        }
222
223        return $output;
224    }
225
226    /**
227     * Fix up the HTML a bit
228     *
229     * FIXME This is far from perfect and most of it should be moved to
230     * our own renderer instead of modifying the HTML at all.
231     */
232    protected function arrangeHtml(&$html, $norendertags = '' ) {
233
234        // insert a pagebreak for support of WRAP and PAGEBREAK plugins
235        $html = str_replace('<br style="page-break-after:always;">','<pagebreak />',$html);
236        $html = str_replace('<div class="wrap_pagebreak"></div>','<pagebreak />',$html);
237        $html = str_replace('<span class="wrap_pagebreak"></span>','<pagebreak />',$html);
238
239    }
240
241
242    /**
243     * Strip unwanted tags
244     *
245     * @fixme could this be done by strip_tags?
246     * @author Jared Ong
247     */
248    protected function strip_only(&$str, $tags) {
249        if(!is_array($tags)) {
250            $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
251            if(end($tags) == '') array_pop($tags);
252        }
253        foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
254    }
255}
256