xref: /dokuwiki/inc/parser/xhtml.php (revision b52b15965611fc865058c0331b55e4e9bccabd2e)
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    private $schemes = null; // protocol schemes
44
45    /**
46     * Register a new edit section range
47     *
48     * @param $type  string The section type identifier
49     * @param $title string The section title
50     * @param $start int    The byte position for the edit start
51     * @return string A marker class for the starting HTML element
52     * @author Adrian Lang <lang@cosmocode.de>
53     */
54    public function startSectionEdit($start, $type, $title = null) {
55        static $lastsecid = 0;
56        $this->sectionedits[] = array(++$lastsecid, $start, $type, $title);
57        return 'sectionedit' . $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            $id = 0;
106            foreach ( $this->footnotes as $footnote ) {
107                $id++;   // the number of the current footnote
108
109                // check its not a placeholder that indicates actual footnote text is elsewhere
110                if (substr($footnote, 0, 5) != "@@FNT") {
111
112                    // open the footnote and set the anchor and backlink
113                    $this->doc .= '<div class="fn">';
114                    $this->doc .= '<sup><a href="#fnt__'.$id.'" id="fn__'.$id.'" name="fn__'.$id.'" class="fn_bot">';
115                    $this->doc .= $id.')</a></sup> '.DOKU_LF;
116
117                    // get any other footnotes that use the same markup
118                    $alt = array_keys($this->footnotes, "@@FNT$id");
119
120                    if (count($alt)) {
121                      foreach ($alt as $ref) {
122                        // set anchor and backlink for the other footnotes
123                        $this->doc .= ', <sup><a href="#fnt__'.($ref+1).'" id="fn__'.($ref+1).'" name="fn__'.($ref+1).'" class="fn_bot">';
124                        $this->doc .= ($ref+1).')</a></sup> '.DOKU_LF;
125                      }
126                    }
127
128                    // add footnote markup and close this footnote
129                    $this->doc .= $footnote;
130                    $this->doc .= '</div>' . DOKU_LF;
131                }
132            }
133            $this->doc .= '</div>'.DOKU_LF;
134        }
135
136        // Prepare the TOC
137        global $conf;
138        if($this->info['toc'] && is_array($this->toc) && $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads']){
139            global $TOC;
140            $TOC = $this->toc;
141        }
142
143        // make sure there are no empty paragraphs
144        $this->doc = preg_replace('#<p>\s*</p>#','',$this->doc);
145    }
146
147    function toc_additem($id, $text, $level) {
148        global $conf;
149
150        //handle TOC
151        if($level >= $conf['toptoclevel'] && $level <= $conf['maxtoclevel']){
152            $this->toc[] = html_mktocitem($id, $text, $level-$conf['toptoclevel']+1);
153        }
154    }
155
156    function header($text, $level, $pos) {
157        global $conf;
158
159        if(!$text) return; //skip empty headlines
160
161        $hid = $this->_headerToLink($text,true);
162
163        //only add items within configured levels
164        $this->toc_additem($hid, $text, $level);
165
166        // adjust $node to reflect hierarchy of levels
167        $this->node[$level-1]++;
168        if ($level < $this->lastlevel) {
169            for ($i = 0; $i < $this->lastlevel-$level; $i++) {
170                $this->node[$this->lastlevel-$i-1] = 0;
171            }
172        }
173        $this->lastlevel = $level;
174
175        if ($level <= $conf['maxseclevel'] &&
176            count($this->sectionedits) > 0 &&
177            $this->sectionedits[count($this->sectionedits) - 1][2] === 'section') {
178            $this->finishSectionEdit($pos - 1);
179        }
180
181        // write the header
182        $this->doc .= DOKU_LF.'<h'.$level;
183        if ($level <= $conf['maxseclevel']) {
184            $this->doc .= ' class="' . $this->startSectionEdit($pos, 'section', $text) . '"';
185        }
186        $this->doc .= '><a name="'.$hid.'" id="'.$hid.'">';
187        $this->doc .= $this->_xmlEntities($text);
188        $this->doc .= "</a></h$level>".DOKU_LF;
189    }
190
191    function section_open($level) {
192        $this->doc .= '<div class="level' . $level . '">' . DOKU_LF;
193    }
194
195    function section_close() {
196        $this->doc .= DOKU_LF.'</div>'.DOKU_LF;
197    }
198
199    function cdata($text) {
200        $this->doc .= $this->_xmlEntities($text);
201    }
202
203    function p_open() {
204        $this->doc .= DOKU_LF.'<p>'.DOKU_LF;
205    }
206
207    function p_close() {
208        $this->doc .= DOKU_LF.'</p>'.DOKU_LF;
209    }
210
211    function linebreak() {
212        $this->doc .= '<br/>'.DOKU_LF;
213    }
214
215    function hr() {
216        $this->doc .= '<hr />'.DOKU_LF;
217    }
218
219    function strong_open() {
220        $this->doc .= '<strong>';
221    }
222
223    function strong_close() {
224        $this->doc .= '</strong>';
225    }
226
227    function emphasis_open() {
228        $this->doc .= '<em>';
229    }
230
231    function emphasis_close() {
232        $this->doc .= '</em>';
233    }
234
235    function underline_open() {
236        $this->doc .= '<em class="u">';
237    }
238
239    function underline_close() {
240        $this->doc .= '</em>';
241    }
242
243    function monospace_open() {
244        $this->doc .= '<code>';
245    }
246
247    function monospace_close() {
248        $this->doc .= '</code>';
249    }
250
251    function subscript_open() {
252        $this->doc .= '<sub>';
253    }
254
255    function subscript_close() {
256        $this->doc .= '</sub>';
257    }
258
259    function superscript_open() {
260        $this->doc .= '<sup>';
261    }
262
263    function superscript_close() {
264        $this->doc .= '</sup>';
265    }
266
267    function deleted_open() {
268        $this->doc .= '<del>';
269    }
270
271    function deleted_close() {
272        $this->doc .= '</del>';
273    }
274
275    /**
276     * Callback for footnote start syntax
277     *
278     * All following content will go to the footnote instead of
279     * the document. To achieve this the previous rendered content
280     * is moved to $store and $doc is cleared
281     *
282     * @author Andreas Gohr <andi@splitbrain.org>
283     */
284    function footnote_open() {
285
286        // move current content to store and record footnote
287        $this->store = $this->doc;
288        $this->doc   = '';
289    }
290
291    /**
292     * Callback for footnote end syntax
293     *
294     * All rendered content is moved to the $footnotes array and the old
295     * content is restored from $store again
296     *
297     * @author Andreas Gohr
298     */
299    function footnote_close() {
300
301        // recover footnote into the stack and restore old content
302        $footnote = $this->doc;
303        $this->doc = $this->store;
304        $this->store = '';
305
306        // check to see if this footnote has been seen before
307        $i = array_search($footnote, $this->footnotes);
308
309        if ($i === false) {
310            // its a new footnote, add it to the $footnotes array
311            $id = count($this->footnotes)+1;
312            $this->footnotes[count($this->footnotes)] = $footnote;
313        } else {
314            // seen this one before, translate the index to an id and save a placeholder
315            $i++;
316            $id = count($this->footnotes)+1;
317            $this->footnotes[count($this->footnotes)] = "@@FNT".($i);
318        }
319
320        // output the footnote reference and link
321        $this->doc .= '<sup><a href="#fn__'.$id.'" name="fnt__'.$id.'" id="fnt__'.$id.'" class="fn_top">'.$id.')</a></sup>';
322    }
323
324    function listu_open() {
325        $this->doc .= '<ul>'.DOKU_LF;
326    }
327
328    function listu_close() {
329        $this->doc .= '</ul>'.DOKU_LF;
330    }
331
332    function listo_open() {
333        $this->doc .= '<ol>'.DOKU_LF;
334    }
335
336    function listo_close() {
337        $this->doc .= '</ol>'.DOKU_LF;
338    }
339
340    function listitem_open($level) {
341        $this->doc .= '<li class="level'.$level.'">';
342    }
343
344    function listitem_close() {
345        $this->doc .= '</li>'.DOKU_LF;
346    }
347
348    function listcontent_open() {
349        $this->doc .= '<div class="li">';
350    }
351
352    function listcontent_close() {
353        $this->doc .= '</div>'.DOKU_LF;
354    }
355
356    function unformatted($text) {
357        $this->doc .= $this->_xmlEntities($text);
358    }
359
360    /**
361     * Execute PHP code if allowed
362     *
363     * @param  string   $wrapper   html element to wrap result if $conf['phpok'] is okff
364     *
365     * @author Andreas Gohr <andi@splitbrain.org>
366     */
367    function php($text, $wrapper='code') {
368        global $conf;
369
370        if($conf['phpok']){
371          ob_start();
372          eval($text);
373          $this->doc .= ob_get_contents();
374          ob_end_clean();
375        } else {
376          $this->doc .= p_xhtml_cached_geshi($text, 'php', $wrapper);
377        }
378    }
379
380    function phpblock($text) {
381        $this->php($text, 'pre');
382    }
383
384    /**
385     * Insert HTML if allowed
386     *
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 .= '<acronym title="'.$title
477                .'">'.$this->_xmlEntities($acronym).'</acronym>';
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="middle" 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.' &crarr;';
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
572        $params = '';
573        $parts = explode('?', $id, 2);
574        if (count($parts) === 2) {
575            $id = $parts[0];
576            $params = $parts[1];
577        }
578
579        // For empty $id we need to know the current $ID
580        // We need this check because _simpleTitle needs
581        // correct $id and resolve_pageid() use cleanID($id)
582        // (some things could be lost)
583        if ($id === '') {
584            $id = $ID;
585        }
586
587        // default name is based on $id as given
588        $default = $this->_simpleTitle($id);
589
590        // now first resolve and clean up the $id
591        resolve_pageid(getNS($ID),$id,$exists);
592
593        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
594        if ( !$isImage ) {
595            if ( $exists ) {
596                $class='wikilink1';
597            } else {
598                $class='wikilink2';
599                $link['rel']='nofollow';
600            }
601        } else {
602            $class='media';
603        }
604
605        //keep hash anchor
606        list($id,$hash) = explode('#',$id,2);
607        if(!empty($hash)) $hash = $this->_headerToLink($hash);
608
609        //prepare for formating
610        $link['target'] = $conf['target']['wiki'];
611        $link['style']  = '';
612        $link['pre']    = '';
613        $link['suf']    = '';
614        // highlight link to current page
615        if ($id == $ID) {
616            $link['pre']    = '<span class="curid">';
617            $link['suf']    = '</span>';
618        }
619        $link['more']   = '';
620        $link['class']  = $class;
621        $link['url']    = wl($id, $params);
622        $link['name']   = $name;
623        $link['title']  = $id;
624        //add search string
625        if($search){
626            ($conf['userewrite']) ? $link['url'].='?' : $link['url'].='&amp;';
627            if(is_array($search)){
628                $search = array_map('rawurlencode',$search);
629                $link['url'] .= 's[]='.join('&amp;s[]=',$search);
630            }else{
631                $link['url'] .= 's='.rawurlencode($search);
632            }
633        }
634
635        //keep hash
636        if($hash) $link['url'].='#'.$hash;
637
638        //output formatted
639        if($returnonly){
640            return $this->_formatLink($link);
641        }else{
642            $this->doc .= $this->_formatLink($link);
643        }
644    }
645
646    function externallink($url, $name = NULL) {
647        global $conf;
648
649        $name = $this->_getLinkTitle($name, $url, $isImage);
650
651        // url might be an attack vector, only allow registered protocols
652        if(is_null($this->schemes)) $this->schemes = getSchemes();
653        list($scheme) = explode('://',$url);
654        $scheme = strtolower($scheme);
655        if(!in_array($scheme,$this->schemes)) $url = '';
656
657        // is there still an URL?
658        if(!$url){
659            $this->doc .= $name;
660            return;
661        }
662
663        // set class
664        if ( !$isImage ) {
665            $class='urlextern';
666        } else {
667            $class='media';
668        }
669
670        //prepare for formating
671        $link['target'] = $conf['target']['extern'];
672        $link['style']  = '';
673        $link['pre']    = '';
674        $link['suf']    = '';
675        $link['more']   = '';
676        $link['class']  = $class;
677        $link['url']    = $url;
678
679        $link['name']   = $name;
680        $link['title']  = $this->_xmlEntities($url);
681        if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"';
682
683        //output formatted
684        $this->doc .= $this->_formatLink($link);
685    }
686
687    /**
688    */
689    function interwikilink($match, $name = NULL, $wikiName, $wikiUri) {
690        global $conf;
691
692        $link = array();
693        $link['target'] = $conf['target']['interwiki'];
694        $link['pre']    = '';
695        $link['suf']    = '';
696        $link['more']   = '';
697        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
698
699        //get interwiki URL
700        $url = $this->_resolveInterWiki($wikiName,$wikiUri);
701
702        if ( !$isImage ) {
703            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$wikiName);
704            $link['class'] = "interwiki iw_$class";
705        } else {
706            $link['class'] = 'media';
707        }
708
709        //do we stay at the same server? Use local target
710        if( strpos($url,DOKU_URL) === 0 ){
711            $link['target'] = $conf['target']['wiki'];
712        }
713
714        $link['url'] = $url;
715        $link['title'] = htmlspecialchars($link['url']);
716
717        //output formatted
718        $this->doc .= $this->_formatLink($link);
719    }
720
721    /**
722     */
723    function windowssharelink($url, $name = NULL) {
724        global $conf;
725        global $lang;
726        //simple setup
727        $link['target'] = $conf['target']['windows'];
728        $link['pre']    = '';
729        $link['suf']   = '';
730        $link['style']  = '';
731
732        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
733        if ( !$isImage ) {
734            $link['class'] = 'windows';
735        } else {
736            $link['class'] = 'media';
737        }
738
739
740        $link['title'] = $this->_xmlEntities($url);
741        $url = str_replace('\\','/',$url);
742        $url = 'file:///'.$url;
743        $link['url'] = $url;
744
745        //output formatted
746        $this->doc .= $this->_formatLink($link);
747    }
748
749    function emaillink($address, $name = NULL) {
750        global $conf;
751        //simple setup
752        $link = array();
753        $link['target'] = '';
754        $link['pre']    = '';
755        $link['suf']   = '';
756        $link['style']  = '';
757        $link['more']   = '';
758
759        $name = $this->_getLinkTitle($name, '', $isImage);
760        if ( !$isImage ) {
761            $link['class']='mail';
762        } else {
763            $link['class']='media';
764        }
765
766        $address = $this->_xmlEntities($address);
767        $address = obfuscate($address);
768        $title   = $address;
769
770        if(empty($name)){
771            $name = $address;
772        }
773
774        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
775
776        $link['url']   = 'mailto:'.$address;
777        $link['name']  = $name;
778        $link['title'] = $title;
779
780        //output formatted
781        $this->doc .= $this->_formatLink($link);
782    }
783
784    function internalmedia ($src, $title=NULL, $align=NULL, $width=NULL,
785                            $height=NULL, $cache=NULL, $linking=NULL) {
786        global $ID;
787        list($src,$hash) = explode('#',$src,2);
788        resolve_mediaid(getNS($ID),$src, $exists);
789
790        $noLink = false;
791        $render = ($linking == 'linkonly') ? false : true;
792        $link = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
793
794        list($ext,$mime,$dl) = mimetype($src,false);
795        if(substr($mime,0,5) == 'image' && $render){
796            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
797        }elseif($mime == 'application/x-shockwave-flash' && $render){
798            // don't link flash movies
799            $noLink = true;
800        }else{
801            // add file icons
802            $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
803            $link['class'] .= ' mediafile mf_'.$class;
804            $link['url'] = ml($src,array('id'=>$ID,'cache'=>$cache),true);
805        }
806
807        if($hash) $link['url'] .= '#'.$hash;
808
809        //markup non existing files
810        if (!$exists)
811          $link['class'] .= ' wikilink2';
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                    // lnkurl might be an attack vector, only allow registered protocols
887                    if(is_null($this->schemes)) $this->schemes = getSchemes();
888                    list($scheme) = explode('://',$lnkurl);
889                    $scheme = strtolower($scheme);
890                    if(!in_array($scheme,$this->schemes)) $lnkurl = '';
891                }
892
893                if($lnkurl){
894                    // title is escaped by SimplePie, we unescape here because it
895                    // is escaped again in externallink() FS#1705
896                    $this->externallink($item->get_permalink(),
897                                        htmlspecialchars_decode($item->get_title()));
898                }else{
899                    $this->doc .= ' '.$item->get_title();
900                }
901                if($params['author']){
902                    $author = $item->get_author(0);
903                    if($author){
904                        $name = $author->get_name();
905                        if(!$name) $name = $author->get_email();
906                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
907                    }
908                }
909                if($params['date']){
910                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
911                }
912                if($params['details']){
913                    $this->doc .= '<div class="detail">';
914                    if($conf['htmlok']){
915                        $this->doc .= $item->get_description();
916                    }else{
917                        $this->doc .= strip_tags($item->get_description());
918                    }
919                    $this->doc .= '</div>';
920                }
921
922                $this->doc .= '</div></li>';
923            }
924        }else{
925            $this->doc .= '<li><div class="li">';
926            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
927            $this->externallink($url);
928            if($conf['allowdebug']){
929                $this->doc .= '<!--'.hsc($feed->error).'-->';
930            }
931            $this->doc .= '</div></li>';
932        }
933        $this->doc .= '</ul>';
934    }
935
936    // $numrows not yet implemented
937    function table_open($maxcols = null, $numrows = null, $pos = null){
938        global $lang;
939        // initialize the row counter used for classes
940        $this->_counter['row_counter'] = 0;
941        $class = 'table';
942        if ($pos !== null) {
943            $class .= ' ' . $this->startSectionEdit($pos, 'table');
944        }
945        $this->doc .= '<div class="' . $class . '"><table class="inline">' .
946                      DOKU_LF;
947    }
948
949    function table_close($pos = null){
950        $this->doc .= '</table></div>'.DOKU_LF;
951        if ($pos !== null) {
952            $this->finishSectionEdit($pos);
953        }
954    }
955
956    function tablerow_open(){
957        // initialize the cell counter used for classes
958        $this->_counter['cell_counter'] = 0;
959        $class = 'row' . $this->_counter['row_counter']++;
960        $this->doc .= DOKU_TAB . '<tr class="'.$class.'">' . DOKU_LF . DOKU_TAB . DOKU_TAB;
961    }
962
963    function tablerow_close(){
964        $this->doc .= DOKU_LF . DOKU_TAB . '</tr>' . DOKU_LF;
965    }
966
967    function tableheader_open($colspan = 1, $align = NULL, $rowspan = 1){
968        $class = 'class="col' . $this->_counter['cell_counter']++;
969        if ( !is_null($align) ) {
970            $class .= ' '.$align.'align';
971        }
972        $class .= '"';
973        $this->doc .= '<th ' . $class;
974        if ( $colspan > 1 ) {
975            $this->_counter['cell_counter'] += $colspan-1;
976            $this->doc .= ' colspan="'.$colspan.'"';
977        }
978        if ( $rowspan > 1 ) {
979            $this->doc .= ' rowspan="'.$rowspan.'"';
980        }
981        $this->doc .= '>';
982    }
983
984    function tableheader_close(){
985        $this->doc .= '</th>';
986    }
987
988    function tablecell_open($colspan = 1, $align = NULL, $rowspan = 1){
989        $class = 'class="col' . $this->_counter['cell_counter']++;
990        if ( !is_null($align) ) {
991            $class .= ' '.$align.'align';
992        }
993        $class .= '"';
994        $this->doc .= '<td '.$class;
995        if ( $colspan > 1 ) {
996            $this->_counter['cell_counter'] += $colspan-1;
997            $this->doc .= ' colspan="'.$colspan.'"';
998        }
999        if ( $rowspan > 1 ) {
1000            $this->doc .= ' rowspan="'.$rowspan.'"';
1001        }
1002        $this->doc .= '>';
1003    }
1004
1005    function tablecell_close(){
1006        $this->doc .= '</td>';
1007    }
1008
1009    //----------------------------------------------------------
1010    // Utils
1011
1012    /**
1013     * Build a link
1014     *
1015     * Assembles all parts defined in $link returns HTML for the link
1016     *
1017     * @author Andreas Gohr <andi@splitbrain.org>
1018     */
1019    function _formatLink($link){
1020        //make sure the url is XHTML compliant (skip mailto)
1021        if(substr($link['url'],0,7) != 'mailto:'){
1022            $link['url'] = str_replace('&','&amp;',$link['url']);
1023            $link['url'] = str_replace('&amp;amp;','&amp;',$link['url']);
1024        }
1025        //remove double encodings in titles
1026        $link['title'] = str_replace('&amp;amp;','&amp;',$link['title']);
1027
1028        // be sure there are no bad chars in url or title
1029        // (we can't do this for name because it can contain an img tag)
1030        $link['url']   = strtr($link['url'],array('>'=>'%3E','<'=>'%3C','"'=>'%22'));
1031        $link['title'] = strtr($link['title'],array('>'=>'&gt;','<'=>'&lt;','"'=>'&quot;'));
1032
1033        $ret  = '';
1034        $ret .= $link['pre'];
1035        $ret .= '<a href="'.$link['url'].'"';
1036        if(!empty($link['class']))  $ret .= ' class="'.$link['class'].'"';
1037        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1038        if(!empty($link['title']))  $ret .= ' title="'.$link['title'].'"';
1039        if(!empty($link['style']))  $ret .= ' style="'.$link['style'].'"';
1040        if(!empty($link['rel']))    $ret .= ' rel="'.$link['rel'].'"';
1041        if(!empty($link['more']))   $ret .= ' '.$link['more'];
1042        $ret .= '>';
1043        $ret .= $link['name'];
1044        $ret .= '</a>';
1045        $ret .= $link['suf'];
1046        return $ret;
1047    }
1048
1049    /**
1050     * Renders internal and external media
1051     *
1052     * @author Andreas Gohr <andi@splitbrain.org>
1053     */
1054    function _media ($src, $title=NULL, $align=NULL, $width=NULL,
1055                      $height=NULL, $cache=NULL, $render = true) {
1056
1057        $ret = '';
1058
1059        list($ext,$mime,$dl) = mimetype($src);
1060        if(substr($mime,0,5) == 'image'){
1061            // first get the $title
1062            if (!is_null($title)) {
1063                $title  = $this->_xmlEntities($title);
1064            }elseif($ext == 'jpg' || $ext == 'jpeg'){
1065                //try to use the caption from IPTC/EXIF
1066                require_once(DOKU_INC.'inc/JpegMeta.php');
1067                $jpeg =new JpegMeta(mediaFN($src));
1068                if($jpeg !== false) $cap = $jpeg->getTitle();
1069                if($cap){
1070                    $title = $this->_xmlEntities($cap);
1071                }
1072            }
1073            if (!$render) {
1074                // if the picture is not supposed to be rendered
1075                // return the title of the picture
1076                if (!$title) {
1077                    // just show the sourcename
1078                    $title = $this->_xmlEntities(basename(noNS($src)));
1079                }
1080                return $title;
1081            }
1082            //add image tag
1083            $ret .= '<img src="'.ml($src,array('w'=>$width,'h'=>$height,'cache'=>$cache)).'"';
1084            $ret .= ' class="media'.$align.'"';
1085
1086            // make left/right alignment for no-CSS view work (feeds)
1087            if($align == 'right') $ret .= ' align="right"';
1088            if($align == 'left')  $ret .= ' align="left"';
1089
1090            if ($title) {
1091                $ret .= ' title="' . $title . '"';
1092                $ret .= ' alt="'   . $title .'"';
1093            }else{
1094                $ret .= ' alt=""';
1095            }
1096
1097            if ( !is_null($width) )
1098                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1099
1100            if ( !is_null($height) )
1101                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1102
1103            $ret .= ' />';
1104
1105        }elseif($mime == 'application/x-shockwave-flash'){
1106            if (!$render) {
1107                // if the flash is not supposed to be rendered
1108                // return the title of the flash
1109                if (!$title) {
1110                    // just show the sourcename
1111                    $title = basename(noNS($src));
1112                }
1113                return $this->_xmlEntities($title);
1114            }
1115
1116            $att = array();
1117            $att['class'] = "media$align";
1118            if($align == 'right') $att['align'] = 'right';
1119            if($align == 'left')  $att['align'] = 'left';
1120            $ret .= html_flashobject(ml($src,array('cache'=>$cache),true,'&'),$width,$height,
1121                                     array('quality' => 'high'),
1122                                     null,
1123                                     $att,
1124                                     $this->_xmlEntities($title));
1125        }elseif($title){
1126            // well at least we have a title to display
1127            $ret .= $this->_xmlEntities($title);
1128        }else{
1129            // just show the sourcename
1130            $ret .= $this->_xmlEntities(basename(noNS($src)));
1131        }
1132
1133        return $ret;
1134    }
1135
1136    function _xmlEntities($string) {
1137        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
1138    }
1139
1140    /**
1141     * Creates a linkid from a headline
1142     *
1143     * @param string  $title   The headline title
1144     * @param boolean $create  Create a new unique ID?
1145     * @author Andreas Gohr <andi@splitbrain.org>
1146     */
1147    function _headerToLink($title,$create=false) {
1148        if($create){
1149            return sectionID($title,$this->headers);
1150        }else{
1151            $check = false;
1152            return sectionID($title,$check);
1153        }
1154    }
1155
1156    /**
1157     * Construct a title and handle images in titles
1158     *
1159     * @author Harry Fuecks <hfuecks@gmail.com>
1160     */
1161    function _getLinkTitle($title, $default, & $isImage, $id=NULL, $linktype='content') {
1162        global $conf;
1163
1164        $isImage = false;
1165        if ( is_array($title) ) {
1166            $isImage = true;
1167            return $this->_imageTitle($title);
1168        } elseif ( is_null($title) || trim($title)=='') {
1169            if (useHeading($linktype) && $id) {
1170                $heading = p_get_first_heading($id);
1171                if ($heading) {
1172                    return $this->_xmlEntities($heading);
1173                }
1174            }
1175            return $this->_xmlEntities($default);
1176        } else {
1177            return $this->_xmlEntities($title);
1178        }
1179    }
1180
1181    /**
1182     * Returns an HTML code for images used in link titles
1183     *
1184     * @todo Resolve namespace on internal images
1185     * @author Andreas Gohr <andi@splitbrain.org>
1186     */
1187    function _imageTitle($img) {
1188        global $ID;
1189
1190        // some fixes on $img['src']
1191        // see internalmedia() and externalmedia()
1192        list($img['src'],$hash) = explode('#',$img['src'],2);
1193        if ($img['type'] == 'internalmedia') {
1194            resolve_mediaid(getNS($ID),$img['src'],$exists);
1195        }
1196
1197        return $this->_media($img['src'],
1198                              $img['title'],
1199                              $img['align'],
1200                              $img['width'],
1201                              $img['height'],
1202                              $img['cache']);
1203    }
1204
1205    /**
1206     * _getMediaLinkConf is a helperfunction to internalmedia() and externalmedia()
1207     * which returns a basic link to a media.
1208     *
1209     * @author Pierre Spring <pierre.spring@liip.ch>
1210     * @param string $src
1211     * @param string $title
1212     * @param string $align
1213     * @param string $width
1214     * @param string $height
1215     * @param string $cache
1216     * @param string $render
1217     * @access protected
1218     * @return array
1219     */
1220    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render)
1221    {
1222        global $conf;
1223
1224        $link = array();
1225        $link['class']  = 'media';
1226        $link['style']  = '';
1227        $link['pre']    = '';
1228        $link['suf']    = '';
1229        $link['more']   = '';
1230        $link['target'] = $conf['target']['media'];
1231        $link['title']  = $this->_xmlEntities($src);
1232        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1233
1234        return $link;
1235    }
1236
1237
1238}
1239
1240//Setup VIM: ex: et ts=4 :
1241