xref: /dokuwiki/inc/parser/xhtml.php (revision e2d881567163b1ea21877d5d17e1247b3710e1af)
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
20/**
21 * The XHTML Renderer
22 *
23 * This is DokuWiki's main renderer used to display page content in the wiki
24 */
25class Doku_Renderer_xhtml extends Doku_Renderer {
26    /** @var array store the table of contents */
27    public $toc = array();
28
29    /** @var array A stack of section edit data */
30    protected $sectionedits = array();
31    var $date_at = '';    // link pages and media against this revision
32
33    /** @var int last section edit id, used by startSectionEdit */
34    protected $lastsecid = 0;
35
36    /** @var array the list of headers used to create unique link ids */
37    protected $headers = array();
38
39    /** @var array a list of footnotes, list starts at 1! */
40    protected $footnotes = array();
41
42    /** @var int current section level */
43    protected $lastlevel = 0;
44    /** @var array section node tracker */
45    protected $node = array(0, 0, 0, 0, 0);
46
47    /** @var string temporary $doc store */
48    protected $store = '';
49
50    /** @var array global counter, for table classes etc. */
51    protected $_counter = array(); //
52
53    /** @var int counts the code and file blocks, used to provide download links */
54    protected $_codeblock = 0;
55
56    /** @var array list of allowed URL schemes */
57    protected $schemes = null;
58
59    /**
60     * Register a new edit section range
61     *
62     * @param string $type   The section type identifier
63     * @param string $title  The section title
64     * @param int    $start  The byte position for the edit start
65     * @return string  A marker class for the starting HTML element
66     *
67     * @author Adrian Lang <lang@cosmocode.de>
68     */
69    public function startSectionEdit($start, $type, $title = null) {
70        $this->sectionedits[] = array(++$this->lastsecid, $start, $type, $title);
71        return 'sectionedit'.$this->lastsecid;
72    }
73
74    /**
75     * Finish an edit section range
76     *
77     * @param int  $end     The byte position for the edit end; null for the rest of the page
78     *
79     * @author Adrian Lang <lang@cosmocode.de>
80     */
81    public function finishSectionEdit($end = null) {
82        list($id, $start, $type, $title) = array_pop($this->sectionedits);
83        if(!is_null($end) && $end <= $start) {
84            return;
85        }
86        $this->doc .= "<!-- EDIT$id ".strtoupper($type).' ';
87        if(!is_null($title)) {
88            $this->doc .= '"'.str_replace('"', '', $title).'" ';
89        }
90        $this->doc .= "[$start-".(is_null($end) ? '' : $end).'] -->';
91    }
92
93    /**
94     * Returns the format produced by this renderer.
95     *
96     * @return string always 'xhtml'
97     */
98    function getFormat() {
99        return 'xhtml';
100    }
101
102    /**
103     * Initialize the document
104     */
105    function document_start() {
106        //reset some internals
107        $this->toc     = array();
108        $this->headers = array();
109    }
110
111    /**
112     * Finalize the document
113     */
114    function document_end() {
115        // Finish open section edits.
116        while(count($this->sectionedits) > 0) {
117            if($this->sectionedits[count($this->sectionedits) - 1][1] <= 1) {
118                // If there is only one section, do not write a section edit
119                // marker.
120                array_pop($this->sectionedits);
121            } else {
122                $this->finishSectionEdit();
123            }
124        }
125
126        if(count($this->footnotes) > 0) {
127            $this->doc .= '<div class="footnotes">'.DOKU_LF;
128
129            foreach($this->footnotes as $id => $footnote) {
130                // check its not a placeholder that indicates actual footnote text is elsewhere
131                if(substr($footnote, 0, 5) != "@@FNT") {
132
133                    // open the footnote and set the anchor and backlink
134                    $this->doc .= '<div class="fn">';
135                    $this->doc .= '<sup><a href="#fnt__'.$id.'" id="fn__'.$id.'" class="fn_bot">';
136                    $this->doc .= $id.')</a></sup> '.DOKU_LF;
137
138                    // get any other footnotes that use the same markup
139                    $alt = array_keys($this->footnotes, "@@FNT$id");
140
141                    if(count($alt)) {
142                        foreach($alt as $ref) {
143                            // set anchor and backlink for the other footnotes
144                            $this->doc .= ', <sup><a href="#fnt__'.($ref).'" id="fn__'.($ref).'" class="fn_bot">';
145                            $this->doc .= ($ref).')</a></sup> '.DOKU_LF;
146                        }
147                    }
148
149                    // add footnote markup and close this footnote
150                    $this->doc .= '<div class="content">'.$footnote.'</div>';
151                    $this->doc .= '</div>'.DOKU_LF;
152                }
153            }
154            $this->doc .= '</div>'.DOKU_LF;
155        }
156
157        // Prepare the TOC
158        global $conf;
159        if($this->info['toc'] && is_array($this->toc) && $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads']) {
160            global $TOC;
161            $TOC = $this->toc;
162        }
163
164        // make sure there are no empty paragraphs
165        $this->doc = preg_replace('#<p>\s*</p>#', '', $this->doc);
166    }
167
168    /**
169     * Add an item to the TOC
170     *
171     * @param string $id       the hash link
172     * @param string $text     the text to display
173     * @param int    $level    the nesting level
174     */
175    function toc_additem($id, $text, $level) {
176        global $conf;
177
178        //handle TOC
179        if($level >= $conf['toptoclevel'] && $level <= $conf['maxtoclevel']) {
180            $this->toc[] = html_mktocitem($id, $text, $level - $conf['toptoclevel'] + 1);
181        }
182    }
183
184    /**
185     * Render a heading
186     *
187     * @param string $text  the text to display
188     * @param int    $level header level
189     * @param int    $pos   byte position in the original source
190     */
191    function header($text, $level, $pos) {
192        global $conf;
193
194        if(blank($text)) return; //skip empty headlines
195
196        $hid = $this->_headerToLink($text, true);
197
198        //only add items within configured levels
199        $this->toc_additem($hid, $text, $level);
200
201        // adjust $node to reflect hierarchy of levels
202        $this->node[$level - 1]++;
203        if($level < $this->lastlevel) {
204            for($i = 0; $i < $this->lastlevel - $level; $i++) {
205                $this->node[$this->lastlevel - $i - 1] = 0;
206            }
207        }
208        $this->lastlevel = $level;
209
210        if($level <= $conf['maxseclevel'] &&
211            count($this->sectionedits) > 0 &&
212            $this->sectionedits[count($this->sectionedits) - 1][2] === 'section'
213        ) {
214            $this->finishSectionEdit($pos - 1);
215        }
216
217        // write the header
218        $this->doc .= DOKU_LF.'<h'.$level;
219        if($level <= $conf['maxseclevel']) {
220            $this->doc .= ' class="'.$this->startSectionEdit($pos, 'section', $text).'"';
221        }
222        $this->doc .= ' id="'.$hid.'">';
223        $this->doc .= $this->_xmlEntities($text);
224        $this->doc .= "</h$level>".DOKU_LF;
225    }
226
227    /**
228     * Open a new section
229     *
230     * @param int $level section level (as determined by the previous header)
231     */
232    function section_open($level) {
233        $this->doc .= '<div class="level'.$level.'">'.DOKU_LF;
234    }
235
236    /**
237     * Close the current section
238     */
239    function section_close() {
240        $this->doc .= DOKU_LF.'</div>'.DOKU_LF;
241    }
242
243    /**
244     * Render plain text data
245     *
246     * @param $text
247     */
248    function cdata($text) {
249        $this->doc .= $this->_xmlEntities($text);
250    }
251
252    /**
253     * Open a paragraph
254     */
255    function p_open() {
256        $this->doc .= DOKU_LF.'<p>'.DOKU_LF;
257    }
258
259    /**
260     * Close a paragraph
261     */
262    function p_close() {
263        $this->doc .= DOKU_LF.'</p>'.DOKU_LF;
264    }
265
266    /**
267     * Create a line break
268     */
269    function linebreak() {
270        $this->doc .= '<br/>'.DOKU_LF;
271    }
272
273    /**
274     * Create a horizontal line
275     */
276    function hr() {
277        $this->doc .= '<hr />'.DOKU_LF;
278    }
279
280    /**
281     * Start strong (bold) formatting
282     */
283    function strong_open() {
284        $this->doc .= '<strong>';
285    }
286
287    /**
288     * Stop strong (bold) formatting
289     */
290    function strong_close() {
291        $this->doc .= '</strong>';
292    }
293
294    /**
295     * Start emphasis (italics) formatting
296     */
297    function emphasis_open() {
298        $this->doc .= '<em>';
299    }
300
301    /**
302     * Stop emphasis (italics) formatting
303     */
304    function emphasis_close() {
305        $this->doc .= '</em>';
306    }
307
308    /**
309     * Start underline formatting
310     */
311    function underline_open() {
312        $this->doc .= '<em class="u">';
313    }
314
315    /**
316     * Stop underline formatting
317     */
318    function underline_close() {
319        $this->doc .= '</em>';
320    }
321
322    /**
323     * Start monospace formatting
324     */
325    function monospace_open() {
326        $this->doc .= '<code>';
327    }
328
329    /**
330     * Stop monospace formatting
331     */
332    function monospace_close() {
333        $this->doc .= '</code>';
334    }
335
336    /**
337     * Start a subscript
338     */
339    function subscript_open() {
340        $this->doc .= '<sub>';
341    }
342
343    /**
344     * Stop a subscript
345     */
346    function subscript_close() {
347        $this->doc .= '</sub>';
348    }
349
350    /**
351     * Start a superscript
352     */
353    function superscript_open() {
354        $this->doc .= '<sup>';
355    }
356
357    /**
358     * Stop a superscript
359     */
360    function superscript_close() {
361        $this->doc .= '</sup>';
362    }
363
364    /**
365     * Start deleted (strike-through) formatting
366     */
367    function deleted_open() {
368        $this->doc .= '<del>';
369    }
370
371    /**
372     * Stop deleted (strike-through) formatting
373     */
374    function deleted_close() {
375        $this->doc .= '</del>';
376    }
377
378    /**
379     * Callback for footnote start syntax
380     *
381     * All following content will go to the footnote instead of
382     * the document. To achieve this the previous rendered content
383     * is moved to $store and $doc is cleared
384     *
385     * @author Andreas Gohr <andi@splitbrain.org>
386     */
387    function footnote_open() {
388
389        // move current content to store and record footnote
390        $this->store = $this->doc;
391        $this->doc   = '';
392    }
393
394    /**
395     * Callback for footnote end syntax
396     *
397     * All rendered content is moved to the $footnotes array and the old
398     * content is restored from $store again
399     *
400     * @author Andreas Gohr
401     */
402    function footnote_close() {
403        /** @var $fnid int takes track of seen footnotes, assures they are unique even across multiple docs FS#2841 */
404        static $fnid = 0;
405        // assign new footnote id (we start at 1)
406        $fnid++;
407
408        // recover footnote into the stack and restore old content
409        $footnote    = $this->doc;
410        $this->doc   = $this->store;
411        $this->store = '';
412
413        // check to see if this footnote has been seen before
414        $i = array_search($footnote, $this->footnotes);
415
416        if($i === false) {
417            // its a new footnote, add it to the $footnotes array
418            $this->footnotes[$fnid] = $footnote;
419        } else {
420            // seen this one before, save a placeholder
421            $this->footnotes[$fnid] = "@@FNT".($i);
422        }
423
424        // output the footnote reference and link
425        $this->doc .= '<sup><a href="#fn__'.$fnid.'" id="fnt__'.$fnid.'" class="fn_top">'.$fnid.')</a></sup>';
426    }
427
428    /**
429     * Open an unordered list
430     *
431     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
432     */
433    function listu_open($classes = null) {
434        $class = '';
435        if($classes !== null) {
436            if(is_array($classes)) $classes = join(' ', $classes);
437            $class = " class=\"$classes\"";
438        }
439        $this->doc .= "<ul$class>".DOKU_LF;
440    }
441
442    /**
443     * Close an unordered list
444     */
445    function listu_close() {
446        $this->doc .= '</ul>'.DOKU_LF;
447    }
448
449    /**
450     * Open an ordered list
451     *
452     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
453     */
454    function listo_open($classes = null) {
455        $class = '';
456        if($classes !== null) {
457            if(is_array($classes)) $classes = join(' ', $classes);
458            $class = " class=\"$classes\"";
459        }
460        $this->doc .= "<ol$class>".DOKU_LF;
461    }
462
463    /**
464     * Close an ordered list
465     */
466    function listo_close() {
467        $this->doc .= '</ol>'.DOKU_LF;
468    }
469
470    /**
471     * Open a list item
472     *
473     * @param int $level the nesting level
474     * @param bool $node true when a node; false when a leaf
475     */
476    function listitem_open($level, $node=false) {
477        $branching = $node ? ' node' : '';
478        $this->doc .= '<li class="level'.$level.$branching.'">';
479    }
480
481    /**
482     * Close a list item
483     */
484    function listitem_close() {
485        $this->doc .= '</li>'.DOKU_LF;
486    }
487
488    /**
489     * Start the content of a list item
490     */
491    function listcontent_open() {
492        $this->doc .= '<div class="li">';
493    }
494
495    /**
496     * Stop the content of a list item
497     */
498    function listcontent_close() {
499        $this->doc .= '</div>'.DOKU_LF;
500    }
501
502    /**
503     * Output unformatted $text
504     *
505     * Defaults to $this->cdata()
506     *
507     * @param string $text
508     */
509    function unformatted($text) {
510        $this->doc .= $this->_xmlEntities($text);
511    }
512
513    /**
514     * Execute PHP code if allowed
515     *
516     * @param  string $text      PHP code that is either executed or printed
517     * @param  string $wrapper   html element to wrap result if $conf['phpok'] is okff
518     *
519     * @author Andreas Gohr <andi@splitbrain.org>
520     */
521    function php($text, $wrapper = 'code') {
522        global $conf;
523
524        if($conf['phpok']) {
525            ob_start();
526            eval($text);
527            $this->doc .= ob_get_contents();
528            ob_end_clean();
529        } else {
530            $this->doc .= p_xhtml_cached_geshi($text, 'php', $wrapper);
531        }
532    }
533
534    /**
535     * Output block level PHP code
536     *
537     * If $conf['phpok'] is true this should evaluate the given code and append the result
538     * to $doc
539     *
540     * @param string $text The PHP code
541     */
542    function phpblock($text) {
543        $this->php($text, 'pre');
544    }
545
546    /**
547     * Insert HTML if allowed
548     *
549     * @param  string $text      html text
550     * @param  string $wrapper   html element to wrap result if $conf['htmlok'] is okff
551     *
552     * @author Andreas Gohr <andi@splitbrain.org>
553     */
554    function html($text, $wrapper = 'code') {
555        global $conf;
556
557        if($conf['htmlok']) {
558            $this->doc .= $text;
559        } else {
560            $this->doc .= p_xhtml_cached_geshi($text, 'html4strict', $wrapper);
561        }
562    }
563
564    /**
565     * Output raw block-level HTML
566     *
567     * If $conf['htmlok'] is true this should add the code as is to $doc
568     *
569     * @param string $text The HTML
570     */
571    function htmlblock($text) {
572        $this->html($text, 'pre');
573    }
574
575    /**
576     * Start a block quote
577     */
578    function quote_open() {
579        $this->doc .= '<blockquote><div class="no">'.DOKU_LF;
580    }
581
582    /**
583     * Stop a block quote
584     */
585    function quote_close() {
586        $this->doc .= '</div></blockquote>'.DOKU_LF;
587    }
588
589    /**
590     * Output preformatted text
591     *
592     * @param string $text
593     */
594    function preformatted($text) {
595        $this->doc .= '<pre class="code">'.trim($this->_xmlEntities($text), "\n\r").'</pre>'.DOKU_LF;
596    }
597
598    /**
599     * Display text as file content, optionally syntax highlighted
600     *
601     * @param string $text     text to show
602     * @param string $language programming language to use for syntax highlighting
603     * @param string $filename file path label
604     * @param array  $options  assoziative array with additional geshi options
605     */
606    function file($text, $language = null, $filename = null, $options=null) {
607        $this->_highlight('file', $text, $language, $filename, $options);
608    }
609
610    /**
611     * Display text as code content, optionally syntax highlighted
612     *
613     * @param string $text     text to show
614     * @param string $language programming language to use for syntax highlighting
615     * @param string $filename file path label
616     * @param array  $options  assoziative array with additional geshi options
617     */
618    function code($text, $language = null, $filename = null, $options=null) {
619        $this->_highlight('code', $text, $language, $filename, $options);
620    }
621
622    /**
623     * Use GeSHi to highlight language syntax in code and file blocks
624     *
625     * @author Andreas Gohr <andi@splitbrain.org>
626     * @param string $type     code|file
627     * @param string $text     text to show
628     * @param string $language programming language to use for syntax highlighting
629     * @param string $filename file path label
630     * @param array  $options  assoziative array with additional geshi options
631     */
632    function _highlight($type, $text, $language = null, $filename = null, $options = null) {
633        global $ID;
634        global $lang;
635
636        if($filename) {
637            // add icon
638            list($ext) = mimetype($filename, false);
639            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
640            $class = 'mediafile mf_'.$class;
641
642            $this->doc .= '<dl class="'.$type.'">'.DOKU_LF;
643            $this->doc .= '<dt><a href="'.exportlink($ID, 'code', array('codeblock' => $this->_codeblock)).'" title="'.$lang['download'].'" class="'.$class.'">';
644            $this->doc .= hsc($filename);
645            $this->doc .= '</a></dt>'.DOKU_LF.'<dd>';
646        }
647
648        if($text{0} == "\n") {
649            $text = substr($text, 1);
650        }
651        if(substr($text, -1) == "\n") {
652            $text = substr($text, 0, -1);
653        }
654
655        if(is_null($language)) {
656            $this->doc .= '<pre class="'.$type.'">'.$this->_xmlEntities($text).'</pre>'.DOKU_LF;
657        } else {
658            $class = 'code'; //we always need the code class to make the syntax highlighting apply
659            if($type != 'code') $class .= ' '.$type;
660
661            $this->doc .= "<pre class=\"$class $language\">".p_xhtml_cached_geshi($text, $language, '', $options).'</pre>'.DOKU_LF;
662        }
663
664        if($filename) {
665            $this->doc .= '</dd></dl>'.DOKU_LF;
666        }
667
668        $this->_codeblock++;
669    }
670
671    /**
672     * Format an acronym
673     *
674     * Uses $this->acronyms
675     *
676     * @param string $acronym
677     */
678    function acronym($acronym) {
679
680        if(array_key_exists($acronym, $this->acronyms)) {
681
682            $title = $this->_xmlEntities($this->acronyms[$acronym]);
683
684            $this->doc .= '<abbr title="'.$title
685                .'">'.$this->_xmlEntities($acronym).'</abbr>';
686
687        } else {
688            $this->doc .= $this->_xmlEntities($acronym);
689        }
690    }
691
692    /**
693     * Format a smiley
694     *
695     * Uses $this->smiley
696     *
697     * @param string $smiley
698     */
699    function smiley($smiley) {
700        if(array_key_exists($smiley, $this->smileys)) {
701            $this->doc .= '<img src="'.DOKU_BASE.'lib/images/smileys/'.$this->smileys[$smiley].
702                '" class="icon" alt="'.
703                $this->_xmlEntities($smiley).'" />';
704        } else {
705            $this->doc .= $this->_xmlEntities($smiley);
706        }
707    }
708
709    /**
710     * Format an entity
711     *
712     * Entities are basically small text replacements
713     *
714     * Uses $this->entities
715     *
716     * @param string $entity
717     */
718    function entity($entity) {
719        if(array_key_exists($entity, $this->entities)) {
720            $this->doc .= $this->entities[$entity];
721        } else {
722            $this->doc .= $this->_xmlEntities($entity);
723        }
724    }
725
726    /**
727     * Typographically format a multiply sign
728     *
729     * Example: ($x=640, $y=480) should result in "640×480"
730     *
731     * @param string|int $x first value
732     * @param string|int $y second value
733     */
734    function multiplyentity($x, $y) {
735        $this->doc .= "$x&times;$y";
736    }
737
738    /**
739     * Render an opening single quote char (language specific)
740     */
741    function singlequoteopening() {
742        global $lang;
743        $this->doc .= $lang['singlequoteopening'];
744    }
745
746    /**
747     * Render a closing single quote char (language specific)
748     */
749    function singlequoteclosing() {
750        global $lang;
751        $this->doc .= $lang['singlequoteclosing'];
752    }
753
754    /**
755     * Render an apostrophe char (language specific)
756     */
757    function apostrophe() {
758        global $lang;
759        $this->doc .= $lang['apostrophe'];
760    }
761
762    /**
763     * Render an opening double quote char (language specific)
764     */
765    function doublequoteopening() {
766        global $lang;
767        $this->doc .= $lang['doublequoteopening'];
768    }
769
770    /**
771     * Render an closinging double quote char (language specific)
772     */
773    function doublequoteclosing() {
774        global $lang;
775        $this->doc .= $lang['doublequoteclosing'];
776    }
777
778    /**
779     * Render a CamelCase link
780     *
781     * @param string $link       The link name
782     * @param bool   $returnonly whether to return html or write to doc attribute
783     * @return void|string writes to doc attribute or returns html depends on $returnonly
784     *
785     * @see http://en.wikipedia.org/wiki/CamelCase
786     */
787    function camelcaselink($link, $returnonly = false) {
788        if($returnonly) {
789          return $this->internallink($link, $link, null, true);
790        } else {
791          $this->internallink($link, $link);
792        }
793    }
794
795    /**
796     * Render a page local link
797     *
798     * @param string $hash       hash link identifier
799     * @param string $name       name for the link
800     * @param bool   $returnonly whether to return html or write to doc attribute
801     * @return void|string writes to doc attribute or returns html depends on $returnonly
802     */
803    function locallink($hash, $name = null, $returnonly = false) {
804        global $ID;
805        $name  = $this->_getLinkTitle($name, $hash, $isImage);
806        $hash  = $this->_headerToLink($hash);
807        $title = $ID.' ↵';
808
809        $doc = '<a href="#'.$hash.'" title="'.$title.'" class="wikilink1">';
810        $doc .= $name;
811        $doc .= '</a>';
812
813        if($returnonly) {
814          return $doc;
815        } else {
816          $this->doc .= $doc;
817        }
818    }
819
820    /**
821     * Render an internal Wiki Link
822     *
823     * $search,$returnonly & $linktype are not for the renderer but are used
824     * elsewhere - no need to implement them in other renderers
825     *
826     * @author Andreas Gohr <andi@splitbrain.org>
827     * @param string      $id         pageid
828     * @param string|null $name       link name
829     * @param string|null $search     adds search url param
830     * @param bool        $returnonly whether to return html or write to doc attribute
831     * @param string      $linktype   type to set use of headings
832     * @return void|string writes to doc attribute or returns html depends on $returnonly
833     */
834    function internallink($id, $name = null, $search = null, $returnonly = false, $linktype = 'content') {
835        global $conf;
836        global $ID;
837        global $INFO;
838
839        $params = '';
840        $parts  = explode('?', $id, 2);
841        if(count($parts) === 2) {
842            $id     = $parts[0];
843            $params = $parts[1];
844        }
845
846        // For empty $id we need to know the current $ID
847        // We need this check because _simpleTitle needs
848        // correct $id and resolve_pageid() use cleanID($id)
849        // (some things could be lost)
850        if($id === '') {
851            $id = $ID;
852        }
853
854        // default name is based on $id as given
855        $default = $this->_simpleTitle($id);
856
857        // now first resolve and clean up the $id
858        resolve_pageid(getNS($ID), $id, $exists, $this->date_at, true);
859
860        $link = array();
861        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
862        if(!$isImage) {
863            if($exists) {
864                $class = 'wikilink1';
865            } else {
866                $class       = 'wikilink2';
867                $link['rel'] = 'nofollow';
868            }
869        } else {
870            $class = 'media';
871        }
872
873        //keep hash anchor
874        @list($id, $hash) = explode('#', $id, 2);
875        if(!empty($hash)) $hash = $this->_headerToLink($hash);
876
877        //prepare for formating
878        $link['target'] = $conf['target']['wiki'];
879        $link['style']  = '';
880        $link['pre']    = '';
881        $link['suf']    = '';
882        // highlight link to current page
883        if($id == $INFO['id']) {
884            $link['pre'] = '<span class="curid">';
885            $link['suf'] = '</span>';
886        }
887        $link['more']   = '';
888        $link['class']  = $class;
889        if($this->date_at) {
890            $params['at'] = $this->date_at;
891        }
892        $link['url']    = wl($id, $params);
893        $link['name']   = $name;
894        $link['title']  = $id;
895        //add search string
896        if($search) {
897            ($conf['userewrite']) ? $link['url'] .= '?' : $link['url'] .= '&amp;';
898            if(is_array($search)) {
899                $search = array_map('rawurlencode', $search);
900                $link['url'] .= 's[]='.join('&amp;s[]=', $search);
901            } else {
902                $link['url'] .= 's='.rawurlencode($search);
903            }
904        }
905
906        //keep hash
907        if($hash) $link['url'] .= '#'.$hash;
908
909        //output formatted
910        if($returnonly) {
911            return $this->_formatLink($link);
912        } else {
913            $this->doc .= $this->_formatLink($link);
914        }
915    }
916
917    /**
918     * Render an external link
919     *
920     * @param string       $url        full URL with scheme
921     * @param string|array $name       name for the link, array for media file
922     * @param bool         $returnonly whether to return html or write to doc attribute
923     * @return void|string writes to doc attribute or returns html depends on $returnonly
924     */
925    function externallink($url, $name = null, $returnonly = false) {
926        global $conf;
927
928        $name = $this->_getLinkTitle($name, $url, $isImage);
929
930        // url might be an attack vector, only allow registered protocols
931        if(is_null($this->schemes)) $this->schemes = getSchemes();
932        list($scheme) = explode('://', $url);
933        $scheme = strtolower($scheme);
934        if(!in_array($scheme, $this->schemes)) $url = '';
935
936        // is there still an URL?
937        if(!$url) {
938            if($returnonly) {
939                return $name;
940            } else {
941                $this->doc .= $name;
942            }
943            return;
944        }
945
946        // set class
947        if(!$isImage) {
948            $class = 'urlextern';
949        } else {
950            $class = 'media';
951        }
952
953        //prepare for formating
954        $link = array();
955        $link['target'] = $conf['target']['extern'];
956        $link['style']  = '';
957        $link['pre']    = '';
958        $link['suf']    = '';
959        $link['more']   = '';
960        $link['class']  = $class;
961        $link['url']    = $url;
962        $link['rel']    = '';
963
964        $link['name']  = $name;
965        $link['title'] = $this->_xmlEntities($url);
966        if($conf['relnofollow']) $link['rel'] .= ' nofollow';
967        if($conf['target']['extern']) $link['rel'] .= ' noopener';
968
969        //output formatted
970        if($returnonly) {
971            return $this->_formatLink($link);
972        } else {
973            $this->doc .= $this->_formatLink($link);
974        }
975    }
976
977    /**
978     * Render an interwiki link
979     *
980     * You may want to use $this->_resolveInterWiki() here
981     *
982     * @param string       $match      original link - probably not much use
983     * @param string|array $name       name for the link, array for media file
984     * @param string       $wikiName   indentifier (shortcut) for the remote wiki
985     * @param string       $wikiUri    the fragment parsed from the original link
986     * @param bool         $returnonly whether to return html or write to doc attribute
987     * @return void|string writes to doc attribute or returns html depends on $returnonly
988     */
989    function interwikilink($match, $name = null, $wikiName, $wikiUri, $returnonly = false) {
990        global $conf;
991
992        $link           = array();
993        $link['target'] = $conf['target']['interwiki'];
994        $link['pre']    = '';
995        $link['suf']    = '';
996        $link['more']   = '';
997        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
998        $link['rel']    = '';
999
1000        //get interwiki URL
1001        $exists = null;
1002        $url    = $this->_resolveInterWiki($wikiName, $wikiUri, $exists);
1003
1004        if(!$isImage) {
1005            $class         = preg_replace('/[^_\-a-z0-9]+/i', '_', $wikiName);
1006            $link['class'] = "interwiki iw_$class";
1007        } else {
1008            $link['class'] = 'media';
1009        }
1010
1011        //do we stay at the same server? Use local target
1012        if(strpos($url, DOKU_URL) === 0 OR strpos($url, DOKU_BASE) === 0) {
1013            $link['target'] = $conf['target']['wiki'];
1014        }
1015        if($exists !== null && !$isImage) {
1016            if($exists) {
1017                $link['class'] .= ' wikilink1';
1018            } else {
1019                $link['class'] .= ' wikilink2';
1020                $link['rel'] .= ' nofollow';
1021            }
1022        }
1023        if($conf['target']['interwiki']) $link['rel'] .= ' noopener';
1024
1025        $link['url']   = $url;
1026        $link['title'] = htmlspecialchars($link['url']);
1027
1028        //output formatted
1029        if($returnonly) {
1030            return $this->_formatLink($link);
1031        } else {
1032            $this->doc .= $this->_formatLink($link);
1033        }
1034    }
1035
1036    /**
1037     * Link to windows share
1038     *
1039     * @param string       $url        the link
1040     * @param string|array $name       name for the link, array for media file
1041     * @param bool         $returnonly whether to return html or write to doc attribute
1042     * @return void|string writes to doc attribute or returns html depends on $returnonly
1043     */
1044    function windowssharelink($url, $name = null, $returnonly = false) {
1045        global $conf;
1046
1047        //simple setup
1048        $link = array();
1049        $link['target'] = $conf['target']['windows'];
1050        $link['pre']    = '';
1051        $link['suf']    = '';
1052        $link['style']  = '';
1053
1054        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
1055        if(!$isImage) {
1056            $link['class'] = 'windows';
1057        } else {
1058            $link['class'] = 'media';
1059        }
1060
1061        $link['title'] = $this->_xmlEntities($url);
1062        $url           = str_replace('\\', '/', $url);
1063        $url           = 'file:///'.$url;
1064        $link['url']   = $url;
1065
1066        //output formatted
1067        if($returnonly) {
1068            return $this->_formatLink($link);
1069        } else {
1070            $this->doc .= $this->_formatLink($link);
1071        }
1072    }
1073
1074    /**
1075     * Render a linked E-Mail Address
1076     *
1077     * Honors $conf['mailguard'] setting
1078     *
1079     * @param string       $address    Email-Address
1080     * @param string|array $name       name for the link, array for media file
1081     * @param bool         $returnonly whether to return html or write to doc attribute
1082     * @return void|string writes to doc attribute or returns html depends on $returnonly
1083     */
1084    function emaillink($address, $name = null, $returnonly = false) {
1085        global $conf;
1086        //simple setup
1087        $link           = array();
1088        $link['target'] = '';
1089        $link['pre']    = '';
1090        $link['suf']    = '';
1091        $link['style']  = '';
1092        $link['more']   = '';
1093
1094        $name = $this->_getLinkTitle($name, '', $isImage);
1095        if(!$isImage) {
1096            $link['class'] = 'mail';
1097        } else {
1098            $link['class'] = 'media';
1099        }
1100
1101        $address = $this->_xmlEntities($address);
1102        $address = obfuscate($address);
1103        $title   = $address;
1104
1105        if(empty($name)) {
1106            $name = $address;
1107        }
1108
1109        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
1110
1111        $link['url']   = 'mailto:'.$address;
1112        $link['name']  = $name;
1113        $link['title'] = $title;
1114
1115        //output formatted
1116        if($returnonly) {
1117            return $this->_formatLink($link);
1118        } else {
1119            $this->doc .= $this->_formatLink($link);
1120        }
1121    }
1122
1123    /**
1124     * Render an internal media file
1125     *
1126     * @param string $src       media ID
1127     * @param string $title     descriptive text
1128     * @param string $align     left|center|right
1129     * @param int    $width     width of media in pixel
1130     * @param int    $height    height of media in pixel
1131     * @param string $cache     cache|recache|nocache
1132     * @param string $linking   linkonly|detail|nolink
1133     * @param bool   $return    return HTML instead of adding to $doc
1134     * @return void|string writes to doc attribute or returns html depends on $return
1135     */
1136    function internalmedia($src, $title = null, $align = null, $width = null,
1137                           $height = null, $cache = null, $linking = null, $return = false) {
1138        global $ID;
1139        list($src, $hash) = explode('#', $src, 2);
1140        resolve_mediaid(getNS($ID), $src, $exists, $this->date_at, true);
1141
1142        $noLink = false;
1143        $render = ($linking == 'linkonly') ? false : true;
1144        $link   = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
1145
1146        list($ext, $mime) = mimetype($src, false);
1147        if(substr($mime, 0, 5) == 'image' && $render) {
1148            $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src)), ($linking == 'direct'));
1149        } elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render) {
1150            // don't link movies
1151            $noLink = true;
1152        } else {
1153            // add file icons
1154            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1155            $link['class'] .= ' mediafile mf_'.$class;
1156            $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache , 'rev'=>$this->_getLastMediaRevisionAt($src)), true);
1157            if($exists) $link['title'] .= ' ('.filesize_h(filesize(mediaFN($src))).')';
1158        }
1159
1160        if($hash) $link['url'] .= '#'.$hash;
1161
1162        //markup non existing files
1163        if(!$exists) {
1164            $link['class'] .= ' wikilink2';
1165        }
1166
1167        //output formatted
1168        if($return) {
1169            if($linking == 'nolink' || $noLink) return $link['name'];
1170            else return $this->_formatLink($link);
1171        } else {
1172            if($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
1173            else $this->doc .= $this->_formatLink($link);
1174        }
1175    }
1176
1177    /**
1178     * Render an external media file
1179     *
1180     * @param string $src     full media URL
1181     * @param string $title   descriptive text
1182     * @param string $align   left|center|right
1183     * @param int    $width   width of media in pixel
1184     * @param int    $height  height of media in pixel
1185     * @param string $cache   cache|recache|nocache
1186     * @param string $linking linkonly|detail|nolink
1187     * @param bool   $return  return HTML instead of adding to $doc
1188     * @return void|string writes to doc attribute or returns html depends on $return
1189     */
1190    function externalmedia($src, $title = null, $align = null, $width = null,
1191                           $height = null, $cache = null, $linking = null, $return = false) {
1192        if(link_isinterwiki($src)){
1193            list($shortcut, $reference) = explode('>', $src, 2);
1194            $exists = null;
1195            $src = $this->_resolveInterWiki($shortcut, $reference, $exists);
1196        }
1197        list($src, $hash) = explode('#', $src, 2);
1198        $noLink = false;
1199        $render = ($linking == 'linkonly') ? false : true;
1200        $link   = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
1201
1202        $link['url'] = ml($src, array('cache' => $cache));
1203
1204        list($ext, $mime) = mimetype($src, false);
1205        if(substr($mime, 0, 5) == 'image' && $render) {
1206            // link only jpeg images
1207            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
1208        } elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render) {
1209            // don't link movies
1210            $noLink = true;
1211        } else {
1212            // add file icons
1213            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1214            $link['class'] .= ' mediafile mf_'.$class;
1215        }
1216
1217        if($hash) $link['url'] .= '#'.$hash;
1218
1219        //output formatted
1220        if($return) {
1221            if($linking == 'nolink' || $noLink) return $link['name'];
1222            else return $this->_formatLink($link);
1223        } else {
1224            if($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
1225            else $this->doc .= $this->_formatLink($link);
1226        }
1227    }
1228
1229    /**
1230     * Renders an RSS feed
1231     *
1232     * @param string $url    URL of the feed
1233     * @param array  $params Finetuning of the output
1234     *
1235     * @author Andreas Gohr <andi@splitbrain.org>
1236     */
1237    function rss($url, $params) {
1238        global $lang;
1239        global $conf;
1240
1241        require_once(DOKU_INC.'inc/FeedParser.php');
1242        $feed = new FeedParser();
1243        $feed->set_feed_url($url);
1244
1245        //disable warning while fetching
1246        if(!defined('DOKU_E_LEVEL')) {
1247            $elvl = error_reporting(E_ERROR);
1248        }
1249        $rc = $feed->init();
1250        if(isset($elvl)) {
1251            error_reporting($elvl);
1252        }
1253
1254        if($params['nosort']) $feed->enable_order_by_date(false);
1255
1256        //decide on start and end
1257        if($params['reverse']) {
1258            $mod   = -1;
1259            $start = $feed->get_item_quantity() - 1;
1260            $end   = $start - ($params['max']);
1261            $end   = ($end < -1) ? -1 : $end;
1262        } else {
1263            $mod   = 1;
1264            $start = 0;
1265            $end   = $feed->get_item_quantity();
1266            $end   = ($end > $params['max']) ? $params['max'] : $end;
1267        }
1268
1269        $this->doc .= '<ul class="rss">';
1270        if($rc) {
1271            for($x = $start; $x != $end; $x += $mod) {
1272                $item = $feed->get_item($x);
1273                $this->doc .= '<li><div class="li">';
1274                // support feeds without links
1275                $lnkurl = $item->get_permalink();
1276                if($lnkurl) {
1277                    // title is escaped by SimplePie, we unescape here because it
1278                    // is escaped again in externallink() FS#1705
1279                    $this->externallink(
1280                        $item->get_permalink(),
1281                        html_entity_decode($item->get_title(), ENT_QUOTES, 'UTF-8')
1282                    );
1283                } else {
1284                    $this->doc .= ' '.$item->get_title();
1285                }
1286                if($params['author']) {
1287                    $author = $item->get_author(0);
1288                    if($author) {
1289                        $name = $author->get_name();
1290                        if(!$name) $name = $author->get_email();
1291                        if($name) $this->doc .= ' '.$lang['by'].' '.$name;
1292                    }
1293                }
1294                if($params['date']) {
1295                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
1296                }
1297                if($params['details']) {
1298                    $this->doc .= '<div class="detail">';
1299                    if($conf['htmlok']) {
1300                        $this->doc .= $item->get_description();
1301                    } else {
1302                        $this->doc .= strip_tags($item->get_description());
1303                    }
1304                    $this->doc .= '</div>';
1305                }
1306
1307                $this->doc .= '</div></li>';
1308            }
1309        } else {
1310            $this->doc .= '<li><div class="li">';
1311            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
1312            $this->externallink($url);
1313            if($conf['allowdebug']) {
1314                $this->doc .= '<!--'.hsc($feed->error).'-->';
1315            }
1316            $this->doc .= '</div></li>';
1317        }
1318        $this->doc .= '</ul>';
1319    }
1320
1321    /**
1322     * Start a table
1323     *
1324     * @param int $maxcols maximum number of columns
1325     * @param int $numrows NOT IMPLEMENTED
1326     * @param int $pos byte position in the original source
1327     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1328     */
1329    function table_open($maxcols = null, $numrows = null, $pos = null, $classes = null) {
1330        // initialize the row counter used for classes
1331        $this->_counter['row_counter'] = 0;
1332        $class                         = 'table';
1333        if($classes !== null) {
1334            if(is_array($classes)) $classes = join(' ', $classes);
1335            $class .= ' ' . $classes;
1336        }
1337        if($pos !== null) {
1338            $class .= ' '.$this->startSectionEdit($pos, 'table');
1339        }
1340        $this->doc .= '<div class="'.$class.'"><table class="inline">'.
1341            DOKU_LF;
1342    }
1343
1344    /**
1345     * Close a table
1346     *
1347     * @param int $pos byte position in the original source
1348     */
1349    function table_close($pos = null) {
1350        $this->doc .= '</table></div>'.DOKU_LF;
1351        if($pos !== null) {
1352            $this->finishSectionEdit($pos);
1353        }
1354    }
1355
1356    /**
1357     * Open a table header
1358     */
1359    function tablethead_open() {
1360        $this->doc .= DOKU_TAB.'<thead>'.DOKU_LF;
1361    }
1362
1363    /**
1364     * Close a table header
1365     */
1366    function tablethead_close() {
1367        $this->doc .= DOKU_TAB.'</thead>'.DOKU_LF;
1368    }
1369
1370    /**
1371     * Open a table body
1372     */
1373    function tabletbody_open() {
1374        $this->doc .= DOKU_TAB.'<tbody>'.DOKU_LF;
1375    }
1376
1377    /**
1378     * Close a table body
1379     */
1380    function tabletbody_close() {
1381        $this->doc .= DOKU_TAB.'</tbody>'.DOKU_LF;
1382    }
1383
1384    /**
1385     * Open a table footer
1386     */
1387    function tabletfoot_open() {
1388        $this->doc .= DOKU_TAB.'<tfoot>'.DOKU_LF;
1389    }
1390
1391    /**
1392     * Close a table footer
1393     */
1394    function tabletfoot_close() {
1395        $this->doc .= DOKU_TAB.'</tfoot>'.DOKU_LF;
1396    }
1397
1398    /**
1399     * Open a table row
1400     *
1401     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1402     */
1403    function tablerow_open($classes = null) {
1404        // initialize the cell counter used for classes
1405        $this->_counter['cell_counter'] = 0;
1406        $class                          = 'row'.$this->_counter['row_counter']++;
1407        if($classes !== null) {
1408            if(is_array($classes)) $classes = join(' ', $classes);
1409            $class .= ' ' . $classes;
1410        }
1411        $this->doc .= DOKU_TAB.'<tr class="'.$class.'">'.DOKU_LF.DOKU_TAB.DOKU_TAB;
1412    }
1413
1414    /**
1415     * Close a table row
1416     */
1417    function tablerow_close() {
1418        $this->doc .= DOKU_LF.DOKU_TAB.'</tr>'.DOKU_LF;
1419    }
1420
1421    /**
1422     * Open a table header cell
1423     *
1424     * @param int    $colspan
1425     * @param string $align left|center|right
1426     * @param int    $rowspan
1427     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1428     */
1429    function tableheader_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) {
1430        $class = 'class="col'.$this->_counter['cell_counter']++;
1431        if(!is_null($align)) {
1432            $class .= ' '.$align.'align';
1433        }
1434        if($classes !== null) {
1435            if(is_array($classes)) $classes = join(' ', $classes);
1436            $class .= ' ' . $classes;
1437        }
1438        $class .= '"';
1439        $this->doc .= '<th '.$class;
1440        if($colspan > 1) {
1441            $this->_counter['cell_counter'] += $colspan - 1;
1442            $this->doc .= ' colspan="'.$colspan.'"';
1443        }
1444        if($rowspan > 1) {
1445            $this->doc .= ' rowspan="'.$rowspan.'"';
1446        }
1447        $this->doc .= '>';
1448    }
1449
1450    /**
1451     * Close a table header cell
1452     */
1453    function tableheader_close() {
1454        $this->doc .= '</th>';
1455    }
1456
1457    /**
1458     * Open a table cell
1459     *
1460     * @param int       $colspan
1461     * @param string    $align left|center|right
1462     * @param int       $rowspan
1463     * @param string|string[]    $classes css classes - have to be valid, do not pass unfiltered user input
1464     */
1465    function tablecell_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) {
1466        $class = 'class="col'.$this->_counter['cell_counter']++;
1467        if(!is_null($align)) {
1468            $class .= ' '.$align.'align';
1469        }
1470        if($classes !== null) {
1471            if(is_array($classes)) $classes = join(' ', $classes);
1472            $class .= ' ' . $classes;
1473        }
1474        $class .= '"';
1475        $this->doc .= '<td '.$class;
1476        if($colspan > 1) {
1477            $this->_counter['cell_counter'] += $colspan - 1;
1478            $this->doc .= ' colspan="'.$colspan.'"';
1479        }
1480        if($rowspan > 1) {
1481            $this->doc .= ' rowspan="'.$rowspan.'"';
1482        }
1483        $this->doc .= '>';
1484    }
1485
1486    /**
1487     * Close a table cell
1488     */
1489    function tablecell_close() {
1490        $this->doc .= '</td>';
1491    }
1492
1493    /**
1494     * Returns the current header level.
1495     * (required e.g. by the filelist plugin)
1496     *
1497     * @return int The current header level
1498     */
1499    function getLastlevel() {
1500        return $this->lastlevel;
1501    }
1502
1503    #region Utility functions
1504
1505    /**
1506     * Build a link
1507     *
1508     * Assembles all parts defined in $link returns HTML for the link
1509     *
1510     * @param array $link attributes of a link
1511     * @return string
1512     *
1513     * @author Andreas Gohr <andi@splitbrain.org>
1514     */
1515    function _formatLink($link) {
1516        //make sure the url is XHTML compliant (skip mailto)
1517        if(substr($link['url'], 0, 7) != 'mailto:') {
1518            $link['url'] = str_replace('&', '&amp;', $link['url']);
1519            $link['url'] = str_replace('&amp;amp;', '&amp;', $link['url']);
1520        }
1521        //remove double encodings in titles
1522        $link['title'] = str_replace('&amp;amp;', '&amp;', $link['title']);
1523
1524        // be sure there are no bad chars in url or title
1525        // (we can't do this for name because it can contain an img tag)
1526        $link['url']   = strtr($link['url'], array('>' => '%3E', '<' => '%3C', '"' => '%22'));
1527        $link['title'] = strtr($link['title'], array('>' => '&gt;', '<' => '&lt;', '"' => '&quot;'));
1528
1529        $ret = '';
1530        $ret .= $link['pre'];
1531        $ret .= '<a href="'.$link['url'].'"';
1532        if(!empty($link['class'])) $ret .= ' class="'.$link['class'].'"';
1533        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1534        if(!empty($link['title'])) $ret .= ' title="'.$link['title'].'"';
1535        if(!empty($link['style'])) $ret .= ' style="'.$link['style'].'"';
1536        if(!empty($link['rel'])) $ret .= ' rel="'.trim($link['rel']).'"';
1537        if(!empty($link['more'])) $ret .= ' '.$link['more'];
1538        $ret .= '>';
1539        $ret .= $link['name'];
1540        $ret .= '</a>';
1541        $ret .= $link['suf'];
1542        return $ret;
1543    }
1544
1545    /**
1546     * Renders internal and external media
1547     *
1548     * @author Andreas Gohr <andi@splitbrain.org>
1549     * @param string $src       media ID
1550     * @param string $title     descriptive text
1551     * @param string $align     left|center|right
1552     * @param int    $width     width of media in pixel
1553     * @param int    $height    height of media in pixel
1554     * @param string $cache     cache|recache|nocache
1555     * @param bool   $render    should the media be embedded inline or just linked
1556     * @return string
1557     */
1558    function _media($src, $title = null, $align = null, $width = null,
1559                    $height = null, $cache = null, $render = true) {
1560
1561        $ret = '';
1562
1563        list($ext, $mime) = mimetype($src);
1564        if(substr($mime, 0, 5) == 'image') {
1565            // first get the $title
1566            if(!is_null($title)) {
1567                $title = $this->_xmlEntities($title);
1568            } elseif($ext == 'jpg' || $ext == 'jpeg') {
1569                //try to use the caption from IPTC/EXIF
1570                require_once(DOKU_INC.'inc/JpegMeta.php');
1571                $jpeg = new JpegMeta(mediaFN($src));
1572                if($jpeg !== false) $cap = $jpeg->getTitle();
1573                if(!empty($cap)) {
1574                    $title = $this->_xmlEntities($cap);
1575                }
1576            }
1577            if(!$render) {
1578                // if the picture is not supposed to be rendered
1579                // return the title of the picture
1580                if(!$title) {
1581                    // just show the sourcename
1582                    $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1583                }
1584                return $title;
1585            }
1586            //add image tag
1587            $ret .= '<img src="'.ml($src, array('w' => $width, 'h' => $height, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src))).'"';
1588            $ret .= ' class="media'.$align.'"';
1589
1590            if($title) {
1591                $ret .= ' title="'.$title.'"';
1592                $ret .= ' alt="'.$title.'"';
1593            } else {
1594                $ret .= ' alt=""';
1595            }
1596
1597            if(!is_null($width))
1598                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1599
1600            if(!is_null($height))
1601                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1602
1603            $ret .= ' />';
1604
1605        } elseif(media_supportedav($mime, 'video') || media_supportedav($mime, 'audio')) {
1606            // first get the $title
1607            $title = !is_null($title) ? $this->_xmlEntities($title) : false;
1608            if(!$render) {
1609                // if the file is not supposed to be rendered
1610                // return the title of the file (just the sourcename if there is no title)
1611                return $title ? $title : $this->_xmlEntities(utf8_basename(noNS($src)));
1612            }
1613
1614            $att          = array();
1615            $att['class'] = "media$align";
1616            if($title) {
1617                $att['title'] = $title;
1618            }
1619
1620            if(media_supportedav($mime, 'video')) {
1621                //add video
1622                $ret .= $this->_video($src, $width, $height, $att);
1623            }
1624            if(media_supportedav($mime, 'audio')) {
1625                //add audio
1626                $ret .= $this->_audio($src, $att);
1627            }
1628
1629        } elseif($mime == 'application/x-shockwave-flash') {
1630            if(!$render) {
1631                // if the flash is not supposed to be rendered
1632                // return the title of the flash
1633                if(!$title) {
1634                    // just show the sourcename
1635                    $title = utf8_basename(noNS($src));
1636                }
1637                return $this->_xmlEntities($title);
1638            }
1639
1640            $att          = array();
1641            $att['class'] = "media$align";
1642            if($align == 'right') $att['align'] = 'right';
1643            if($align == 'left') $att['align'] = 'left';
1644            $ret .= html_flashobject(
1645                ml($src, array('cache' => $cache), true, '&'), $width, $height,
1646                array('quality' => 'high'),
1647                null,
1648                $att,
1649                $this->_xmlEntities($title)
1650            );
1651        } elseif($title) {
1652            // well at least we have a title to display
1653            $ret .= $this->_xmlEntities($title);
1654        } else {
1655            // just show the sourcename
1656            $ret .= $this->_xmlEntities(utf8_basename(noNS($src)));
1657        }
1658
1659        return $ret;
1660    }
1661
1662    /**
1663     * Escape string for output
1664     *
1665     * @param $string
1666     * @return string
1667     */
1668    function _xmlEntities($string) {
1669        return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
1670    }
1671
1672    /**
1673     * Creates a linkid from a headline
1674     *
1675     * @author Andreas Gohr <andi@splitbrain.org>
1676     * @param string  $title   The headline title
1677     * @param boolean $create  Create a new unique ID?
1678     * @return string
1679     */
1680    function _headerToLink($title, $create = false) {
1681        if($create) {
1682            return sectionID($title, $this->headers);
1683        } else {
1684            $check = false;
1685            return sectionID($title, $check);
1686        }
1687    }
1688
1689    /**
1690     * Construct a title and handle images in titles
1691     *
1692     * @author Harry Fuecks <hfuecks@gmail.com>
1693     * @param string|array $title    either string title or media array
1694     * @param string       $default  default title if nothing else is found
1695     * @param bool         $isImage  will be set to true if it's a media file
1696     * @param null|string  $id       linked page id (used to extract title from first heading)
1697     * @param string       $linktype content|navigation
1698     * @return string      HTML of the title, might be full image tag or just escaped text
1699     */
1700    function _getLinkTitle($title, $default, &$isImage, $id = null, $linktype = 'content') {
1701        $isImage = false;
1702        if(is_array($title)) {
1703            $isImage = true;
1704            return $this->_imageTitle($title);
1705        } elseif(is_null($title) || trim($title) == '') {
1706            if(useHeading($linktype) && $id) {
1707                $heading = p_get_first_heading($id);
1708                if(!blank($heading)) {
1709                    return $this->_xmlEntities($heading);
1710                }
1711            }
1712            return $this->_xmlEntities($default);
1713        } else {
1714            return $this->_xmlEntities($title);
1715        }
1716    }
1717
1718    /**
1719     * Returns HTML code for images used in link titles
1720     *
1721     * @author Andreas Gohr <andi@splitbrain.org>
1722     * @param array $img
1723     * @return string HTML img tag or similar
1724     */
1725    function _imageTitle($img) {
1726        global $ID;
1727
1728        // some fixes on $img['src']
1729        // see internalmedia() and externalmedia()
1730        list($img['src']) = explode('#', $img['src'], 2);
1731        if($img['type'] == 'internalmedia') {
1732            resolve_mediaid(getNS($ID), $img['src'], $exists ,$this->date_at, true);
1733        }
1734
1735        return $this->_media(
1736            $img['src'],
1737            $img['title'],
1738            $img['align'],
1739            $img['width'],
1740            $img['height'],
1741            $img['cache']
1742        );
1743    }
1744
1745    /**
1746     * helperfunction to return a basic link to a media
1747     *
1748     * used in internalmedia() and externalmedia()
1749     *
1750     * @author   Pierre Spring <pierre.spring@liip.ch>
1751     * @param string $src       media ID
1752     * @param string $title     descriptive text
1753     * @param string $align     left|center|right
1754     * @param int    $width     width of media in pixel
1755     * @param int    $height    height of media in pixel
1756     * @param string $cache     cache|recache|nocache
1757     * @param bool   $render    should the media be embedded inline or just linked
1758     * @return array associative array with link config
1759     */
1760    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) {
1761        global $conf;
1762
1763        $link           = array();
1764        $link['class']  = 'media';
1765        $link['style']  = '';
1766        $link['pre']    = '';
1767        $link['suf']    = '';
1768        $link['more']   = '';
1769        $link['target'] = $conf['target']['media'];
1770        if($conf['target']['media']) $link['rel'] = 'noopener';
1771        $link['title']  = $this->_xmlEntities($src);
1772        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1773
1774        return $link;
1775    }
1776
1777    /**
1778     * Embed video(s) in HTML
1779     *
1780     * @author Anika Henke <anika@selfthinker.org>
1781     *
1782     * @param string $src         - ID of video to embed
1783     * @param int    $width       - width of the video in pixels
1784     * @param int    $height      - height of the video in pixels
1785     * @param array  $atts        - additional attributes for the <video> tag
1786     * @return string
1787     */
1788    function _video($src, $width, $height, $atts = null) {
1789        // prepare width and height
1790        if(is_null($atts)) $atts = array();
1791        $atts['width']  = (int) $width;
1792        $atts['height'] = (int) $height;
1793        if(!$atts['width']) $atts['width'] = 320;
1794        if(!$atts['height']) $atts['height'] = 240;
1795
1796        $posterUrl = '';
1797        $files = array();
1798        $isExternal = media_isexternal($src);
1799
1800        if ($isExternal) {
1801            // take direct source for external files
1802            list(/*ext*/, $srcMime) = mimetype($src);
1803            $files[$srcMime] = $src;
1804        } else {
1805            // prepare alternative formats
1806            $extensions   = array('webm', 'ogv', 'mp4');
1807            $files        = media_alternativefiles($src, $extensions);
1808            $poster       = media_alternativefiles($src, array('jpg', 'png'));
1809            if(!empty($poster)) {
1810                $posterUrl = ml(reset($poster), '', true, '&');
1811            }
1812        }
1813
1814        $out = '';
1815        // open video tag
1816        $out .= '<video '.buildAttributes($atts).' controls="controls"';
1817        if($posterUrl) $out .= ' poster="'.hsc($posterUrl).'"';
1818        $out .= '>'.NL;
1819        $fallback = '';
1820
1821        // output source for each alternative video format
1822        foreach($files as $mime => $file) {
1823            if ($isExternal) {
1824                $url = $file;
1825                $linkType = 'externalmedia';
1826            } else {
1827                $url = ml($file, '', true, '&');
1828                $linkType = 'internalmedia';
1829            }
1830            $title = $atts['title'] ? $atts['title'] : $this->_xmlEntities(utf8_basename(noNS($file)));
1831
1832            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1833            // alternative content (just a link to the file)
1834            $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true);
1835        }
1836
1837        // finish
1838        $out .= $fallback;
1839        $out .= '</video>'.NL;
1840        return $out;
1841    }
1842
1843    /**
1844     * Embed audio in HTML
1845     *
1846     * @author Anika Henke <anika@selfthinker.org>
1847     *
1848     * @param string $src       - ID of audio to embed
1849     * @param array  $atts      - additional attributes for the <audio> tag
1850     * @return string
1851     */
1852    function _audio($src, $atts = array()) {
1853        $files = array();
1854        $isExternal = media_isexternal($src);
1855
1856        if ($isExternal) {
1857            // take direct source for external files
1858            list(/*ext*/, $srcMime) = mimetype($src);
1859            $files[$srcMime] = $src;
1860        } else {
1861            // prepare alternative formats
1862            $extensions   = array('ogg', 'mp3', 'wav');
1863            $files        = media_alternativefiles($src, $extensions);
1864        }
1865
1866        $out = '';
1867        // open audio tag
1868        $out .= '<audio '.buildAttributes($atts).' controls="controls">'.NL;
1869        $fallback = '';
1870
1871        // output source for each alternative audio format
1872        foreach($files as $mime => $file) {
1873            if ($isExternal) {
1874                $url = $file;
1875                $linkType = 'externalmedia';
1876            } else {
1877                $url = ml($file, '', true, '&');
1878                $linkType = 'internalmedia';
1879            }
1880            $title = $atts['title'] ? $atts['title'] : $this->_xmlEntities(utf8_basename(noNS($file)));
1881
1882            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1883            // alternative content (just a link to the file)
1884            $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true);
1885        }
1886
1887        // finish
1888        $out .= $fallback;
1889        $out .= '</audio>'.NL;
1890        return $out;
1891    }
1892
1893    /**
1894     * _getLastMediaRevisionAt is a helperfunction to internalmedia() and _media()
1895     * which returns an existing media revision less or equal to rev or date_at
1896     *
1897     * @author lisps
1898     * @param string $media_id
1899     * @access protected
1900     * @return string revision ('' for current)
1901     */
1902    function _getLastMediaRevisionAt($media_id){
1903        if(!$this->date_at || media_isexternal($media_id)) return '';
1904        $pagelog = new MediaChangeLog($media_id);
1905        return $pagelog->getLastRevisionAt($this->date_at);
1906    }
1907
1908    #endregion
1909}
1910
1911//Setup VIM: ex: et ts=4 :
1912