xref: /dokuwiki/inc/parser/xhtml.php (revision 4c3263af6652b0a479e2c742914eb67a7929b9b9)
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    var $date_at = '';    // link pages and media against this revision
32
33    var $sectionedits = array(); // A stack of section edit data
34    private $lastsecid = 0; // last section edit id, used by startSectionEdit
35
36    var $headers = array();
37    /** @var array a list of footnotes, list starts at 1! */
38    var $footnotes = array();
39    var $lastlevel = 0;
40    var $node = array(0,0,0,0,0);
41    var $store = '';
42
43    var $_counter   = array(); // used as global counter, introduced for table classes
44    var $_codeblock = 0; // counts the code and file blocks, used to provide download links
45
46    /**
47     * Register a new edit section range
48     *
49     * @param $type  string The section type identifier
50     * @param $title string The section title
51     * @param $start int    The byte position for the edit start
52     * @return string A marker class for the starting HTML element
53     * @author Adrian Lang <lang@cosmocode.de>
54     */
55    public function startSectionEdit($start, $type, $title = null) {
56        $this->sectionedits[] = array(++$this->lastsecid, $start, $type, $title);
57        return 'sectionedit' . $this->lastsecid;
58    }
59
60    /**
61     * Finish an edit section range
62     *
63     * @param $end int The byte position for the edit end; null for the rest of
64     *                 the page
65     * @author Adrian Lang <lang@cosmocode.de>
66     */
67    public function finishSectionEdit($end = null) {
68        list($id, $start, $type, $title) = array_pop($this->sectionedits);
69        if (!is_null($end) && $end <= $start) {
70            return;
71        }
72        $this->doc .= "<!-- EDIT$id " . strtoupper($type) . ' ';
73        if (!is_null($title)) {
74            $this->doc .= '"' . str_replace('"', '', $title) . '" ';
75        }
76        $this->doc .= "[$start-" . (is_null($end) ? '' : $end) . '] -->';
77    }
78
79    function getFormat(){
80        return 'xhtml';
81    }
82
83
84    function document_start() {
85        //reset some internals
86        $this->toc     = array();
87        $this->headers = array();
88    }
89
90    function document_end() {
91        // Finish open section edits.
92        while (count($this->sectionedits) > 0) {
93            if ($this->sectionedits[count($this->sectionedits) - 1][1] <= 1) {
94                // If there is only one section, do not write a section edit
95                // marker.
96                array_pop($this->sectionedits);
97            } else {
98                $this->finishSectionEdit();
99            }
100        }
101
102        if ( count ($this->footnotes) > 0 ) {
103            $this->doc .= '<div class="footnotes">'.DOKU_LF;
104
105            foreach ( $this->footnotes as $id => $footnote ) {
106                // check its not a placeholder that indicates actual footnote text is elsewhere
107                if (substr($footnote, 0, 5) != "@@FNT") {
108
109                    // open the footnote and set the anchor and backlink
110                    $this->doc .= '<div class="fn">';
111                    $this->doc .= '<sup><a href="#fnt__'.$id.'" id="fn__'.$id.'" class="fn_bot">';
112                    $this->doc .= $id.')</a></sup> '.DOKU_LF;
113
114                    // get any other footnotes that use the same markup
115                    $alt = array_keys($this->footnotes, "@@FNT$id");
116
117                    if (count($alt)) {
118                        foreach ($alt as $ref) {
119                            // set anchor and backlink for the other footnotes
120                            $this->doc .= ', <sup><a href="#fnt__'.($ref).'" id="fn__'.($ref).'" class="fn_bot">';
121                            $this->doc .= ($ref).')</a></sup> '.DOKU_LF;
122                        }
123                    }
124
125                    // add footnote markup and close this footnote
126                    $this->doc .= $footnote;
127                    $this->doc .= '</div>' . DOKU_LF;
128                }
129            }
130            $this->doc .= '</div>'.DOKU_LF;
131        }
132
133        // Prepare the TOC
134        global $conf;
135        if($this->info['toc'] && is_array($this->toc) && $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads']){
136            global $TOC;
137            $TOC = $this->toc;
138        }
139
140        // make sure there are no empty paragraphs
141        $this->doc = preg_replace('#<p>\s*</p>#','',$this->doc);
142    }
143
144    function toc_additem($id, $text, $level) {
145        global $conf;
146
147        //handle TOC
148        if($level >= $conf['toptoclevel'] && $level <= $conf['maxtoclevel']){
149            $this->toc[] = html_mktocitem($id, $text, $level-$conf['toptoclevel']+1);
150        }
151    }
152
153    function header($text, $level, $pos) {
154        global $conf;
155
156        if(!$text) return; //skip empty headlines
157
158        $hid = $this->_headerToLink($text,true);
159
160        //only add items within configured levels
161        $this->toc_additem($hid, $text, $level);
162
163        // adjust $node to reflect hierarchy of levels
164        $this->node[$level-1]++;
165        if ($level < $this->lastlevel) {
166            for ($i = 0; $i < $this->lastlevel-$level; $i++) {
167                $this->node[$this->lastlevel-$i-1] = 0;
168            }
169        }
170        $this->lastlevel = $level;
171
172        if ($level <= $conf['maxseclevel'] &&
173            count($this->sectionedits) > 0 &&
174            $this->sectionedits[count($this->sectionedits) - 1][2] === 'section') {
175            $this->finishSectionEdit($pos - 1);
176        }
177
178        // write the header
179        $this->doc .= DOKU_LF.'<h'.$level;
180        if ($level <= $conf['maxseclevel']) {
181            $this->doc .= ' class="' . $this->startSectionEdit($pos, 'section', $text) . '"';
182        }
183        $this->doc .= ' id="'.$hid.'">';
184        $this->doc .= $this->_xmlEntities($text);
185        $this->doc .= "</h$level>".DOKU_LF;
186    }
187
188    function section_open($level) {
189        $this->doc .= '<div class="level' . $level . '">' . DOKU_LF;
190    }
191
192    function section_close() {
193        $this->doc .= DOKU_LF.'</div>'.DOKU_LF;
194    }
195
196    function cdata($text) {
197        $this->doc .= $this->_xmlEntities($text);
198    }
199
200    function p_open() {
201        $this->doc .= DOKU_LF.'<p>'.DOKU_LF;
202    }
203
204    function p_close() {
205        $this->doc .= DOKU_LF.'</p>'.DOKU_LF;
206    }
207
208    function linebreak() {
209        $this->doc .= '<br/>'.DOKU_LF;
210    }
211
212    function hr() {
213        $this->doc .= '<hr />'.DOKU_LF;
214    }
215
216    function strong_open() {
217        $this->doc .= '<strong>';
218    }
219
220    function strong_close() {
221        $this->doc .= '</strong>';
222    }
223
224    function emphasis_open() {
225        $this->doc .= '<em>';
226    }
227
228    function emphasis_close() {
229        $this->doc .= '</em>';
230    }
231
232    function underline_open() {
233        $this->doc .= '<em class="u">';
234    }
235
236    function underline_close() {
237        $this->doc .= '</em>';
238    }
239
240    function monospace_open() {
241        $this->doc .= '<code>';
242    }
243
244    function monospace_close() {
245        $this->doc .= '</code>';
246    }
247
248    function subscript_open() {
249        $this->doc .= '<sub>';
250    }
251
252    function subscript_close() {
253        $this->doc .= '</sub>';
254    }
255
256    function superscript_open() {
257        $this->doc .= '<sup>';
258    }
259
260    function superscript_close() {
261        $this->doc .= '</sup>';
262    }
263
264    function deleted_open() {
265        $this->doc .= '<del>';
266    }
267
268    function deleted_close() {
269        $this->doc .= '</del>';
270    }
271
272    /**
273     * Callback for footnote start syntax
274     *
275     * All following content will go to the footnote instead of
276     * the document. To achieve this the previous rendered content
277     * is moved to $store and $doc is cleared
278     *
279     * @author Andreas Gohr <andi@splitbrain.org>
280     */
281    function footnote_open() {
282
283        // move current content to store and record footnote
284        $this->store = $this->doc;
285        $this->doc   = '';
286    }
287
288    /**
289     * Callback for footnote end syntax
290     *
291     * All rendered content is moved to the $footnotes array and the old
292     * content is restored from $store again
293     *
294     * @author Andreas Gohr
295     */
296    function footnote_close() {
297        /** @var $fnid int takes track of seen footnotes, assures they are unique even across multiple docs FS#2841 */
298        static $fnid = 0;
299        // assign new footnote id (we start at 1)
300        $fnid++;
301
302        // recover footnote into the stack and restore old content
303        $footnote = $this->doc;
304        $this->doc = $this->store;
305        $this->store = '';
306
307        // check to see if this footnote has been seen before
308        $i = array_search($footnote, $this->footnotes);
309
310        if ($i === false) {
311            // its a new footnote, add it to the $footnotes array
312            $this->footnotes[$fnid] = $footnote;
313        } else {
314            // seen this one before, save a placeholder
315            $this->footnotes[$fnid] = "@@FNT".($i);
316        }
317
318        // output the footnote reference and link
319        $this->doc .= '<sup><a href="#fn__'.$fnid.'" id="fnt__'.$fnid.'" class="fn_top">'.$fnid.')</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        if($this->date_at) {
623            $params['at'] = $this->date_at;
624        }
625        $link['url']    = wl($id, $params);
626        $link['name']   = $name;
627        $link['title']  = $id;
628        //add search string
629        if($search){
630            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
631            if(is_array($search)){
632                $search = array_map('rawurlencode',$search);
633                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
634            }else{
635                $link['url'] .= 's='.rawurlencode($search);
636            }
637        }
638
639        //keep hash
640        if($hash) $link['url'].='#'.$hash;
641
642        //output formatted
643        if($returnonly){
644            return $this->_formatLink($link);
645        }else{
646            $this->doc .= $this->_formatLink($link);
647        }
648    }
649
650    function externallink($url, $name = null) {
651        global $conf;
652
653        $name = $this->_getLinkTitle($name, $url, $isImage);
654
655        // url might be an attack vector, only allow registered protocols
656        if(is_null($this->schemes)) $this->schemes = getSchemes();
657        list($scheme) = explode('://',$url);
658        $scheme = strtolower($scheme);
659        if(!in_array($scheme,$this->schemes)) $url = '';
660
661        // is there still an URL?
662        if(!$url){
663            $this->doc .= $name;
664            return;
665        }
666
667        // set class
668        if ( !$isImage ) {
669            $class='urlextern';
670        } else {
671            $class='media';
672        }
673
674        //prepare for formating
675        $link['target'] = $conf['target']['extern'];
676        $link['style']  = '';
677        $link['pre']    = '';
678        $link['suf']    = '';
679        $link['more']   = '';
680        $link['class']  = $class;
681        $link['url']    = $url;
682
683        $link['name']   = $name;
684        $link['title']  = $this->_xmlEntities($url);
685        if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"';
686
687        //output formatted
688        $this->doc .= $this->_formatLink($link);
689    }
690
691    /**
692    */
693    function interwikilink($match, $name = null, $wikiName, $wikiUri) {
694        global $conf;
695
696        $link = array();
697        $link['target'] = $conf['target']['interwiki'];
698        $link['pre']    = '';
699        $link['suf']    = '';
700        $link['more']   = '';
701        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
702
703        //get interwiki URL
704        $url = $this->_resolveInterWiki($wikiName,$wikiUri);
705
706        if ( !$isImage ) {
707            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$wikiName);
708            $link['class'] = "interwiki iw_$class";
709        } else {
710            $link['class'] = 'media';
711        }
712
713        //do we stay at the same server? Use local target
714        if( strpos($url,DOKU_URL) === 0 ){
715            $link['target'] = $conf['target']['wiki'];
716        }
717
718        $link['url'] = $url;
719        $link['title'] = htmlspecialchars($link['url']);
720
721        //output formatted
722        $this->doc .= $this->_formatLink($link);
723    }
724
725    /**
726     */
727    function windowssharelink($url, $name = null) {
728        global $conf;
729        global $lang;
730        //simple setup
731        $link['target'] = $conf['target']['windows'];
732        $link['pre']    = '';
733        $link['suf']   = '';
734        $link['style']  = '';
735
736        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
737        if ( !$isImage ) {
738            $link['class'] = 'windows';
739        } else {
740            $link['class'] = 'media';
741        }
742
743        $link['title'] = $this->_xmlEntities($url);
744        $url = str_replace('\\','/',$url);
745        $url = 'file:///'.$url;
746        $link['url'] = $url;
747
748        //output formatted
749        $this->doc .= $this->_formatLink($link);
750    }
751
752    function emaillink($address, $name = null) {
753        global $conf;
754        //simple setup
755        $link = array();
756        $link['target'] = '';
757        $link['pre']    = '';
758        $link['suf']   = '';
759        $link['style']  = '';
760        $link['more']   = '';
761
762        $name = $this->_getLinkTitle($name, '', $isImage);
763        if ( !$isImage ) {
764            $link['class']='mail';
765        } else {
766            $link['class']='media';
767        }
768
769        $address = $this->_xmlEntities($address);
770        $address = obfuscate($address);
771        $title   = $address;
772
773        if(empty($name)){
774            $name = $address;
775        }
776
777        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
778
779        $link['url']   = 'mailto:'.$address;
780        $link['name']  = $name;
781        $link['title'] = $title;
782
783        //output formatted
784        $this->doc .= $this->_formatLink($link);
785    }
786
787    function internalmedia ($src, $title=null, $align=null, $width=null,
788                            $height=null, $cache=null, $linking=null) {
789        global $ID;
790        list($src,$hash) = explode('#',$src,2);
791        resolve_mediaid(getNS($ID),$src, $exists);
792
793        $noLink = false;
794        $render = ($linking == 'linkonly') ? false : true;
795        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
796
797        list($ext,$mime,$dl) = mimetype($src,false);
798        if(substr($mime,0,5) == 'image' && $render){
799            if($this->date_at) {
800                $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache,'rev'=>$this->_getProperMediaRevision($src)),($linking=='direct'));
801            } else {
802                $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
803            }
804        }elseif($mime == 'application/x-shockwave-flash' && $render){
805            // don't link flash movies
806            $noLink = true;
807        }else{
808            // add file icons
809            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
810            $link['class'] .= ' mediafile mf_'.$class;
811            if($this->date_at) {
812                $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache,'rev'=>$this->_getProperMediaRevision($src)),true);
813            } else {
814                $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
815            }
816            if ($exists) $link['title'] .= ' (' . filesize_h(filesize(mediaFN($src))).')';
817        }
818
819        if($hash) $link['url'] .= '#'.$hash;
820
821        //markup non existing files
822        if (!$exists) {
823            $link['class'] .= ' wikilink2';
824        }
825
826        //output formatted
827        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
828        else $this->doc .= $this->_formatLink($link);
829    }
830
831    function externalmedia ($src, $title=null, $align=null, $width=null,
832                            $height=null, $cache=null, $linking=null) {
833        list($src,$hash) = explode('#',$src,2);
834        $noLink = false;
835        $render = ($linking == 'linkonly') ? false : true;
836        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
837
838        $link['url']    = ml($src,array('cache'=>$cache));
839
840        list($ext,$mime,$dl) = mimetype($src,false);
841        if(substr($mime,0,5) == 'image' && $render){
842            // link only jpeg images
843            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
844        }elseif($mime == 'application/x-shockwave-flash' && $render){
845            // don't link flash movies
846            $noLink = true;
847        }else{
848            // add file icons
849            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
850            $link['class'] .= ' mediafile mf_'.$class;
851        }
852
853        if($hash) $link['url'] .= '#'.$hash;
854
855        //output formatted
856        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
857        else $this->doc .= $this->_formatLink($link);
858    }
859
860    /**
861     * Renders an RSS feed
862     *
863     * @author Andreas Gohr <andi@splitbrain.org>
864     */
865    function rss ($url,$params){
866        global $lang;
867        global $conf;
868
869        require_once(DOKU_INC.'inc/FeedParser.php');
870        $feed = new FeedParser();
871        $feed->set_feed_url($url);
872
873        //disable warning while fetching
874        if (!defined('DOKU_E_LEVEL')) { $elvl = error_reporting(E_ERROR); }
875        $rc = $feed->init();
876        if (!defined('DOKU_E_LEVEL')) { error_reporting($elvl); }
877
878        //decide on start and end
879        if($params['reverse']){
880            $mod = -1;
881            $start = $feed->get_item_quantity()-1;
882            $end   = $start - ($params['max']);
883            $end   = ($end < -1) ? -1 : $end;
884        }else{
885            $mod   = 1;
886            $start = 0;
887            $end   = $feed->get_item_quantity();
888            $end   = ($end > $params['max']) ? $params['max'] : $end;
889        }
890
891        $this->doc .= '<ul class="rss">';
892        if($rc){
893            for ($x = $start; $x != $end; $x += $mod) {
894                $item = $feed->get_item($x);
895                $this->doc .= '<li><div class="li">';
896                // support feeds without links
897                $lnkurl = $item->get_permalink();
898                if($lnkurl){
899                    // title is escaped by SimplePie, we unescape here because it
900                    // is escaped again in externallink() FS#1705
901                    $this->externallink($item->get_permalink(),
902                                        html_entity_decode($item->get_title(), ENT_QUOTES, 'UTF-8'));
903                }else{
904                    $this->doc .= ' '.$item->get_title();
905                }
906                if($params['author']){
907                    $author = $item->get_author(0);
908                    if($author){
909                        $name = $author->get_name();
910                        if(!$name) $name = $author->get_email();
911                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
912                    }
913                }
914                if($params['date']){
915                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
916                }
917                if($params['details']){
918                    $this->doc .= '<div class="detail">';
919                    if($conf['htmlok']){
920                        $this->doc .= $item->get_description();
921                    }else{
922                        $this->doc .= strip_tags($item->get_description());
923                    }
924                    $this->doc .= '</div>';
925                }
926
927                $this->doc .= '</div></li>';
928            }
929        }else{
930            $this->doc .= '<li><div class="li">';
931            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
932            $this->externallink($url);
933            if($conf['allowdebug']){
934                $this->doc .= '<!--'.hsc($feed->error).'-->';
935            }
936            $this->doc .= '</div></li>';
937        }
938        $this->doc .= '</ul>';
939    }
940
941    // $numrows not yet implemented
942    function table_open($maxcols = null, $numrows = null, $pos = null){
943        global $lang;
944        // initialize the row counter used for classes
945        $this->_counter['row_counter'] = 0;
946        $class = 'table';
947        if ($pos !== null) {
948            $class .= ' ' . $this->startSectionEdit($pos, 'table');
949        }
950        $this->doc .= '<div class="' . $class . '"><table class="inline">' .
951                      DOKU_LF;
952    }
953
954    function table_close($pos = null){
955        $this->doc .= '</table></div>'.DOKU_LF;
956        if ($pos !== null) {
957            $this->finishSectionEdit($pos);
958        }
959    }
960
961    function tablerow_open(){
962        // initialize the cell counter used for classes
963        $this->_counter['cell_counter'] = 0;
964        $class = 'row' . $this->_counter['row_counter']++;
965        $this->doc .= DOKU_TAB . '<tr class="'.$class.'">' . DOKU_LF . DOKU_TAB . DOKU_TAB;
966    }
967
968    function tablerow_close(){
969        $this->doc .= DOKU_LF . DOKU_TAB . '</tr>' . DOKU_LF;
970    }
971
972    function tableheader_open($colspan = 1, $align = null, $rowspan = 1){
973        $class = 'class="col' . $this->_counter['cell_counter']++;
974        if ( !is_null($align) ) {
975            $class .= ' '.$align.'align';
976        }
977        $class .= '"';
978        $this->doc .= '<th ' . $class;
979        if ( $colspan > 1 ) {
980            $this->_counter['cell_counter'] += $colspan-1;
981            $this->doc .= ' colspan="'.$colspan.'"';
982        }
983        if ( $rowspan > 1 ) {
984            $this->doc .= ' rowspan="'.$rowspan.'"';
985        }
986        $this->doc .= '>';
987    }
988
989    function tableheader_close(){
990        $this->doc .= '</th>';
991    }
992
993    function tablecell_open($colspan = 1, $align = null, $rowspan = 1){
994        $class = 'class="col' . $this->_counter['cell_counter']++;
995        if ( !is_null($align) ) {
996            $class .= ' '.$align.'align';
997        }
998        $class .= '"';
999        $this->doc .= '<td '.$class;
1000        if ( $colspan > 1 ) {
1001            $this->_counter['cell_counter'] += $colspan-1;
1002            $this->doc .= ' colspan="'.$colspan.'"';
1003        }
1004        if ( $rowspan > 1 ) {
1005            $this->doc .= ' rowspan="'.$rowspan.'"';
1006        }
1007        $this->doc .= '>';
1008    }
1009
1010    function tablecell_close(){
1011        $this->doc .= '</td>';
1012    }
1013
1014    //----------------------------------------------------------
1015    // Utils
1016
1017    /**
1018     * Build a link
1019     *
1020     * Assembles all parts defined in $link returns HTML for the link
1021     *
1022     * @author Andreas Gohr <andi@splitbrain.org>
1023     */
1024    function _formatLink($link){
1025        //make sure the url is XHTML compliant (skip mailto)
1026        if(substr($link['url'],0,7) != 'mailto:'){
1027            $link['url'] = str_replace('&','&amp;',$link['url']);
1028            $link['url'] = str_replace('&amp;amp;','&amp;',$link['url']);
1029        }
1030        //remove double encodings in titles
1031        $link['title'] = str_replace('&amp;amp;','&amp;',$link['title']);
1032
1033        // be sure there are no bad chars in url or title
1034        // (we can't do this for name because it can contain an img tag)
1035        $link['url']   = strtr($link['url'],array('>'=>'%3E','<'=>'%3C','"'=>'%22'));
1036        $link['title'] = strtr($link['title'],array('>'=>'&gt;','<'=>'&lt;','"'=>'&quot;'));
1037
1038        $ret  = '';
1039        $ret .= $link['pre'];
1040        $ret .= '<a href="'.$link['url'].'"';
1041        if(!empty($link['class']))  $ret .= ' class="'.$link['class'].'"';
1042        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1043        if(!empty($link['title']))  $ret .= ' title="'.$link['title'].'"';
1044        if(!empty($link['style']))  $ret .= ' style="'.$link['style'].'"';
1045        if(!empty($link['rel']))    $ret .= ' rel="'.$link['rel'].'"';
1046        if(!empty($link['more']))   $ret .= ' '.$link['more'];
1047        $ret .= '>';
1048        $ret .= $link['name'];
1049        $ret .= '</a>';
1050        $ret .= $link['suf'];
1051        return $ret;
1052    }
1053
1054    /**
1055     * Renders internal and external media
1056     *
1057     * @author Andreas Gohr <andi@splitbrain.org>
1058     */
1059    function _media ($src, $title=null, $align=null, $width=null,
1060                      $height=null, $cache=null, $render = true) {
1061
1062        $ret = '';
1063        $intern = !media_isexternal($src);
1064        list($ext,$mime,$dl) = mimetype($src);
1065        if(substr($mime,0,5) == 'image'){
1066            // first get the $title
1067            if (!is_null($title)) {
1068                $title  = $this->_xmlEntities($title);
1069            }elseif($ext == 'jpg' || $ext == 'jpeg'){
1070                //try to use the caption from IPTC/EXIF
1071                require_once(DOKU_INC.'inc/JpegMeta.php');
1072                $jpeg =new JpegMeta(mediaFN($src));
1073                if($jpeg !== false) $cap = $jpeg->getTitle();
1074                if($cap){
1075                    $title = $this->_xmlEntities($cap);
1076                }
1077            }
1078            if (!$render) {
1079                // if the picture is not supposed to be rendered
1080                // return the title of the picture
1081                if (!$title) {
1082                    // just show the sourcename
1083                    $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1084                }
1085                return $title;
1086            }
1087            //add image tag
1088            if($intern && $this->date_at) {
1089                $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache,'rev'=>$this->_getProperMediaRevision($src))).'"';
1090            } else {
1091                $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache)).'"';
1092            }
1093            $ret .= ' class="media'.$align.'"';
1094
1095            if ($title) {
1096                $ret .= ' title="' . $title . '"';
1097                $ret .= ' alt="'   . $title .'"';
1098            }else{
1099                $ret .= ' alt=""';
1100            }
1101
1102            if ( !is_null($width) )
1103                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1104
1105            if ( !is_null($height) )
1106                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1107
1108            $ret .= ' />';
1109
1110        }elseif($mime == 'application/x-shockwave-flash'){
1111            if (!$render) {
1112                // if the flash is not supposed to be rendered
1113                // return the title of the flash
1114                if (!$title) {
1115                    // just show the sourcename
1116                    $title = utf8_basename(noNS($src));
1117                }
1118                return $this->_xmlEntities($title);
1119            }
1120
1121            $att = array();
1122            $att['class'] = "media$align";
1123            if($align == 'right') $att['align'] = 'right';
1124            if($align == 'left')  $att['align'] = 'left';
1125            $ret .= html_flashobject(ml($src,array('cache'=>$cache),true,'&'),$width,$height,
1126                                     array('quality' => 'high'),
1127                                     null,
1128                                     $att,
1129                                     $this->_xmlEntities($title));
1130        }elseif($title){
1131            // well at least we have a title to display
1132            $ret .= $this->_xmlEntities($title);
1133        }else{
1134            // just show the sourcename
1135            $ret .= $this->_xmlEntities(utf8_basename(noNS($src)));
1136        }
1137
1138        return $ret;
1139    }
1140
1141    function _xmlEntities($string) {
1142        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
1143    }
1144
1145    /**
1146     * Creates a linkid from a headline
1147     *
1148     * @param string  $title   The headline title
1149     * @param boolean $create  Create a new unique ID?
1150     * @author Andreas Gohr <andi@splitbrain.org>
1151     */
1152    function _headerToLink($title,$create=false) {
1153        if($create){
1154            return sectionID($title,$this->headers);
1155        }else{
1156            $check = false;
1157            return sectionID($title,$check);
1158        }
1159    }
1160
1161    /**
1162     * Construct a title and handle images in titles
1163     *
1164     * @author Harry Fuecks <hfuecks@gmail.com>
1165     */
1166    function _getLinkTitle($title, $default, & $isImage, $id=null, $linktype='content') {
1167        global $conf;
1168
1169        $isImage = false;
1170        if ( is_array($title) ) {
1171            $isImage = true;
1172            return $this->_imageTitle($title);
1173        } elseif ( is_null($title) || trim($title)=='') {
1174            if (useHeading($linktype) && $id) {
1175                $heading = p_get_first_heading($id);
1176                if ($heading) {
1177                    return $this->_xmlEntities($heading);
1178                }
1179            }
1180            return $this->_xmlEntities($default);
1181        } else {
1182            return $this->_xmlEntities($title);
1183        }
1184    }
1185
1186    /**
1187     * Returns an HTML code for images used in link titles
1188     *
1189     * @todo Resolve namespace on internal images
1190     * @author Andreas Gohr <andi@splitbrain.org>
1191     */
1192    function _imageTitle($img) {
1193        global $ID;
1194
1195        // some fixes on $img['src']
1196        // see internalmedia() and externalmedia()
1197        list($img['src'],$hash) = explode('#',$img['src'],2);
1198        if ($img['type'] == 'internalmedia') {
1199            resolve_mediaid(getNS($ID),$img['src'],$exists);
1200        }
1201
1202        return $this->_media($img['src'],
1203                              $img['title'],
1204                              $img['align'],
1205                              $img['width'],
1206                              $img['height'],
1207                              $img['cache']);
1208    }
1209
1210    /**
1211     * _getMediaLinkConf is a helperfunction to internalmedia() and externalmedia()
1212     * which returns a basic link to a media.
1213     *
1214     * @author Pierre Spring <pierre.spring@liip.ch>
1215     * @param string $src
1216     * @param string $title
1217     * @param string $align
1218     * @param string $width
1219     * @param string $height
1220     * @param string $cache
1221     * @param string $render
1222     * @access protected
1223     * @return array
1224     */
1225    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) {
1226        global $conf;
1227
1228        $link = array();
1229        $link['class']  = 'media';
1230        $link['style']  = '';
1231        $link['pre']    = '';
1232        $link['suf']    = '';
1233        $link['more']   = '';
1234        $link['target'] = $conf['target']['media'];
1235        $link['title']  = $this->_xmlEntities($src);
1236        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1237
1238        return $link;
1239    }
1240
1241    /**
1242     * _getProperMediaRevision is a helperfunction to internalmedia() and _media()
1243     * which returns an existing media revision less or equal to rev or date_at
1244     *
1245     * @author lisps
1246     * @param string $media_id
1247     * @access protected
1248     * @return string revision ('' for current)
1249     */
1250    function _getProperMediaRevision($media_id){
1251        $pagelog = new MediaChangeLog($media_id);
1252        return $pagelog->getLastRevisionAt($this->date_at);
1253    }
1254
1255
1256}
1257
1258//Setup VIM: ex: et ts=4 :
1259