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