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