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