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