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