xref: /dokuwiki/inc/template.php (revision e5d413b07e3797d0f7a9df3342f08a2e51ec9fc0)
1<?php
2
3/**
4 * DokuWiki template functions
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use dokuwiki\ActionRouter;
11use dokuwiki\Action\Exception\FatalException;
12use dokuwiki\Extension\PluginInterface;
13use dokuwiki\Ui\Admin;
14use dokuwiki\StyleUtils;
15use dokuwiki\Menu\Item\AbstractItem;
16use dokuwiki\Form\Form;
17use dokuwiki\Menu\MobileMenu;
18use dokuwiki\Ui\Subscribe;
19use dokuwiki\Extension\AdminPlugin;
20use dokuwiki\Extension\Event;
21use dokuwiki\File\PageResolver;
22
23/**
24 * Access a template file
25 *
26 * Returns the path to the given file inside the current template, uses
27 * default template if the custom version doesn't exist.
28 *
29 * @param string $file
30 * @return string
31 *
32 * @author Andreas Gohr <andi@splitbrain.org>
33 */
34function template($file)
35{
36    global $conf;
37
38    if (@is_readable(DOKU_INC . 'lib/tpl/' . $conf['template'] . '/' . $file))
39        return DOKU_INC . 'lib/tpl/' . $conf['template'] . '/' . $file;
40
41    return DOKU_INC . 'lib/tpl/dokuwiki/' . $file;
42}
43
44/**
45 * Convenience function to access template dir from local FS
46 *
47 * This replaces the deprecated DOKU_TPLINC constant
48 *
49 * @param string $tpl The template to use, default to current one
50 * @return string
51 *
52 * @author Andreas Gohr <andi@splitbrain.org>
53 */
54function tpl_incdir($tpl = '')
55{
56    global $conf;
57    if (!$tpl) $tpl = $conf['template'];
58    return DOKU_INC . 'lib/tpl/' . $tpl . '/';
59}
60
61/**
62 * Convenience function to access template dir from web
63 *
64 * This replaces the deprecated DOKU_TPL constant
65 *
66 * @param string $tpl The template to use, default to current one
67 * @return string
68 *
69 * @author Andreas Gohr <andi@splitbrain.org>
70 */
71function tpl_basedir($tpl = '')
72{
73    global $conf;
74    if (!$tpl) $tpl = $conf['template'];
75    return DOKU_BASE . 'lib/tpl/' . $tpl . '/';
76}
77
78/**
79 * Print the content
80 *
81 * This function is used for printing all the usual content
82 * (defined by the global $ACT var) by calling the appropriate
83 * outputfunction(s) from html.php
84 *
85 * Everything that doesn't use the main template file isn't
86 * handled by this function. ACL stuff is not done here either.
87 *
88 * @param bool $prependTOC should the TOC be displayed here?
89 * @return bool true if any output
90 *
91 * @triggers TPL_ACT_RENDER
92 * @triggers TPL_CONTENT_DISPLAY
93 * @author Andreas Gohr <andi@splitbrain.org>
94 */
95function tpl_content($prependTOC = true)
96{
97    global $ACT;
98    global $INFO;
99    $INFO['prependTOC'] = $prependTOC;
100
101    ob_start();
102    Event::createAndTrigger('TPL_ACT_RENDER', $ACT, 'tpl_content_core');
103    $html_output = ob_get_clean();
104    Event::createAndTrigger('TPL_CONTENT_DISPLAY', $html_output, function ($html_output) {
105        echo $html_output;
106    });
107
108    return !empty($html_output);
109}
110
111/**
112 * Default Action of TPL_ACT_RENDER
113 *
114 * @return bool
115 */
116function tpl_content_core()
117{
118    $router = ActionRouter::getInstance();
119    try {
120        $router->getAction()->tplContent();
121    } catch (FatalException $e) {
122        // there was no content for the action
123        msg(hsc($e->getMessage()), -1);
124        return false;
125    }
126    return true;
127}
128
129/**
130 * Places the TOC where the function is called
131 *
132 * If you use this you most probably want to call tpl_content with
133 * a false argument
134 *
135 * @param bool $return Should the TOC be returned instead to be printed?
136 * @return string
137 *
138 * @author Andreas Gohr <andi@splitbrain.org>
139 */
140function tpl_toc($return = false)
141{
142    global $TOC;
143    global $ACT;
144    global $ID;
145    global $REV;
146    global $INFO;
147    global $conf;
148    $toc = [];
149
150    if (is_array($TOC)) {
151        // if a TOC was prepared in global scope, always use it
152        $toc = $TOC;
153    } elseif (($ACT == 'show' || str_starts_with($ACT, 'export')) && !$REV && $INFO['exists']) {
154        // get TOC from metadata, render if neccessary
155        $meta = p_get_metadata($ID, '', METADATA_RENDER_USING_CACHE);
156        $tocok = $meta['internal']['toc'] ?? true;
157        $toc = $meta['description']['tableofcontents'] ?? null;
158        if (!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
159            $toc = [];
160        }
161    } elseif ($ACT == 'admin') {
162        // try to load admin plugin TOC
163        /** @var AdminPlugin $plugin */
164        if ($plugin = plugin_getRequestAdminPlugin()) {
165            $toc = $plugin->getTOC();
166            $TOC = $toc; // avoid later rebuild
167        }
168    }
169
170    Event::createAndTrigger('TPL_TOC_RENDER', $toc, null, false);
171    $html = html_TOC($toc);
172    if ($return) return $html;
173    echo $html;
174    return '';
175}
176
177/**
178 * Handle the admin page contents
179 *
180 * @return bool
181 *
182 * @author Andreas Gohr <andi@splitbrain.org>
183 */
184function tpl_admin()
185{
186    global $INFO;
187    global $TOC;
188    global $INPUT;
189
190    $plugin = null;
191    $class = $INPUT->str('page');
192    if (!empty($class)) {
193        $pluginlist = plugin_list('admin');
194
195        if (in_array($class, $pluginlist)) {
196            // attempt to load the plugin
197            /** @var AdminPlugin $plugin */
198            $plugin = plugin_load('admin', $class);
199        }
200    }
201
202    if ($plugin instanceof PluginInterface) {
203        if (!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
204        if ($INFO['prependTOC']) tpl_toc();
205        $plugin->html();
206    } else {
207        $admin = new Admin();
208        $admin->show();
209    }
210    return true;
211}
212
213/**
214 * Print the correct HTML meta headers
215 *
216 * This has to go into the head section of your template.
217 *
218 * @param bool $alt Should feeds and alternative format links be added?
219 * @return bool
220 * @throws JsonException
221 *
222 * @author Andreas Gohr <andi@splitbrain.org>
223 * @triggers TPL_METAHEADER_OUTPUT
224 */
225function tpl_metaheaders($alt = true)
226{
227    global $ID;
228    global $REV;
229    global $INFO;
230    global $JSINFO;
231    global $ACT;
232    global $QUERY;
233    global $lang;
234    global $conf;
235    global $updateVersion;
236    /** @var Input $INPUT */
237    global $INPUT;
238
239    // prepare the head array
240    $head = [];
241
242    // prepare seed for js and css
243    $tseed = $updateVersion;
244    $depends = getConfigFiles('main');
245    $depends[] = DOKU_CONF . "tpl/" . $conf['template'] . "/style.ini";
246    foreach ($depends as $f) $tseed .= @filemtime($f);
247    $tseed = md5($tseed);
248
249    // the usual stuff
250    $head['meta'][] = ['name' => 'generator', 'content' => 'DokuWiki'];
251    if (actionOK('search')) {
252        $head['link'][] = [
253            'rel' => 'search',
254            'type' => 'application/opensearchdescription+xml',
255            'href' => DOKU_BASE . 'lib/exe/opensearch.php',
256            'title' => $conf['title']
257        ];
258    }
259
260    $head['link'][] = ['rel' => 'start', 'href' => DOKU_BASE];
261    if (actionOK('index')) {
262        $head['link'][] = [
263            'rel' => 'contents',
264            'href' => wl($ID, 'do=index', false, '&'),
265            'title' => $lang['btn_index']
266        ];
267    }
268
269    if (actionOK('manifest')) {
270        $head['link'][] = [
271            'rel' => 'manifest',
272            'href' => DOKU_BASE . 'lib/exe/manifest.php'
273        ];
274    }
275
276    $styleUtil = new StyleUtils();
277    $styleIni = $styleUtil->cssStyleini();
278    $replacements = $styleIni['replacements'];
279    if (!empty($replacements['__theme_color__'])) {
280        $head['meta'][] = [
281            'name' => 'theme-color',
282            'content' => $replacements['__theme_color__']
283        ];
284    }
285
286    if ($alt) {
287        if (actionOK('rss')) {
288            $head['link'][] = [
289                'rel' => 'alternate',
290                'type' => 'application/rss+xml',
291                'title' => $lang['btn_recent'],
292                'href' => DOKU_BASE . 'feed.php'
293            ];
294            $head['link'][] = [
295                'rel' => 'alternate',
296                'type' => 'application/rss+xml',
297                'title' => $lang['currentns'],
298                'href' => DOKU_BASE . 'feed.php?mode=list&ns=' . (isset($INFO) ? $INFO['namespace'] : '')
299            ];
300        }
301        if (($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
302            $head['link'][] = [
303                'rel' => 'edit',
304                'title' => $lang['btn_edit'],
305                'href' => wl($ID, 'do=edit', false, '&')
306            ];
307        }
308
309        if (actionOK('rss') && $ACT == 'search') {
310            $head['link'][] = [
311                'rel' => 'alternate',
312                'type' => 'application/rss+xml',
313                'title' => $lang['searchresult'],
314                'href' => DOKU_BASE . 'feed.php?mode=search&q=' . $QUERY
315            ];
316        }
317
318        if (actionOK('export_xhtml')) {
319            $head['link'][] = [
320                'rel' => 'alternate',
321                'type' => 'text/html',
322                'title' => $lang['plainhtml'],
323                'href' => exportlink($ID, 'xhtml', '', false, '&')
324            ];
325        }
326
327        if (actionOK('export_raw')) {
328            $head['link'][] = [
329                'rel' => 'alternate',
330                'type' => 'text/plain',
331                'title' => $lang['wikimarkup'],
332                'href' => exportlink($ID, 'raw', '', false, '&')
333            ];
334        }
335    }
336
337    // setup robot tags appropriate for different modes
338    if (($ACT == 'show' || $ACT == 'export_xhtml') && !$REV) {
339        if ($INFO['exists']) {
340            //delay indexing:
341            if ((time() - $INFO['lastmod']) >= $conf['indexdelay'] && !isHiddenPage($ID)) {
342                $head['meta'][] = ['name' => 'robots', 'content' => 'index,follow'];
343            } else {
344                $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,nofollow'];
345            }
346            $canonicalUrl = wl($ID, '', true, '&');
347            if ($ID == $conf['start']) {
348                $canonicalUrl = DOKU_URL;
349            }
350            $head['link'][] = ['rel' => 'canonical', 'href' => $canonicalUrl];
351        } else {
352            $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,follow'];
353        }
354    } elseif (defined('DOKU_MEDIADETAIL')) {
355        $head['meta'][] = ['name' => 'robots', 'content' => 'index,follow'];
356    } else {
357        $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,nofollow'];
358    }
359
360    // set metadata
361    if ($ACT == 'show' || $ACT == 'export_xhtml') {
362        // keywords (explicit or implicit)
363        if (!empty($INFO['meta']['subject'])) {
364            $head['meta'][] = ['name' => 'keywords', 'content' => implode(',', $INFO['meta']['subject'])];
365        } else {
366            $head['meta'][] = ['name' => 'keywords', 'content' => str_replace(':', ',', $ID)];
367        }
368    }
369
370    // load stylesheets
371    $head['link'][] = [
372        'rel' => 'stylesheet',
373        'href' => DOKU_BASE . 'lib/exe/css.php?t=' . rawurlencode($conf['template']) . '&tseed=' . $tseed
374    ];
375
376    $script = "var NS='" . (isset($INFO) ? $INFO['namespace'] : '') . "';";
377    if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
378        $script .= "var SIG=" . toolbar_signature() . ";";
379    }
380    jsinfo();
381    $script .= 'var JSINFO = ' . json_encode($JSINFO, JSON_THROW_ON_ERROR) . ';';
382    $head['script'][] = ['_data' => $script];
383
384    // load jquery
385    $jquery = getCdnUrls();
386    foreach ($jquery as $src) {
387        $head['script'][] = [
388                '_data' => '',
389                'src' => $src
390            ] + ($conf['defer_js'] ? ['defer' => 'defer'] : []);
391    }
392
393    // load our javascript dispatcher
394    $head['script'][] = [
395            '_data' => '',
396            'src' => DOKU_BASE . 'lib/exe/js.php' . '?t=' . rawurlencode($conf['template']) . '&tseed=' . $tseed
397        ] + ($conf['defer_js'] ? ['defer' => 'defer'] : []);
398
399    // trigger event here
400    Event::createAndTrigger('TPL_METAHEADER_OUTPUT', $head, '_tpl_metaheaders_action', true);
401    return true;
402}
403
404/**
405 * prints the array build by tpl_metaheaders
406 *
407 * $data is an array of different header tags. Each tag can have multiple
408 * instances. Attributes are given as key value pairs. Values will be HTML
409 * encoded automatically so they should be provided as is in the $data array.
410 *
411 * For tags having a body attribute specify the body data in the special
412 * attribute '_data'. This field will NOT BE ESCAPED automatically.
413 *
414 * Inline scripts will use any nonce provided in the environment variable 'NONCE'.
415 *
416 * @param array $data
417 *
418 * @author Andreas Gohr <andi@splitbrain.org>
419 */
420function _tpl_metaheaders_action($data)
421{
422    $nonce = getenv('NONCE');
423    foreach ($data as $tag => $inst) {
424        foreach ($inst as $attr) {
425            if (empty($attr)) {
426                continue;
427            }
428            if ($nonce && $tag == 'script' && !empty($attr['_data'])) {
429                $attr['nonce'] = $nonce; // add nonce to inline script tags
430            }
431            echo '<', $tag, ' ', buildAttributes($attr);
432            if (isset($attr['_data']) || $tag == 'script') {
433                echo '>', $attr['_data'] ?? '', '</', $tag, '>';
434            } else {
435                echo '/>';
436            }
437            echo "\n";
438        }
439    }
440}
441
442/**
443 * Print a link
444 *
445 * Just builds a link.
446 *
447 * @param string $url
448 * @param string $name
449 * @param string $more
450 * @param bool $return if true return the link html, otherwise print
451 * @return bool|string html of the link, or true if printed
452 *
453 * @author Andreas Gohr <andi@splitbrain.org>
454 */
455function tpl_link($url, $name, $more = '', $return = false)
456{
457    $out = '<a href="' . $url . '" ';
458    if ($more) $out .= ' ' . $more;
459    $out .= ">$name</a>";
460    if ($return) return $out;
461    echo $out;
462    return true;
463}
464
465/**
466 * Prints a link to a WikiPage
467 *
468 * Wrapper around html_wikilink
469 *
470 * @param string $id page id
471 * @param string|null $name the name of the link
472 * @param bool $return
473 * @return true|string
474 *
475 * @author Andreas Gohr <andi@splitbrain.org>
476 */
477function tpl_pagelink($id, $name = null, $return = false)
478{
479    $out = '<bdi>' . html_wikilink($id, $name) . '</bdi>';
480    if ($return) return $out;
481    echo $out;
482    return true;
483}
484
485/**
486 * get the parent page
487 *
488 * Tries to find out which page is parent.
489 * returns false if none is available
490 *
491 * @param string $id page id
492 * @return false|string
493 *
494 * @author Andreas Gohr <andi@splitbrain.org>
495 */
496function tpl_getparent($id)
497{
498    $resolver = new PageResolver('root');
499
500    $parent = getNS($id) . ':';
501    $parent = $resolver->resolveId($parent);
502    if ($parent == $id) {
503        $pos = strrpos(getNS($id), ':');
504        $parent = substr($parent, 0, $pos) . ':';
505        $parent = $resolver->resolveId($parent);
506        if ($parent == $id) return false;
507    }
508    return $parent;
509}
510
511/**
512 * Print one of the buttons
513 *
514 * @param string $type
515 * @param bool $return
516 * @return bool|string html, or false if no data, true if printed
517 * @see    tpl_get_action
518 *
519 * @author Adrian Lang <mail@adrianlang.de>
520 * @deprecated 2017-09-01 see devel:menus
521 */
522function tpl_button($type, $return = false)
523{
524    dbg_deprecated('see devel:menus');
525    $data = tpl_get_action($type);
526    if ($data === false) {
527        return false;
528    } elseif (!is_array($data)) {
529        $out = sprintf($data, 'button');
530    } else {
531        /**
532         * @var string $accesskey
533         * @var string $id
534         * @var string $method
535         * @var array $params
536         */
537        extract($data);
538        if ($id === '#dokuwiki__top') {
539            $out = html_topbtn();
540        } else {
541            $out = html_btn($type, $id, $accesskey, $params, $method);
542        }
543    }
544    if ($return) return $out;
545    echo $out;
546    return true;
547}
548
549/**
550 * Like the action buttons but links
551 *
552 * @param string $type action command
553 * @param string $pre prefix of link
554 * @param string $suf suffix of link
555 * @param string $inner innerHML of link
556 * @param bool $return if true it returns html, otherwise prints
557 * @return bool|string html or false if no data, true if printed
558 *
559 * @see    tpl_get_action
560 * @author Adrian Lang <mail@adrianlang.de>
561 * @deprecated 2017-09-01 see devel:menus
562 */
563function tpl_actionlink($type, $pre = '', $suf = '', $inner = '', $return = false)
564{
565    dbg_deprecated('see devel:menus');
566    global $lang;
567    $data = tpl_get_action($type);
568    if ($data === false) {
569        return false;
570    } elseif (!is_array($data)) {
571        $out = sprintf($data, 'link');
572    } else {
573        /**
574         * @var string $accesskey
575         * @var string $id
576         * @var string $method
577         * @var bool $nofollow
578         * @var array $params
579         * @var string $replacement
580         */
581        extract($data);
582        if (strpos($id, '#') === 0) {
583            $linktarget = $id;
584        } else {
585            $linktarget = wl($id, $params);
586        }
587        $caption = $lang['btn_' . $type];
588        if (strpos($caption, '%s')) {
589            $caption = sprintf($caption, $replacement);
590        }
591        $akey = '';
592        $addTitle = '';
593        if ($accesskey) {
594            $akey = 'accesskey="' . $accesskey . '" ';
595            $addTitle = ' [' . strtoupper($accesskey) . ']';
596        }
597        $rel = $nofollow ? 'rel="nofollow" ' : '';
598        $out = tpl_link(
599            $linktarget,
600            $pre . ($inner ?: $caption) . $suf,
601            'class="action ' . $type . '" ' .
602            $akey . $rel .
603            'title="' . hsc($caption) . $addTitle . '"',
604            true
605        );
606    }
607    if ($return) return $out;
608    echo $out;
609    return true;
610}
611
612/**
613 * Check the actions and get data for buttons and links
614 *
615 * @param string $type
616 * @return array|bool|string
617 *
618 * @author Adrian Lang <mail@adrianlang.de>
619 * @author Andreas Gohr <andi@splitbrain.org>
620 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
621 * @deprecated 2017-09-01 see devel:menus
622 */
623function tpl_get_action($type)
624{
625    dbg_deprecated('see devel:menus');
626    if ($type == 'history') $type = 'revisions';
627    if ($type == 'subscription') $type = 'subscribe';
628    if ($type == 'img_backto') $type = 'imgBackto';
629
630    $class = '\\dokuwiki\\Menu\\Item\\' . ucfirst($type);
631    if (class_exists($class)) {
632        try {
633            /** @var AbstractItem $item */
634            $item = new $class();
635            $data = $item->getLegacyData();
636            $unknown = false;
637        } catch (RuntimeException $ignored) {
638            return false;
639        }
640    } else {
641        global $ID;
642        $data = [
643            'accesskey' => null,
644            'type' => $type,
645            'id' => $ID,
646            'method' => 'get',
647            'params' => ['do' => $type],
648            'nofollow' => true,
649            'replacement' => ''
650        ];
651        $unknown = true;
652    }
653
654    $evt = new Event('TPL_ACTION_GET', $data);
655    if ($evt->advise_before()) {
656        //handle unknown types
657        if ($unknown) {
658            $data = '[unknown %s type]';
659        }
660    }
661    $evt->advise_after();
662    unset($evt);
663
664    return $data;
665}
666
667/**
668 * Wrapper around tpl_button() and tpl_actionlink()
669 *
670 * @param string $type action command
671 * @param bool $link link or form button?
672 * @param string|bool $wrapper HTML element wrapper
673 * @param bool $return return or print
674 * @param string $pre prefix for links
675 * @param string $suf suffix for links
676 * @param string $inner inner HTML for links
677 * @return bool|string
678 *
679 * @author Anika Henke <anika@selfthinker.org>
680 * @deprecated 2017-09-01 see devel:menus
681 */
682function tpl_action($type, $link = false, $wrapper = false, $return = false, $pre = '', $suf = '', $inner = '')
683{
684    dbg_deprecated('see devel:menus');
685    $out = '';
686    if ($link) {
687        $out .= tpl_actionlink($type, $pre, $suf, $inner, true);
688    } else {
689        $out .= tpl_button($type, true);
690    }
691    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
692
693    if ($return) return $out;
694    echo $out;
695    return (bool)$out;
696}
697
698/**
699 * Print the search form
700 *
701 * If the first parameter is given a div with the ID 'qsearch_out' will
702 * be added which instructs the ajax pagequicksearch to kick in and place
703 * its output into this div. The second parameter controls the propritary
704 * attribute autocomplete. If set to false this attribute will be set with an
705 * value of "off" to instruct the browser to disable it's own built in
706 * autocompletion feature (MSIE and Firefox)
707 *
708 * @param bool $ajax
709 * @param bool $autocomplete
710 * @return bool
711 *
712 * @author Andreas Gohr <andi@splitbrain.org>
713 */
714function tpl_searchform($ajax = true, $autocomplete = true)
715{
716    global $lang;
717    global $ACT;
718    global $QUERY;
719    global $ID;
720
721    // don't print the search form if search action has been disabled
722    if (!actionOK('search')) return false;
723
724    $searchForm = new Form([
725        'action' => wl(),
726        'method' => 'get',
727        'role' => 'search',
728        'class' => 'search',
729        'id' => 'dw__search',
730    ], true);
731    $searchForm->addTagOpen('div')->addClass('no');
732    $searchForm->setHiddenField('do', 'search');
733    $searchForm->setHiddenField('id', $ID);
734    $searchForm->addTextInput('q')
735        ->addClass('edit')
736        ->attrs([
737            'title' => '[F]',
738            'accesskey' => 'f',
739            'placeholder' => $lang['btn_search'],
740            'autocomplete' => $autocomplete ? 'on' : 'off',
741        ])
742        ->id('qsearch__in')
743        ->val($ACT === 'search' ? $QUERY : '')
744        ->useInput(false);
745    $searchForm->addButton('', $lang['btn_search'])->attrs([
746        'type' => 'submit',
747        'title' => $lang['btn_search'],
748    ]);
749    if ($ajax) {
750        $searchForm->addTagOpen('div')->id('qsearch__out')->addClass('ajax_qsearch JSpopup');
751        $searchForm->addTagClose('div');
752    }
753    $searchForm->addTagClose('div');
754
755    echo $searchForm->toHTML('QuickSearch');
756
757    return true;
758}
759
760/**
761 * Print the breadcrumbs trace
762 *
763 * @param string $sep Separator between entries
764 * @param bool $return return or print
765 * @return bool|string
766 *
767 * @author Andreas Gohr <andi@splitbrain.org>
768 */
769function tpl_breadcrumbs($sep = null, $return = false)
770{
771    global $lang;
772    global $conf;
773
774    //check if enabled
775    if (!$conf['breadcrumbs']) return false;
776
777    //set default
778    if (is_null($sep)) $sep = '•';
779
780    $out = '';
781
782    $crumbs = breadcrumbs(); //setup crumb trace
783
784    $crumbs_sep = ' <span class="bcsep">' . $sep . '</span> ';
785
786    //render crumbs, highlight the last one
787    $out .= '<span class="bchead">' . $lang['breadcrumb'] . '</span>';
788    $last = count($crumbs);
789    $i = 0;
790    foreach ($crumbs as $id => $name) {
791        $i++;
792        $out .= $crumbs_sep;
793        if ($i == $last) $out .= '<span class="curid">';
794        $out .= '<bdi>' . tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="' . $id . '"', true) . '</bdi>';
795        if ($i == $last) $out .= '</span>';
796    }
797    if ($return) return $out;
798    echo $out;
799    return (bool)$out;
800}
801
802/**
803 * Hierarchical breadcrumbs
804 *
805 * This code was suggested as replacement for the usual breadcrumbs.
806 * It only makes sense with a deep site structure.
807 *
808 * @param string $sep Separator between entries
809 * @param bool $return return or print
810 * @return bool|string
811 *
812 * @todo   May behave strangely in RTL languages
813 * @author <fredrik@averpil.com>
814 * @author Andreas Gohr <andi@splitbrain.org>
815 * @author Nigel McNie <oracle.shinoda@gmail.com>
816 * @author Sean Coates <sean@caedmon.net>
817 */
818function tpl_youarehere($sep = null, $return = false)
819{
820    global $conf;
821    global $ID;
822    global $lang;
823
824    // check if enabled
825    if (!$conf['youarehere']) return false;
826
827    //set default
828    if (is_null($sep)) $sep = ' » ';
829
830    $out = '';
831
832    $parts = explode(':', $ID);
833    $count = count($parts);
834
835    $out .= '<span class="bchead">' . $lang['youarehere'] . ' </span>';
836
837    // always print the startpage
838    $out .= '<span class="home">' . tpl_pagelink(':' . $conf['start'], null, true) . '</span>';
839
840    // print intermediate namespace links
841    $part = '';
842    for ($i = 0; $i < $count - 1; $i++) {
843        $part .= $parts[$i] . ':';
844        $page = $part;
845        if ($page == $conf['start']) continue; // Skip startpage
846
847        // output
848        $out .= $sep . tpl_pagelink($page, null, true);
849    }
850
851    // print current page, skipping start page, skipping for namespace index
852    if (isset($page)) {
853        $page = (new PageResolver('root'))->resolveId($page);
854        if ($page == $part . $parts[$i]) {
855            if ($return) return $out;
856            echo $out;
857            return true;
858        }
859    }
860    $page = $part . $parts[$i];
861    if ($page == $conf['start']) {
862        if ($return) return $out;
863        echo $out;
864        return true;
865    }
866    $out .= $sep;
867    $out .= tpl_pagelink($page, null, true);
868    if ($return) return $out;
869    echo $out;
870    return (bool)$out;
871}
872
873/**
874 * Print info if the user is logged in
875 * and show full name in that case
876 *
877 * Could be enhanced with a profile link in future?
878 *
879 * @return bool
880 *
881 * @author Andreas Gohr <andi@splitbrain.org>
882 */
883function tpl_userinfo()
884{
885    global $lang;
886    /** @var Input $INPUT */
887    global $INPUT;
888
889    if ($INPUT->server->str('REMOTE_USER')) {
890        echo $lang['loggedinas'] . ' ' . userlink();
891        return true;
892    }
893    return false;
894}
895
896/**
897 * Print some info about the current page
898 *
899 * @param bool $ret return content instead of printing it
900 * @return bool|string
901 *
902 * @author Andreas Gohr <andi@splitbrain.org>
903 */
904function tpl_pageinfo($ret = false)
905{
906    global $conf;
907    global $lang;
908    global $INFO;
909    global $ID;
910
911    // return if we are not allowed to view the page
912    if (!auth_quickaclcheck($ID)) {
913        return false;
914    }
915
916    // prepare date and path
917    $fn = $INFO['filepath'];
918    if (!$conf['fullpath']) {
919        if ($INFO['rev']) {
920            $fn = str_replace($conf['olddir'] . '/', '', $fn);
921        } else {
922            $fn = str_replace($conf['datadir'] . '/', '', $fn);
923        }
924    }
925    $fn = utf8_decodeFN($fn);
926    $date = dformat($INFO['lastmod']);
927
928    // print it
929    if ($INFO['exists']) {
930        $out = '<bdi>' . $fn . '</bdi>';
931        $out .= ' · ';
932        $out .= $lang['lastmod'];
933        $out .= ' ';
934        $out .= $date;
935        if ($INFO['editor']) {
936            $out .= ' ' . $lang['by'] . ' ';
937            $out .= '<bdi>' . editorinfo($INFO['editor']) . '</bdi>';
938        } else {
939            $out .= ' (' . $lang['external_edit'] . ')';
940        }
941        if ($INFO['locked']) {
942            $out .= ' · ';
943            $out .= $lang['lockedby'];
944            $out .= ' ';
945            $out .= '<bdi>' . editorinfo($INFO['locked']) . '</bdi>';
946        }
947        if ($ret) {
948            return $out;
949        } else {
950            echo $out;
951            return true;
952        }
953    }
954    return false;
955}
956
957/**
958 * Prints or returns the name of the given page (current one if none given).
959 *
960 * If useheading is enabled this will use the first headline else
961 * the given ID is used.
962 *
963 * @param string $id page id
964 * @param bool $ret return content instead of printing
965 * @return bool|string
966 *
967 * @author Andreas Gohr <andi@splitbrain.org>
968 */
969function tpl_pagetitle($id = null, $ret = false)
970{
971    global $ACT, $conf, $lang;
972
973    if (is_null($id)) {
974        global $ID;
975        $id = $ID;
976    }
977
978    $name = $id;
979    if (useHeading('navigation')) {
980        $first_heading = p_get_first_heading($id);
981        if ($first_heading) $name = $first_heading;
982    }
983
984    // default page title is the page name, modify with the current action
985    switch ($ACT) {
986        // admin functions
987        case 'admin':
988            $page_title = $lang['btn_admin'];
989            // try to get the plugin name
990            /** @var AdminPlugin $plugin */
991            if ($plugin = plugin_getRequestAdminPlugin()) {
992                $plugin_title = $plugin->getMenuText($conf['lang']);
993                $page_title = $plugin_title ?: $plugin->getPluginName();
994            }
995            break;
996
997        // show action as title
998        case 'login':
999        case 'profile':
1000        case 'register':
1001        case 'resendpwd':
1002        case 'index':
1003        case 'search':
1004            $page_title = $lang['btn_' . $ACT];
1005            break;
1006
1007        // add pen during editing
1008        case 'edit':
1009        case 'preview':
1010            $page_title = "✎ " . $name;
1011            break;
1012
1013        // add action to page name
1014        case 'revisions':
1015            $page_title = $name . ' - ' . $lang['btn_revs'];
1016            break;
1017
1018        // add action to page name
1019        case 'backlink':
1020        case 'recent':
1021        case 'subscribe':
1022            $page_title = $name . ' - ' . $lang['btn_' . $ACT];
1023            break;
1024
1025        default: // SHOW and anything else not included
1026            $page_title = $name;
1027    }
1028
1029    if ($ret) {
1030        return hsc($page_title);
1031    } else {
1032        echo hsc($page_title);
1033        return true;
1034    }
1035}
1036
1037/**
1038 * Returns the requested EXIF/IPTC tag from the current image
1039 *
1040 * If $tags is an array all given tags are tried until a
1041 * value is found. If no value is found $alt is returned.
1042 *
1043 * Which texts are known is defined in the functions _exifTagNames
1044 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1045 * to the names of the latter one)
1046 *
1047 * Only allowed in: detail.php
1048 *
1049 * @param array|string $tags tag or array of tags to try
1050 * @param string $alt alternative output if no data was found
1051 * @param null|string $src the image src, uses global $SRC if not given
1052 * @return string
1053 *
1054 * @author Andreas Gohr <andi@splitbrain.org>
1055 */
1056function tpl_img_getTag($tags, $alt = '', $src = null)
1057{
1058    // Init Exif Reader
1059    global $SRC, $imgMeta;
1060
1061    if (is_null($src)) $src = $SRC;
1062    if (is_null($src)) return $alt;
1063
1064    if (!isset($imgMeta)) {
1065        $imgMeta = new JpegMeta($src);
1066    }
1067    if ($imgMeta === false) return $alt;
1068    $info = cleanText($imgMeta->getField($tags));
1069    if (!$info) return $alt;
1070    return $info;
1071}
1072
1073
1074/**
1075 * Garbage collects up the open JpegMeta object.
1076 */
1077function tpl_img_close()
1078{
1079    global $imgMeta;
1080    $imgMeta = null;
1081}
1082
1083/**
1084 * Prints a html description list of the metatags of the current image
1085 */
1086function tpl_img_meta()
1087{
1088    global $lang;
1089
1090    $tags = tpl_get_img_meta();
1091
1092    echo '<dl>';
1093    foreach ($tags as $tag) {
1094        $label = $lang[$tag['langkey']];
1095        if (!$label) $label = $tag['langkey'] . ':';
1096
1097        echo '<dt>' . $label . '</dt><dd>';
1098        if ($tag['type'] == 'date') {
1099            echo dformat($tag['value']);
1100        } else {
1101            echo hsc($tag['value']);
1102        }
1103        echo '</dd>';
1104    }
1105    echo '</dl>';
1106}
1107
1108/**
1109 * Returns metadata as configured in mediameta config file, ready for creating html
1110 *
1111 * @return array with arrays containing the entries:
1112 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1113 *   - string type     type of value
1114 *   - string value    tag value (unescaped)
1115 */
1116function tpl_get_img_meta()
1117{
1118
1119    $config_files = getConfigFiles('mediameta');
1120    foreach ($config_files as $config_file) {
1121        if (file_exists($config_file)) {
1122            include($config_file);
1123        }
1124    }
1125    $tags = [];
1126    foreach ($fields as $tag) {
1127        $t = [];
1128        if (!empty($tag[0])) {
1129            $t = [$tag[0]];
1130        }
1131        if (isset($tag[3]) && is_array($tag[3])) {
1132            $t = array_merge($t, $tag[3]);
1133        }
1134        $value = tpl_img_getTag($t);
1135        if ($value) {
1136            $tags[] = ['langkey' => $tag[1], 'type' => $tag[2], 'value' => $value];
1137        }
1138    }
1139    return $tags;
1140}
1141
1142/**
1143 * Prints the image with a link to the full sized version
1144 *
1145 * Only allowed in: detail.php
1146 *
1147 * @triggers TPL_IMG_DISPLAY
1148 * @param int $maxwidth - maximal width of the image
1149 * @param int $maxheight - maximal height of the image
1150 * @param bool $link - link to the orginal size?
1151 * @param array $params - additional image attributes
1152 * @return bool Result of TPL_IMG_DISPLAY
1153 */
1154function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null)
1155{
1156    global $IMG;
1157    /** @var Input $INPUT */
1158    global $INPUT;
1159    global $REV;
1160    $w = (int)tpl_img_getTag('File.Width');
1161    $h = (int)tpl_img_getTag('File.Height');
1162
1163    //resize to given max values
1164    $ratio = 1;
1165    if ($w >= $h) {
1166        if ($maxwidth && $w >= $maxwidth) {
1167            $ratio = $maxwidth / $w;
1168        } elseif ($maxheight && $h > $maxheight) {
1169            $ratio = $maxheight / $h;
1170        }
1171    } elseif ($maxheight && $h >= $maxheight) {
1172        $ratio = $maxheight / $h;
1173    } elseif ($maxwidth && $w > $maxwidth) {
1174        $ratio = $maxwidth / $w;
1175    }
1176    if ($ratio) {
1177        $w = floor($ratio * $w);
1178        $h = floor($ratio * $h);
1179    }
1180
1181    //prepare URLs
1182    $url = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV], true, '&');
1183    $src = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV, 'w' => $w, 'h' => $h], true, '&');
1184
1185    //prepare attributes
1186    $alt = tpl_img_getTag('Simple.Title');
1187    if (is_null($params)) {
1188        $p = [];
1189    } else {
1190        $p = $params;
1191    }
1192    if ($w) $p['width'] = $w;
1193    if ($h) $p['height'] = $h;
1194    $p['class'] = 'img_detail';
1195    if ($alt) {
1196        $p['alt'] = $alt;
1197        $p['title'] = $alt;
1198    } else {
1199        $p['alt'] = '';
1200    }
1201    $p['src'] = $src;
1202
1203    $data = ['url' => ($link ? $url : null), 'params' => $p];
1204    return Event::createAndTrigger('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1205}
1206
1207/**
1208 * Default action for TPL_IMG_DISPLAY
1209 *
1210 * @param array $data
1211 * @return bool
1212 */
1213function _tpl_img_action($data)
1214{
1215    global $lang;
1216    $p = buildAttributes($data['params']);
1217
1218    if ($data['url']) echo '<a href="' . hsc($data['url']) . '" title="' . $lang['mediaview'] . '">';
1219    echo '<img ' . $p . '/>';
1220    if ($data['url']) echo '</a>';
1221    return true;
1222}
1223
1224/**
1225 * This function inserts a small gif which in reality is the indexer function.
1226 *
1227 * Should be called somewhere at the very end of the main.php template
1228 *
1229 * @return bool
1230 */
1231function tpl_indexerWebBug()
1232{
1233    global $ID;
1234
1235    $p = [];
1236    $p['src'] = DOKU_BASE . 'lib/exe/taskrunner.php?id=' . rawurlencode($ID) .
1237        '&' . time();
1238    $p['width'] = 2; //no more 1x1 px image because we live in times of ad blockers...
1239    $p['height'] = 1;
1240    $p['alt'] = '';
1241    $att = buildAttributes($p);
1242    echo "<img $att />";
1243    return true;
1244}
1245
1246/**
1247 * tpl_getConf($id)
1248 *
1249 * use this function to access template configuration variables
1250 *
1251 * @param string $id name of the value to access
1252 * @param mixed $notset what to return if the setting is not available
1253 * @return mixed
1254 */
1255function tpl_getConf($id, $notset = false)
1256{
1257    global $conf;
1258    static $tpl_configloaded = false;
1259
1260    $tpl = $conf['template'];
1261
1262    if (!$tpl_configloaded) {
1263        $tconf = tpl_loadConfig();
1264        if ($tconf !== false) {
1265            foreach ($tconf as $key => $value) {
1266                if (isset($conf['tpl'][$tpl][$key])) continue;
1267                $conf['tpl'][$tpl][$key] = $value;
1268            }
1269            $tpl_configloaded = true;
1270        }
1271    }
1272
1273    return $conf['tpl'][$tpl][$id] ?? $notset;
1274}
1275
1276/**
1277 * tpl_loadConfig()
1278 *
1279 * reads all template configuration variables
1280 * this function is automatically called by tpl_getConf()
1281 *
1282 * @return false|array
1283 */
1284function tpl_loadConfig()
1285{
1286
1287    $file = tpl_incdir() . '/conf/default.php';
1288    $conf = [];
1289
1290    if (!file_exists($file)) return false;
1291
1292    // load default config file
1293    include($file);
1294
1295    return $conf;
1296}
1297
1298// language methods
1299
1300/**
1301 * tpl_getLang($id)
1302 *
1303 * use this function to access template language variables
1304 *
1305 * @param string $id key of language string
1306 * @return string
1307 */
1308function tpl_getLang($id)
1309{
1310    static $lang = [];
1311
1312    if (count($lang) === 0) {
1313        global $conf, $config_cascade; // definitely don't invoke "global $lang"
1314
1315        $path = tpl_incdir() . 'lang/';
1316
1317        $lang = [];
1318
1319        // don't include once
1320        @include($path . 'en/lang.php');
1321        foreach ($config_cascade['lang']['template'] as $config_file) {
1322            if (file_exists($config_file . $conf['template'] . '/en/lang.php')) {
1323                include($config_file . $conf['template'] . '/en/lang.php');
1324            }
1325        }
1326
1327        if ($conf['lang'] != 'en') {
1328            @include($path . $conf['lang'] . '/lang.php');
1329            foreach ($config_cascade['lang']['template'] as $config_file) {
1330                if (file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
1331                    include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
1332                }
1333            }
1334        }
1335    }
1336    return $lang[$id] ?? '';
1337}
1338
1339/**
1340 * Retrieve a language dependent file and pass to xhtml renderer for display
1341 * template equivalent of p_locale_xhtml()
1342 *
1343 * @param string $id id of language dependent wiki page
1344 * @return  string     parsed contents of the wiki page in xhtml format
1345 */
1346function tpl_locale_xhtml($id)
1347{
1348    return p_cached_output(tpl_localeFN($id));
1349}
1350
1351/**
1352 * Prepends appropriate path for a language dependent filename
1353 *
1354 * @param string $id id of localized text
1355 * @return string wiki text
1356 */
1357function tpl_localeFN($id)
1358{
1359    $path = tpl_incdir() . 'lang/';
1360    global $conf;
1361    $file = DOKU_CONF . 'template_lang/' . $conf['template'] . '/' . $conf['lang'] . '/' . $id . '.txt';
1362    if (!file_exists($file)) {
1363        $file = $path . $conf['lang'] . '/' . $id . '.txt';
1364        if (!file_exists($file)) {
1365            //fall back to english
1366            $file = $path . 'en/' . $id . '.txt';
1367        }
1368    }
1369    return $file;
1370}
1371
1372/**
1373 * prints the "main content" in the mediamanager popup
1374 *
1375 * Depending on the user's actions this may be a list of
1376 * files in a namespace, the meta editing dialog or
1377 * a message of referencing pages
1378 *
1379 * Only allowed in mediamanager.php
1380 *
1381 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1382 * @param bool $fromajax - set true when calling this function via ajax
1383 * @param string $sort
1384 *
1385 * @author Andreas Gohr <andi@splitbrain.org>
1386 */
1387function tpl_mediaContent($fromajax = false, $sort = 'natural')
1388{
1389    global $IMG;
1390    global $AUTH;
1391    global $INUSE;
1392    global $NS;
1393    global $JUMPTO;
1394    /** @var Input $INPUT */
1395    global $INPUT;
1396
1397    $do = $INPUT->extract('do')->str('do');
1398    if (in_array($do, ['save', 'cancel'])) $do = '';
1399
1400    if (!$do) {
1401        if ($INPUT->bool('edit')) {
1402            $do = 'metaform';
1403        } elseif (is_array($INUSE)) {
1404            $do = 'filesinuse';
1405        } else {
1406            $do = 'filelist';
1407        }
1408    }
1409
1410    // output the content pane, wrapped in an event.
1411    if (!$fromajax) echo '<div id="media__content">';
1412    $data = ['do' => $do];
1413    $evt = new Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1414    if ($evt->advise_before()) {
1415        $do = $data['do'];
1416        if ($do == 'filesinuse') {
1417            media_filesinuse($INUSE, $IMG);
1418        } elseif ($do == 'filelist') {
1419            media_filelist($NS, $AUTH, $JUMPTO, false, $sort);
1420        } elseif ($do == 'searchlist') {
1421            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1422        } else {
1423            msg('Unknown action ' . hsc($do), -1);
1424        }
1425    }
1426    $evt->advise_after();
1427    unset($evt);
1428    if (!$fromajax) echo '</div>';
1429}
1430
1431/**
1432 * Prints the central column in full-screen media manager
1433 * Depending on the opened tab this may be a list of
1434 * files in a namespace, upload form or search form
1435 *
1436 * @author Kate Arzamastseva <pshns@ukr.net>
1437 */
1438function tpl_mediaFileList()
1439{
1440    global $AUTH;
1441    global $NS;
1442    global $JUMPTO;
1443    global $lang;
1444    /** @var Input $INPUT */
1445    global $INPUT;
1446
1447    $opened_tab = $INPUT->str('tab_files');
1448    if (!$opened_tab || !in_array($opened_tab, ['files', 'upload', 'search'])) $opened_tab = 'files';
1449    if ($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1450
1451    echo '<h2 class="a11y">' . $lang['mediaselect'] . '</h2>' . NL;
1452
1453    media_tabs_files($opened_tab);
1454
1455    echo '<div class="panelHeader">' . NL;
1456    echo '<h3>';
1457    $tabTitle = $NS ?: '[' . $lang['mediaroot'] . ']';
1458    printf($lang['media_' . $opened_tab], '<strong>' . hsc($tabTitle) . '</strong>');
1459    echo '</h3>' . NL;
1460    if ($opened_tab === 'search' || $opened_tab === 'files') {
1461        media_tab_files_options();
1462    }
1463    echo '</div>' . NL;
1464
1465    echo '<div class="panelContent">' . NL;
1466    if ($opened_tab == 'files') {
1467        media_tab_files($NS, $AUTH, $JUMPTO);
1468    } elseif ($opened_tab == 'upload') {
1469        media_tab_upload($NS, $AUTH, $JUMPTO);
1470    } elseif ($opened_tab == 'search') {
1471        media_tab_search($NS, $AUTH);
1472    }
1473    echo '</div>' . NL;
1474}
1475
1476/**
1477 * Prints the third column in full-screen media manager
1478 * Depending on the opened tab this may be details of the
1479 * selected file, the meta editing dialog or
1480 * list of file revisions
1481 *
1482 * @param string $image
1483 * @param boolean $rev
1484 *
1485 * @author Kate Arzamastseva <pshns@ukr.net>
1486 */
1487function tpl_mediaFileDetails($image, $rev)
1488{
1489    global $conf, $DEL, $lang;
1490    /** @var Input $INPUT */
1491    global $INPUT;
1492
1493    $removed = (
1494        !file_exists(mediaFN($image)) &&
1495        file_exists(mediaMetaFN($image, '.changes')) &&
1496        $conf['mediarevisions']
1497    );
1498    if (!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1499    if ($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1500    $ns = getNS($image);
1501    $do = $INPUT->str('mediado');
1502
1503    $opened_tab = $INPUT->str('tab_details');
1504
1505    $tab_array = ['view'];
1506    [, $mime] = mimetype($image);
1507    if ($mime == 'image/jpeg') {
1508        $tab_array[] = 'edit';
1509    }
1510    if ($conf['mediarevisions']) {
1511        $tab_array[] = 'history';
1512    }
1513
1514    if (!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1515    if ($INPUT->bool('edit')) $opened_tab = 'edit';
1516    if ($do == 'restore') $opened_tab = 'view';
1517
1518    media_tabs_details($image, $opened_tab);
1519
1520    echo '<div class="panelHeader"><h3>';
1521    [$ext] = mimetype($image, false);
1522    $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1523    $class = 'select mediafile mf_' . $class;
1524
1525    $attributes = $rev ? ['rev' => $rev] : [];
1526    $tabTitle = sprintf(
1527        '<strong><a href="%s" class="%s" title="%s">%s</a></strong>',
1528        ml($image, $attributes),
1529        $class,
1530        $lang['mediaview'],
1531        $image
1532    );
1533    if ($opened_tab === 'view' && $rev) {
1534        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1535    } else {
1536        printf($lang['media_' . $opened_tab], $tabTitle);
1537    }
1538
1539    echo '</h3></div>' . NL;
1540
1541    echo '<div class="panelContent">' . NL;
1542
1543    if ($opened_tab == 'view') {
1544        media_tab_view($image, $ns, null, $rev);
1545    } elseif ($opened_tab == 'edit' && !$removed) {
1546        media_tab_edit($image, $ns);
1547    } elseif ($opened_tab == 'history' && $conf['mediarevisions']) {
1548        media_tab_history($image, $ns);
1549    }
1550
1551    echo '</div>' . NL;
1552}
1553
1554/**
1555 * prints the namespace tree in the mediamanager popup
1556 *
1557 * Only allowed in mediamanager.php
1558 *
1559 * @author Andreas Gohr <andi@splitbrain.org>
1560 */
1561function tpl_mediaTree()
1562{
1563    global $NS;
1564    echo '<div id="media__tree">';
1565    media_nstree($NS);
1566    echo '</div>';
1567}
1568
1569/**
1570 * Print a dropdown menu with all DokuWiki actions
1571 *
1572 * Note: this will not use any pretty URLs
1573 *
1574 * @param string $empty empty option label
1575 * @param string $button submit button label
1576 *
1577 * @author Andreas Gohr <andi@splitbrain.org>
1578 * @deprecated 2017-09-01 see devel:menus
1579 */
1580function tpl_actiondropdown($empty = '', $button = '&gt;')
1581{
1582    dbg_deprecated('see devel:menus');
1583    $menu = new MobileMenu();
1584    echo $menu->getDropdown($empty, $button);
1585}
1586
1587/**
1588 * Print a informational line about the used license
1589 *
1590 * @param string $img print image? (|button|badge)
1591 * @param bool $imgonly skip the textual description?
1592 * @param bool $return when true don't print, but return HTML
1593 * @param bool $wrap wrap in div with class="license"?
1594 * @return string
1595 *
1596 * @author Andreas Gohr <andi@splitbrain.org>
1597 */
1598function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true)
1599{
1600    global $license;
1601    global $conf;
1602    global $lang;
1603    if (!$conf['license']) return '';
1604    if (!is_array($license[$conf['license']])) return '';
1605    $lic = $license[$conf['license']];
1606    $target = ($conf['target']['extern']) ? ' target="' . $conf['target']['extern'] . '"' : '';
1607
1608    $out = '';
1609    if ($wrap) $out .= '<div class="license">';
1610    if ($img) {
1611        $src = license_img($img);
1612        if ($src) {
1613            $out .= '<a href="' . $lic['url'] . '" rel="license"' . $target;
1614            $out .= '><img src="' . DOKU_BASE . $src . '" alt="' . $lic['name'] . '" /></a>';
1615            if (!$imgonly) $out .= ' ';
1616        }
1617    }
1618    if (!$imgonly) {
1619        $out .= $lang['license'] . ' ';
1620        $out .= '<bdi><a href="' . $lic['url'] . '" rel="license" class="urlextern"' . $target;
1621        $out .= '>' . $lic['name'] . '</a></bdi>';
1622    }
1623    if ($wrap) $out .= '</div>';
1624
1625    if ($return) return $out;
1626    echo $out;
1627    return '';
1628}
1629
1630/**
1631 * Includes the rendered HTML of a given page
1632 *
1633 * This function is useful to populate sidebars or similar features in a
1634 * template
1635 *
1636 * @param string $pageid The page name you want to include
1637 * @param bool $print Should the content be printed or returned only
1638 * @param bool $propagate Search higher namespaces, too?
1639 * @param bool $useacl Include the page only if the ACLs check out?
1640 * @return bool|null|string
1641 */
1642function tpl_include_page($pageid, $print = true, $propagate = false, $useacl = true)
1643{
1644    if ($propagate) {
1645        $pageid = page_findnearest($pageid, $useacl);
1646    } elseif ($useacl && auth_quickaclcheck($pageid) == AUTH_NONE) {
1647        return false;
1648    }
1649    if (!$pageid) return false;
1650
1651    global $TOC;
1652    $oldtoc = $TOC;
1653    $html = p_wiki_xhtml($pageid, '', false);
1654    $TOC = $oldtoc;
1655
1656    if ($print) echo $html;
1657    return $html;
1658}
1659
1660/**
1661 * Display the subscribe form
1662 *
1663 * @author Adrian Lang <lang@cosmocode.de>
1664 * @deprecated 2020-07-23
1665 */
1666function tpl_subscribe()
1667{
1668    dbg_deprecated(Subscribe::class . '::show()');
1669    (new Subscribe())->show();
1670}
1671
1672/**
1673 * Tries to send already created content right to the browser
1674 *
1675 * Wraps around ob_flush() and flush()
1676 *
1677 * @author Andreas Gohr <andi@splitbrain.org>
1678 */
1679function tpl_flush()
1680{
1681    if (ob_get_level() > 0) ob_flush();
1682    flush();
1683}
1684
1685/**
1686 * Tries to find a ressource file in the given locations.
1687 *
1688 * If a given location starts with a colon it is assumed to be a media
1689 * file, otherwise it is assumed to be relative to the current template
1690 *
1691 * @param string[] $search locations to look at
1692 * @param bool $abs if to use absolute URL
1693 * @param array    &$imginfo filled with getimagesize()
1694 * @param bool $fallback use fallback image if target isn't found or return 'false' if potential
1695 *                                false result is required
1696 * @return string
1697 *
1698 * @author Andreas  Gohr <andi@splitbrain.org>
1699 */
1700function tpl_getMediaFile($search, $abs = false, &$imginfo = null, $fallback = true)
1701{
1702    $img = '';
1703    $file = '';
1704    $ismedia = false;
1705    // loop through candidates until a match was found:
1706    foreach ($search as $img) {
1707        if (str_starts_with($img, ':')) {
1708            $file = mediaFN($img);
1709            $ismedia = true;
1710        } else {
1711            $file = tpl_incdir() . $img;
1712            $ismedia = false;
1713        }
1714
1715        if (file_exists($file)) break;
1716    }
1717
1718    // manage non existing target
1719    if (!file_exists($file)) {
1720        // give result for fallback image
1721        if ($fallback) {
1722            $file = DOKU_INC . 'lib/images/blank.gif';
1723            // stop process if false result is required (if $fallback is false)
1724        } else {
1725            return false;
1726        }
1727    }
1728
1729    // fetch image data if requested
1730    if (!is_null($imginfo)) {
1731        $imginfo = getimagesize($file);
1732    }
1733
1734    // build URL
1735    if ($ismedia) {
1736        $url = ml($img, '', true, '', $abs);
1737    } else {
1738        $url = tpl_basedir() . $img;
1739        if ($abs) $url = DOKU_URL . substr($url, strlen(DOKU_REL));
1740    }
1741
1742    return $url;
1743}
1744
1745/**
1746 * PHP include a file
1747 *
1748 * either from the conf directory if it exists, otherwise use
1749 * file in the template's root directory.
1750 *
1751 * The function honours config cascade settings and looks for the given
1752 * file next to the ´main´ config files, in the order protected, local,
1753 * default.
1754 *
1755 * Note: no escaping or sanity checking is done here. Never pass user input
1756 * to this function!
1757 *
1758 * @param string $file
1759 *
1760 * @author Andreas Gohr <andi@splitbrain.org>
1761 * @author Anika Henke <anika@selfthinker.org>
1762 */
1763function tpl_includeFile($file)
1764{
1765    global $config_cascade;
1766    foreach (['protected', 'local', 'default'] as $config_group) {
1767        if (empty($config_cascade['main'][$config_group])) continue;
1768        foreach ($config_cascade['main'][$config_group] as $conf_file) {
1769            $dir = dirname($conf_file);
1770            if (file_exists("$dir/$file")) {
1771                include("$dir/$file");
1772                return;
1773            }
1774        }
1775    }
1776
1777    // still here? try the template dir
1778    $file = tpl_incdir() . $file;
1779    if (file_exists($file)) {
1780        include($file);
1781    }
1782}
1783
1784/**
1785 * Returns <link> tag for various icon types (favicon|mobile|generic)
1786 *
1787 * @param array $types - list of icon types to display (favicon|mobile|generic)
1788 * @return string
1789 *
1790 * @author Anika Henke <anika@selfthinker.org>
1791 */
1792function tpl_favicon($types = ['favicon'])
1793{
1794
1795    $return = '';
1796
1797    foreach ($types as $type) {
1798        switch ($type) {
1799            case 'favicon':
1800                $look = [':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico'];
1801                $return .= '<link rel="shortcut icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1802                break;
1803            case 'mobile':
1804                $look = [':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png'];
1805                $return .= '<link rel="apple-touch-icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1806                break;
1807            case 'generic':
1808                // ideal world solution, which doesn't work in any browser yet
1809                $look = [':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg'];
1810                $return .= '<link rel="icon" href="' . tpl_getMediaFile($look) . '" type="image/svg+xml" />' . NL;
1811                break;
1812        }
1813    }
1814
1815    return $return;
1816}
1817
1818/**
1819 * Prints full-screen media manager
1820 *
1821 * @author Kate Arzamastseva <pshns@ukr.net>
1822 */
1823function tpl_media()
1824{
1825    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1826    $fullscreen = true;
1827    require_once DOKU_INC . 'lib/exe/mediamanager.php';
1828
1829    $rev = '';
1830    $image = cleanID($INPUT->str('image'));
1831    if (isset($IMG)) $image = $IMG;
1832    if (isset($JUMPTO)) $image = $JUMPTO;
1833    if (isset($REV) && !$JUMPTO) $rev = $REV;
1834
1835    echo '<div id="mediamanager__page">' . NL;
1836    echo '<h1>' . $lang['btn_media'] . '</h1>' . NL;
1837    html_msgarea();
1838
1839    echo '<div class="panel namespaces">' . NL;
1840    echo '<h2>' . $lang['namespaces'] . '</h2>' . NL;
1841    echo '<div class="panelHeader">';
1842    echo $lang['media_namespaces'];
1843    echo '</div>' . NL;
1844
1845    echo '<div class="panelContent" id="media__tree">' . NL;
1846    media_nstree($NS);
1847    echo '</div>' . NL;
1848    echo '</div>' . NL;
1849
1850    echo '<div class="panel filelist">' . NL;
1851    tpl_mediaFileList();
1852    echo '</div>' . NL;
1853
1854    echo '<div class="panel file">' . NL;
1855    echo '<h2 class="a11y">' . $lang['media_file'] . '</h2>' . NL;
1856    tpl_mediaFileDetails($image, $rev);
1857    echo '</div>' . NL;
1858
1859    echo '</div>' . NL;
1860}
1861
1862/**
1863 * Return useful layout classes
1864 *
1865 * @return string
1866 *
1867 * @author Anika Henke <anika@selfthinker.org>
1868 */
1869function tpl_classes()
1870{
1871    global $ACT, $conf, $ID, $INFO;
1872    /** @var Input $INPUT */
1873    global $INPUT;
1874
1875    $classes = [
1876        'dokuwiki',
1877        'mode_' . $ACT,
1878        'tpl_' . $conf['template'],
1879        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1880        (isset($INFO['exists']) && $INFO['exists']) ? '' : 'notFound',
1881        ($ID == $conf['start']) ? 'home' : ''
1882    ];
1883    return implode(' ', $classes);
1884}
1885
1886/**
1887 * Create event for tools menues
1888 *
1889 * @param string $toolsname name of menu
1890 * @param array $items
1891 * @param string $view e.g. 'main', 'detail', ...
1892 *
1893 * @author Anika Henke <anika@selfthinker.org>
1894 * @deprecated 2017-09-01 see devel:menus
1895 */
1896function tpl_toolsevent($toolsname, $items, $view = 'main')
1897{
1898    dbg_deprecated('see devel:menus');
1899    $data = ['view' => $view, 'items' => $items];
1900
1901    $hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
1902    $evt = new Event($hook, $data);
1903    if ($evt->advise_before()) {
1904        foreach ($evt->data['items'] as $html) echo $html;
1905    }
1906    $evt->advise_after();
1907}
1908