xref: /dokuwiki/inc/parser/xhtml.php (revision cc01c067547239aad897eac3b3525d5437f7809b)
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
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.'" 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   $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 .= '<abbr title="'.$title
475                .'">'.$this->_xmlEntities($acronym).'</abbr>';
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="icon" 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.' ↵';
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        global $INFO;
570
571        $params = '';
572        $parts = explode('?', $id, 2);
573        if (count($parts) === 2) {
574            $id = $parts[0];
575            $params = $parts[1];
576        }
577
578        // For empty $id we need to know the current $ID
579        // We need this check because _simpleTitle needs
580        // correct $id and resolve_pageid() use cleanID($id)
581        // (some things could be lost)
582        if ($id === '') {
583            $id = $ID;
584        }
585
586        // default name is based on $id as given
587        $default = $this->_simpleTitle($id);
588
589        // now first resolve and clean up the $id
590        resolve_pageid(getNS($ID),$id,$exists);
591
592        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
593        if ( !$isImage ) {
594            if ( $exists ) {
595                $class='wikilink1';
596            } else {
597                $class='wikilink2';
598                $link['rel']='nofollow';
599            }
600        } else {
601            $class='media';
602        }
603
604        //keep hash anchor
605        list($id,$hash) = explode('#',$id,2);
606        if(!empty($hash)) $hash = $this->_headerToLink($hash);
607
608        //prepare for formating
609        $link['target'] = $conf['target']['wiki'];
610        $link['style']  = '';
611        $link['pre']    = '';
612        $link['suf']    = '';
613        // highlight link to current page
614        if ($id == $INFO['id']) {
615            $link['pre']    = '<span class="curid">';
616            $link['suf']    = '</span>';
617        }
618        $link['more']   = '';
619        $link['class']  = $class;
620        $link['url']    = wl($id, $params);
621        $link['name']   = $name;
622        $link['title']  = $id;
623        //add search string
624        if($search){
625            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
626            if(is_array($search)){
627                $search = array_map('rawurlencode',$search);
628                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
629            }else{
630                $link['url'] .= 's='.rawurlencode($search);
631            }
632        }
633
634        //keep hash
635        if($hash) $link['url'].='#'.$hash;
636
637        //output formatted
638        if($returnonly){
639            return $this->_formatLink($link);
640        }else{
641            $this->doc .= $this->_formatLink($link);
642        }
643    }
644
645    function externallink($url, $name = NULL) {
646        global $conf;
647
648        $name = $this->_getLinkTitle($name, $url, $isImage);
649
650        // url might be an attack vector, only allow registered protocols
651        if(is_null($this->schemes)) $this->schemes = getSchemes();
652        list($scheme) = explode('://',$url);
653        $scheme = strtolower($scheme);
654        if(!in_array($scheme,$this->schemes)) $url = '';
655
656        // is there still an URL?
657        if(!$url){
658            $this->doc .= $name;
659            return;
660        }
661
662        // set class
663        if ( !$isImage ) {
664            $class='urlextern';
665        } else {
666            $class='media';
667        }
668
669        //prepare for formating
670        $link['target'] = $conf['target']['extern'];
671        $link['style']  = '';
672        $link['pre']    = '';
673        $link['suf']    = '';
674        $link['more']   = '';
675        $link['class']  = $class;
676        $link['url']    = $url;
677
678        $link['name']   = $name;
679        $link['title']  = $this->_xmlEntities($url);
680        if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"';
681
682        //output formatted
683        $this->doc .= $this->_formatLink($link);
684    }
685
686    /**
687    */
688    function interwikilink($match, $name = NULL, $wikiName, $wikiUri) {
689        global $conf;
690
691        $link = array();
692        $link['target'] = $conf['target']['interwiki'];
693        $link['pre']    = '';
694        $link['suf']    = '';
695        $link['more']   = '';
696        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
697
698        //get interwiki URL
699        $url = $this->_resolveInterWiki($wikiName,$wikiUri);
700
701        if ( !$isImage ) {
702            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$wikiName);
703            $link['class'] = "interwiki iw_$class";
704        } else {
705            $link['class'] = 'media';
706        }
707
708        //do we stay at the same server? Use local target
709        if( strpos($url,DOKU_URL) === 0 ){
710            $link['target'] = $conf['target']['wiki'];
711        }
712
713        $link['url'] = $url;
714        $link['title'] = htmlspecialchars($link['url']);
715
716        //output formatted
717        $this->doc .= $this->_formatLink($link);
718    }
719
720    /**
721     */
722    function windowssharelink($url, $name = NULL) {
723        global $conf;
724        global $lang;
725        //simple setup
726        $link['target'] = $conf['target']['windows'];
727        $link['pre']    = '';
728        $link['suf']   = '';
729        $link['style']  = '';
730
731        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
732        if ( !$isImage ) {
733            $link['class'] = 'windows';
734        } else {
735            $link['class'] = 'media';
736        }
737
738
739        $link['title'] = $this->_xmlEntities($url);
740        $url = str_replace('\\','/',$url);
741        $url = 'file:///'.$url;
742        $link['url'] = $url;
743
744        //output formatted
745        $this->doc .= $this->_formatLink($link);
746    }
747
748    function emaillink($address, $name = NULL) {
749        global $conf;
750        //simple setup
751        $link = array();
752        $link['target'] = '';
753        $link['pre']    = '';
754        $link['suf']   = '';
755        $link['style']  = '';
756        $link['more']   = '';
757
758        $name = $this->_getLinkTitle($name, '', $isImage);
759        if ( !$isImage ) {
760            $link['class']='mail';
761        } else {
762            $link['class']='media';
763        }
764
765        $address = $this->_xmlEntities($address);
766        $address = obfuscate($address);
767        $title   = $address;
768
769        if(empty($name)){
770            $name = $address;
771        }
772
773        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
774
775        $link['url']   = 'mailto:'.$address;
776        $link['name']  = $name;
777        $link['title'] = $title;
778
779        //output formatted
780        $this->doc .= $this->_formatLink($link);
781    }
782
783    function internalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
784                            $height=NULL, $cache=NULL, $linking=NULL) {
785        global $ID;
786        list($src,$hash) = explode('#',$src,2);
787        resolve_mediaid(getNS($ID),$src, $exists);
788
789        $noLink = false;
790        $render = ($linking == 'linkonly') ? false : true;
791        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
792
793        list($ext,$mime,$dl) = mimetype($src,false);
794        if(substr($mime,0,5) == 'image' && $render){
795            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
796        }elseif($mime == 'application/x-shockwave-flash' && $render){
797            // don't link flash movies
798            $noLink = true;
799        }else{
800            // add file icons
801            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
802            $link['class'] .= ' mediafile mf_'.$class;
803            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
804        }
805
806        if($hash) $link['url'] .= '#'.$hash;
807
808        //markup non existing files
809        if (!$exists) {
810            $link['class'] .= ' wikilink2';
811        }
812
813        //output formatted
814        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
815        else $this->doc .= $this->_formatLink($link);
816    }
817
818    function externalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
819                            $height=NULL, $cache=NULL, $linking=NULL) {
820        list($src,$hash) = explode('#',$src,2);
821        $noLink = false;
822        $render = ($linking == 'linkonly') ? false : true;
823        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
824
825        $link['url']    = ml($src,array('cache'=>$cache));
826
827        list($ext,$mime,$dl) = mimetype($src,false);
828        if(substr($mime,0,5) == 'image' && $render){
829            // link only jpeg images
830            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
831        }elseif($mime == 'application/x-shockwave-flash' && $render){
832            // don't link flash movies
833            $noLink = true;
834        }else{
835            // add file icons
836            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
837            $link['class'] .= ' mediafile mf_'.$class;
838        }
839
840        if($hash) $link['url'] .= '#'.$hash;
841
842        //output formatted
843        if ($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
844        else $this->doc .= $this->_formatLink($link);
845    }
846
847    /**
848     * Renders an RSS feed
849     *
850     * @author Andreas Gohr <andi@splitbrain.org>
851     */
852    function rss ($url,$params){
853        global $lang;
854        global $conf;
855
856        require_once(DOKU_INC.'inc/FeedParser.php');
857        $feed = new FeedParser();
858        $feed->set_feed_url($url);
859
860        //disable warning while fetching
861        if (!defined('DOKU_E_LEVEL')) { $elvl = error_reporting(E_ERROR); }
862        $rc = $feed->init();
863        if (!defined('DOKU_E_LEVEL')) { error_reporting($elvl); }
864
865        //decide on start and end
866        if($params['reverse']){
867            $mod = -1;
868            $start = $feed->get_item_quantity()-1;
869            $end   = $start - ($params['max']);
870            $end   = ($end < -1) ? -1 : $end;
871        }else{
872            $mod   = 1;
873            $start = 0;
874            $end   = $feed->get_item_quantity();
875            $end   = ($end > $params['max']) ? $params['max'] : $end;;
876        }
877
878        $this->doc .= '<ul class="rss">';
879        if($rc){
880            for ($x = $start; $x != $end; $x += $mod) {
881                $item = $feed->get_item($x);
882                $this->doc .= '<li><div class="li">';
883                // support feeds without links
884                $lnkurl = $item->get_permalink();
885                if($lnkurl){
886                    // title is escaped by SimplePie, we unescape here because it
887                    // is escaped again in externallink() FS#1705
888                    $this->externallink($item->get_permalink(),
889                                        htmlspecialchars_decode($item->get_title()));
890                }else{
891                    $this->doc .= ' '.$item->get_title();
892                }
893                if($params['author']){
894                    $author = $item->get_author(0);
895                    if($author){
896                        $name = $author->get_name();
897                        if(!$name) $name = $author->get_email();
898                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
899                    }
900                }
901                if($params['date']){
902                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
903                }
904                if($params['details']){
905                    $this->doc .= '<div class="detail">';
906                    if($conf['htmlok']){
907                        $this->doc .= $item->get_description();
908                    }else{
909                        $this->doc .= strip_tags($item->get_description());
910                    }
911                    $this->doc .= '</div>';
912                }
913
914                $this->doc .= '</div></li>';
915            }
916        }else{
917            $this->doc .= '<li><div class="li">';
918            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
919            $this->externallink($url);
920            if($conf['allowdebug']){
921                $this->doc .= '<!--'.hsc($feed->error).'-->';
922            }
923            $this->doc .= '</div></li>';
924        }
925        $this->doc .= '</ul>';
926    }
927
928    // $numrows not yet implemented
929    function table_open($maxcols = null, $numrows = null, $pos = null){
930        global $lang;
931        // initialize the row counter used for classes
932        $this->_counter['row_counter'] = 0;
933        $class = 'table';
934        if ($pos !== null) {
935            $class .= ' ' . $this->startSectionEdit($pos, 'table');
936        }
937        $this->doc .= '<div class="' . $class . '"><table class="inline">' .
938                      DOKU_LF;
939    }
940
941    function table_close($pos = null){
942        $this->doc .= '</table></div>'.DOKU_LF;
943        if ($pos !== null) {
944            $this->finishSectionEdit($pos);
945        }
946    }
947
948    function tablerow_open(){
949        // initialize the cell counter used for classes
950        $this->_counter['cell_counter'] = 0;
951        $class = 'row' . $this->_counter['row_counter']++;
952        $this->doc .= DOKU_TAB . '<tr class="'.$class.'">' . DOKU_LF . DOKU_TAB . DOKU_TAB;
953    }
954
955    function tablerow_close(){
956        $this->doc .= DOKU_LF . DOKU_TAB . '</tr>' . DOKU_LF;
957    }
958
959    function tableheader_open($colspan = 1, $align = NULL, $rowspan = 1){
960        $class = 'class="col' . $this->_counter['cell_counter']++;
961        if ( !is_null($align) ) {
962            $class .= ' '.$align.'align';
963        }
964        $class .= '"';
965        $this->doc .= '<th ' . $class;
966        if ( $colspan > 1 ) {
967            $this->_counter['cell_counter'] += $colspan-1;
968            $this->doc .= ' colspan="'.$colspan.'"';
969        }
970        if ( $rowspan > 1 ) {
971            $this->doc .= ' rowspan="'.$rowspan.'"';
972        }
973        $this->doc .= '>';
974    }
975
976    function tableheader_close(){
977        $this->doc .= '</th>';
978    }
979
980    function tablecell_open($colspan = 1, $align = NULL, $rowspan = 1){
981        $class = 'class="col' . $this->_counter['cell_counter']++;
982        if ( !is_null($align) ) {
983            $class .= ' '.$align.'align';
984        }
985        $class .= '"';
986        $this->doc .= '<td '.$class;
987        if ( $colspan > 1 ) {
988            $this->_counter['cell_counter'] += $colspan-1;
989            $this->doc .= ' colspan="'.$colspan.'"';
990        }
991        if ( $rowspan > 1 ) {
992            $this->doc .= ' rowspan="'.$rowspan.'"';
993        }
994        $this->doc .= '>';
995    }
996
997    function tablecell_close(){
998        $this->doc .= '</td>';
999    }
1000
1001    //----------------------------------------------------------
1002    // Utils
1003
1004    /**
1005     * Build a link
1006     *
1007     * Assembles all parts defined in $link returns HTML for the link
1008     *
1009     * @author Andreas Gohr <andi@splitbrain.org>
1010     */
1011    function _formatLink($link){
1012        //make sure the url is XHTML compliant (skip mailto)
1013        if(substr($link['url'],0,7) != 'mailto:'){
1014            $link['url'] = str_replace('&','&amp;',$link['url']);
1015            $link['url'] = str_replace('&amp;amp;','&amp;',$link['url']);
1016        }
1017        //remove double encodings in titles
1018        $link['title'] = str_replace('&amp;amp;','&amp;',$link['title']);
1019
1020        // be sure there are no bad chars in url or title
1021        // (we can't do this for name because it can contain an img tag)
1022        $link['url']   = strtr($link['url'],array('>'=>'%3E','<'=>'%3C','"'=>'%22'));
1023        $link['title'] = strtr($link['title'],array('>'=>'&gt;','<'=>'&lt;','"'=>'&quot;'));
1024
1025        $ret  = '';
1026        $ret .= $link['pre'];
1027        $ret .= '<a href="'.$link['url'].'"';
1028        if(!empty($link['class']))  $ret .= ' class="'.$link['class'].'"';
1029        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1030        if(!empty($link['title']))  $ret .= ' title="'.$link['title'].'"';
1031        if(!empty($link['style']))  $ret .= ' style="'.$link['style'].'"';
1032        if(!empty($link['rel']))    $ret .= ' rel="'.$link['rel'].'"';
1033        if(!empty($link['more']))   $ret .= ' '.$link['more'];
1034        $ret .= '>';
1035        $ret .= $link['name'];
1036        $ret .= '</a>';
1037        $ret .= $link['suf'];
1038        return $ret;
1039    }
1040
1041    /**
1042     * Renders internal and external media
1043     *
1044     * @author Andreas Gohr <andi@splitbrain.org>
1045     */
1046    function _media ($src, $title=NULL, $align=NULL, $width=NULL,
1047                      $height=NULL, $cache=NULL, $render = true) {
1048
1049        $ret = '';
1050
1051        list($ext,$mime,$dl) = mimetype($src);
1052        if(substr($mime,0,5) == 'image'){
1053            // first get the $title
1054            if (!is_null($title)) {
1055                $title  = $this->_xmlEntities($title);
1056            }elseif($ext == 'jpg' || $ext == 'jpeg'){
1057                //try to use the caption from IPTC/EXIF
1058                require_once(DOKU_INC.'inc/JpegMeta.php');
1059                $jpeg =new JpegMeta(mediaFN($src));
1060                if($jpeg !== false) $cap = $jpeg->getTitle();
1061                if($cap){
1062                    $title = $this->_xmlEntities($cap);
1063                }
1064            }
1065            if (!$render) {
1066                // if the picture is not supposed to be rendered
1067                // return the title of the picture
1068                if (!$title) {
1069                    // just show the sourcename
1070                    $title = $this->_xmlEntities(basename(noNS($src)));
1071                }
1072                return $title;
1073            }
1074            //add image tag
1075            $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache)).'"';
1076            $ret .= ' class="media'.$align.'"';
1077
1078            if ($title) {
1079                $ret .= ' title="' . $title . '"';
1080                $ret .= ' alt="'   . $title .'"';
1081            }else{
1082                $ret .= ' alt=""';
1083            }
1084
1085            if ( !is_null($width) )
1086                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1087
1088            if ( !is_null($height) )
1089                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1090
1091            $ret .= ' />';
1092
1093        }elseif($mime == 'application/x-shockwave-flash'){
1094            if (!$render) {
1095                // if the flash is not supposed to be rendered
1096                // return the title of the flash
1097                if (!$title) {
1098                    // just show the sourcename
1099                    $title = basename(noNS($src));
1100                }
1101                return $this->_xmlEntities($title);
1102            }
1103
1104            $att = array();
1105            $att['class'] = "media$align";
1106            if($align == 'right') $att['align'] = 'right';
1107            if($align == 'left')  $att['align'] = 'left';
1108            $ret .= html_flashobject(ml($src,array('cache'=>$cache),true,'&'),$width,$height,
1109                                     array('quality' => 'high'),
1110                                     null,
1111                                     $att,
1112                                     $this->_xmlEntities($title));
1113        }elseif($title){
1114            // well at least we have a title to display
1115            $ret .= $this->_xmlEntities($title);
1116        }else{
1117            // just show the sourcename
1118            $ret .= $this->_xmlEntities(basename(noNS($src)));
1119        }
1120
1121        return $ret;
1122    }
1123
1124    function _xmlEntities($string) {
1125        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
1126    }
1127
1128    /**
1129     * Creates a linkid from a headline
1130     *
1131     * @param string  $title   The headline title
1132     * @param boolean $create  Create a new unique ID?
1133     * @author Andreas Gohr <andi@splitbrain.org>
1134     */
1135    function _headerToLink($title,$create=false) {
1136        if($create){
1137            return sectionID($title,$this->headers);
1138        }else{
1139            $check = false;
1140            return sectionID($title,$check);
1141        }
1142    }
1143
1144    /**
1145     * Construct a title and handle images in titles
1146     *
1147     * @author Harry Fuecks <hfuecks@gmail.com>
1148     */
1149    function _getLinkTitle($title, $default, & $isImage, $id=NULL, $linktype='content') {
1150        global $conf;
1151
1152        $isImage = false;
1153        if ( is_array($title) ) {
1154            $isImage = true;
1155            return $this->_imageTitle($title);
1156        } elseif ( is_null($title) || trim($title)=='') {
1157            if (useHeading($linktype) && $id) {
1158                $heading = p_get_first_heading($id);
1159                if ($heading) {
1160                    return $this->_xmlEntities($heading);
1161                }
1162            }
1163            return $this->_xmlEntities($default);
1164        } else {
1165            return $this->_xmlEntities($title);
1166        }
1167    }
1168
1169    /**
1170     * Returns an HTML code for images used in link titles
1171     *
1172     * @todo Resolve namespace on internal images
1173     * @author Andreas Gohr <andi@splitbrain.org>
1174     */
1175    function _imageTitle($img) {
1176        global $ID;
1177
1178        // some fixes on $img['src']
1179        // see internalmedia() and externalmedia()
1180        list($img['src'],$hash) = explode('#',$img['src'],2);
1181        if ($img['type'] == 'internalmedia') {
1182            resolve_mediaid(getNS($ID),$img['src'],$exists);
1183        }
1184
1185        return $this->_media($img['src'],
1186                              $img['title'],
1187                              $img['align'],
1188                              $img['width'],
1189                              $img['height'],
1190                              $img['cache']);
1191    }
1192
1193    /**
1194     * _getMediaLinkConf is a helperfunction to internalmedia() and externalmedia()
1195     * which returns a basic link to a media.
1196     *
1197     * @author Pierre Spring <pierre.spring@liip.ch>
1198     * @param string $src
1199     * @param string $title
1200     * @param string $align
1201     * @param string $width
1202     * @param string $height
1203     * @param string $cache
1204     * @param string $render
1205     * @access protected
1206     * @return array
1207     */
1208    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render)
1209    {
1210        global $conf;
1211
1212        $link = array();
1213        $link['class']  = 'media';
1214        $link['style']  = '';
1215        $link['pre']    = '';
1216        $link['suf']    = '';
1217        $link['more']   = '';
1218        $link['target'] = $conf['target']['media'];
1219        $link['title']  = $this->_xmlEntities($src);
1220        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1221
1222        return $link;
1223    }
1224
1225
1226}
1227
1228//Setup VIM: ex: et ts=4 :
1229