xref: /dokuwiki/inc/parser/xhtml.php (revision 1987d368afe497e222089d29493d5116c962e110)
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     */
605    function file($text, $language = null, $filename = null) {
606        $this->_highlight('file', $text, $language, $filename);
607    }
608
609    /**
610     * Display text as code content, optionally syntax highlighted
611     *
612     * @param string $text     text to show
613     * @param string $language programming language to use for syntax highlighting
614     * @param string $filename file path label
615     */
616    function code($text, $language = null, $filename = null) {
617        $this->_highlight('code', $text, $language, $filename);
618    }
619
620    /**
621     * Use GeSHi to highlight language syntax in code and file blocks
622     *
623     * @author Andreas Gohr <andi@splitbrain.org>
624     * @param string $type     code|file
625     * @param string $text     text to show
626     * @param string $language programming language to use for syntax highlighting
627     * @param string $filename file path label
628     */
629    function _highlight($type, $text, $language = null, $filename = null) {
630        global $ID;
631        global $lang;
632
633        $language = preg_replace(PREG_PATTERN_VALID_LANGUAGE, '', $language);
634
635        if($filename) {
636            // add icon
637            list($ext) = mimetype($filename, false);
638            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
639            $class = 'mediafile mf_'.$class;
640
641            $this->doc .= '<dl class="'.$type.'">'.DOKU_LF;
642            $this->doc .= '<dt><a href="'.exportlink($ID, 'code', array('codeblock' => $this->_codeblock)).'" title="'.$lang['download'].'" class="'.$class.'">';
643            $this->doc .= hsc($filename);
644            $this->doc .= '</a></dt>'.DOKU_LF.'<dd>';
645        }
646
647        if($text{0} == "\n") {
648            $text = substr($text, 1);
649        }
650        if(substr($text, -1) == "\n") {
651            $text = substr($text, 0, -1);
652        }
653
654        if(is_null($language)) {
655            $this->doc .= '<pre class="'.$type.'">'.$this->_xmlEntities($text).'</pre>'.DOKU_LF;
656        } else {
657            $class = 'code'; //we always need the code class to make the syntax highlighting apply
658            if($type != 'code') $class .= ' '.$type;
659
660            $this->doc .= "<pre class=\"$class $language\">".p_xhtml_cached_geshi($text, $language, '').'</pre>'.DOKU_LF;
661        }
662
663        if($filename) {
664            $this->doc .= '</dd></dl>'.DOKU_LF;
665        }
666
667        $this->_codeblock++;
668    }
669
670    /**
671     * Format an acronym
672     *
673     * Uses $this->acronyms
674     *
675     * @param string $acronym
676     */
677    function acronym($acronym) {
678
679        if(array_key_exists($acronym, $this->acronyms)) {
680
681            $title = $this->_xmlEntities($this->acronyms[$acronym]);
682
683            $this->doc .= '<abbr title="'.$title
684                .'">'.$this->_xmlEntities($acronym).'</abbr>';
685
686        } else {
687            $this->doc .= $this->_xmlEntities($acronym);
688        }
689    }
690
691    /**
692     * Format a smiley
693     *
694     * Uses $this->smiley
695     *
696     * @param string $smiley
697     */
698    function smiley($smiley) {
699        if(array_key_exists($smiley, $this->smileys)) {
700            $this->doc .= '<img src="'.DOKU_BASE.'lib/images/smileys/'.$this->smileys[$smiley].
701                '" class="icon" alt="'.
702                $this->_xmlEntities($smiley).'" />';
703        } else {
704            $this->doc .= $this->_xmlEntities($smiley);
705        }
706    }
707
708    /**
709     * Format an entity
710     *
711     * Entities are basically small text replacements
712     *
713     * Uses $this->entities
714     *
715     * @param string $entity
716     */
717    function entity($entity) {
718        if(array_key_exists($entity, $this->entities)) {
719            $this->doc .= $this->entities[$entity];
720        } else {
721            $this->doc .= $this->_xmlEntities($entity);
722        }
723    }
724
725    /**
726     * Typographically format a multiply sign
727     *
728     * Example: ($x=640, $y=480) should result in "640×480"
729     *
730     * @param string|int $x first value
731     * @param string|int $y second value
732     */
733    function multiplyentity($x, $y) {
734        $this->doc .= "$x&times;$y";
735    }
736
737    /**
738     * Render an opening single quote char (language specific)
739     */
740    function singlequoteopening() {
741        global $lang;
742        $this->doc .= $lang['singlequoteopening'];
743    }
744
745    /**
746     * Render a closing single quote char (language specific)
747     */
748    function singlequoteclosing() {
749        global $lang;
750        $this->doc .= $lang['singlequoteclosing'];
751    }
752
753    /**
754     * Render an apostrophe char (language specific)
755     */
756    function apostrophe() {
757        global $lang;
758        $this->doc .= $lang['apostrophe'];
759    }
760
761    /**
762     * Render an opening double quote char (language specific)
763     */
764    function doublequoteopening() {
765        global $lang;
766        $this->doc .= $lang['doublequoteopening'];
767    }
768
769    /**
770     * Render an closinging double quote char (language specific)
771     */
772    function doublequoteclosing() {
773        global $lang;
774        $this->doc .= $lang['doublequoteclosing'];
775    }
776
777    /**
778     * Render a CamelCase link
779     *
780     * @param string $link       The link name
781     * @param bool   $returnonly whether to return html or write to doc attribute
782     * @return void|string writes to doc attribute or returns html depends on $returnonly
783     *
784     * @see http://en.wikipedia.org/wiki/CamelCase
785     */
786    function camelcaselink($link, $returnonly = false) {
787        if($returnonly) {
788          return $this->internallink($link, $link, null, true);
789        } else {
790          $this->internallink($link, $link);
791        }
792    }
793
794    /**
795     * Render a page local link
796     *
797     * @param string $hash       hash link identifier
798     * @param string $name       name for the link
799     * @param bool   $returnonly whether to return html or write to doc attribute
800     * @return void|string writes to doc attribute or returns html depends on $returnonly
801     */
802    function locallink($hash, $name = null, $returnonly = false) {
803        global $ID;
804        $name  = $this->_getLinkTitle($name, $hash, $isImage);
805        $hash  = $this->_headerToLink($hash);
806        $title = $ID.' ↵';
807
808        $doc = '<a href="#'.$hash.'" title="'.$title.'" class="wikilink1">';
809        $doc .= $name;
810        $doc .= '</a>';
811
812        if($returnonly) {
813          return $doc;
814        } else {
815          $this->doc .= $doc;
816        }
817    }
818
819    /**
820     * Render an internal Wiki Link
821     *
822     * $search,$returnonly & $linktype are not for the renderer but are used
823     * elsewhere - no need to implement them in other renderers
824     *
825     * @author Andreas Gohr <andi@splitbrain.org>
826     * @param string      $id         pageid
827     * @param string|null $name       link name
828     * @param string|null $search     adds search url param
829     * @param bool        $returnonly whether to return html or write to doc attribute
830     * @param string      $linktype   type to set use of headings
831     * @return void|string writes to doc attribute or returns html depends on $returnonly
832     */
833    function internallink($id, $name = null, $search = null, $returnonly = false, $linktype = 'content') {
834        global $conf;
835        global $ID;
836        global $INFO;
837
838        $params = '';
839        $parts  = explode('?', $id, 2);
840        if(count($parts) === 2) {
841            $id     = $parts[0];
842            $params = $parts[1];
843        }
844
845        // For empty $id we need to know the current $ID
846        // We need this check because _simpleTitle needs
847        // correct $id and resolve_pageid() use cleanID($id)
848        // (some things could be lost)
849        if($id === '') {
850            $id = $ID;
851        }
852
853        // default name is based on $id as given
854        $default = $this->_simpleTitle($id);
855
856        // now first resolve and clean up the $id
857        resolve_pageid(getNS($ID), $id, $exists, $this->date_at, true);
858
859        $link = array();
860        $name = $this->_getLinkTitle($name, $default, $isImage, $id, $linktype);
861        if(!$isImage) {
862            if($exists) {
863                $class = 'wikilink1';
864            } else {
865                $class       = 'wikilink2';
866                $link['rel'] = 'nofollow';
867            }
868        } else {
869            $class = 'media';
870        }
871
872        //keep hash anchor
873        @list($id, $hash) = explode('#', $id, 2);
874        if(!empty($hash)) $hash = $this->_headerToLink($hash);
875
876        //prepare for formating
877        $link['target'] = $conf['target']['wiki'];
878        $link['style']  = '';
879        $link['pre']    = '';
880        $link['suf']    = '';
881        // highlight link to current page
882        if($id == $INFO['id']) {
883            $link['pre'] = '<span class="curid">';
884            $link['suf'] = '</span>';
885        }
886        $link['more']   = '';
887        $link['class']  = $class;
888        if($this->date_at) {
889            $params['at'] = $this->date_at;
890        }
891        $link['url']    = wl($id, $params);
892        $link['name']   = $name;
893        $link['title']  = $id;
894        //add search string
895        if($search) {
896            ($conf['userewrite']) ? $link['url'] .= '?' : $link['url'] .= '&amp;';
897            if(is_array($search)) {
898                $search = array_map('rawurlencode', $search);
899                $link['url'] .= 's[]='.join('&amp;s[]=', $search);
900            } else {
901                $link['url'] .= 's='.rawurlencode($search);
902            }
903        }
904
905        //keep hash
906        if($hash) $link['url'] .= '#'.$hash;
907
908        //output formatted
909        if($returnonly) {
910            return $this->_formatLink($link);
911        } else {
912            $this->doc .= $this->_formatLink($link);
913        }
914    }
915
916    /**
917     * Render an external link
918     *
919     * @param string       $url        full URL with scheme
920     * @param string|array $name       name for the link, array for media file
921     * @param bool         $returnonly whether to return html or write to doc attribute
922     * @return void|string writes to doc attribute or returns html depends on $returnonly
923     */
924    function externallink($url, $name = null, $returnonly = false) {
925        global $conf;
926
927        $name = $this->_getLinkTitle($name, $url, $isImage);
928
929        // url might be an attack vector, only allow registered protocols
930        if(is_null($this->schemes)) $this->schemes = getSchemes();
931        list($scheme) = explode('://', $url);
932        $scheme = strtolower($scheme);
933        if(!in_array($scheme, $this->schemes)) $url = '';
934
935        // is there still an URL?
936        if(!$url) {
937            if($returnonly) {
938                return $name;
939            } else {
940                $this->doc .= $name;
941            }
942            return;
943        }
944
945        // set class
946        if(!$isImage) {
947            $class = 'urlextern';
948        } else {
949            $class = 'media';
950        }
951
952        //prepare for formating
953        $link = array();
954        $link['target'] = $conf['target']['extern'];
955        $link['style']  = '';
956        $link['pre']    = '';
957        $link['suf']    = '';
958        $link['more']   = '';
959        $link['class']  = $class;
960        $link['url']    = $url;
961        $link['rel']    = '';
962
963        $link['name']  = $name;
964        $link['title'] = $this->_xmlEntities($url);
965        if($conf['relnofollow']) $link['rel'] .= ' nofollow';
966        if($conf['target']['extern']) $link['rel'] .= ' noopener';
967
968        //output formatted
969        if($returnonly) {
970            return $this->_formatLink($link);
971        } else {
972            $this->doc .= $this->_formatLink($link);
973        }
974    }
975
976    /**
977     * Render an interwiki link
978     *
979     * You may want to use $this->_resolveInterWiki() here
980     *
981     * @param string       $match      original link - probably not much use
982     * @param string|array $name       name for the link, array for media file
983     * @param string       $wikiName   indentifier (shortcut) for the remote wiki
984     * @param string       $wikiUri    the fragment parsed from the original link
985     * @param bool         $returnonly whether to return html or write to doc attribute
986     * @return void|string writes to doc attribute or returns html depends on $returnonly
987     */
988    function interwikilink($match, $name = null, $wikiName, $wikiUri, $returnonly = false) {
989        global $conf;
990
991        $link           = array();
992        $link['target'] = $conf['target']['interwiki'];
993        $link['pre']    = '';
994        $link['suf']    = '';
995        $link['more']   = '';
996        $link['name']   = $this->_getLinkTitle($name, $wikiUri, $isImage);
997        $link['rel']    = '';
998
999        //get interwiki URL
1000        $exists = null;
1001        $url    = $this->_resolveInterWiki($wikiName, $wikiUri, $exists);
1002
1003        if(!$isImage) {
1004            $class         = preg_replace('/[^_\-a-z0-9]+/i', '_', $wikiName);
1005            $link['class'] = "interwiki iw_$class";
1006        } else {
1007            $link['class'] = 'media';
1008        }
1009
1010        //do we stay at the same server? Use local target
1011        if(strpos($url, DOKU_URL) === 0 OR strpos($url, DOKU_BASE) === 0) {
1012            $link['target'] = $conf['target']['wiki'];
1013        }
1014        if($exists !== null && !$isImage) {
1015            if($exists) {
1016                $link['class'] .= ' wikilink1';
1017            } else {
1018                $link['class'] .= ' wikilink2';
1019                $link['rel'] .= ' nofollow';
1020            }
1021        }
1022        if($conf['target']['interwiki']) $link['rel'] .= ' noopener';
1023
1024        $link['url']   = $url;
1025        $link['title'] = htmlspecialchars($link['url']);
1026
1027        //output formatted
1028        if($returnonly) {
1029            return $this->_formatLink($link);
1030        } else {
1031            $this->doc .= $this->_formatLink($link);
1032        }
1033    }
1034
1035    /**
1036     * Link to windows share
1037     *
1038     * @param string       $url        the link
1039     * @param string|array $name       name for the link, array for media file
1040     * @param bool         $returnonly whether to return html or write to doc attribute
1041     * @return void|string writes to doc attribute or returns html depends on $returnonly
1042     */
1043    function windowssharelink($url, $name = null, $returnonly = false) {
1044        global $conf;
1045
1046        //simple setup
1047        $link = array();
1048        $link['target'] = $conf['target']['windows'];
1049        $link['pre']    = '';
1050        $link['suf']    = '';
1051        $link['style']  = '';
1052
1053        $link['name'] = $this->_getLinkTitle($name, $url, $isImage);
1054        if(!$isImage) {
1055            $link['class'] = 'windows';
1056        } else {
1057            $link['class'] = 'media';
1058        }
1059
1060        $link['title'] = $this->_xmlEntities($url);
1061        $url           = str_replace('\\', '/', $url);
1062        $url           = 'file:///'.$url;
1063        $link['url']   = $url;
1064
1065        //output formatted
1066        if($returnonly) {
1067            return $this->_formatLink($link);
1068        } else {
1069            $this->doc .= $this->_formatLink($link);
1070        }
1071    }
1072
1073    /**
1074     * Render a linked E-Mail Address
1075     *
1076     * Honors $conf['mailguard'] setting
1077     *
1078     * @param string       $address    Email-Address
1079     * @param string|array $name       name for the link, array for media file
1080     * @param bool         $returnonly whether to return html or write to doc attribute
1081     * @return void|string writes to doc attribute or returns html depends on $returnonly
1082     */
1083    function emaillink($address, $name = null, $returnonly = false) {
1084        global $conf;
1085        //simple setup
1086        $link           = array();
1087        $link['target'] = '';
1088        $link['pre']    = '';
1089        $link['suf']    = '';
1090        $link['style']  = '';
1091        $link['more']   = '';
1092
1093        $name = $this->_getLinkTitle($name, '', $isImage);
1094        if(!$isImage) {
1095            $link['class'] = 'mail';
1096        } else {
1097            $link['class'] = 'media';
1098        }
1099
1100        $address = $this->_xmlEntities($address);
1101        $address = obfuscate($address);
1102        $title   = $address;
1103
1104        if(empty($name)) {
1105            $name = $address;
1106        }
1107
1108        if($conf['mailguard'] == 'visible') $address = rawurlencode($address);
1109
1110        $link['url']   = 'mailto:'.$address;
1111        $link['name']  = $name;
1112        $link['title'] = $title;
1113
1114        //output formatted
1115        if($returnonly) {
1116            return $this->_formatLink($link);
1117        } else {
1118            $this->doc .= $this->_formatLink($link);
1119        }
1120    }
1121
1122    /**
1123     * Render an internal media file
1124     *
1125     * @param string $src       media ID
1126     * @param string $title     descriptive text
1127     * @param string $align     left|center|right
1128     * @param int    $width     width of media in pixel
1129     * @param int    $height    height of media in pixel
1130     * @param string $cache     cache|recache|nocache
1131     * @param string $linking   linkonly|detail|nolink
1132     * @param bool   $return    return HTML instead of adding to $doc
1133     * @return void|string writes to doc attribute or returns html depends on $return
1134     */
1135    function internalmedia($src, $title = null, $align = null, $width = null,
1136                           $height = null, $cache = null, $linking = null, $return = false) {
1137        global $ID;
1138        if (strpos($src, '#') !== false) {
1139            list($src, $hash) = explode('#', $src, 2);
1140        }
1141        resolve_mediaid(getNS($ID), $src, $exists, $this->date_at, true);
1142
1143        $noLink = false;
1144        $render = ($linking == 'linkonly') ? false : true;
1145        $link   = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
1146
1147        list($ext, $mime) = mimetype($src, false);
1148        if(substr($mime, 0, 5) == 'image' && $render) {
1149            $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src)), ($linking == 'direct'));
1150        } elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render) {
1151            // don't link movies
1152            $noLink = true;
1153        } else {
1154            // add file icons
1155            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1156            $link['class'] .= ' mediafile mf_'.$class;
1157            $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache , 'rev'=>$this->_getLastMediaRevisionAt($src)), true);
1158            if($exists) $link['title'] .= ' ('.filesize_h(filesize(mediaFN($src))).')';
1159        }
1160
1161        if (!empty($hash)) $link['url'] .= '#'.$hash;
1162
1163        //markup non existing files
1164        if(!$exists) {
1165            $link['class'] .= ' wikilink2';
1166        }
1167
1168        //output formatted
1169        if($return) {
1170            if($linking == 'nolink' || $noLink) return $link['name'];
1171            else return $this->_formatLink($link);
1172        } else {
1173            if($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
1174            else $this->doc .= $this->_formatLink($link);
1175        }
1176    }
1177
1178    /**
1179     * Render an external media file
1180     *
1181     * @param string $src     full media URL
1182     * @param string $title   descriptive text
1183     * @param string $align   left|center|right
1184     * @param int    $width   width of media in pixel
1185     * @param int    $height  height of media in pixel
1186     * @param string $cache   cache|recache|nocache
1187     * @param string $linking linkonly|detail|nolink
1188     * @param bool   $return  return HTML instead of adding to $doc
1189     * @return void|string writes to doc attribute or returns html depends on $return
1190     */
1191    function externalmedia($src, $title = null, $align = null, $width = null,
1192                           $height = null, $cache = null, $linking = null, $return = false) {
1193        if(link_isinterwiki($src)){
1194            list($shortcut, $reference) = explode('>', $src, 2);
1195            $exists = null;
1196            $src = $this->_resolveInterWiki($shortcut, $reference, $exists);
1197        }
1198        list($src, $hash) = explode('#', $src, 2);
1199        $noLink = false;
1200        $render = ($linking == 'linkonly') ? false : true;
1201        $link   = $this->_getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render);
1202
1203        $link['url'] = ml($src, array('cache' => $cache));
1204
1205        list($ext, $mime) = mimetype($src, false);
1206        if(substr($mime, 0, 5) == 'image' && $render) {
1207            // link only jpeg images
1208            // if ($ext != 'jpg' && $ext != 'jpeg') $noLink = true;
1209        } elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render) {
1210            // don't link movies
1211            $noLink = true;
1212        } else {
1213            // add file icons
1214            $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1215            $link['class'] .= ' mediafile mf_'.$class;
1216        }
1217
1218        if($hash) $link['url'] .= '#'.$hash;
1219
1220        //output formatted
1221        if($return) {
1222            if($linking == 'nolink' || $noLink) return $link['name'];
1223            else return $this->_formatLink($link);
1224        } else {
1225            if($linking == 'nolink' || $noLink) $this->doc .= $link['name'];
1226            else $this->doc .= $this->_formatLink($link);
1227        }
1228    }
1229
1230    /**
1231     * Renders an RSS feed
1232     *
1233     * @param string $url    URL of the feed
1234     * @param array  $params Finetuning of the output
1235     *
1236     * @author Andreas Gohr <andi@splitbrain.org>
1237     */
1238    function rss($url, $params) {
1239        global $lang;
1240        global $conf;
1241
1242        require_once(DOKU_INC.'inc/FeedParser.php');
1243        $feed = new FeedParser();
1244        $feed->set_feed_url($url);
1245
1246        //disable warning while fetching
1247        if(!defined('DOKU_E_LEVEL')) {
1248            $elvl = error_reporting(E_ERROR);
1249        }
1250        $rc = $feed->init();
1251        if(isset($elvl)) {
1252            error_reporting($elvl);
1253        }
1254
1255        if($params['nosort']) $feed->enable_order_by_date(false);
1256
1257        //decide on start and end
1258        if($params['reverse']) {
1259            $mod   = -1;
1260            $start = $feed->get_item_quantity() - 1;
1261            $end   = $start - ($params['max']);
1262            $end   = ($end < -1) ? -1 : $end;
1263        } else {
1264            $mod   = 1;
1265            $start = 0;
1266            $end   = $feed->get_item_quantity();
1267            $end   = ($end > $params['max']) ? $params['max'] : $end;
1268        }
1269
1270        $this->doc .= '<ul class="rss">';
1271        if($rc) {
1272            for($x = $start; $x != $end; $x += $mod) {
1273                $item = $feed->get_item($x);
1274                $this->doc .= '<li><div class="li">';
1275                // support feeds without links
1276                $lnkurl = $item->get_permalink();
1277                if($lnkurl) {
1278                    // title is escaped by SimplePie, we unescape here because it
1279                    // is escaped again in externallink() FS#1705
1280                    $this->externallink(
1281                        $item->get_permalink(),
1282                        html_entity_decode($item->get_title(), ENT_QUOTES, 'UTF-8')
1283                    );
1284                } else {
1285                    $this->doc .= ' '.$item->get_title();
1286                }
1287                if($params['author']) {
1288                    $author = $item->get_author(0);
1289                    if($author) {
1290                        $name = $author->get_name();
1291                        if(!$name) $name = $author->get_email();
1292                        if($name) $this->doc .= ' '.$lang['by'].' '.hsc($name);
1293                    }
1294                }
1295                if($params['date']) {
1296                    $this->doc .= ' ('.$item->get_local_date($conf['dformat']).')';
1297                }
1298                if($params['details']) {
1299                    $this->doc .= '<div class="detail">';
1300                    if($conf['htmlok']) {
1301                        $this->doc .= $item->get_description();
1302                    } else {
1303                        $this->doc .= strip_tags($item->get_description());
1304                    }
1305                    $this->doc .= '</div>';
1306                }
1307
1308                $this->doc .= '</div></li>';
1309            }
1310        } else {
1311            $this->doc .= '<li><div class="li">';
1312            $this->doc .= '<em>'.$lang['rssfailed'].'</em>';
1313            $this->externallink($url);
1314            if($conf['allowdebug']) {
1315                $this->doc .= '<!--'.hsc($feed->error).'-->';
1316            }
1317            $this->doc .= '</div></li>';
1318        }
1319        $this->doc .= '</ul>';
1320    }
1321
1322    /**
1323     * Start a table
1324     *
1325     * @param int $maxcols maximum number of columns
1326     * @param int $numrows NOT IMPLEMENTED
1327     * @param int $pos byte position in the original source
1328     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1329     */
1330    function table_open($maxcols = null, $numrows = null, $pos = null, $classes = null) {
1331        // initialize the row counter used for classes
1332        $this->_counter['row_counter'] = 0;
1333        $class                         = 'table';
1334        if($classes !== null) {
1335            if(is_array($classes)) $classes = join(' ', $classes);
1336            $class .= ' ' . $classes;
1337        }
1338        if($pos !== null) {
1339            $class .= ' '.$this->startSectionEdit($pos, 'table');
1340        }
1341        $this->doc .= '<div class="'.$class.'"><table class="inline">'.
1342            DOKU_LF;
1343    }
1344
1345    /**
1346     * Close a table
1347     *
1348     * @param int $pos byte position in the original source
1349     */
1350    function table_close($pos = null) {
1351        $this->doc .= '</table></div>'.DOKU_LF;
1352        if($pos !== null) {
1353            $this->finishSectionEdit($pos);
1354        }
1355    }
1356
1357    /**
1358     * Open a table header
1359     */
1360    function tablethead_open() {
1361        $this->doc .= DOKU_TAB.'<thead>'.DOKU_LF;
1362    }
1363
1364    /**
1365     * Close a table header
1366     */
1367    function tablethead_close() {
1368        $this->doc .= DOKU_TAB.'</thead>'.DOKU_LF;
1369    }
1370
1371    /**
1372     * Open a table body
1373     */
1374    function tabletbody_open() {
1375        $this->doc .= DOKU_TAB.'<tbody>'.DOKU_LF;
1376    }
1377
1378    /**
1379     * Close a table body
1380     */
1381    function tabletbody_close() {
1382        $this->doc .= DOKU_TAB.'</tbody>'.DOKU_LF;
1383    }
1384
1385    /**
1386     * Open a table footer
1387     */
1388    function tabletfoot_open() {
1389        $this->doc .= DOKU_TAB.'<tfoot>'.DOKU_LF;
1390    }
1391
1392    /**
1393     * Close a table footer
1394     */
1395    function tabletfoot_close() {
1396        $this->doc .= DOKU_TAB.'</tfoot>'.DOKU_LF;
1397    }
1398
1399    /**
1400     * Open a table row
1401     *
1402     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1403     */
1404    function tablerow_open($classes = null) {
1405        // initialize the cell counter used for classes
1406        $this->_counter['cell_counter'] = 0;
1407        $class                          = 'row'.$this->_counter['row_counter']++;
1408        if($classes !== null) {
1409            if(is_array($classes)) $classes = join(' ', $classes);
1410            $class .= ' ' . $classes;
1411        }
1412        $this->doc .= DOKU_TAB.'<tr class="'.$class.'">'.DOKU_LF.DOKU_TAB.DOKU_TAB;
1413    }
1414
1415    /**
1416     * Close a table row
1417     */
1418    function tablerow_close() {
1419        $this->doc .= DOKU_LF.DOKU_TAB.'</tr>'.DOKU_LF;
1420    }
1421
1422    /**
1423     * Open a table header cell
1424     *
1425     * @param int    $colspan
1426     * @param string $align left|center|right
1427     * @param int    $rowspan
1428     * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input
1429     */
1430    function tableheader_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) {
1431        $class = 'class="col'.$this->_counter['cell_counter']++;
1432        if(!is_null($align)) {
1433            $class .= ' '.$align.'align';
1434        }
1435        if($classes !== null) {
1436            if(is_array($classes)) $classes = join(' ', $classes);
1437            $class .= ' ' . $classes;
1438        }
1439        $class .= '"';
1440        $this->doc .= '<th '.$class;
1441        if($colspan > 1) {
1442            $this->_counter['cell_counter'] += $colspan - 1;
1443            $this->doc .= ' colspan="'.$colspan.'"';
1444        }
1445        if($rowspan > 1) {
1446            $this->doc .= ' rowspan="'.$rowspan.'"';
1447        }
1448        $this->doc .= '>';
1449    }
1450
1451    /**
1452     * Close a table header cell
1453     */
1454    function tableheader_close() {
1455        $this->doc .= '</th>';
1456    }
1457
1458    /**
1459     * Open a table cell
1460     *
1461     * @param int       $colspan
1462     * @param string    $align left|center|right
1463     * @param int       $rowspan
1464     * @param string|string[]    $classes css classes - have to be valid, do not pass unfiltered user input
1465     */
1466    function tablecell_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) {
1467        $class = 'class="col'.$this->_counter['cell_counter']++;
1468        if(!is_null($align)) {
1469            $class .= ' '.$align.'align';
1470        }
1471        if($classes !== null) {
1472            if(is_array($classes)) $classes = join(' ', $classes);
1473            $class .= ' ' . $classes;
1474        }
1475        $class .= '"';
1476        $this->doc .= '<td '.$class;
1477        if($colspan > 1) {
1478            $this->_counter['cell_counter'] += $colspan - 1;
1479            $this->doc .= ' colspan="'.$colspan.'"';
1480        }
1481        if($rowspan > 1) {
1482            $this->doc .= ' rowspan="'.$rowspan.'"';
1483        }
1484        $this->doc .= '>';
1485    }
1486
1487    /**
1488     * Close a table cell
1489     */
1490    function tablecell_close() {
1491        $this->doc .= '</td>';
1492    }
1493
1494    /**
1495     * Returns the current header level.
1496     * (required e.g. by the filelist plugin)
1497     *
1498     * @return int The current header level
1499     */
1500    function getLastlevel() {
1501        return $this->lastlevel;
1502    }
1503
1504    #region Utility functions
1505
1506    /**
1507     * Build a link
1508     *
1509     * Assembles all parts defined in $link returns HTML for the link
1510     *
1511     * @param array $link attributes of a link
1512     * @return string
1513     *
1514     * @author Andreas Gohr <andi@splitbrain.org>
1515     */
1516    function _formatLink($link) {
1517        //make sure the url is XHTML compliant (skip mailto)
1518        if(substr($link['url'], 0, 7) != 'mailto:') {
1519            $link['url'] = str_replace('&', '&amp;', $link['url']);
1520            $link['url'] = str_replace('&amp;amp;', '&amp;', $link['url']);
1521        }
1522        //remove double encodings in titles
1523        $link['title'] = str_replace('&amp;amp;', '&amp;', $link['title']);
1524
1525        // be sure there are no bad chars in url or title
1526        // (we can't do this for name because it can contain an img tag)
1527        $link['url']   = strtr($link['url'], array('>' => '%3E', '<' => '%3C', '"' => '%22'));
1528        $link['title'] = strtr($link['title'], array('>' => '&gt;', '<' => '&lt;', '"' => '&quot;'));
1529
1530        $ret = '';
1531        $ret .= $link['pre'];
1532        $ret .= '<a href="'.$link['url'].'"';
1533        if(!empty($link['class'])) $ret .= ' class="'.$link['class'].'"';
1534        if(!empty($link['target'])) $ret .= ' target="'.$link['target'].'"';
1535        if(!empty($link['title'])) $ret .= ' title="'.$link['title'].'"';
1536        if(!empty($link['style'])) $ret .= ' style="'.$link['style'].'"';
1537        if(!empty($link['rel'])) $ret .= ' rel="'.trim($link['rel']).'"';
1538        if(!empty($link['more'])) $ret .= ' '.$link['more'];
1539        $ret .= '>';
1540        $ret .= $link['name'];
1541        $ret .= '</a>';
1542        $ret .= $link['suf'];
1543        return $ret;
1544    }
1545
1546    /**
1547     * Renders internal and external media
1548     *
1549     * @author Andreas Gohr <andi@splitbrain.org>
1550     * @param string $src       media ID
1551     * @param string $title     descriptive text
1552     * @param string $align     left|center|right
1553     * @param int    $width     width of media in pixel
1554     * @param int    $height    height of media in pixel
1555     * @param string $cache     cache|recache|nocache
1556     * @param bool   $render    should the media be embedded inline or just linked
1557     * @return string
1558     */
1559    function _media($src, $title = null, $align = null, $width = null,
1560                    $height = null, $cache = null, $render = true) {
1561
1562        $ret = '';
1563
1564        list($ext, $mime) = mimetype($src);
1565        if(substr($mime, 0, 5) == 'image') {
1566            // first get the $title
1567            if(!is_null($title)) {
1568                $title = $this->_xmlEntities($title);
1569            } elseif($ext == 'jpg' || $ext == 'jpeg') {
1570                //try to use the caption from IPTC/EXIF
1571                require_once(DOKU_INC.'inc/JpegMeta.php');
1572                $jpeg = new JpegMeta(mediaFN($src));
1573                if($jpeg !== false) $cap = $jpeg->getTitle();
1574                if(!empty($cap)) {
1575                    $title = $this->_xmlEntities($cap);
1576                }
1577            }
1578            if(!$render) {
1579                // if the picture is not supposed to be rendered
1580                // return the title of the picture
1581                if(!$title) {
1582                    // just show the sourcename
1583                    $title = $this->_xmlEntities(utf8_basename(noNS($src)));
1584                }
1585                return $title;
1586            }
1587            //add image tag
1588            $ret .= '<img src="'.ml($src, array('w' => $width, 'h' => $height, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src))).'"';
1589            $ret .= ' class="media'.$align.'"';
1590
1591            if($title) {
1592                $ret .= ' title="'.$title.'"';
1593                $ret .= ' alt="'.$title.'"';
1594            } else {
1595                $ret .= ' alt=""';
1596            }
1597
1598            if(!is_null($width))
1599                $ret .= ' width="'.$this->_xmlEntities($width).'"';
1600
1601            if(!is_null($height))
1602                $ret .= ' height="'.$this->_xmlEntities($height).'"';
1603
1604            $ret .= ' />';
1605
1606        } elseif(media_supportedav($mime, 'video') || media_supportedav($mime, 'audio')) {
1607            // first get the $title
1608            $title = !is_null($title) ? $this->_xmlEntities($title) : false;
1609            if(!$render) {
1610                // if the file is not supposed to be rendered
1611                // return the title of the file (just the sourcename if there is no title)
1612                return $title ? $title : $this->_xmlEntities(utf8_basename(noNS($src)));
1613            }
1614
1615            $att          = array();
1616            $att['class'] = "media$align";
1617            if($title) {
1618                $att['title'] = $title;
1619            }
1620
1621            if(media_supportedav($mime, 'video')) {
1622                //add video
1623                $ret .= $this->_video($src, $width, $height, $att);
1624            }
1625            if(media_supportedav($mime, 'audio')) {
1626                //add audio
1627                $ret .= $this->_audio($src, $att);
1628            }
1629
1630        } elseif($mime == 'application/x-shockwave-flash') {
1631            if(!$render) {
1632                // if the flash is not supposed to be rendered
1633                // return the title of the flash
1634                if(!$title) {
1635                    // just show the sourcename
1636                    $title = utf8_basename(noNS($src));
1637                }
1638                return $this->_xmlEntities($title);
1639            }
1640
1641            $att          = array();
1642            $att['class'] = "media$align";
1643            if($align == 'right') $att['align'] = 'right';
1644            if($align == 'left') $att['align'] = 'left';
1645            $ret .= html_flashobject(
1646                ml($src, array('cache' => $cache), true, '&'), $width, $height,
1647                array('quality' => 'high'),
1648                null,
1649                $att,
1650                $this->_xmlEntities($title)
1651            );
1652        } elseif($title) {
1653            // well at least we have a title to display
1654            $ret .= $this->_xmlEntities($title);
1655        } else {
1656            // just show the sourcename
1657            $ret .= $this->_xmlEntities(utf8_basename(noNS($src)));
1658        }
1659
1660        return $ret;
1661    }
1662
1663    /**
1664     * Escape string for output
1665     *
1666     * @param $string
1667     * @return string
1668     */
1669    function _xmlEntities($string) {
1670        return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
1671    }
1672
1673    /**
1674     * Creates a linkid from a headline
1675     *
1676     * @author Andreas Gohr <andi@splitbrain.org>
1677     * @param string  $title   The headline title
1678     * @param boolean $create  Create a new unique ID?
1679     * @return string
1680     */
1681    function _headerToLink($title, $create = false) {
1682        if($create) {
1683            return sectionID($title, $this->headers);
1684        } else {
1685            $check = false;
1686            return sectionID($title, $check);
1687        }
1688    }
1689
1690    /**
1691     * Construct a title and handle images in titles
1692     *
1693     * @author Harry Fuecks <hfuecks@gmail.com>
1694     * @param string|array $title    either string title or media array
1695     * @param string       $default  default title if nothing else is found
1696     * @param bool         $isImage  will be set to true if it's a media file
1697     * @param null|string  $id       linked page id (used to extract title from first heading)
1698     * @param string       $linktype content|navigation
1699     * @return string      HTML of the title, might be full image tag or just escaped text
1700     */
1701    function _getLinkTitle($title, $default, &$isImage, $id = null, $linktype = 'content') {
1702        $isImage = false;
1703        if(is_array($title)) {
1704            $isImage = true;
1705            return $this->_imageTitle($title);
1706        } elseif(is_null($title) || trim($title) == '') {
1707            if(useHeading($linktype) && $id) {
1708                $heading = p_get_first_heading($id);
1709                if(!blank($heading)) {
1710                    return $this->_xmlEntities($heading);
1711                }
1712            }
1713            return $this->_xmlEntities($default);
1714        } else {
1715            return $this->_xmlEntities($title);
1716        }
1717    }
1718
1719    /**
1720     * Returns HTML code for images used in link titles
1721     *
1722     * @author Andreas Gohr <andi@splitbrain.org>
1723     * @param array $img
1724     * @return string HTML img tag or similar
1725     */
1726    function _imageTitle($img) {
1727        global $ID;
1728
1729        // some fixes on $img['src']
1730        // see internalmedia() and externalmedia()
1731        list($img['src']) = explode('#', $img['src'], 2);
1732        if($img['type'] == 'internalmedia') {
1733            resolve_mediaid(getNS($ID), $img['src'], $exists ,$this->date_at, true);
1734        }
1735
1736        return $this->_media(
1737            $img['src'],
1738            $img['title'],
1739            $img['align'],
1740            $img['width'],
1741            $img['height'],
1742            $img['cache']
1743        );
1744    }
1745
1746    /**
1747     * helperfunction to return a basic link to a media
1748     *
1749     * used in internalmedia() and externalmedia()
1750     *
1751     * @author   Pierre Spring <pierre.spring@liip.ch>
1752     * @param string $src       media ID
1753     * @param string $title     descriptive text
1754     * @param string $align     left|center|right
1755     * @param int    $width     width of media in pixel
1756     * @param int    $height    height of media in pixel
1757     * @param string $cache     cache|recache|nocache
1758     * @param bool   $render    should the media be embedded inline or just linked
1759     * @return array associative array with link config
1760     */
1761    function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) {
1762        global $conf;
1763
1764        $link           = array();
1765        $link['class']  = 'media';
1766        $link['style']  = '';
1767        $link['pre']    = '';
1768        $link['suf']    = '';
1769        $link['more']   = '';
1770        $link['target'] = $conf['target']['media'];
1771        if($conf['target']['media']) $link['rel'] = 'noopener';
1772        $link['title']  = $this->_xmlEntities($src);
1773        $link['name']   = $this->_media($src, $title, $align, $width, $height, $cache, $render);
1774
1775        return $link;
1776    }
1777
1778    /**
1779     * Embed video(s) in HTML
1780     *
1781     * @author Anika Henke <anika@selfthinker.org>
1782     *
1783     * @param string $src         - ID of video to embed
1784     * @param int    $width       - width of the video in pixels
1785     * @param int    $height      - height of the video in pixels
1786     * @param array  $atts        - additional attributes for the <video> tag
1787     * @return string
1788     */
1789    function _video($src, $width, $height, $atts = null) {
1790        // prepare width and height
1791        if(is_null($atts)) $atts = array();
1792        $atts['width']  = (int) $width;
1793        $atts['height'] = (int) $height;
1794        if(!$atts['width']) $atts['width'] = 320;
1795        if(!$atts['height']) $atts['height'] = 240;
1796
1797        $posterUrl = '';
1798        $files = array();
1799        $isExternal = media_isexternal($src);
1800
1801        if ($isExternal) {
1802            // take direct source for external files
1803            list(/*ext*/, $srcMime) = mimetype($src);
1804            $files[$srcMime] = $src;
1805        } else {
1806            // prepare alternative formats
1807            $extensions   = array('webm', 'ogv', 'mp4');
1808            $files        = media_alternativefiles($src, $extensions);
1809            $poster       = media_alternativefiles($src, array('jpg', 'png'));
1810            if(!empty($poster)) {
1811                $posterUrl = ml(reset($poster), '', true, '&');
1812            }
1813        }
1814
1815        $out = '';
1816        // open video tag
1817        $out .= '<video '.buildAttributes($atts).' controls="controls"';
1818        if($posterUrl) $out .= ' poster="'.hsc($posterUrl).'"';
1819        $out .= '>'.NL;
1820        $fallback = '';
1821
1822        // output source for each alternative video format
1823        foreach($files as $mime => $file) {
1824            if ($isExternal) {
1825                $url = $file;
1826                $linkType = 'externalmedia';
1827            } else {
1828                $url = ml($file, '', true, '&');
1829                $linkType = 'internalmedia';
1830            }
1831            $title = $atts['title'] ? $atts['title'] : $this->_xmlEntities(utf8_basename(noNS($file)));
1832
1833            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1834            // alternative content (just a link to the file)
1835            $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true);
1836        }
1837
1838        // finish
1839        $out .= $fallback;
1840        $out .= '</video>'.NL;
1841        return $out;
1842    }
1843
1844    /**
1845     * Embed audio in HTML
1846     *
1847     * @author Anika Henke <anika@selfthinker.org>
1848     *
1849     * @param string $src       - ID of audio to embed
1850     * @param array  $atts      - additional attributes for the <audio> tag
1851     * @return string
1852     */
1853    function _audio($src, $atts = array()) {
1854        $files = array();
1855        $isExternal = media_isexternal($src);
1856
1857        if ($isExternal) {
1858            // take direct source for external files
1859            list(/*ext*/, $srcMime) = mimetype($src);
1860            $files[$srcMime] = $src;
1861        } else {
1862            // prepare alternative formats
1863            $extensions   = array('ogg', 'mp3', 'wav');
1864            $files        = media_alternativefiles($src, $extensions);
1865        }
1866
1867        $out = '';
1868        // open audio tag
1869        $out .= '<audio '.buildAttributes($atts).' controls="controls">'.NL;
1870        $fallback = '';
1871
1872        // output source for each alternative audio format
1873        foreach($files as $mime => $file) {
1874            if ($isExternal) {
1875                $url = $file;
1876                $linkType = 'externalmedia';
1877            } else {
1878                $url = ml($file, '', true, '&');
1879                $linkType = 'internalmedia';
1880            }
1881            $title = $atts['title'] ? $atts['title'] : $this->_xmlEntities(utf8_basename(noNS($file)));
1882
1883            $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL;
1884            // alternative content (just a link to the file)
1885            $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true);
1886        }
1887
1888        // finish
1889        $out .= $fallback;
1890        $out .= '</audio>'.NL;
1891        return $out;
1892    }
1893
1894    /**
1895     * _getLastMediaRevisionAt is a helperfunction to internalmedia() and _media()
1896     * which returns an existing media revision less or equal to rev or date_at
1897     *
1898     * @author lisps
1899     * @param string $media_id
1900     * @access protected
1901     * @return string revision ('' for current)
1902     */
1903    function _getLastMediaRevisionAt($media_id){
1904        if(!$this->date_at || media_isexternal($media_id)) return '';
1905        $pagelog = new MediaChangeLog($media_id);
1906        return $pagelog->getLastRevisionAt($this->date_at);
1907    }
1908
1909    #endregion
1910}
1911
1912//Setup VIM: ex: et ts=4 :
1913