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*</\1>#','',$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('useHeadAnchorInsteadOfHeaderID') ) {
163                $matches = [];
164                preg_match("/id=\"(.*?)\"/", $this->doc, $matches);
165                if ( count($matches) > 1 ) {
166                    $this->doc = preg_replace("/id=\".*?\"/", '', $this->doc);
167                    $this->doc = DOKU_LF.'<a id="'. $matches[1] .'" class="head-anchor" style="visibility:hidden"></a>'.DOKU_LF . $this->doc;
168                }
169            }
170
171            if ( $this->getConf('useSectionArticle') ) {
172                $this->doc = $doc . preg_replace("/(<h([1-9]))/", "<".($this->sectionLevel<1?'section':'article')." class=\"level\\2{$class}\">\\1", $this->doc);
173            } else {
174                $this->doc = $doc . $this->doc;
175            }
176
177            $conf['maxseclevel'] = $maxLevel;
178
179        } else if ( $INFO['perm'] > AUTH_READ ) {
180
181            if ( $hasSeenHeader ) $this->finishSectionEdit($pos);
182
183            // write the header
184            $name = $this->startSectionEdit($pos, array( 'target' => 'section_empty', 'name' => rand() . $level));
185            if ( $this->getConf('useSectionArticle') ) {
186                $this->doc .= '<'.($this->sectionLevel<1?'section':'article').' class="'.$name.'">';
187            }
188
189            $this->doc .= DOKU_LF.'<a name="'. $name .'" class="' . $name . '" ></a>'.DOKU_LF;
190        }
191
192        $hasSeenHeader = true;
193    }
194
195    public function finishSectionEdit($end = null, $hid = null) {
196        global $INFO;
197        if ( $INFO['perm'] > AUTH_READ )
198        {
199            return parent::finishSectionEdit($end, $hid);
200        }
201    }
202
203    public function startSectionEdit($start, $data) {
204        global $INFO;
205        if ( $INFO['perm'] > AUTH_READ )
206        {
207            return parent::startSectionEdit($start, $data);
208        }
209
210        return "";
211    }
212
213    function section_close() {
214        $this->sectionLevel--;
215        $this->doc .= DOKU_LF.'</div>'.DOKU_LF;
216        if ( $this->getConf('useSectionArticle') ) {
217            $this->doc .= '</'.($this->sectionLevel<1?'section':'article').'>'.DOKU_LF;
218        }
219    }
220
221    function section_open($level) {
222        $this->sectionLevel++;
223        return parent::section_open($level);
224    }
225
226    function internalmedia ($src, $title=null, $align=null, $width=null,
227                            $height=null, $cache=null, $linking=null, $return=NULL) {
228        global $ID;
229        list($src,$hash) = explode('#',$src,2);
230        resolve_mediaid(getNS($ID),$src, $exists);
231
232        $noLink = false;
233        $render = ($linking == 'linkonly') ? false : true;
234        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
235
236        list($ext,$mime,$dl) = mimetype($src);
237        if(substr($mime,0,5) == 'image' && $render){
238            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
239            if ( substr($mime,0,5) == 'image' && $linking='details' ) { $noLink = true;}
240        }elseif($mime == 'application/x-shockwave-flash' && $render){
241            // don't link flash movies
242            $noLink = true;
243        }else{
244            // add file icons
245            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
246            $link['class'] .= ' mediafile mf_'.$class;
247            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
248        }
249
250        if($hash) $link['url'] .= '#'.$hash;
251
252        //markup non existing files
253        if (!$exists)
254        $link['class'] .= ' wikilink2';
255
256        //output formatted
257        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
258        else $this->doc .= $this->_formatLink($link);
259    }
260
261    /**
262     * Render an internal Wiki Link
263     *
264     * $search,$returnonly & $linktype are not for the renderer but are used
265     * elsewhere - no need to implement them in other renderers
266     *
267     * @author Andreas Gohr <andi@splitbrain.org>
268     */
269    function internallink($id, $name = null, $search=null,$returnonly=false,$linktype='content') {
270        global $conf;
271        global $ID;
272        global $INFO;
273
274        $params = '';
275        $parts = explode('?', $id, 2);
276        if (count($parts) === 2) {
277            $id = $parts[0];
278            $params = $parts[1];
279        }
280
281        // For empty $id we need to know the current $ID
282        // We need this check because _simpleTitle needs
283        // correct $id and resolve_pageid() use cleanID($id)
284        // (some things could be lost)
285        if ($id === '') {
286            $id = $ID;
287        }
288
289        // default name is based on $id as given
290        $default = $this->_simpleTitle($id);
291
292        // now first resolve and clean up the $id
293        resolve_pageid(getNS($ID),$id,$exists);
294
295        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
296        if ( !$isImage ) {
297            if ( $exists ) {
298                $class='wikilink1';
299            } else {
300                $class='wikilink2';
301                $link['rel']='nofollow';
302            }
303        } else {
304            $class='media';
305        }
306
307        //keep hash anchor
308        list($id,$hash) = explode('#',$id,2);
309        if(!empty($hash)) $hash = $this->_headerToLink($hash);
310
311        //prepare for formating
312        $link['target'] = $conf['target']['wiki'];
313        $link['style']  = '';
314        $link['pre']    = '';
315        $link['suf']    = '';
316        // highlight link to current page
317        if ($id == $INFO['id']) {
318            $link['pre']    = '<span class="curid">';
319            $link['suf']    = '</span>';
320        }
321        $link['more']   = '';
322        $link['class']  = $class;
323        $link['url']    = wl($id, $params);
324        $link['name']   = $name;
325        $link['title']  = $this->_getLinkTitle(null, $default, $isImage, $id, $linktype);
326        //add search string
327        if($search){
328            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
329            if(is_array($search)){
330                $search = array_map('rawurlencode',$search);
331                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
332            }else{
333                $link['url'] .= 's='.rawurlencode($search);
334            }
335        }
336
337        //keep hash
338        if($hash) $link['url'].='#'.$hash;
339
340        //output formatted
341        if($returnonly){
342            return $this->_formatLink($link);
343        }else{
344            $this->doc .= $this->_formatLink($link);
345        }
346    }
347
348    function locallink($hash, $name = NULL, $returnonly = false){
349        global $ID;
350        $name  = $this->_getLinkTitle($name, $hash, $isImage);
351        $hash  = $this->_headerToLink($hash);
352        $title = $name;
353        $this->doc .= '<a href="#'.$hash.'" title="'.$title.'" class="wikilink1">';
354        $this->doc .= $name;
355        $this->doc .= '</a>';
356    }
357
358    function acronym($acronym) {
359
360        if ( empty($this->acronymsExchanged) ) {
361            $this->acronymsExchanged = $this->acronyms;
362            $this->acronyms = array();
363
364            foreach( $this->acronymsExchanged as $key => $value ) {
365                $this->acronyms[str_replace('_', ' ', $key)] = $value;
366            }
367        }
368
369        parent::acronym($acronym);
370    }
371
372    function entity($entity) {
373
374        if ( array_key_exists($entity, $this->entities) ) {
375            $entity = $this->entities[$entity];
376        }
377
378        $this->doc .= $this->_xmlEntities($entity);
379    }
380
381    function _xmlEntities($string) {
382
383        // No double encode ...
384        $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8', false);
385        // $string = parent::_xmlEntities($string);
386        $string = htmlentities($string, 8, 'UTF-8');
387        $string = $this->superentities($string);
388
389        if ( $this->info['scriptmode'] ) {
390            $string = str_replace(    array( "&lt;%", "%&gt;", "&lt;?", "?&gt;"),
391            array( "<%", "%>", "<?", "?>"),
392            $string);
393        }
394
395        return $string;
396    }
397
398    // Unicode-proof htmlentities.
399    // Returns 'normal' chars as chars and weirdos as numeric html entites.
400    function superentities( $str ){
401        // get rid of existing entities else double-escape
402        $str2 = '';
403        $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
404        $ar = preg_split('/(?<!^)(?!$)(?!\n)/u', $str );  // return array of every multi-byte character
405        foreach ($ar as $c){
406            $o = ord($c);
407            if ( // (strlen($c) > 1) || /* multi-byte [unicode] */
408                ($o > 127) // || /* <- control / latin weirdos -> */
409                // ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
410                // ($o >33 && $o < 40) ||/* quotes + ambersand */
411                // ($o >59 && $o < 63) /* html */
412
413            ) {
414                // convert to numeric entity
415                $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
416            }
417            $str2 .= $c;
418        }
419        return $str2;
420    }
421
422    /**
423     * Renders internal and external media
424     *
425     * @author Andreas Gohr <andi@splitbrain.org>
426     * @param string $src       media ID
427     * @param string $title     descriptive text
428     * @param string $align     left|center|right
429     * @param int    $width     width of media in pixel
430     * @param int    $height    height of media in pixel
431     * @param string $cache     cache|recache|nocache
432     * @param bool   $render    should the media be embedded inline or just linked
433     * @return string
434     */
435    function _media($src, $title = null, $align = null, $w = null,
436                    $h = null, $cache = null, $render = true) {
437
438        list($ext, $mime) = mimetype($src);
439        if(substr($mime, 0, 5) == 'image') {
440
441            $info = @getimagesize(mediaFN($src)); //get original size
442            $srcset = [];
443
444            if($info !== false) {
445
446	            $origWidth = $info[0];
447	            $origHeight = $info[1];
448
449	            if ( !$w && !$h ) $w = $info[0];
450                if(!$h) $h = round(($w * $info[1]) / $info[0]);
451                if(!$w) $w = round(($h * $info[0]) / $info[1]);
452
453                // There is a two times image
454                if ( 2*2/3*$w <= $origWidth ) { // If the image is at least 1.6 times as large ...
455	                $srcset[] = ml($src, array('w' => 2*$w, 'h' => 2*$h, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src))) . ' 2x';
456                } else {
457
458	                // Check for alternate image
459	                $ext = strrpos($src, '.');
460
461                    foreach ( array( '@2x.', '-2x.', '_2x.') as $extension ) {
462    	                $additionalSrc = substr( $src, 0, $ext) . $extension . substr($src, $ext+1);
463    	                $additionalInfo = @getimagesize(mediaFN($additionalSrc)); //get original size
464    	                if ( $additionalInfo !== false ) {
465                            // Image exists
466                            $srcset[] = ml($additionalSrc, array('w' => 2*$w, 'h' => 2*$h, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($srcSetURL))) . ' 2x';
467                            break;
468    	                }
469                    }
470                }
471
472				$ret = parent::_media($src, $title, $align, $w, $h, $cache, $render);
473                if ( count($srcset) > 0 ) {
474                    return str_replace("/>", ' srcset="' . implode(',', $srcset) . '" />', $ret );
475                } else {
476                    return $ret;
477                }
478            }
479        }
480
481        return parent::_media($src, $title, $align, $w, $h, $cache, $render);
482    }
483}
484
485//Setup VIM: ex: et ts=4 enc=utf-8 :
486