xref: /plugin/dw2pdf/action.php (revision 87c86dda39eeb0ddea49546eaa31824c410f1821)
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            $mpdf->defaultheaderfontsize  = 8;  // in pts
68            $mpdf->defaultheaderfontstyle = ''; // blank, B, I, or BI
69            $mpdf->defaultheaderline      = 1;  // 1 to include line below header/above footer
70            $mpdf->defaultfooterfontsize  = 8;  // in pts
71            $mpdf->defaultfooterfontstyle = ''; // blank, B, I, or BI
72            $mpdf->defaultfooterline      = 1;  // 1 to include line below header/above footer
73
74            // prepare HTML header styles
75            $html  = '<html><head>';
76            $html .= '<style>';
77            $html .= file_get_contents(DOKU_INC.'lib/styles/screen.css');
78            $html .= file_get_contents(DOKU_INC.'lib/styles/print.css');
79            $html .= file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.css');
80            $html .= @file_get_contents(DOKU_PLUGIN.'dw2pdf/conf/style.local.css');
81            $html .= '</style>';
82            $html .= '</head><body>';
83
84            // set headers/footers
85            $this->prepare_headers($mpdf);
86
87            // loop over all pages
88            $cnt = count($list);
89            for($n=0; $n<$cnt; $n++){
90                $page = $list[$n];
91
92                $html .= p_cached_output(wikiFN($page,$REV),'dw2pdf',$page);
93                if($this->getConf('addcitation')){
94                    $html .= $this->citation($page);
95                }
96                if ($n < ($cnt - 1)){
97                    $html .= '<pagebreak />';
98                }
99            }
100
101            $this->arrangeHtml($html, $this->getConf("norender"));
102            $mpdf->WriteHTML($html);
103
104            // write to cache file
105            $mpdf->Output($cache->cache, 'F');
106        }
107
108        // deliver the file
109        header('Content-Type: application/pdf');
110        header('Expires: '.gmdate("D, d M Y H:i:s", time()+max($conf['cachetime'], 3600)).' GMT');
111        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
112        header('Pragma: public');
113        http_conditionalRequest(filemtime($cache->cache));
114
115        $title = $_GET['pdfbook_title'];
116        if(!$title) $title = noNS($ID);
117        if($this->getConf('output') == 'file'){
118            header('Content-Disposition: attachment; filename="'.urlencode($title).'.pdf";');
119        }else{
120            header('Content-Disposition: inline; filename="'.urlencode($title).'.pdf";');
121        }
122
123        if (http_sendfile($cache->cache)) exit;
124
125        $fp = @fopen($cache->cache,"rb");
126        if($fp){
127            http_rangeRequest($fp,filesize($cache->cache),'application/pdf');
128        }else{
129            header("HTTP/1.0 500 Internal Server Error");
130            print "Could not read file - bad permissions?";
131        }
132        exit();
133    }
134
135    /**
136     * Setup the page headers and footers
137     */
138    protected function prepare_headers(&$mpdf){
139        global $ID;
140        global $REV;
141        global $conf;
142
143        if($_GET['pdfbook_title']){
144            $title = $_GET['pdfbook_title'];
145        }else{
146            $title = p_get_first_heading($ID);
147        }
148        if(!$title) $title = noNS($ID);
149
150        // prepare replacements
151        $replace = array(
152                '@ID@'      => $ID,
153                '@PAGE@'    => '{PAGENO}',
154                '@PAGES@'   => '{nb}',
155                '@TITLE@'   => $title,
156                '@WIKI@'    => $conf['title'],
157                '@WIKIURL@' => DOKU_URL,
158                '@UPDATE@'  => dformat(filemtime(wikiFN($ID,$REV))),
159                '@PAGEURL@' => wl($ID,($REV)?array('rev'=>$REV):false, true, "&"),
160                '@DATE@'    => dformat(time()),
161        );
162
163        // do the replacements
164        $fo = str_replace(array_keys($replace), array_values($replace), $this->getConf("footer_odd"));
165        $fe = str_replace(array_keys($replace), array_values($replace), $this->getConf("footer_even"));
166        $ho = str_replace(array_keys($replace), array_values($replace), $this->getConf("header_odd"));
167        $he = str_replace(array_keys($replace), array_values($replace), $this->getConf("header_even"));
168
169        // set the headers/footers
170        $mpdf->SetHeader($ho);
171        $mpdf->SetHeader($he, 'E');
172        $mpdf->SetFooter($fo);
173        $mpdf->SetFooter($fe, 'E');
174
175        // title
176        $mpdf->SetTitle($title);
177    }
178
179    /**
180     * Fix up the HTML a bit
181     *
182     * FIXME This is far from perfect and most of it should be moved to
183     * our own renderer instead of modifying the HTML at all.
184     */
185    protected function arrangeHtml(&$html, $norendertags = '' ) {
186
187        // insert a pagebreak for support of WRAP and PAGEBREAK plugins
188        $html = str_replace('<br style="page-break-after:always;">','<pagebreak />',$html);
189        $html = str_replace('<div class="wrap_pagebreak"></div>','<pagebreak />',$html);
190        $html = str_replace('<span class="wrap_pagebreak"></span>','<pagebreak />',$html);
191
192    }
193
194    /**
195     * Create the citation box
196     *
197     * @todo can we drop the inline style here?
198     */
199    protected function citation($page) {
200        global $conf;
201
202        $date = filemtime(wikiFN($page));
203        $html  = '';
204        $html .= "<br><br><div style='font-size: 80%; border: solid 0.5mm #DDDDDD;background-color: #EEEEEE; padding: 2mm; border-radius: 2mm 2mm; width: 100%;'>";
205        $html .= "From:<br>";
206        $html .= "<a href='".DOKU_URL."'>".DOKU_URL."</a>&nbsp;-&nbsp;"."<b>".$conf['title']."</b>";
207        $html .= "<br><br>Permanent link:<br>";
208        $html .= "<b><a href='".wl($page, false, true, "&")."'>".wl($page, false, true, "&")."</a></b>";
209        $html .= "<br><br>Last update: <b>".dformat($date)."</b><br>";
210        $html .= "</div>";
211        return $html;
212    }
213
214    /**
215     * Strip unwanted tags
216     *
217     * @fixme could this be done by strip_tags?
218     * @author Jared Ong
219     */
220    protected function strip_only(&$str, $tags) {
221        if(!is_array($tags)) {
222            $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
223            if(end($tags) == '') array_pop($tags);
224        }
225        foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
226    }
227}
228