xref: /plugin/dw2pdf/action.php (revision d01d2a42f471f41a1abd059f5addf0b91a3daaa2)
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        // prepare cache
47        $cache = new cache(join(',',$list).$REV,'.dw2.pdf');
48        $depends['files']   = array_map('wikiFN',$list);
49        $depends['files'][] = __FILE__;
50        $depends['files'][] = dirname(__FILE__).'/renderer.php';
51        $depends['files'][] = dirname(__FILE__).'/mpdf/mpdf.php';
52
53        // hard work only when no cache available
54        if(!$this->getConf('usecache') || !$cache->useCache($depends)){
55            // initialize PDF library
56            require_once(dirname(__FILE__)."/DokuPDF.class.php");
57            $mpdf = new DokuPDF();
58
59            // let mpdf fix local links
60            $self = parse_url(DOKU_URL);
61            $url  = $self['scheme'].'://'.$self['host'];
62            if($self['port']) $url .= ':'.$port;
63            $mpdf->setBasePath($url);
64
65            // Set the title
66            $title = $_GET['pdfbook_title'];
67            if(!$title) $title = p_get_first_heading($ID);
68            $mpdf->SetTitle($title);
69
70            // some default settings
71            $mpdf->mirrorMargins          = 1;  // Use different Odd/Even headers and footers and mirror margins
72            $mdpf->useOddEven = 1;
73
74            // load the template
75            $template = $this->load_template($title); //FIXME
76
77            // prepare HTML header styles
78            $html  = '<html><head>';
79            $html .= '<style>';
80            $html .= file_get_contents(DOKU_INC.'lib/styles/screen.css');
81            $html .= file_get_contents(DOKU_INC.'lib/styles/print.css');
82            $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.css');
83            $html .= @file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.local.css');
84            $html .= '@page {'.$template['page'].'}';
85            $html .= '@page :first {'.$template['first'].'}';
86            $html .= '@page :last {'.$template['last'].'}';
87            $html .= $template['css'];
88            $html .= '</style>';
89            $html .= '</head><body>';
90            $html .= $template['html'];
91
92            // loop over all pages
93            $cnt = count($list);
94            for($n=0; $n<$cnt; $n++){
95                $page = $list[$n];
96
97                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
98                $html .= $template['cite'];
99                if ($n < ($cnt - 1)){
100                    $html .= '<pagebreak />';
101                }
102            }
103
104            $this->arrangeHtml($html, $this->getConf("norender"));
105            $mpdf->WriteHTML($html);
106
107            // write to cache file
108            $mpdf->Output($cache->cache, 'F');
109        }
110
111        // deliver the file
112        header('Content-Type: application/pdf');
113        header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
114        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
115        header('Pragma: public');
116        http_conditionalRequest(filemtime($cache->cache));
117
118        if($this->getConf('output') == 'file'){
119            header('Content-Disposition: attachment; filename="'.rawurlencode($title).'.pdf";');
120        }else{
121            header('Content-Disposition: inline; filename="'.rawurlencode($title).'.pdf";');
122        }
123
124        if (http_sendfile($cache->cache)) exit;
125
126        $fp = @fopen($cache->cache,"rb");
127        if($fp){
128            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
129        }else{
130            header("HTTP/1.0 500 Internal Server Error");
131            print "Could not read file - bad permissions?";
132        }
133        exit();
134    }
135
136    /**
137     * Choose the correct template
138     */
139    protected function select_template(){
140        $tpl;
141        if(isset($_REQUEST['tpl'])){
142            $tpl = trim(preg_replace('/[^A-Za-z0-9_\-]+/','',$_REQUEST['tpl']));
143        }
144        if(!$tpl) $tpl = $this->getConf('template');
145        if(!$tpl) $tpl = 'default';
146        if(!is_dir(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl)) $tpl = 'default';
147
148        return $tpl;
149    }
150
151    /**
152     * Load the various template files and prepare the HTML/CSS for insertion
153     */
154    protected function load_template($title){
155        global $ID;
156        global $REV;
157        global $conf;
158
159        $tpl = $this->select_template();
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        );
206
207        // set HTML element
208        $output['html'] = str_replace(array_keys($replace), array_values($replace), $html);
209
210        // citation box
211        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
212            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
213            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
214        }
215
216        // set custom styles
217        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css')){
218            $output['css'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css');
219        }
220
221        return $output;
222    }
223
224    /**
225     * Fix up the HTML a bit
226     *
227     * FIXME This is far from perfect and most of it should be moved to
228     * our own renderer instead of modifying the HTML at all.
229     */
230    protected function arrangeHtml(&$html, $norendertags = '' ) {
231
232        // insert a pagebreak for support of WRAP and PAGEBREAK plugins
233        $html = str_replace('<br style="page-break-after:always;">','<pagebreak />',$html);
234        $html = str_replace('<div class="wrap_pagebreak"></div>','<pagebreak />',$html);
235        $html = str_replace('<span class="wrap_pagebreak"></span>','<pagebreak />',$html);
236
237    }
238
239
240    /**
241     * Strip unwanted tags
242     *
243     * @fixme could this be done by strip_tags?
244     * @author Jared Ong
245     */
246    protected function strip_only(&$str, $tags) {
247        if(!is_array($tags)) {
248            $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
249            if(end($tags) == '') array_pop($tags);
250        }
251        foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
252    }
253}
254