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