xref: /dokuwiki/inc/parser/xhtml.php (revision 6198904b0be1a338f774922e09c4b0d5050d853e)
1<?php
2/**
3 * Renderer for XHTML output
4 *
5 * @author Harry Fuecks <hfuecks@gmail.com>
6 * @author Andreas Gohr <andi@splitbrain.org>
7 */
8if(!defined('DOKU_INC')) die('meh.');
9
10if ( !defined('DOKU_LF') ) {
11    // Some whitespace to help View > Source
12    define ('DOKU_LF',"\n");
13}
14
15if ( !defined('DOKU_TAB') ) {
16    // Some whitespace to help View > Source
17    define ('DOKU_TAB',"\t");
18}
19
20require_once DOKU_INC . 'inc/parser/renderer.php';
21require_once DOKU_INC . 'inc/html.php';
22
23/**
24 * The Renderer
25 */
26class Doku_Renderer_xhtml extends Doku_Renderer {
27
28    // @access public
29    var $doc = '';        // will contain the whole document
30    var $toc = array();   // will contain the Table of Contents
31
32    var $sectionedits = array(); // A stack of section edit data
33    private $lastsecid = 0; // last section edit id, used by startSectionEdit
34
35    var $headers = array();
36    /** @var array a list of footnotes, list starts at 1! */
37    var $footnotes = array();
38    var $lastlevel = 0;
39    var $node = array(0,0,0,0,0);
40    var $store = '';
41
42    var $_counter   = array(); // used as global counter, introduced for table classes
43    var $_codeblock = 0; // counts the code and file blocks, used to provide download links
44
45    /**
46     * Register a new edit section range
47     *
48     * @param $type  string The section type identifier
49     * @param $title string The section title
50     * @param $start int    The byte position for the edit start
51     * @return string A marker class for the starting HTML element
52     * @author Adrian Lang <lang@cosmocode.de>
53     */
54    public function startSectionEdit($start, $type, $title = null) {
55        $this->sectionedits[] = array(++$this->lastsecid, $start, $type, $title);
56        return 'sectionedit' . $this->lastsecid;
57    }
58
59    /**
60     * Finish an edit section range
61     *
62     * @param $end int The byte position for the edit end; null for the rest of
63     *                 the page
64     * @author Adrian Lang <lang@cosmocode.de>
65     */
66    public function finishSectionEdit($end = null) {
67        list($id, $start, $type, $title) = array_pop($this->sectionedits);
68        if (!is_null($end) && $end <= $start) {
69            return;
70        }
71        $this->doc .= "<!-- EDIT$id " . strtoupper($type) . ' ';
72        if (!is_null($title)) {
73            $this->doc .= '"' . str_replace('"', '', $title) . '" ';
74        }
75        $this->doc .= "[$start-" . (is_null($end) ? '' : $end) . '] -->';
76    }
77
78    function getFormat(){
79        return 'xhtml';
80    }
81
82
83    function document_start() {
84        //reset some internals
85        $this->toc     = array();
86        $this->headers = array();
87    }
88
89    function document_end() {
90        // Finish open section edits.
91        while (count($this->sectionedits) > 0) {
92            if ($this->sectionedits[count($this->sectionedits) - 1][1] <= 1) {
93                // If there is only one section, do not write a section edit
94                // marker.
95                array_pop($this->sectionedits);
96            } else {
97                $this->finishSectionEdit();
98            }
99        }
100
101        if ( count ($this->footnotes) > 0 ) {
102            $this->doc .= '<div class="footnotes">'.DOKU_LF;
103
104            foreach ( $this->footnotes as $id => $footnote ) {
105                // check its not a placeholder that indicates actual footnote text is elsewhere
106                if (substr($footnote, 0, 5) != "@@FNT") {
107
108                    // open the footnote and set the anchor and backlink
109                    $this->doc .= '<div class="fn">';
110                    $this->doc .= '<sup><a href="#fnt__'.$id.'" id="fn__'.$id.'" class="fn_bot">';
111                    $this->doc .= $id.')</a></sup> '.DOKU_LF;
112
113                    // get any other footnotes that use the same markup
114                    $alt = array_keys($this->footnotes, "@@FNT$id");
115
116                    if (count($alt)) {
117                        foreach ($alt as $ref) {
118                            // set anchor and backlink for the other footnotes
119                            $this->doc .= ', <sup><a href="#fnt__'.($ref).'" id="fn__'.($ref).'" class="fn_bot">';
120                            $this->doc .= ($ref).')</a></sup> '.DOKU_LF;
121                        }
122                    }
123
124                    // add footnote markup and close this footnote
125                    $this->doc .= $footnote;
126                    $this->doc .= '</div>' . DOKU_LF;
127                }
128            }
129            $this->doc .= '</div>'.DOKU_LF;
130        }
131
132        // Prepare the TOC
133        global $conf;
134        if($this->info['toc'] && is_array($this->toc) && $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads']){
135            global $TOC;
136            $TOC = $this->toc;
137        }
138
139        // make sure there are no empty paragraphs
140        $this->doc = preg_replace('#<p>\s*</p>#','',$this->doc);
141    }
142
143    function toc_additem($id, $text, $level) {
144        global $conf;
145
146        //handle TOC
147        if($level >= $conf['toptoclevel'] && $level <= $conf['maxtoclevel']){
148            $this->toc[] = html_mktocitem($id, $text, $level-$conf['toptoclevel']+1);
149        }
150    }
151
152    function header($text, $level, $pos) {
153        global $conf;
154
155        if(!$text) return; //skip empty headlines
156
157        $hid = $this->_headerToLink($text,true);
158
159        //only add items within configured levels
160        $this->toc_additem($hid, $text, $level);
161
162        // adjust $node to reflect hierarchy of levels
163        $this->node[$level-1]++;
164        if ($level < $this->lastlevel) {
165            for ($i = 0; $i < $this->lastlevel-$level; $i++) {
166                $this->node[$this->lastlevel-$i-1] = 0;
167            }
168        }
169        $this->lastlevel = $level;
170
171        if ($level <= $conf['maxseclevel'] &&
172            count($this->sectionedits) > 0 &&
173            $this->sectionedits[count($this->sectionedits) - 1][2] === 'section') {
174            $this->finishSectionEdit($pos - 1);
175        }
176
177        // write the header
178        $this->doc .= DOKU_LF.'<h'.$level;
179        if ($level <= $conf['maxseclevel']) {
180            $this->doc .= ' class="' . $this->startSectionEdit($pos, 'section', $text) . '"';
181        }
182        $this->doc .= ' id="'.$hid.'">';
183        $this->doc .= $this->_xmlEntities($text);
184        $this->doc .= "</h$level>".DOKU_LF;
185    }
186
187    function section_open($level) {
188        $this->doc .= '<div class="level' . $level . '">' . DOKU_LF;
189    }
190
191    function section_close() {
192        $this->doc .= DOKU_LF.'</div>'.DOKU_LF;
193    }
194
195    function cdata($text) {
196        $this->doc .= $this->_xmlEntities($text);
197    }
198
199    function p_open() {
200        $this->doc .= DOKU_LF.'<p>'.DOKU_LF;
201    }
202
203    function p_close() {
204        $this->doc .= DOKU_LF.'</p>'.DOKU_LF;
205    }
206
207    function linebreak() {
208        $this->doc .= '<br/>'.DOKU_LF;
209    }
210
211    function hr() {
212        $this->doc .= '<hr />'.DOKU_LF;
213    }
214
215    function strong_open() {
216        $this->doc .= '<strong>';
217    }
218
219    function strong_close() {
220        $this->doc .= '</strong>';
221    }
222
223    function emphasis_open() {
224        $this->doc .= '<em>';
225    }
226
227    function emphasis_close() {
228        $this->doc .= '</em>';
229    }
230
231    function underline_open() {
232        $this->doc .= '<em class="u">';
233    }
234
235    function underline_close() {
236        $this->doc .= '</em>';
237    }
238
239    function monospace_open() {
240        $this->doc .= '<code>';
241    }
242
243    function monospace_close() {
244        $this->doc .= '</code>';
245    }
246
247    function subscript_open() {
248        $this->doc .= '<sub>';
249    }
250
251    function subscript_close() {
252        $this->doc .= '</sub>';
253    }
254
255    function superscript_open() {
256        $this->doc .= '<sup>';
257    }
258
259    function superscript_close() {
260        $this->doc .= '</sup>';
261    }
262
263    function deleted_open() {
264        $this->doc .= '<del>';
265    }
266
267    function deleted_close() {
268        $this->doc .= '</del>';
269    }
270
271    /**
272     * Callback for footnote start syntax
273     *
274     * All following content will go to the footnote instead of
275     * the document. To achieve this the previous rendered content
276     * is moved to $store and $doc is cleared
277     *
278     * @author Andreas Gohr <andi@splitbrain.org>
279     */
280    function footnote_open() {
281
282        // move current content to store and record footnote
283        $this->store = $this->doc;
284        $this->doc   = '';
285    }
286
287    /**
288     * Callback for footnote end syntax
289     *
290     * All rendered content is moved to the $footnotes array and the old
291     * content is restored from $store again
292     *
293     * @author Andreas Gohr
294     */
295    function footnote_close() {
296        /** @var $fnid int takes track of seen footnotes, assures they are unique even across multiple docs FS#2841 */
297        static $fnid = 0;
298        // assign new footnote id (we start at 1)
299        $fnid++;
300
301        // recover footnote into the stack and restore old content
302        $footnote = $this->doc;
303        $this->doc = $this->store;
304        $this->store = '';
305
306        // check to see if this footnote has been seen before
307        $i = array_search($footnote, $this->footnotes);
308
309        if ($i === false) {
310            // its a new footnote, add it to the $footnotes array
311            $this->footnotes[$fnid] = $footnote;
312        } else {
313            // seen this one before, save a placeholder
314            $this->footnotes[$fnid] = "@@FNT".($i);
315        }
316
317        // output the footnote reference and link
318        $this->doc .= '<sup><a href="#fn__'.$fnid.'" id="fnt__'.$fnid.'" class="fn_top">'.$fnid.')</a></sup>';
319    }
320
321    function listu_open() {
322        $this->doc .= '<ul>'.DOKU_LF;
323    }
324
325    function listu_close() {
326        $this->doc .= '</ul>'.DOKU_LF;
327    }
328
329    function listo_open() {
330        $this->doc .= '<ol>'.DOKU_LF;
331    }
332
333    function listo_close() {
334        $this->doc .= '</ol>'.DOKU_LF;
335    }
336
337    function listitem_open($level) {
338        $this->doc .= '<li class="level'.$level.'">';
339    }
340
341    function listitem_close() {
342        $this->doc .= '</li>'.DOKU_LF;
343    }
344
345    function listcontent_open() {
346        $this->doc .= '<div class="li">';
347    }
348
349    function listcontent_close() {
350        $this->doc .= '</div>'.DOKU_LF;
351    }
352
353    function unformatted($text) {
354        $this->doc .= $this->_xmlEntities($text);
355    }
356
357    /**
358     * Execute PHP code if allowed
359     *
360     * @param  string   $text      PHP code that is either executed or printed
361     * @param  string   $wrapper   html element to wrap result if $conf['phpok'] is okff
362     *
363     * @author Andreas Gohr <andi@splitbrain.org>
364     */
365    function php($text, $wrapper='code') {
366        global $conf;
367
368        if($conf['phpok']){
369            ob_start();
370            eval($text);
371            $this->doc .= ob_get_contents();
372            ob_end_clean();
373        } else {
374            $this->doc .= p_xhtml_cached_geshi($text, 'php', $wrapper);
375        }
376    }
377
378    function phpblock($text) {
379        $this->php($text, 'pre');
380    }
381
382    /**
383     * Insert HTML if allowed
384     *
385     * @param  string   $text      html text
386     * @param  string   $wrapper   html element to wrap result if $conf['htmlok'] is okff
387     *
388     * @author Andreas Gohr <andi@splitbrain.org>
389     */
390    function html($text, $wrapper='code') {
391        global $conf;
392
393        if($conf['htmlok']){
394            $this->doc .= $text;
395        } else {
396            $this->doc .= p_xhtml_cached_geshi($text, 'html4strict', $wrapper);
397        }
398    }
399
400    function htmlblock($text) {
401        $this->html($text, 'pre');
402    }
403
404    function quote_open() {
405        $this->doc .= '<blockquote><div class="no">'.DOKU_LF;
406    }
407
408    function quote_close() {
409        $this->doc .= '</div></blockquote>'.DOKU_LF;
410    }
411
412    function preformatted($text) {
413        $this->doc .= '<pre class="code">' . trim($this->_xmlEntities($text),"\n\r") . '</pre>'. DOKU_LF;
414    }
415
416    function file($text, $language=null, $filename=null) {
417        $this->_highlight('file',$text,$language,$filename);
418    }
419
420    function code($text, $language=null, $filename=null) {
421        $this->_highlight('code',$text,$language,$filename);
422    }
423
424    /**
425     * Use GeSHi to highlight language syntax in code and file blocks
426     *
427     * @author Andreas Gohr <andi@splitbrain.org>
428     */
429    function _highlight($type, $text, $language=null, $filename=null) {
430        global $conf;
431        global $ID;
432        global $lang;
433
434        if($filename){
435            // add icon
436            list($ext) = mimetype($filename,false);
437            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
438            $class = 'mediafile mf_'.$class;
439
440            $this->doc .= '<dl class="'.$type.'">'.DOKU_LF;
441            $this->doc .= '<dt><a href="'.exportlink($ID,'code',array('codeblock'=>$this->_codeblock)).'" title="'.$lang['download'].'" class="'.$class.'">';
442            $this->doc .= hsc($filename);
443            $this->doc .= '</a></dt>'.DOKU_LF.'<dd>';
444        }
445
446        if ($text{0} == "\n") {
447            $text = substr($text, 1);
448        }
449        if (substr($text, -1) == "\n") {
450            $text = substr($text, 0, -1);
451        }
452
453        if ( is_null($language) ) {
454            $this->doc .= '<pre class="'.$type.'">'.$this->_xmlEntities($text).'</pre>'.DOKU_LF;
455        } else {
456            $class = 'code'; //we always need the code class to make the syntax highlighting apply
457            if($type != 'code') $class .= ' '.$type;
458
459            $this->doc .= "<pre class=\"$class $language\">".p_xhtml_cached_geshi($text, $language, '').'</pre>'.DOKU_LF;
460        }
461
462        if($filename){
463            $this->doc .= '</dd></dl>'.DOKU_LF;
464        }
465
466        $this->_codeblock++;
467    }
468
469    function acronym($acronym) {
470
471        if ( array_key_exists($acronym, $this->acronyms) ) {
472
473            $title = $this->_xmlEntities($this->acronyms[$acronym]);
474
475            $this->doc .= '<abbr title="'.$title
476                .'">'.$this->_xmlEntities($acronym).'</abbr>';
477
478        } else {
479            $this->doc .= $this->_xmlEntities($acronym);
480        }
481    }
482
483    function smiley($smiley) {
484        if ( array_key_exists($smiley, $this->smileys) ) {
485            $title = $this->_xmlEntities($this->smileys[$smiley]);
486            $this->doc .= '<img src="'.DOKU_BASE.'lib/images/smileys/'.$this->smileys[$smiley].
487                '" class="icon" alt="'.
488                    $this->_xmlEntities($smiley).'" />';
489        } else {
490            $this->doc .= $this->_xmlEntities($smiley);
491        }
492    }
493
494    /*
495    * not used
496    function wordblock($word) {
497        if ( array_key_exists($word, $this->badwords) ) {
498            $this->doc .= '** BLEEP **';
499        } else {
500            $this->doc .= $this->_xmlEntities($word);
501        }
502    }
503    */
504
505    function entity($entity) {
506        if ( array_key_exists($entity, $this->entities) ) {
507            $this->doc .= $this->entities[$entity];
508        } else {
509            $this->doc .= $this->_xmlEntities($entity);
510        }
511    }
512
513    function multiplyentity($x, $y) {
514        $this->doc .= "$x&times;$y";
515    }
516
517    function singlequoteopening() {
518        global $lang;
519        $this->doc .= $lang['singlequoteopening'];
520    }
521
522    function singlequoteclosing() {
523        global $lang;
524        $this->doc .= $lang['singlequoteclosing'];
525    }
526
527    function apostrophe() {
528        global $lang;
529        $this->doc .= $lang['apostrophe'];
530    }
531
532    function doublequoteopening() {
533        global $lang;
534        $this->doc .= $lang['doublequoteopening'];
535    }
536
537    function doublequoteclosing() {
538        global $lang;
539        $this->doc .= $lang['doublequoteclosing'];
540    }
541
542    /**
543     */
544    function camelcaselink($link) {
545        $this->internallink($link,$link);
546    }
547
548
549    function locallink($hash, $name = null){
550        global $ID;
551        $name  = $this->_getLinkTitle($name, $hash, $isImage);
552        $hash  = $this->_headerToLink($hash);
553        $title = $ID.' ↵';
554        $this->doc .= '<a href="#'.$hash.'" title="'.$title.'" class="wikilink1">';
555        $this->doc .= $name;
556        $this->doc .= '</a>';
557    }
558
559    /**
560     * Render an internal Wiki Link
561     *
562     * $search,$returnonly & $linktype are not for the renderer but are used
563     * elsewhere - no need to implement them in other renderers
564     *
565     * @author Andreas Gohr <andi@splitbrain.org>
566     */
567    function internallink($id, $name = null, $search=null,$returnonly=false,$linktype='content') {
568        global $conf;
569        global $ID;
570        global $INFO;
571
572        $params = '';
573        $parts = explode('?', $id, 2);
574        if (count($parts) === 2) {
575            $id = $parts[0];
576            $params = $parts[1];
577        }
578
579        // For empty $id we need to know the current $ID
580        // We need this check because _simpleTitle needs
581        // correct $id and resolve_pageid() use cleanID($id)
582        // (some things could be lost)
583        if ($id === '') {
584            $id = $ID;
585        }
586
587        // default name is based on $id as given
588        $default = $this->_simpleTitle($id);
589
590        // now first resolve and clean up the $id
591        resolve_pageid(getNS($ID),$id,$exists);
592
593        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
594        if ( !$isImage ) {
595            if ( $exists ) {
596                $class='wikilink1';
597            } else {
598                $class='wikilink2';
599                $link['rel']='nofollow';
600            }
601        } else {
602            $class='media';
603        }
604
605        //keep hash anchor
606        list($id,$hash) = explode('#',$id,2);
607        if(!empty($hash)) $hash = $this->_headerToLink($hash);
608
609        //prepare for formating
610        $link['target'] = $conf['target']['wiki'];
611        $link['style']  = '';
612        $link['pre']    = '';
613        $link['suf']    = '';
614        // highlight link to current page
615        if ($id == $INFO['id']) {
616            $link['pre']    = '<span class="curid">';
617            $link['suf']    = '</span>';
618        }
619        $link['more']   = '';
620        $link['class']  = $class;
621        $link['url']    = wl($id, $params);
622        $link['name']   = $name;
623        $link['title']  = $id;
624        //add search string
625        if($search){
626            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
627            if(is_array($search)){
628                $search = array_map('rawurlencode',$search);
629                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
630            }else{
631                $link['url'] .= 's='.rawurlencode($search);
632            }
633        }
634
635        //keep hash
636        if($hash) $link['url'].='#'.$hash;
637
638        //output formatted
639        if($returnonly){
640            return $this->_formatLink($link);
641        }else{
642            $this->doc .= $this->_formatLink($link);
643        }
644    }
645
646    function externallink($url, $name = null) {
647        global $conf;
648
649        $name = $this->_getLinkTitle($name, $url, $isImage);
650
651        // url might be an attack vector, only allow registered protocols
652        if(is_null($this->schemes)) $this->schemes = getSchemes();
653        list($scheme) = explode('://',$url);
654        $scheme = strtolower($scheme);
655        if(!in_array($scheme,$this->schemes)) $url = '';
656
657        // is there still an URL?
658        if(!$url){
659            $this->doc .= $name;
660            return;
661        }
662
663        // set class
664        if ( !$isImage ) {
665            $class='urlextern';
666        } else {
667            $class='media';
668        }
669
670        //prepare for formating
671        $link['target'] = $conf['target']['extern'];
672        $link['style']  = '';
673        $link['pre']    = '';
674        $link['suf']    = '';
675        $link['more']   = '';
676        $link['class']  = $class;
677        $link['url']    = $url;
678
679        $link['name']   = $name;
680        $link['title']  = $this->_xmlEntities($url);
681        if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"';
682
683        //output formatted
684        $this->doc .= $this->_formatLink($link);
685    }
686
687    /**
688     */
689    function interwikilink($match, $name = null, $wikiName, $wikiUri) {
690        global $conf;
691
692        $link = array();
693        $link['target'] = $conf['target']['interwiki'];
694        $link['pre']    = '';
695        $link['suf']    = '';
696        $link['more']   = '';
697        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
698
699        //get interwiki URL
700        $exists = null;
701        $url = $this->_resolveInterWiki($wikiName, $wikiUri, $exists);
702
703        if(!$isImage) {
704            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $wikiName);
705            $link['class'] = "interwiki iw_$class";
706        } else {
707            $link['class'] = 'media';
708        }
709
710        //do we stay at the same server? Use local target
711        if(strpos($url, DOKU_URL) === 0 OR strpos($url, DOKU_BASE) === 0) {
712            $link['target'] = $conf['target']['wiki'];
713        }
714        if($exists !== null && !$isImage) {
715            if($exists) {
716                $link['class'] .= ' wikilink1';
717            } else {
718                $link['class'] .= ' wikilink2';
719                $link['rel'] = 'nofollow';
720            }
721        }
722
723        $link['url'] = $url;
724        $link['title'] = htmlspecialchars($link['url']);
725
726        //output formatted
727        $this->doc .= $this->_formatLink($link);
728    }
729
730    /**
731     */
732    function windowssharelink($url, $name = null) {
733        global $conf;
734        global $lang;
735        //simple setup
736        $link['target'] = $conf['target']['windows'];
737        $link['pre']    = '';
738        $link['suf']   = '';
739        $link['style']  = '';
740
741        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
742        if ( !$isImage ) {
743            $link['class'] = 'windows';
744        } else {
745            $link['class'] = 'media';
746        }
747
748        $link['title'] = $this->_xmlEntities($url);
749        $url = str_replace('\\','/',$url);
750        $url = 'file:///'.$url;
751        $link['url'] = $url;
752
753        //output formatted
754        $this->doc .= $this->_formatLink($link);
755    }
756
757    function emaillink($address, $name = null) {
758        global $conf;
759        //simple setup
760        $link = array();
761        $link['target'] = '';
762        $link['pre']    = '';
763        $link['suf']   = '';
764        $link['style']  = '';
765        $link['more']   = '';
766
767        $name = $this->_getLinkTitle($name, '', $isImage);
768        if ( !$isImage ) {
769            $link['class']='mail';
770        } else {
771            $link['class']='media';
772        }
773
774        $address = $this->_xmlEntities($address);
775        $address = obfuscate($address);
776        $title   = $address;
777
778        if(empty($name)){
779            $name = $address;
780        }
781
782        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
783
784        $link['url']   = 'mailto:'.$address;
785        $link['name']  = $name;
786        $link['title'] = $title;
787
788        //output formatted
789        $this->doc .= $this->_formatLink($link);
790    }
791
792    function internalmedia ($src, $title=null, $align=null, $width=null,
793                            $height=null, $cache=null, $linking=null, $return=NULL) {
794        global $ID;
795        list($src,$hash) = explode('#',$src,2);
796        resolve_mediaid(getNS($ID),$src, $exists);
797
798        $noLink = false;
799        $render = ($linking == 'linkonly') ? false : true;
800        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
801
802        list($ext,$mime,$dl) = mimetype($src,false);
803        if(substr($mime,0,5) == 'image' && $render){
804            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
805        }elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render){
806            // don't link movies
807            $noLink = true;
808        }else{
809            // add file icons
810            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
811            $link['class'] .= ' mediafile mf_'.$class;
812            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
813            if ($exists) $link['title'] .= ' (' . filesize_h(filesize(mediaFN($src))).')';
814        }
815
816        if($hash) $link['url'] .= '#'.$hash;
817
818        //markup non existing files
819        if (!$exists) {
820            $link['class'] .= ' wikilink2';
821        }
822
823        //output formatted
824        if ($return) {
825            if ($linking == 'nolink' || $noLink) return $link['name'];
826            else return $this->_formatLink($link);
827        } else {
828            if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
829            else $this->doc .= $this->_formatLink($link);
830        }
831    }
832
833    function externalmedia ($src, $title=null, $align=null, $width=null,
834                            $height=null, $cache=null, $linking=null) {
835        list($src,$hash) = explode('#',$src,2);
836        $noLink = false;
837        $render = ($linking == 'linkonly') ? false : true;
838        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
839
840        $link['url']    = ml($src,array('cache'=>$cache));
841
842        list($ext,$mime,$dl) = mimetype($src,false);
843        if(substr($mime,0,5) == 'image' && $render){
844            // link only jpeg images
845            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
846        }elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render){
847            // don't link movies
848            $noLink = true;
849        }else{
850            // add file icons
851            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
852            $link['class'] .= ' mediafile mf_'.$class;
853        }
854
855        if($hash) $link['url'] .= '#'.$hash;
856
857        //output formatted
858        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
859        else $this->doc .= $this->_formatLink($link);
860    }
861
862    /**
863     * Renders an RSS feed
864     *
865     * @author Andreas Gohr <andi@splitbrain.org>
866     */
867    function rss ($url,$params){
868        global $lang;
869        global $conf;
870
871        require_once(DOKU_INC.'inc/FeedParser.php');
872        $feed = new FeedParser();
873        $feed->set_feed_url($url);
874
875        //disable warning while fetching
876        if (!defined('DOKU_E_LEVEL')) { $elvl = error_reporting(E_ERROR); }
877        $rc = $feed->init();
878        if (!defined('DOKU_E_LEVEL')) { error_reporting($elvl); }
879
880        //decide on start and end
881        if($params['reverse']){
882            $mod = -1;
883            $start = $feed->get_item_quantity()-1;
884            $end   = $start - ($params['max']);
885            $end   = ($end < -1) ? -1 : $end;
886        }else{
887            $mod   = 1;
888            $start = 0;
889            $end   = $feed->get_item_quantity();
890            $end   = ($end > $params['max']) ? $params['max'] : $end;
891        }
892
893        $this->doc .= '<ul class="rss">';
894        if($rc){
895            for ($x = $start; $x != $end; $x += $mod) {
896                $item = $feed->get_item($x);
897                $this->doc .= '<li><div class="li">';
898                // support feeds without links
899                $lnkurl = $item->get_permalink();
900                if($lnkurl){
901                    // title is escaped by SimplePie, we unescape here because it
902                    // is escaped again in externallink() FS#1705
903                    $this->externallink($item->get_permalink(),
904                                        html_entity_decode($item->get_title(), ENT_QUOTES, 'UTF-8'));
905                }else{
906                    $this->doc .= ' '.$item->get_title();
907                }
908                if($params['author']){
909                    $author = $item->get_author(0);
910                    if($author){
911                        $name = $author->get_name();
912                        if(!$name) $name = $author->get_email();
913                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
914                    }
915                }
916                if($params['date']){
917                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
918                }
919                if($params['details']){
920                    $this->doc .= '<div class="detail">';
921                    if($conf['htmlok']){
922                        $this->doc .= $item->get_description();
923                    }else{
924                        $this->doc .= strip_tags($item->get_description());
925                    }
926                    $this->doc .= '</div>';
927                }
928
929                $this->doc .= '</div></li>';
930            }
931        }else{
932            $this->doc .= '<li><div class="li">';
933            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
934            $this->externallink($url);
935            if($conf['allowdebug']){
936                $this->doc .= '<!--'.hsc($feed->error).'-->';
937            }
938            $this->doc .= '</div></li>';
939        }
940        $this->doc .= '</ul>';
941    }
942
943    // $numrows not yet implemented
944    function table_open($maxcols = null, $numrows = null, $pos = null){
945        global $lang;
946        // initialize the row counter used for classes
947        $this->_counter['row_counter'] = 0;
948        $class = 'table';
949        if ($pos !== null) {
950            $class .= ' ' . $this->startSectionEdit($pos, 'table');
951        }
952        $this->doc .= '<div class="' . $class . '"><table class="inline">' .
953                      DOKU_LF;
954    }
955
956    function table_close($pos = null){
957        $this->doc .= '</table></div>'.DOKU_LF;
958        if ($pos !== null) {
959            $this->finishSectionEdit($pos);
960        }
961    }
962
963    function tablerow_open(){
964        // initialize the cell counter used for classes
965        $this->_counter['cell_counter'] = 0;
966        $class = 'row' . $this->_counter['row_counter']++;
967        $this->doc .= DOKU_TAB . '<tr class="'.$class.'">' . DOKU_LF . DOKU_TAB . DOKU_TAB;
968    }
969
970    function tablerow_close(){
971        $this->doc .= DOKU_LF . DOKU_TAB . '</tr>' . DOKU_LF;
972    }
973
974    function tableheader_open($colspan = 1, $align = null, $rowspan = 1){
975        $class = 'class="col' . $this->_counter['cell_counter']++;
976        if ( !is_null($align) ) {
977            $class .= ' '.$align.'align';
978        }
979        $class .= '"';
980        $this->doc .= '<th ' . $class;
981        if ( $colspan > 1 ) {
982            $this->_counter['cell_counter'] += $colspan-1;
983            $this->doc .= ' colspan="'.$colspan.'"';
984        }
985        if ( $rowspan > 1 ) {
986            $this->doc .= ' rowspan="'.$rowspan.'"';
987        }
988        $this->doc .= '>';
989    }
990
991    function tableheader_close(){
992        $this->doc .= '</th>';
993    }
994
995    function tablecell_open($colspan = 1, $align = null, $rowspan = 1){
996        $class = 'class="col' . $this->_counter['cell_counter']++;
997        if ( !is_null($align) ) {
998            $class .= ' '.$align.'align';
999        }
1000        $class .= '"';
1001        $this->doc .= '<td '.$class;
1002        if ( $colspan > 1 ) {
1003            $this->_counter['cell_counter'] += $colspan-1;
1004            $this->doc .= ' colspan="'.$colspan.'"';
1005        }
1006        if ( $rowspan > 1 ) {
1007            $this->doc .= ' rowspan="'.$rowspan.'"';
1008        }
1009        $this->doc .= '>';
1010    }
1011
1012    function tablecell_close(){
1013        $this->doc .= '</td>';
1014    }
1015
1016    //----------------------------------------------------------
1017    // Utils
1018
1019    /**
1020     * Build a link
1021     *
1022     * Assembles all parts defined in $link returns HTML for the link
1023     *
1024     * @author Andreas Gohr <andi@splitbrain.org>
1025     */
1026    function _formatLink($link){
1027        //make sure the url is XHTML compliant (skip mailto)
1028        if(substr($link['url'],0,7) != 'mailto:'){
1029            $link['url'] = str_replace('&','&amp;',$link['url']);
1030            $link['url'] = str_replace('&amp;amp;','&amp;',$link['url']);
1031        }
1032        //remove double encodings in titles
1033        $link['title'] = str_replace('&amp;amp;','&amp;',$link['title']);
1034
1035        // be sure there are no bad chars in url or title
1036        // (we can't do this for name because it can contain an img tag)
1037        $link['url']   = strtr($link['url'],array('>'=>'%3E','<'=>'%3C','"'=>'%22'));
1038        $link['title'] = strtr($link['title'],array('>'=>'&gt;','<'=>'&lt;','"'=>'&quot;'));
1039
1040        $ret  = '';
1041        $ret .= $link['pre'];
1042        $ret .= '<a href="'.$link['url'].'"';
1043        if(!empty($link['class']))  $ret .= ' class="'.$link['class'].'"';
1044        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1045        if(!empty($link['title']))  $ret .= ' title="'.$link['title'].'"';
1046        if(!empty($link['style']))  $ret .= ' style="'.$link['style'].'"';
1047        if(!empty($link['rel']))    $ret .= ' rel="'.$link['rel'].'"';
1048        if(!empty($link['more']))   $ret .= ' '.$link['more'];
1049        $ret .= '>';
1050        $ret .= $link['name'];
1051        $ret .= '</a>';
1052        $ret .= $link['suf'];
1053        return $ret;
1054    }
1055
1056    /**
1057     * Renders internal and external media
1058     *
1059     * @author Andreas Gohr <andi@splitbrain.org>
1060     */
1061    function _media ($src, $title=null, $align=null, $width=null,
1062                      $height=null, $cache=null, $render = true) {
1063
1064        $ret = '';
1065
1066        list($ext,$mime,$dl) = mimetype($src);
1067        if(substr($mime,0,5) == 'image'){
1068            // first get the $title
1069            if (!is_null($title)) {
1070                $title  = $this->_xmlEntities($title);
1071            }elseif($ext == 'jpg' || $ext == 'jpeg'){
1072                //try to use the caption from IPTC/EXIF
1073                require_once(DOKU_INC.'inc/JpegMeta.php');
1074                $jpeg =new JpegMeta(mediaFN($src));
1075                if($jpeg !== false) $cap = $jpeg->getTitle();
1076                if($cap){
1077                    $title = $this->_xmlEntities($cap);
1078                }
1079            }
1080            if (!$render) {
1081                // if the picture is not supposed to be rendered
1082                // return the title of the picture
1083                if (!$title) {
1084                    // just show the sourcename
1085                    $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1086                }
1087                return $title;
1088            }
1089            //add image tag
1090            $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache)).'"';
1091            $ret .= ' class="media'.$align.'"';
1092
1093            if ($title) {
1094                $ret .= ' title="' . $title . '"';
1095                $ret .= ' alt="'   . $title .'"';
1096            }else{
1097                $ret .= ' alt=""';
1098            }
1099
1100            if ( !is_null($width) )
1101                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1102
1103            if ( !is_null($height) )
1104                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1105
1106            $ret .= ' />';
1107
1108        }elseif(media_supportedav($mime, 'video')){
1109            // first get the $title
1110            if (!is_null($title)) {
1111                $title  = $this->_xmlEntities($title);
1112            }
1113            if (!$title) {
1114                // just show the sourcename
1115                $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1116            }
1117            if (!$render) {
1118                // if the video is not supposed to be rendered
1119                // return the title of the video
1120                return $title;
1121            }
1122
1123            $att = array();
1124            $att['class'] = "media$align";
1125
1126            //add video(s)
1127            $ret .= $this->_video($src, $width, $height, $att);
1128
1129        }elseif(media_supportedav($mime, 'audio')){
1130            // first get the $title
1131            if (!is_null($title)) {
1132                $title  = $this->_xmlEntities($title);
1133            }
1134            if (!$title) {
1135                // just show the sourcename
1136                $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1137            }
1138            if (!$render) {
1139                // if the video is not supposed to be rendered
1140                // return the title of the video
1141                return $title;
1142            }
1143
1144            $att = array();
1145            $att['class'] = "media$align";
1146
1147            //add audio
1148            $ret .= $this->_audio($src, $att);
1149
1150        }elseif($mime == 'application/x-shockwave-flash'){
1151            if (!$render) {
1152                // if the flash is not supposed to be rendered
1153                // return the title of the flash
1154                if (!$title) {
1155                    // just show the sourcename
1156                    $title = utf8_basename(noNS($src));
1157                }
1158                return $this->_xmlEntities($title);
1159            }
1160
1161            $att = array();
1162            $att['class'] = "media$align";
1163            if($align == 'right') $att['align'] = 'right';
1164            if($align == 'left')  $att['align'] = 'left';
1165            $ret .= html_flashobject(ml($src,array('cache'=>$cache),true,'&'),$width,$height,
1166                                     array('quality' => 'high'),
1167                                     null,
1168                                     $att,
1169                                     $this->_xmlEntities($title));
1170        }elseif($title){
1171            // well at least we have a title to display
1172            $ret .= $this->_xmlEntities($title);
1173        }else{
1174            // just show the sourcename
1175            $ret .= $this->_xmlEntities(utf8_basename(noNS($src)));
1176        }
1177
1178        return $ret;
1179    }
1180
1181    function _xmlEntities($string) {
1182        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
1183    }
1184
1185    /**
1186     * Creates a linkid from a headline
1187     *
1188     * @param string  $title   The headline title
1189     * @param boolean $create  Create a new unique ID?
1190     * @author Andreas Gohr <andi@splitbrain.org>
1191     */
1192    function _headerToLink($title,$create=false) {
1193        if($create){
1194            return sectionID($title,$this->headers);
1195        }else{
1196            $check = false;
1197            return sectionID($title,$check);
1198        }
1199    }
1200
1201    /**
1202     * Construct a title and handle images in titles
1203     *
1204     * @author Harry Fuecks <hfuecks@gmail.com>
1205     */
1206    function _getLinkTitle($title, $default, & $isImage, $id=null, $linktype='content') {
1207        global $conf;
1208
1209        $isImage = false;
1210        if ( is_array($title) ) {
1211            $isImage = true;
1212            return $this->_imageTitle($title);
1213        } elseif ( is_null($title) || trim($title)=='') {
1214            if (useHeading($linktype) && $id) {
1215                $heading = p_get_first_heading($id);
1216                if ($heading) {
1217                    return $this->_xmlEntities($heading);
1218                }
1219            }
1220            return $this->_xmlEntities($default);
1221        } else {
1222            return $this->_xmlEntities($title);
1223        }
1224    }
1225
1226    /**
1227     * Returns an HTML code for images used in link titles
1228     *
1229     * @todo Resolve namespace on internal images
1230     * @author Andreas Gohr <andi@splitbrain.org>
1231     */
1232    function _imageTitle($img) {
1233        global $ID;
1234
1235        // some fixes on $img['src']
1236        // see internalmedia() and externalmedia()
1237        list($img['src'],$hash) = explode('#',$img['src'],2);
1238        if ($img['type'] == 'internalmedia') {
1239            resolve_mediaid(getNS($ID),$img['src'],$exists);
1240        }
1241
1242        return $this->_media($img['src'],
1243                              $img['title'],
1244                              $img['align'],
1245                              $img['width'],
1246                              $img['height'],
1247                              $img['cache']);
1248    }
1249
1250    /**
1251     * _getMediaLinkConf is a helperfunction to internalmedia() and externalmedia()
1252     * which returns a basic link to a media.
1253     *
1254     * @author Pierre Spring <pierre.spring@liip.ch>
1255     * @param string $src
1256     * @param string $title
1257     * @param string $align
1258     * @param string $width
1259     * @param string $height
1260     * @param string $cache
1261     * @param string $render
1262     * @access protected
1263     * @return array
1264     */
1265    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) {
1266        global $conf;
1267
1268        $link = array();
1269        $link['class']  = 'media';
1270        $link['style']  = '';
1271        $link['pre']    = '';
1272        $link['suf']    = '';
1273        $link['more']   = '';
1274        $link['target'] = $conf['target']['media'];
1275        $link['title']  = $this->_xmlEntities($src);
1276        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1277
1278        return $link;
1279    }
1280
1281
1282    /**
1283     * Embed video(s) in HTML
1284     *
1285     * @author Anika Henke <anika@selfthinker.org>
1286     *
1287     * @param string $src      - ID of video to embed
1288     * @param int $width       - width of the video in pixels
1289     * @param int $height      - height of the video in pixels
1290     * @param array $atts      - additional attributes for the <video> tag
1291     * @return string
1292     */
1293    function _video($src,$width,$height,$atts=null){
1294
1295        // prepare width and height
1296        if(is_null($atts)) $atts = array();
1297        $atts['width']  = (int) $width;
1298        $atts['height'] = (int) $height;
1299        if(!$atts['width'])  $atts['width']  = 320;
1300        if(!$atts['height']) $atts['height'] = 240;
1301
1302        // prepare alternative formats
1303        $extensions = array('webm', 'ogv', 'mp4');
1304        $alternatives = media_alternativefiles($src, $extensions);
1305        $poster = media_alternativefiles($src, array('jpg', 'png'), true);
1306        $posterUrl = '';
1307        if (!empty($poster)) {
1308            $posterUrl = ml(reset($poster),array('cache'=>$cache),true,'&');
1309        }
1310
1311        $out = '';
1312        // open video tag
1313        $out .= '<video '.buildAttributes($atts).' controls="controls"';
1314        if ($posterUrl) $out .= ' poster="'.hsc($posterUrl).'"';
1315        $out .= '>'.NL;
1316        $fallback = '';
1317
1318        // output source for each alternative video format
1319        foreach($alternatives as $mime => $file) {
1320            $url = ml($file,array('cache'=>$cache),true,'&');
1321            $title = $this->_xmlEntities(utf8_basename(noNS($file)));
1322
1323            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1324            // alternative content (just a link to the file)
1325            $fallback .= $this->internalmedia($file, $title, NULL, NULL, NULL, $cache=NULL, $linking='linkonly', $return=true);
1326        }
1327
1328        // finish
1329        $out .= $fallback;
1330        $out .= '</video>'.NL;
1331        return $out;
1332    }
1333
1334    /**
1335     * Embed audio in HTML
1336     *
1337     * @author Anika Henke <anika@selfthinker.org>
1338     *
1339     * @param string $src      - ID of audio to embed
1340     * @param array $atts      - additional attributes for the <audio> tag
1341     * @return string
1342     */
1343    function _audio($src,$atts=null){
1344
1345        // prepare alternative formats
1346        $extensions = array('ogg', 'mp3', 'wav');
1347        $alternatives = media_alternativefiles($src, $extensions);
1348
1349        $out = '';
1350        // open audio tag
1351        $out .= '<audio '.buildAttributes($atts).' controls="controls">'.NL;
1352        $fallback = '';
1353
1354        // output source for each alternative audio format
1355        foreach($alternatives as $mime => $file) {
1356            $url = ml($file,array('cache'=>$cache),true,'&');
1357            $title = $this->_xmlEntities(utf8_basename(noNS($file)));
1358
1359            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1360            // alternative content (just a link to the file)
1361            $fallback .= $this->internalmedia($file, $title, NULL, NULL, NULL, $cache=NULL, $linking='linkonly', $return=true);
1362        }
1363
1364        // finish
1365        $out .= $fallback;
1366        $out .= '</audio>'.NL;
1367        return $out;
1368    }
1369
1370}
1371
1372//Setup VIM: ex: et ts=4 :
1373