xref: /plugin/dw2pdf/action.php (revision 2eedf77d5c48e4340135492064543fbb11a53f7a)
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
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            // some default settings
66            $mpdf->mirrorMargins          = 1;  // Use different Odd/Even headers and footers and mirror margins
67            $mdpf->useOddEven = 1;
68/*            $mpdf->defaultheaderfontsize  = 8;  // in pts
69            $mpdf->defaultheaderfontstyle = ''; // blank, B, I, or BI
70            $mpdf->defaultheaderline      = 1;  // 1 to include line below header/above footer
71            $mpdf->defaultfooterfontsize  = 8;  // in pts
72            $mpdf->defaultfooterfontstyle = ''; // blank, B, I, or BI
73            $mpdf->defaultfooterline      = 1;  // 1 to include line below header/above footer
74*/
75
76        // title
77//        $mpdf->SetTitle($title); //FIXME
78
79            $template = $this->load_template('default'); //FIXME
80
81            // prepare HTML header styles
82            $html  = '<html><head>';
83            $html .= '<style>';
84            $html .= file_get_contents(DOKU_INC.'lib/styles/screen.css');
85            $html .= file_get_contents(DOKU_INC.'lib/styles/print.css');
86            $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.css');
87            $html .= @file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.local.css');
88            $html .= '@page {'.$template['page'].'}';
89            $html .= '@page :first {'.$template['first'].'}';
90            $html .= '@page :last {'.$template['last'].'}';
91            $html .= $template['css'];
92            $html .= '</style>';
93            $html .= '</head><body>';
94            $html .= $template['html'];
95
96
97            // set headers/footers
98        //    $this->prepare_headers($mpdf);
99
100            // loop over all pages
101            $cnt = count($list);
102            for($n=0; $n<$cnt; $n++){
103                $page = $list[$n];
104
105                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
106                $html .= $template['cite'];
107                if ($n < ($cnt - 1)){
108                    $html .= '<pagebreak />';
109                }
110            }
111
112            $this->arrangeHtml($html, $this->getConf("norender"));
113            $mpdf->WriteHTML($html);
114
115            // write to cache file
116            $mpdf->Output($cache->cache, 'F');
117        }
118
119        // deliver the file
120        header('Content-Type: application/pdf');
121        header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
122        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
123        header('Pragma: public');
124        http_conditionalRequest(filemtime($cache->cache));
125
126        $title = $_GET['pdfbook_title'];
127        if(!$title) $title = noNS($ID);
128        if($this->getConf('output') == 'file'){
129            header('Content-Disposition: attachment; filename="'.urlencode($title).'.pdf";');
130        }else{
131            header('Content-Disposition: inline; filename="'.urlencode($title).'.pdf";');
132        }
133
134        if (http_sendfile($cache->cache)) exit;
135
136        $fp = @fopen($cache->cache,"rb");
137        if($fp){
138            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
139        }else{
140            header("HTTP/1.0 500 Internal Server Error");
141            print "Could not read file - bad permissions?";
142        }
143        exit();
144    }
145
146    /**
147     * Load the various template files and prepare the HTML/CSS for insertion
148     */
149    protected function load_template($tpl){
150        global $ID;
151        global $REV;
152        global $conf;
153
154        // this is what we'll return
155        $output = array(
156            'html'  => '',
157            'css'   => '',
158            'page'  => '',
159            'first' => '',
160            'last'  => '',
161            'cite'  => '',
162        );
163
164        // prepare header/footer elements
165        $html = '';
166        foreach(array('header','footer') as $t){
167            foreach(array('','_odd','_even','_first','_last') as $h){
168                if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html')){
169                    $html .= '<htmlpage'.$t.' name="'.$t.$h.'">'.DOKU_LF;
170                    $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/'.$t.$h.'.html').DOKU_LF;
171                    $html .= '</htmlpage'.$t.'>'.DOKU_LF;
172
173                    // register the needed pseudo CSS
174                    if($h == '_last'){
175                        $output['last'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
176                    }elseif($h == '_first'){
177                        $output['first'] .= $t.': html_'.$t.$h.';'.DOKU_LF;
178                    }elseif($h == '_even'){
179                        $output['page'] .= 'even-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
180                    }else{
181                        $output['page'] .= 'odd-'.$t.'-name: html_'.$t.$h.';'.DOKU_LF;
182                    }
183                }
184            }
185        }
186
187        // fixme move title to function params
188        if($_GET['pdfbook_title']){
189            $title = $_GET['pdfbook_title'];
190        }else{
191            $title = p_get_first_heading($ID);
192        }
193        if(!$title) $title = noNS($ID);
194
195        // prepare replacements
196        $replace = array(
197                '@ID@'      => $ID,
198                '@PAGE@'    => '{PAGENO}',
199                '@PAGES@'   => '{nb}',
200                '@TITLE@'   => hsc($title),
201                '@WIKI@'    => $conf['title'],
202                '@WIKIURL@' => DOKU_URL,
203                '@UPDATE@'  => dformat(filemtime(wikiFN($ID,$REV))),
204                '@PAGEURL@' => wl($ID,($REV)?array('rev'=>$REV):false, true, "&"),
205                '@DATE@'    => dformat(time()),
206        );
207
208        // set HTML element
209        $output['html'] = str_replace(array_keys($replace), array_values($replace), $html);
210
211        // citation box
212        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html')){
213            $output['cite'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/citation.html');
214            $output['cite'] = str_replace(array_keys($replace), array_values($replace), $output['cite']);
215        }
216
217        // set custom styles
218        if(file_exists(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css')){
219            $output['css'] = file_get_contents(DOKU_PLUGIN.'dw2pdf/tpl/'.$tpl.'/style.css');
220        }
221
222        return $output;
223    }
224
225    /**
226     * Fix up the HTML a bit
227     *
228     * FIXME This is far from perfect and most of it should be moved to
229     * our own renderer instead of modifying the HTML at all.
230     */
231    protected function arrangeHtml(&$html, $norendertags = '' ) {
232
233        // insert a pagebreak for support of WRAP and PAGEBREAK plugins
234        $html = str_replace('<br style="page-break-after:always;">','<pagebreak />',$html);
235        $html = str_replace('<div class="wrap_pagebreak"></div>','<pagebreak />',$html);
236        $html = str_replace('<span class="wrap_pagebreak"></span>','<pagebreak />',$html);
237
238    }
239
240
241    /**
242     * Strip unwanted tags
243     *
244     * @fixme could this be done by strip_tags?
245     * @author Jared Ong
246     */
247    protected function strip_only(&$str, $tags) {
248        if(!is_array($tags)) {
249            $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
250            if(end($tags) == '') array_pop($tags);
251        }
252        foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
253    }
254}
255