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