xref: /dokuwiki/inc/parser/xhtml.php (revision 8eafbfcb7ac89e193ce01bf8d8eca870b3c17ddd)
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    private $sectionedits = array(); // A stack of section edit data
33
34    var $headers = array();
35    var $footnotes = array();
36    var $lastlevel = 0;
37    var $node = array(0,0,0,0,0);
38    var $store = '';
39
40    var $_counter   = array(); // used as global counter, introduced for table classes
41    var $_codeblock = 0; // counts the code and file blocks, used to provide download links
42
43    /**
44     * Register a new edit section range
45     *
46     * @param $type  string The section type identifier
47     * @param $title string The section title
48     * @param $start int    The byte position for the edit start
49     * @return string A marker class for the starting HTML element
50     * @author Adrian Lang <lang@cosmocode.de>
51     */
52    public function startSectionEdit($start, $type, $title = null) {
53        static $lastsecid = 0;
54        $this->sectionedits[] = array(++$lastsecid, $start, $type, $title);
55        return 'sectionedit' . $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.'" name="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).'" name="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 .= '><a name="'.$hid.'" id="'.$hid.'">';
185        $this->doc .= $this->_xmlEntities($text);
186        $this->doc .= "</a></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.'" name="fnt__'.$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   $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   $wrapper   html element to wrap result if $conf['htmlok'] is okff
386     *
387     * @author Andreas Gohr <andi@splitbrain.org>
388     */
389    function html($text, $wrapper='code') {
390        global $conf;
391
392        if($conf['htmlok']){
393          $this->doc .= $text;
394        } else {
395          $this->doc .= p_xhtml_cached_geshi($text, 'html4strict', $wrapper);
396        }
397    }
398
399    function htmlblock($text) {
400        $this->html($text, 'pre');
401    }
402
403    function quote_open() {
404        $this->doc .= '<blockquote><div class="no">'.DOKU_LF;
405    }
406
407    function quote_close() {
408        $this->doc .= '</div></blockquote>'.DOKU_LF;
409    }
410
411    function preformatted($text) {
412        $this->doc .= '<pre class="code">' . trim($this->_xmlEntities($text),"\n\r") . '</pre>'. DOKU_LF;
413    }
414
415    function file($text, $language=null, $filename=null) {
416        $this->_highlight('file',$text,$language,$filename);
417    }
418
419    function code($text, $language=null, $filename=null) {
420        $this->_highlight('code',$text,$language,$filename);
421    }
422
423    /**
424     * Use GeSHi to highlight language syntax in code and file blocks
425     *
426     * @author Andreas Gohr <andi@splitbrain.org>
427     */
428    function _highlight($type, $text, $language=null, $filename=null) {
429        global $conf;
430        global $ID;
431        global $lang;
432
433        if($filename){
434            // add icon
435            list($ext) = mimetype($filename,false);
436            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
437            $class = 'mediafile mf_'.$class;
438
439            $this->doc .= '<dl class="'.$type.'">'.DOKU_LF;
440            $this->doc .= '<dt><a href="'.exportlink($ID,'code',array('codeblock'=>$this->_codeblock)).'" title="'.$lang['download'].'" class="'.$class.'">';
441            $this->doc .= hsc($filename);
442            $this->doc .= '</a></dt>'.DOKU_LF.'<dd>';
443        }
444
445        if ($text{0} == "\n") {
446            $text = substr($text, 1);
447        }
448        if (substr($text, -1) == "\n") {
449            $text = substr($text, 0, -1);
450        }
451
452        if ( is_null($language) ) {
453            $this->doc .= '<pre class="'.$type.'">'.$this->_xmlEntities($text).'</pre>'.DOKU_LF;
454        } else {
455            $class = 'code'; //we always need the code class to make the syntax highlighting apply
456            if($type != 'code') $class .= ' '.$type;
457
458            $this->doc .= "<pre class=\"$class $language\">".p_xhtml_cached_geshi($text, $language, '').'</pre>'.DOKU_LF;
459        }
460
461        if($filename){
462            $this->doc .= '</dd></dl>'.DOKU_LF;
463        }
464
465        $this->_codeblock++;
466    }
467
468    function acronym($acronym) {
469
470        if ( array_key_exists($acronym, $this->acronyms) ) {
471
472            $title = $this->_xmlEntities($this->acronyms[$acronym]);
473
474            $this->doc .= '<acronym title="'.$title
475                .'">'.$this->_xmlEntities($acronym).'</acronym>';
476
477        } else {
478            $this->doc .= $this->_xmlEntities($acronym);
479        }
480    }
481
482    function smiley($smiley) {
483        if ( array_key_exists($smiley, $this->smileys) ) {
484            $title = $this->_xmlEntities($this->smileys[$smiley]);
485            $this->doc .= '<img src="'.DOKU_BASE.'lib/images/smileys/'.$this->smileys[$smiley].
486                '" class="middle" alt="'.
487                    $this->_xmlEntities($smiley).'" />';
488        } else {
489            $this->doc .= $this->_xmlEntities($smiley);
490        }
491    }
492
493    /*
494    * not used
495    function wordblock($word) {
496        if ( array_key_exists($word, $this->badwords) ) {
497            $this->doc .= '** BLEEP **';
498        } else {
499            $this->doc .= $this->_xmlEntities($word);
500        }
501    }
502    */
503
504    function entity($entity) {
505        if ( array_key_exists($entity, $this->entities) ) {
506            $this->doc .= $this->entities[$entity];
507        } else {
508            $this->doc .= $this->_xmlEntities($entity);
509        }
510    }
511
512    function multiplyentity($x, $y) {
513        $this->doc .= "$x&times;$y";
514    }
515
516    function singlequoteopening() {
517        global $lang;
518        $this->doc .= $lang['singlequoteopening'];
519    }
520
521    function singlequoteclosing() {
522        global $lang;
523        $this->doc .= $lang['singlequoteclosing'];
524    }
525
526    function apostrophe() {
527        global $lang;
528        $this->doc .= $lang['apostrophe'];
529    }
530
531    function doublequoteopening() {
532        global $lang;
533        $this->doc .= $lang['doublequoteopening'];
534    }
535
536    function doublequoteclosing() {
537        global $lang;
538        $this->doc .= $lang['doublequoteclosing'];
539    }
540
541    /**
542    */
543    function camelcaselink($link) {
544      $this->internallink($link,$link);
545    }
546
547
548    function locallink($hash, $name = NULL){
549        global $ID;
550        $name  = $this->_getLinkTitle($name, $hash, $isImage);
551        $hash  = $this->_headerToLink($hash);
552        $title = $ID.' &crarr;';
553        $this->doc .= '<a href="#'.$hash.'" title="'.$title.'" class="wikilink1">';
554        $this->doc .= $name;
555        $this->doc .= '</a>';
556    }
557
558    /**
559     * Render an internal Wiki Link
560     *
561     * $search,$returnonly & $linktype are not for the renderer but are used
562     * elsewhere - no need to implement them in other renderers
563     *
564     * @author Andreas Gohr <andi@splitbrain.org>
565     */
566    function internallink($id, $name = NULL, $search=NULL,$returnonly=false,$linktype='content') {
567        global $conf;
568        global $ID;
569
570        $params = '';
571        $parts = explode('?', $id, 2);
572        if (count($parts) === 2) {
573            $id = $parts[0];
574            $params = $parts[1];
575        }
576
577        // For empty $id we need to know the current $ID
578        // We need this check because _simpleTitle needs
579        // correct $id and resolve_pageid() use cleanID($id)
580        // (some things could be lost)
581        if ($id === '') {
582            $id = $ID;
583        }
584
585        // default name is based on $id as given
586        $default = $this->_simpleTitle($id);
587
588        // now first resolve and clean up the $id
589        resolve_pageid(getNS($ID),$id,$exists);
590
591        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
592        if ( !$isImage ) {
593            if ( $exists ) {
594                $class='wikilink1';
595            } else {
596                $class='wikilink2';
597                $link['rel']='nofollow';
598            }
599        } else {
600            $class='media';
601        }
602
603        //keep hash anchor
604        list($id,$hash) = explode('#',$id,2);
605        if(!empty($hash)) $hash = $this->_headerToLink($hash);
606
607        //prepare for formating
608        $link['target'] = $conf['target']['wiki'];
609        $link['style']  = '';
610        $link['pre']    = '';
611        $link['suf']    = '';
612        // highlight link to current page
613        if ($id == $ID) {
614            $link['pre']    = '<span class="curid">';
615            $link['suf']    = '</span>';
616        }
617        $link['more']   = '';
618        $link['class']  = $class;
619        $link['url']    = wl($id, $params);
620        $link['name']   = $name;
621        $link['title']  = $id;
622        //add search string
623        if($search){
624            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
625            if(is_array($search)){
626                $search = array_map('rawurlencode',$search);
627                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
628            }else{
629                $link['url'] .= 's='.rawurlencode($search);
630            }
631        }
632
633        //keep hash
634        if($hash) $link['url'].='#'.$hash;
635
636        //output formatted
637        if($returnonly){
638            return $this->_formatLink($link);
639        }else{
640            $this->doc .= $this->_formatLink($link);
641        }
642    }
643
644    function externallink($url, $name = NULL) {
645        global $conf;
646
647        $name = $this->_getLinkTitle($name, $url, $isImage);
648
649        if ( !$isImage ) {
650            $class='urlextern';
651        } else {
652            $class='media';
653        }
654
655        //prepare for formating
656        $link['target'] = $conf['target']['extern'];
657        $link['style']  = '';
658        $link['pre']    = '';
659        $link['suf']    = '';
660        $link['more']   = '';
661        $link['class']  = $class;
662        $link['url']    = $url;
663
664        $link['name']   = $name;
665        $link['title']  = $this->_xmlEntities($url);
666        if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"';
667
668        //output formatted
669        $this->doc .= $this->_formatLink($link);
670    }
671
672    /**
673    */
674    function interwikilink($match, $name = NULL, $wikiName, $wikiUri) {
675        global $conf;
676
677        $link = array();
678        $link['target'] = $conf['target']['interwiki'];
679        $link['pre']    = '';
680        $link['suf']    = '';
681        $link['more']   = '';
682        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
683
684        //get interwiki URL
685        $url = $this->_resolveInterWiki($wikiName,$wikiUri);
686
687        if ( !$isImage ) {
688            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$wikiName);
689            $link['class'] = "interwiki iw_$class";
690        } else {
691            $link['class'] = 'media';
692        }
693
694        //do we stay at the same server? Use local target
695        if( strpos($url,DOKU_URL) === 0 ){
696            $link['target'] = $conf['target']['wiki'];
697        }
698
699        $link['url'] = $url;
700        $link['title'] = htmlspecialchars($link['url']);
701
702        //output formatted
703        $this->doc .= $this->_formatLink($link);
704    }
705
706    /**
707     */
708    function windowssharelink($url, $name = NULL) {
709        global $conf;
710        global $lang;
711        //simple setup
712        $link['target'] = $conf['target']['windows'];
713        $link['pre']    = '';
714        $link['suf']   = '';
715        $link['style']  = '';
716
717        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
718        if ( !$isImage ) {
719            $link['class'] = 'windows';
720        } else {
721            $link['class'] = 'media';
722        }
723
724
725        $link['title'] = $this->_xmlEntities($url);
726        $url = str_replace('\\','/',$url);
727        $url = 'file:///'.$url;
728        $link['url'] = $url;
729
730        //output formatted
731        $this->doc .= $this->_formatLink($link);
732    }
733
734    function emaillink($address, $name = NULL) {
735        global $conf;
736        //simple setup
737        $link = array();
738        $link['target'] = '';
739        $link['pre']    = '';
740        $link['suf']   = '';
741        $link['style']  = '';
742        $link['more']   = '';
743
744        $name = $this->_getLinkTitle($name, '', $isImage);
745        if ( !$isImage ) {
746            $link['class']='mail';
747        } else {
748            $link['class']='media';
749        }
750
751        $address = $this->_xmlEntities($address);
752        $address = obfuscate($address);
753        $title   = $address;
754
755        if(empty($name)){
756            $name = $address;
757        }
758
759        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
760
761        $link['url']   = 'mailto:'.$address;
762        $link['name']  = $name;
763        $link['title'] = $title;
764
765        //output formatted
766        $this->doc .= $this->_formatLink($link);
767    }
768
769    function internalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
770                            $height=NULL, $cache=NULL, $linking=NULL) {
771        global $ID;
772        list($src,$hash) = explode('#',$src,2);
773        resolve_mediaid(getNS($ID),$src, $exists);
774
775        $noLink = false;
776        $render = ($linking == 'linkonly') ? false : true;
777        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
778
779        list($ext,$mime,$dl) = mimetype($src,false);
780        if(substr($mime,0,5) == 'image' && $render){
781            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
782        }elseif($mime == 'application/x-shockwave-flash' && $render){
783            // don't link flash movies
784            $noLink = true;
785        }else{
786            // add file icons
787            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
788            $link['class'] .= ' mediafile mf_'.$class;
789            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
790        }
791
792        if($hash) $link['url'] .= '#'.$hash;
793
794        //markup non existing files
795        if (!$exists)
796          $link['class'] .= ' wikilink2';
797
798        //output formatted
799        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
800        else $this->doc .= $this->_formatLink($link);
801    }
802
803    function externalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
804                            $height=NULL, $cache=NULL, $linking=NULL) {
805        list($src,$hash) = explode('#',$src,2);
806        $noLink = false;
807        $render = ($linking == 'linkonly') ? false : true;
808        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
809
810        $link['url']    = ml($src,array('cache'=>$cache));
811
812        list($ext,$mime,$dl) = mimetype($src,false);
813        if(substr($mime,0,5) == 'image' && $render){
814            // link only jpeg images
815            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
816        }elseif($mime == 'application/x-shockwave-flash' && $render){
817            // don't link flash movies
818            $noLink = true;
819        }else{
820            // add file icons
821            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
822            $link['class'] .= ' mediafile mf_'.$class;
823        }
824
825        if($hash) $link['url'] .= '#'.$hash;
826
827        //output formatted
828        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
829        else $this->doc .= $this->_formatLink($link);
830    }
831
832    /**
833     * Renders an RSS feed
834     *
835     * @author Andreas Gohr <andi@splitbrain.org>
836     */
837    function rss ($url,$params){
838        global $lang;
839        global $conf;
840
841        require_once(DOKU_INC.'inc/FeedParser.php');
842        $feed = new FeedParser();
843        $feed->set_feed_url($url);
844
845        //disable warning while fetching
846        if (!defined('DOKU_E_LEVEL')) { $elvl = error_reporting(E_ERROR); }
847        $rc = $feed->init();
848        if (!defined('DOKU_E_LEVEL')) { error_reporting($elvl); }
849
850        //decide on start and end
851        if($params['reverse']){
852            $mod = -1;
853            $start = $feed->get_item_quantity()-1;
854            $end   = $start - ($params['max']);
855            $end   = ($end < -1) ? -1 : $end;
856        }else{
857            $mod   = 1;
858            $start = 0;
859            $end   = $feed->get_item_quantity();
860            $end   = ($end > $params['max']) ? $params['max'] : $end;;
861        }
862
863        $this->doc .= '<ul class="rss">';
864        if($rc){
865            for ($x = $start; $x != $end; $x += $mod) {
866                $item = $feed->get_item($x);
867                $this->doc .= '<li><div class="li">';
868                // support feeds without links
869                $lnkurl = $item->get_permalink();
870                if($lnkurl){
871                    // title is escaped by SimplePie, we unescape here because it
872                    // is escaped again in externallink() FS#1705
873                    $this->externallink($item->get_permalink(),
874                                        htmlspecialchars_decode($item->get_title()));
875                }else{
876                    $this->doc .= ' '.$item->get_title();
877                }
878                if($params['author']){
879                    $author = $item->get_author(0);
880                    if($author){
881                        $name = $author->get_name();
882                        if(!$name) $name = $author->get_email();
883                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
884                    }
885                }
886                if($params['date']){
887                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
888                }
889                if($params['details']){
890                    $this->doc .= '<div class="detail">';
891                    if($conf['htmlok']){
892                        $this->doc .= $item->get_description();
893                    }else{
894                        $this->doc .= strip_tags($item->get_description());
895                    }
896                    $this->doc .= '</div>';
897                }
898
899                $this->doc .= '</div></li>';
900            }
901        }else{
902            $this->doc .= '<li><div class="li">';
903            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
904            $this->externallink($url);
905            if($conf['allowdebug']){
906                $this->doc .= '<!--'.hsc($feed->error).'-->';
907            }
908            $this->doc .= '</div></li>';
909        }
910        $this->doc .= '</ul>';
911    }
912
913    // $numrows not yet implemented
914    function table_open($maxcols = null, $numrows = null, $pos = null){
915        global $lang;
916        // initialize the row counter used for classes
917        $this->_counter['row_counter'] = 0;
918        $class = 'table';
919        if ($pos !== null) {
920            $class .= ' ' . $this->startSectionEdit($pos, 'table');
921        }
922        $this->doc .= '<div class="' . $class . '"><table class="inline">' .
923                      DOKU_LF;
924    }
925
926    function table_close($pos = null){
927        $this->doc .= '</table></div>'.DOKU_LF;
928        if ($pos !== null) {
929            $this->finishSectionEdit($pos);
930        }
931    }
932
933    function tablerow_open(){
934        // initialize the cell counter used for classes
935        $this->_counter['cell_counter'] = 0;
936        $class = 'row' . $this->_counter['row_counter']++;
937        $this->doc .= DOKU_TAB . '<tr class="'.$class.'">' . DOKU_LF . DOKU_TAB . DOKU_TAB;
938    }
939
940    function tablerow_close(){
941        $this->doc .= DOKU_LF . DOKU_TAB . '</tr>' . DOKU_LF;
942    }
943
944    function tableheader_open($colspan = 1, $align = NULL, $rowspan = 1){
945        $class = 'class="col' . $this->_counter['cell_counter']++;
946        if ( !is_null($align) ) {
947            $class .= ' '.$align.'align';
948        }
949        $class .= '"';
950        $this->doc .= '<th ' . $class;
951        if ( $colspan > 1 ) {
952            $this->_counter['cell_counter'] += $colspan-1;
953            $this->doc .= ' colspan="'.$colspan.'"';
954        }
955        if ( $rowspan > 1 ) {
956            $this->doc .= ' rowspan="'.$rowspan.'"';
957        }
958        $this->doc .= '>';
959    }
960
961    function tableheader_close(){
962        $this->doc .= '</th>';
963    }
964
965    function tablecell_open($colspan = 1, $align = NULL, $rowspan = 1){
966        $class = 'class="col' . $this->_counter['cell_counter']++;
967        if ( !is_null($align) ) {
968            $class .= ' '.$align.'align';
969        }
970        $class .= '"';
971        $this->doc .= '<td '.$class;
972        if ( $colspan > 1 ) {
973            $this->_counter['cell_counter'] += $colspan-1;
974            $this->doc .= ' colspan="'.$colspan.'"';
975        }
976        if ( $rowspan > 1 ) {
977            $this->doc .= ' rowspan="'.$rowspan.'"';
978        }
979        $this->doc .= '>';
980    }
981
982    function tablecell_close(){
983        $this->doc .= '</td>';
984    }
985
986    //----------------------------------------------------------
987    // Utils
988
989    /**
990     * Build a link
991     *
992     * Assembles all parts defined in $link returns HTML for the link
993     *
994     * @author Andreas Gohr <andi@splitbrain.org>
995     */
996    function _formatLink($link){
997        //make sure the url is XHTML compliant (skip mailto)
998        if(substr($link['url'],0,7) != 'mailto:'){
999            $link['url'] = str_replace('&','&amp;',$link['url']);
1000            $link['url'] = str_replace('&amp;amp;','&amp;',$link['url']);
1001        }
1002        //remove double encodings in titles
1003        $link['title'] = str_replace('&amp;amp;','&amp;',$link['title']);
1004
1005        // be sure there are no bad chars in url or title
1006        // (we can't do this for name because it can contain an img tag)
1007        $link['url']   = strtr($link['url'],array('>'=>'%3E','<'=>'%3C','"'=>'%22'));
1008        $link['title'] = strtr($link['title'],array('>'=>'&gt;','<'=>'&lt;','"'=>'&quot;'));
1009
1010        $ret  = '';
1011        $ret .= $link['pre'];
1012        $ret .= '<a href="'.$link['url'].'"';
1013        if(!empty($link['class']))  $ret .= ' class="'.$link['class'].'"';
1014        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1015        if(!empty($link['title']))  $ret .= ' title="'.$link['title'].'"';
1016        if(!empty($link['style']))  $ret .= ' style="'.$link['style'].'"';
1017        if(!empty($link['rel']))    $ret .= ' rel="'.$link['rel'].'"';
1018        if(!empty($link['more']))   $ret .= ' '.$link['more'];
1019        $ret .= '>';
1020        $ret .= $link['name'];
1021        $ret .= '</a>';
1022        $ret .= $link['suf'];
1023        return $ret;
1024    }
1025
1026    /**
1027     * Renders internal and external media
1028     *
1029     * @author Andreas Gohr <andi@splitbrain.org>
1030     */
1031    function _media ($src, $title=NULL, $align=NULL, $width=NULL,
1032                      $height=NULL, $cache=NULL, $render = true) {
1033
1034        $ret = '';
1035
1036        list($ext,$mime,$dl) = mimetype($src);
1037        if(substr($mime,0,5) == 'image'){
1038            // first get the $title
1039            if (!is_null($title)) {
1040                $title  = $this->_xmlEntities($title);
1041            }elseif($ext == 'jpg' || $ext == 'jpeg'){
1042                //try to use the caption from IPTC/EXIF
1043                require_once(DOKU_INC.'inc/JpegMeta.php');
1044                $jpeg =new JpegMeta(mediaFN($src));
1045                if($jpeg !== false) $cap = $jpeg->getTitle();
1046                if($cap){
1047                    $title = $this->_xmlEntities($cap);
1048                }
1049            }
1050            if (!$render) {
1051                // if the picture is not supposed to be rendered
1052                // return the title of the picture
1053                if (!$title) {
1054                    // just show the sourcename
1055                    $title = $this->_xmlEntities(basename(noNS($src)));
1056                }
1057                return $title;
1058            }
1059            //add image tag
1060            $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache)).'"';
1061            $ret .= ' class="media'.$align.'"';
1062
1063            // make left/right alignment for no-CSS view work (feeds)
1064            if($align == 'right') $ret .= ' align="right"';
1065            if($align == 'left')  $ret .= ' align="left"';
1066
1067            if ($title) {
1068                $ret .= ' title="' . $title . '"';
1069                $ret .= ' alt="'   . $title .'"';
1070            }else{
1071                $ret .= ' alt=""';
1072            }
1073
1074            if ( !is_null($width) )
1075                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1076
1077            if ( !is_null($height) )
1078                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1079
1080            $ret .= ' />';
1081
1082        }elseif($mime == 'application/x-shockwave-flash'){
1083            if (!$render) {
1084                // if the flash is not supposed to be rendered
1085                // return the title of the flash
1086                if (!$title) {
1087                    // just show the sourcename
1088                    $title = basename(noNS($src));
1089                }
1090                return $this->_xmlEntities($title);
1091            }
1092
1093            $att = array();
1094            $att['class'] = "media$align";
1095            if($align == 'right') $att['align'] = 'right';
1096            if($align == 'left')  $att['align'] = 'left';
1097            $ret .= html_flashobject(ml($src,array('cache'=>$cache),true,'&'),$width,$height,
1098                                     array('quality' => 'high'),
1099                                     null,
1100                                     $att,
1101                                     $this->_xmlEntities($title));
1102        }elseif($title){
1103            // well at least we have a title to display
1104            $ret .= $this->_xmlEntities($title);
1105        }else{
1106            // just show the sourcename
1107            $ret .= $this->_xmlEntities(basename(noNS($src)));
1108        }
1109
1110        return $ret;
1111    }
1112
1113    function _xmlEntities($string) {
1114        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
1115    }
1116
1117    /**
1118     * Creates a linkid from a headline
1119     *
1120     * @param string  $title   The headline title
1121     * @param boolean $create  Create a new unique ID?
1122     * @author Andreas Gohr <andi@splitbrain.org>
1123     */
1124    function _headerToLink($title,$create=false) {
1125        if($create){
1126            return sectionID($title,$this->headers);
1127        }else{
1128            $check = false;
1129            return sectionID($title,$check);
1130        }
1131    }
1132
1133    /**
1134     * Construct a title and handle images in titles
1135     *
1136     * @author Harry Fuecks <hfuecks@gmail.com>
1137     */
1138    function _getLinkTitle($title, $default, & $isImage, $id=NULL, $linktype='content') {
1139        global $conf;
1140
1141        $isImage = false;
1142        if ( is_array($title) ) {
1143            $isImage = true;
1144            return $this->_imageTitle($title);
1145        } elseif ( is_null($title) || trim($title)=='') {
1146            if (useHeading($linktype) && $id) {
1147                $heading = p_get_first_heading($id,true);
1148                if ($heading) {
1149                    return $this->_xmlEntities($heading);
1150                }
1151            }
1152            return $this->_xmlEntities($default);
1153        } else {
1154            return $this->_xmlEntities($title);
1155        }
1156    }
1157
1158    /**
1159     * Returns an HTML code for images used in link titles
1160     *
1161     * @todo Resolve namespace on internal images
1162     * @author Andreas Gohr <andi@splitbrain.org>
1163     */
1164    function _imageTitle($img) {
1165        global $ID;
1166
1167        // some fixes on $img['src']
1168        // see internalmedia() and externalmedia()
1169        list($img['src'],$hash) = explode('#',$img['src'],2);
1170        if ($img['type'] == 'internalmedia') {
1171            resolve_mediaid(getNS($ID),$img['src'],$exists);
1172        }
1173
1174        return $this->_media($img['src'],
1175                              $img['title'],
1176                              $img['align'],
1177                              $img['width'],
1178                              $img['height'],
1179                              $img['cache']);
1180    }
1181
1182    /**
1183     * _getMediaLinkConf is a helperfunction to internalmedia() and externalmedia()
1184     * which returns a basic link to a media.
1185     *
1186     * @author Pierre Spring <pierre.spring@liip.ch>
1187     * @param string $src
1188     * @param string $title
1189     * @param string $align
1190     * @param string $width
1191     * @param string $height
1192     * @param string $cache
1193     * @param string $render
1194     * @access protected
1195     * @return array
1196     */
1197    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render)
1198    {
1199        global $conf;
1200
1201        $link = array();
1202        $link['class']  = 'media';
1203        $link['style']  = '';
1204        $link['pre']    = '';
1205        $link['suf']    = '';
1206        $link['more']   = '';
1207        $link['target'] = $conf['target']['media'];
1208        $link['title']  = $this->_xmlEntities($src);
1209        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1210
1211        return $link;
1212    }
1213
1214
1215}
1216
1217//Setup VIM: ex: et ts=4 :
1218