xref: /plugin/siteexport/renderer/pdf.php (revision 0931afc217403094a4f9b7da21ecfc6d779a3186)
1<?php
2/**
3 * Render Plugin for XHTML  without details link for internal images.
4 *
5 * @author     i-net software <tools@inetsoftware.de>
6 * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
7 */
8
9if(!defined('DOKU_INC')) die();
10if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
11
12require_once DOKU_INC . 'inc/parser/xhtml.php';
13
14/**
15 * The Renderer
16 */
17class renderer_plugin_siteexport_pdf extends Doku_Renderer_xhtml {
18
19    var $acronymsExchanged = null;
20    var $hasSeenHeader = false;
21    var $scriptmode = false;
22
23    var $currentLevel = 0;
24    var $startlevel = 0; // level to start with numbered headings (default = 2)
25    var $levels = array( '======'=>1,
26                         '====='=>2,
27                         '===='=>3,
28                         '==='=>4,
29                         '=='=>5);
30
31    var $info = array(
32        'cache'      => true, // may the rendered result cached?
33        'toc'        => true, // render the TOC?
34        'forceTOC'   => false, // shall I force the TOC?
35        'scriptmode' => false, // In scriptmode, some tags will not be encoded => '<%', '%>'
36    );
37
38    var $headingCount =
39    array(  1=>0,
40    2=>0,
41    3=>0,
42    4=>0,
43    5=>0);
44
45    /**
46     * return some info
47     */
48    function getInfo(){
49        if ( method_exists(parent, 'getInfo')) {
50            $info = parent::getInfo();
51        }
52	    return array_merge(is_array($info) ? $info : confToHash(dirname(__FILE__).'/../plugin.info.txt'), array(
53
54        ));
55    }
56
57    function document_start() {
58        global $TOC, $ID, $INFO;
59
60        parent::document_start();
61
62        // Cheating in again
63        $newMeta = p_get_metadata($ID, 'description tableofcontents', false); // 2010-10-23 This should be save to use
64        if ( !empty( $newMeta ) && count($newMeta) > 1 ) {
65            // $TOC = $this->toc = $newMeta; // 2010-08-23 doubled the TOC
66            $TOC = $newMeta;
67        }
68    }
69
70    function document_end() {
71
72        parent::document_end();
73
74        // Prepare the TOC
75        global $TOC, $ID;
76        $meta = array();
77
78        // NOTOC, and no forceTOC
79        if ( $this->info['toc'] === false && !($this->info['forceTOC'] || $this->meta['forceTOC']) ) {
80            $TOC = $this->toc = array();
81            $meta['internal']['toc'] = false;
82            $meta['description']['tableofcontents'] = array();
83            $meta['forceTOC'] = false;
84
85        } else if ( $this->info['forceTOC'] || $this->meta['forceTOC'] || (utf8_strlen(strip_tags($this->doc)) >= $this->getConf('documentlengthfortoc') && count($this->toc) > 1 ) ) {
86            $TOC = $this->toc;
87            // This is a little bit like cheating ... but this will force the TOC into the metadata
88            $meta = array();
89            $meta['internal']['toc'] = true;
90            $meta['forceTOC'] = $this->info['forceTOC'] || $this->meta['forceTOC'];
91            $meta['description']['tableofcontents'] = $TOC;
92        }
93
94        // allways write new metadata
95        p_set_metadata($ID, $meta);
96        $this->doc = preg_replace('#<p( class=".*?")?>\s*</p>#','',$this->doc);
97    }
98
99    function header($text, $level, $pos) {
100        global $conf;
101        global $ID;
102        global $INFO;
103
104        if($text)
105        {
106            $hid = $this->_headerToLink($text,true);
107
108            //only add items within configured levels
109            $this->toc_additem($hid, $text, $level);
110
111            // adjust $node to reflect hierarchy of levels
112            $this->node[$level-1]++;
113            if ($level < $this->lastlevel) {
114                for ($i = 0; $i < $this->lastlevel-$level; $i++) {
115                    $this->node[$this->lastlevel-$i-1] = 0;
116                }
117            }
118            $this->lastlevel = $level;
119
120
121            /* There should be no class for "sectioneditX" if there is no edit perm */
122            if ($INFO['perm'] > AUTH_READ &&
123                $level <= $conf['maxseclevel'] &&
124                count($this->sectionedits) > 0 &&
125                $this->sectionedits[count($this->sectionedits) - 1][2] === 'section') {
126                $this->finishSectionEdit($pos - 1);
127            }
128
129            $headingNumber = '';
130            $useNumbered = p_get_metadata($ID, 'usenumberedheading', true); // 2011-02-07 This should be save to use
131            if ( $this->getConf('usenumberedheading') || !empty($useNumbered) || !empty($INFO['meta']['usenumberedheading']) || isset($_REQUEST['usenumberedheading'])) {
132
133                // increment the number of the heading
134                $this->headingCount[$level]++;
135
136                // build the actual number
137                for ($i=1;$i<=5;$i++) {
138
139                    // reset the number of the subheadings
140                    if ($i>$level) {
141                        $this->headingCount[$i] = 0;
142                    }
143
144                    // build the number of the heading
145                    $headingNumber .= $this->headingCount[$i] . '.';
146                }
147
148                $headingNumber = preg_replace("/(\.0)+\.?$/", '', $headingNumber) . ' ';
149            }
150
151            // write the header
152            $this->doc .= DOKU_LF.'<h'.$level;
153            $class = array();
154            if ($INFO['perm'] > AUTH_READ &&
155                $level <= $conf['maxseclevel']) {
156                $class[] = $this->startSectionEdit($pos, 'section', $text);
157            }
158
159            if ( !empty($headingNumber) ) {
160	            $class[] = 'level' . trim($headingNumber);
161	            if ( intval($headingNumber) > 1 ) {
162		            $class[] = 'notfirst';
163	            } else {
164		            $class[] = 'first';
165	            }
166            }
167
168			if ( !empty($class) ) {
169				$this->doc .= ' class="' . implode(' ', $class) . '"';
170			}
171
172            $this->doc .= '><a name="'.$hid.'" id="'.$hid.'">';
173            $this->doc .= $this->_xmlEntities($headingNumber . $text);
174            $this->doc .= "</a></h$level>".DOKU_LF;
175
176        } else if ( $INFO['perm'] > AUTH_READ ) {
177
178            if ( $hasSeenHeader ) $this->finishSectionEdit($pos);
179
180            // write the header
181            $name = rand() . $level;
182            $this->doc .= DOKU_LF.'<a name="'. $this->startSectionEdit($pos, 'section_empty', $name) .'" class="' . $this->startSectionEdit($pos, 'section_empty', $name) . '" ></a>'.DOKU_LF;
183        }
184
185        $hasSeenHeader = true;
186    }
187
188    function section_open($level) {
189        $this->currentLevel = $level;
190        parent::section_open($level);
191    }
192
193    function p_open() {
194        $this->doc .= DOKU_LF.'<p class="level' . $this->currentLevel . '">'.DOKU_LF;
195    }
196
197    function listu_open() {
198        $this->doc .= '<ul class="level' . $this->currentLevel . '">'.DOKU_LF;
199    }
200
201    function listo_open() {
202        $this->doc .= '<ol class="level' . $this->currentLevel . '">'.DOKU_LF;
203    }
204
205    public function finishSectionEdit($end = null) {
206        global $INFO;
207        if ( $INFO['perm'] > AUTH_READ )
208        {
209            return parent::finishSectionEdit($end);
210        }
211    }
212
213    public function startSectionEdit($start, $type, $title = null) {
214        global $INFO;
215        if ( $INFO['perm'] > AUTH_READ )
216        {
217            return parent::startSectionEdit($start, $type, $title);
218        }
219
220        return "";
221    }
222
223    /**
224     * Wrap centered media in a div to center it
225     */
226    function _media ($src, $title=NULL, $align=NULL, $width=NULL,
227                      $height=NULL, $cache=NULL, $render = true) {
228
229        $out = '';
230        if($align == 'center'){
231            $out .= '<div align="center" style="text-align: center">';
232        }
233
234        $out .= parent::_media ($src, $title, $align, $width, $height, $cache, $render);
235
236        if($align == 'center'){
237            $out .= '</div>';
238        }
239
240        return $out;
241    }
242
243    function internalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
244    $height=NULL, $cache=NULL, $linking=NULL) {
245        global $ID;
246        list($src,$hash) = explode('#',$src,2);
247        resolve_mediaid(getNS($ID),$src, $exists);
248
249        $noLink = false;
250        $render = ($linking == 'linkonly') ? false : true;
251        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
252
253        list($ext,$mime,$dl) = mimetype($src);
254        if(substr($mime,0,5) == 'image' && $render){
255            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
256            if ( substr($mime,0,5) == 'image' && $linking='details' ) { $noLink = true;}
257        }elseif($mime == 'application/x-shockwave-flash' && $render){
258            // don't link flash movies
259            $noLink = true;
260        }else{
261            // add file icons
262            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
263            $link['class'] .= ' mediafile mf_'.$class;
264            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
265        }
266
267        if($hash) $link['url'] .= '#'.$hash;
268
269        //markup non existing files
270        if (!$exists)
271        $link['class'] .= ' wikilink2';
272
273        //output formatted
274        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
275        else $this->doc .= $this->_formatLink($link);
276    }
277
278    /**
279     * Render an internal Wiki Link
280     *
281     * $search,$returnonly & $linktype are not for the renderer but are used
282     * elsewhere - no need to implement them in other renderers
283     *
284     * @author Andreas Gohr <andi@splitbrain.org>
285     */
286    function internallink($id, $name = NULL, $search=NULL,$returnonly=false,$linktype='content') {
287        global $conf;
288        global $ID;
289        // default name is based on $id as given
290        $default = $this->_simpleTitle($id);
291
292        // now first resolve and clean up the $id
293        resolve_pageid(getNS($ID),$id,$exists);
294        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
295        if ( !$isImage ) {
296            if ( $exists ) {
297                $class='wikilink1';
298            } else {
299                $class='wikilink2';
300                $link['rel']='nofollow';
301            }
302        } else {
303            $class='media';
304        }
305
306        //keep hash anchor
307        list($id,$hash) = explode('#',$id,2);
308        if(!empty($hash)) $hash = $this->_headerToLink($hash);
309
310        //prepare for formating
311        $link['target'] = $conf['target']['wiki'];
312        $link['style']  = '';
313        $link['pre']    = '';
314        $link['suf']    = '';
315        // highlight link to current page
316        if ($id == $ID) {
317            $link['pre']    = '<span class="curid">';
318            $link['suf']    = '</span>';
319        }
320        $link['more']   = '';
321        $link['class']  = $class;
322        $link['url']    = wl($id);
323        $link['name']   = $name;
324        $link['title']  = $this->_getLinkTitle(null, $default, $isImage, $id, $linktype);
325
326        //add search string
327        if($search){
328            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
329            if(is_array($search)){
330                $search = array_map('rawurlencode',$search);
331                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
332            }else{
333                $link['url'] .= 's='.rawurlencode($search);
334            }
335        }
336
337        //keep hash
338        if($hash) $link['url'].='#'.$hash;
339
340        //output formatted
341        if($returnonly){
342            return $this->_formatLink($link);
343        }else{
344            $this->doc .= $this->_formatLink($link);
345        }
346    }
347
348    function acronym($acronym) {
349
350        if ( empty($this->acronymsExchanged) ) {
351            $this->acronymsExchanged = $this->acronyms;
352            $this->acronyms = array();
353
354            foreach( $this->acronymsExchanged as $key => $value ) {
355                $this->acronyms[str_replace('_', ' ', $key)] = $value;
356            }
357        }
358
359        parent::acronym($acronym);
360    }
361
362    function _xmlEntities($string) {
363
364        $string = parent::_xmlEntities($string);
365        $string = htmlentities($string, 8, 'UTF-8');
366        $string = $this->superentities($string);
367
368        if ( $this->info['scriptmode'] ) {
369            $string = str_replace(	array( "&lt;%", "%&gt;", "&lt;?", "?&gt;"),
370            array( "<%", "%>", "<?", "?>"),
371            $string);
372        }
373
374        return $string;
375    }
376
377	// Unicode-proof htmlentities.
378	// Returns 'normal' chars as chars and weirdos as numeric html entites.
379	function superentities( $str ){
380	    // get rid of existing entities else double-escape
381	    $str2 = '';
382	    $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
383	    $ar = preg_split('/(?<!^)(?!$)(?!\n)/u', $str );  // return array of every multi-byte character
384	    foreach ($ar as $c){
385	        $o = ord($c);
386	        if ( // (strlen($c) > 1) || /* multi-byte [unicode] */
387	            ($o > 127) // || /* <- control / latin weirdos -> */
388	            // ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
389	            // ($o >33 && $o < 40) ||/* quotes + ambersand */
390	            // ($o >59 && $o < 63) /* html */
391
392	        ) {
393	            // convert to numeric entity
394	            $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
395	        }
396	        $str2 .= $c;
397	    }
398	    return $str2;
399	}
400
401    function preformatted($text) {
402        $this->doc .= '<div class="pre">';
403        parent::preformatted($text);
404        $this->doc .= '</div>';
405    }
406
407    function _highlight($type, $text, $language = null, $filename = null) {
408        $this->doc .= '<div class="pre">';
409        parent::_highlight($type, $text, $language, $filename);
410        $this->doc .= '</div>';
411    }
412
413    /**
414     * API of the imagereference plugin
415     * https://github.com/i-net-software/dokuwiki-plugin-imagereference
416     *
417     * Allows to specify special imagecaption tags that the renderer (mpdf) can use
418     */
419    public function imageCaptionTags(&$imagereferenceplugin)
420    {
421    	if ( !$imagereferenceplugin->accepts('table') ) {
422		    return array( '<figure id="%s" class="imgcaption%s">', // $captionStart
423					      '</figure>',                             // $captionEnd
424						  '<figcaption class="undercaption">',     // $underCaptionStart
425						  '</figcaption>'                          // $underCaptionEnd
426					);
427    	}
428
429    	return null;
430    }
431}
432
433//Setup VIM: ex: et ts=4 enc=utf-8 :