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