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