xref: /dokuwiki/inc/template.php (revision 3d106cfbb85abe9c1295af2cb4a8aec93ad71b81)
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 * @param array $data
415 *
416 * @author Andreas Gohr <andi@splitbrain.org>
417 */
418function _tpl_metaheaders_action($data)
419{
420    foreach ($data as $tag => $inst) {
421        foreach ($inst as $attr) {
422            if (empty($attr)) {
423                continue;
424            }
425            echo '<', $tag, ' ', buildAttributes($attr);
426            if (isset($attr['_data']) || $tag == 'script') {
427                echo '>', $attr['_data'] ?? '', '</', $tag, '>';
428            } else {
429                echo '/>';
430            }
431            echo "\n";
432        }
433    }
434}
435
436/**
437 * Print a link
438 *
439 * Just builds a link.
440 *
441 * @param string $url
442 * @param string $name
443 * @param string $more
444 * @param bool $return if true return the link html, otherwise print
445 * @return bool|string html of the link, or true if printed
446 *
447 * @author Andreas Gohr <andi@splitbrain.org>
448 */
449function tpl_link($url, $name, $more = '', $return = false)
450{
451    $out = '<a href="' . $url . '" ';
452    if ($more) $out .= ' ' . $more;
453    $out .= ">$name</a>";
454    if ($return) return $out;
455    echo $out;
456    return true;
457}
458
459/**
460 * Prints a link to a WikiPage
461 *
462 * Wrapper around html_wikilink
463 *
464 * @param string $id page id
465 * @param string|null $name the name of the link
466 * @param bool $return
467 * @return true|string
468 *
469 * @author Andreas Gohr <andi@splitbrain.org>
470 */
471function tpl_pagelink($id, $name = null, $return = false)
472{
473    $out = '<bdi>' . html_wikilink($id, $name) . '</bdi>';
474    if ($return) return $out;
475    echo $out;
476    return true;
477}
478
479/**
480 * get the parent page
481 *
482 * Tries to find out which page is parent.
483 * returns false if none is available
484 *
485 * @param string $id page id
486 * @return false|string
487 *
488 * @author Andreas Gohr <andi@splitbrain.org>
489 */
490function tpl_getparent($id)
491{
492    $resolver = new PageResolver('root');
493
494    $parent = getNS($id) . ':';
495    $parent = $resolver->resolveId($parent);
496    if ($parent == $id) {
497        $pos = strrpos(getNS($id), ':');
498        $parent = substr($parent, 0, $pos) . ':';
499        $parent = $resolver->resolveId($parent);
500        if ($parent == $id) return false;
501    }
502    return $parent;
503}
504
505/**
506 * Print one of the buttons
507 *
508 * @param string $type
509 * @param bool $return
510 * @return bool|string html, or false if no data, true if printed
511 * @see    tpl_get_action
512 *
513 * @author Adrian Lang <mail@adrianlang.de>
514 * @deprecated 2017-09-01 see devel:menus
515 */
516function tpl_button($type, $return = false)
517{
518    dbg_deprecated('see devel:menus');
519    $data = tpl_get_action($type);
520    if ($data === false) {
521        return false;
522    } elseif (!is_array($data)) {
523        $out = sprintf($data, 'button');
524    } else {
525        /**
526         * @var string $accesskey
527         * @var string $id
528         * @var string $method
529         * @var array $params
530         */
531        extract($data);
532        if ($id === '#dokuwiki__top') {
533            $out = html_topbtn();
534        } else {
535            $out = html_btn($type, $id, $accesskey, $params, $method);
536        }
537    }
538    if ($return) return $out;
539    echo $out;
540    return true;
541}
542
543/**
544 * Like the action buttons but links
545 *
546 * @param string $type action command
547 * @param string $pre prefix of link
548 * @param string $suf suffix of link
549 * @param string $inner innerHML of link
550 * @param bool $return if true it returns html, otherwise prints
551 * @return bool|string html or false if no data, true if printed
552 *
553 * @see    tpl_get_action
554 * @author Adrian Lang <mail@adrianlang.de>
555 * @deprecated 2017-09-01 see devel:menus
556 */
557function tpl_actionlink($type, $pre = '', $suf = '', $inner = '', $return = false)
558{
559    dbg_deprecated('see devel:menus');
560    global $lang;
561    $data = tpl_get_action($type);
562    if ($data === false) {
563        return false;
564    } elseif (!is_array($data)) {
565        $out = sprintf($data, 'link');
566    } else {
567        /**
568         * @var string $accesskey
569         * @var string $id
570         * @var string $method
571         * @var bool $nofollow
572         * @var array $params
573         * @var string $replacement
574         */
575        extract($data);
576        if (strpos($id, '#') === 0) {
577            $linktarget = $id;
578        } else {
579            $linktarget = wl($id, $params);
580        }
581        $caption = $lang['btn_' . $type];
582        if (strpos($caption, '%s')) {
583            $caption = sprintf($caption, $replacement);
584        }
585        $akey = '';
586        $addTitle = '';
587        if ($accesskey) {
588            $akey = 'accesskey="' . $accesskey . '" ';
589            $addTitle = ' [' . strtoupper($accesskey) . ']';
590        }
591        $rel = $nofollow ? 'rel="nofollow" ' : '';
592        $out = tpl_link(
593            $linktarget,
594            $pre . ($inner ?: $caption) . $suf,
595            'class="action ' . $type . '" ' .
596            $akey . $rel .
597            'title="' . hsc($caption) . $addTitle . '"',
598            true
599        );
600    }
601    if ($return) return $out;
602    echo $out;
603    return true;
604}
605
606/**
607 * Check the actions and get data for buttons and links
608 *
609 * @param string $type
610 * @return array|bool|string
611 *
612 * @author Adrian Lang <mail@adrianlang.de>
613 * @author Andreas Gohr <andi@splitbrain.org>
614 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
615 * @deprecated 2017-09-01 see devel:menus
616 */
617function tpl_get_action($type)
618{
619    dbg_deprecated('see devel:menus');
620    if ($type == 'history') $type = 'revisions';
621    if ($type == 'subscription') $type = 'subscribe';
622    if ($type == 'img_backto') $type = 'imgBackto';
623
624    $class = '\\dokuwiki\\Menu\\Item\\' . ucfirst($type);
625    if (class_exists($class)) {
626        try {
627            /** @var AbstractItem $item */
628            $item = new $class();
629            $data = $item->getLegacyData();
630            $unknown = false;
631        } catch (RuntimeException $ignored) {
632            return false;
633        }
634    } else {
635        global $ID;
636        $data = [
637            'accesskey' => null,
638            'type' => $type,
639            'id' => $ID,
640            'method' => 'get',
641            'params' => ['do' => $type],
642            'nofollow' => true,
643            'replacement' => ''
644        ];
645        $unknown = true;
646    }
647
648    $evt = new Event('TPL_ACTION_GET', $data);
649    if ($evt->advise_before()) {
650        //handle unknown types
651        if ($unknown) {
652            $data = '[unknown %s type]';
653        }
654    }
655    $evt->advise_after();
656    unset($evt);
657
658    return $data;
659}
660
661/**
662 * Wrapper around tpl_button() and tpl_actionlink()
663 *
664 * @param string $type action command
665 * @param bool $link link or form button?
666 * @param string|bool $wrapper HTML element wrapper
667 * @param bool $return return or print
668 * @param string $pre prefix for links
669 * @param string $suf suffix for links
670 * @param string $inner inner HTML for links
671 * @return bool|string
672 *
673 * @author Anika Henke <anika@selfthinker.org>
674 * @deprecated 2017-09-01 see devel:menus
675 */
676function tpl_action($type, $link = false, $wrapper = false, $return = false, $pre = '', $suf = '', $inner = '')
677{
678    dbg_deprecated('see devel:menus');
679    $out = '';
680    if ($link) {
681        $out .= tpl_actionlink($type, $pre, $suf, $inner, true);
682    } else {
683        $out .= tpl_button($type, true);
684    }
685    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
686
687    if ($return) return $out;
688    echo $out;
689    return (bool)$out;
690}
691
692/**
693 * Print the search form
694 *
695 * If the first parameter is given a div with the ID 'qsearch_out' will
696 * be added which instructs the ajax pagequicksearch to kick in and place
697 * its output into this div. The second parameter controls the propritary
698 * attribute autocomplete. If set to false this attribute will be set with an
699 * value of "off" to instruct the browser to disable it's own built in
700 * autocompletion feature (MSIE and Firefox)
701 *
702 * @param bool $ajax
703 * @param bool $autocomplete
704 * @return bool
705 *
706 * @author Andreas Gohr <andi@splitbrain.org>
707 */
708function tpl_searchform($ajax = true, $autocomplete = true)
709{
710    global $lang;
711    global $ACT;
712    global $QUERY;
713    global $ID;
714
715    // don't print the search form if search action has been disabled
716    if (!actionOK('search')) return false;
717
718    $searchForm = new Form([
719        'action' => wl(),
720        'method' => 'get',
721        'role' => 'search',
722        'class' => 'search',
723        'id' => 'dw__search',
724    ], true);
725    $searchForm->addTagOpen('div')->addClass('no');
726    $searchForm->setHiddenField('do', 'search');
727    $searchForm->setHiddenField('id', $ID);
728    $searchForm->addTextInput('q')
729        ->addClass('edit')
730        ->attrs([
731            'title' => '[F]',
732            'accesskey' => 'f',
733            'placeholder' => $lang['btn_search'],
734            'autocomplete' => $autocomplete ? 'on' : 'off',
735        ])
736        ->id('qsearch__in')
737        ->val($ACT === 'search' ? $QUERY : '')
738        ->useInput(false);
739    $searchForm->addButton('', $lang['btn_search'])->attrs([
740        'type' => 'submit',
741        'title' => $lang['btn_search'],
742    ]);
743    if ($ajax) {
744        $searchForm->addTagOpen('div')->id('qsearch__out')->addClass('ajax_qsearch JSpopup');
745        $searchForm->addTagClose('div');
746    }
747    $searchForm->addTagClose('div');
748
749    echo $searchForm->toHTML('QuickSearch');
750
751    return true;
752}
753
754/**
755 * Print the breadcrumbs trace
756 *
757 * @param string $sep Separator between entries
758 * @param bool $return return or print
759 * @return bool|string
760 *
761 * @author Andreas Gohr <andi@splitbrain.org>
762 */
763function tpl_breadcrumbs($sep = null, $return = false)
764{
765    global $lang;
766    global $conf;
767
768    //check if enabled
769    if (!$conf['breadcrumbs']) return false;
770
771    //set default
772    if (is_null($sep)) $sep = '•';
773
774    $out = '';
775
776    $crumbs = breadcrumbs(); //setup crumb trace
777
778    $crumbs_sep = ' <span class="bcsep">' . $sep . '</span> ';
779
780    //render crumbs, highlight the last one
781    $out .= '<span class="bchead">' . $lang['breadcrumb'] . '</span>';
782    $last = count($crumbs);
783    $i = 0;
784    foreach ($crumbs as $id => $name) {
785        $i++;
786        $out .= $crumbs_sep;
787        if ($i == $last) $out .= '<span class="curid">';
788        $out .= '<bdi>' . tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="' . $id . '"', true) . '</bdi>';
789        if ($i == $last) $out .= '</span>';
790    }
791    if ($return) return $out;
792    echo $out;
793    return (bool)$out;
794}
795
796/**
797 * Hierarchical breadcrumbs
798 *
799 * This code was suggested as replacement for the usual breadcrumbs.
800 * It only makes sense with a deep site structure.
801 *
802 * @param string $sep Separator between entries
803 * @param bool $return return or print
804 * @return bool|string
805 *
806 * @todo   May behave strangely in RTL languages
807 * @author <fredrik@averpil.com>
808 * @author Andreas Gohr <andi@splitbrain.org>
809 * @author Nigel McNie <oracle.shinoda@gmail.com>
810 * @author Sean Coates <sean@caedmon.net>
811 */
812function tpl_youarehere($sep = null, $return = false)
813{
814    global $conf;
815    global $ID;
816    global $lang;
817
818    // check if enabled
819    if (!$conf['youarehere']) return false;
820
821    //set default
822    if (is_null($sep)) $sep = ' » ';
823
824    $out = '';
825
826    $parts = explode(':', $ID);
827    $count = count($parts);
828
829    $out .= '<span class="bchead">' . $lang['youarehere'] . ' </span>';
830
831    // always print the startpage
832    $out .= '<span class="home">' . tpl_pagelink(':' . $conf['start'], null, true) . '</span>';
833
834    // print intermediate namespace links
835    $part = '';
836    for ($i = 0; $i < $count - 1; $i++) {
837        $part .= $parts[$i] . ':';
838        $page = $part;
839        if ($page == $conf['start']) continue; // Skip startpage
840
841        // output
842        $out .= $sep . tpl_pagelink($page, null, true);
843    }
844
845    // print current page, skipping start page, skipping for namespace index
846    if (isset($page)) {
847        $page = (new PageResolver('root'))->resolveId($page);
848        if ($page == $part . $parts[$i]) {
849            if ($return) return $out;
850            echo $out;
851            return true;
852        }
853    }
854    $page = $part . $parts[$i];
855    if ($page == $conf['start']) {
856        if ($return) return $out;
857        echo $out;
858        return true;
859    }
860    $out .= $sep;
861    $out .= tpl_pagelink($page, null, true);
862    if ($return) return $out;
863    echo $out;
864    return (bool)$out;
865}
866
867/**
868 * Print info if the user is logged in
869 * and show full name in that case
870 *
871 * Could be enhanced with a profile link in future?
872 *
873 * @return bool
874 *
875 * @author Andreas Gohr <andi@splitbrain.org>
876 */
877function tpl_userinfo()
878{
879    global $lang;
880    /** @var Input $INPUT */
881    global $INPUT;
882
883    if ($INPUT->server->str('REMOTE_USER')) {
884        echo $lang['loggedinas'] . ' ' . userlink();
885        return true;
886    }
887    return false;
888}
889
890/**
891 * Print some info about the current page
892 *
893 * @param bool $ret return content instead of printing it
894 * @return bool|string
895 *
896 * @author Andreas Gohr <andi@splitbrain.org>
897 */
898function tpl_pageinfo($ret = false)
899{
900    global $conf;
901    global $lang;
902    global $INFO;
903    global $ID;
904
905    // return if we are not allowed to view the page
906    if (!auth_quickaclcheck($ID)) {
907        return false;
908    }
909
910    // prepare date and path
911    $fn = $INFO['filepath'];
912    if (!$conf['fullpath']) {
913        if ($INFO['rev']) {
914            $fn = str_replace($conf['olddir'] . '/', '', $fn);
915        } else {
916            $fn = str_replace($conf['datadir'] . '/', '', $fn);
917        }
918    }
919    $fn = utf8_decodeFN($fn);
920    $date = dformat($INFO['lastmod']);
921
922    // print it
923    if ($INFO['exists']) {
924        $out = '<bdi>' . $fn . '</bdi>';
925        $out .= ' · ';
926        $out .= $lang['lastmod'];
927        $out .= ' ';
928        $out .= $date;
929        if ($INFO['editor']) {
930            $out .= ' ' . $lang['by'] . ' ';
931            $out .= '<bdi>' . editorinfo($INFO['editor']) . '</bdi>';
932        } else {
933            $out .= ' (' . $lang['external_edit'] . ')';
934        }
935        if ($INFO['locked']) {
936            $out .= ' · ';
937            $out .= $lang['lockedby'];
938            $out .= ' ';
939            $out .= '<bdi>' . editorinfo($INFO['locked']) . '</bdi>';
940        }
941        if ($ret) {
942            return $out;
943        } else {
944            echo $out;
945            return true;
946        }
947    }
948    return false;
949}
950
951/**
952 * Prints or returns the name of the given page (current one if none given).
953 *
954 * If useheading is enabled this will use the first headline else
955 * the given ID is used.
956 *
957 * @param string $id page id
958 * @param bool $ret return content instead of printing
959 * @return bool|string
960 *
961 * @author Andreas Gohr <andi@splitbrain.org>
962 */
963function tpl_pagetitle($id = null, $ret = false)
964{
965    global $ACT, $conf, $lang;
966
967    if (is_null($id)) {
968        global $ID;
969        $id = $ID;
970    }
971
972    $name = $id;
973    if (useHeading('navigation')) {
974        $first_heading = p_get_first_heading($id);
975        if ($first_heading) $name = $first_heading;
976    }
977
978    // default page title is the page name, modify with the current action
979    switch ($ACT) {
980        // admin functions
981        case 'admin':
982            $page_title = $lang['btn_admin'];
983            // try to get the plugin name
984            /** @var AdminPlugin $plugin */
985            if ($plugin = plugin_getRequestAdminPlugin()) {
986                $plugin_title = $plugin->getMenuText($conf['lang']);
987                $page_title = $plugin_title ?: $plugin->getPluginName();
988            }
989            break;
990
991        // show action as title
992        case 'login':
993        case 'profile':
994        case 'register':
995        case 'resendpwd':
996        case 'index':
997        case 'search':
998            $page_title = $lang['btn_' . $ACT];
999            break;
1000
1001        // add pen during editing
1002        case 'edit':
1003        case 'preview':
1004            $page_title = "✎ " . $name;
1005            break;
1006
1007        // add action to page name
1008        case 'revisions':
1009            $page_title = $name . ' - ' . $lang['btn_revs'];
1010            break;
1011
1012        // add action to page name
1013        case 'backlink':
1014        case 'recent':
1015        case 'subscribe':
1016            $page_title = $name . ' - ' . $lang['btn_' . $ACT];
1017            break;
1018
1019        default: // SHOW and anything else not included
1020            $page_title = $name;
1021    }
1022
1023    if ($ret) {
1024        return hsc($page_title);
1025    } else {
1026        echo hsc($page_title);
1027        return true;
1028    }
1029}
1030
1031/**
1032 * Returns the requested EXIF/IPTC tag from the current image
1033 *
1034 * If $tags is an array all given tags are tried until a
1035 * value is found. If no value is found $alt is returned.
1036 *
1037 * Which texts are known is defined in the functions _exifTagNames
1038 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1039 * to the names of the latter one)
1040 *
1041 * Only allowed in: detail.php
1042 *
1043 * @param array|string $tags tag or array of tags to try
1044 * @param string $alt alternative output if no data was found
1045 * @param null|string $src the image src, uses global $SRC if not given
1046 * @return string
1047 *
1048 * @author Andreas Gohr <andi@splitbrain.org>
1049 */
1050function tpl_img_getTag($tags, $alt = '', $src = null)
1051{
1052    // Init Exif Reader
1053    global $SRC, $imgMeta;
1054
1055    if (is_null($src)) $src = $SRC;
1056    if (is_null($src)) return $alt;
1057
1058    if (!isset($imgMeta)) {
1059        $imgMeta = new JpegMeta($src);
1060    }
1061    if ($imgMeta === false) return $alt;
1062    $info = cleanText($imgMeta->getField($tags));
1063    if (!$info) return $alt;
1064    return $info;
1065}
1066
1067
1068/**
1069 * Garbage collects up the open JpegMeta object.
1070 */
1071function tpl_img_close()
1072{
1073    global $imgMeta;
1074    $imgMeta = null;
1075}
1076
1077/**
1078 * Prints a html description list of the metatags of the current image
1079 */
1080function tpl_img_meta()
1081{
1082    global $lang;
1083
1084    $tags = tpl_get_img_meta();
1085
1086    echo '<dl>';
1087    foreach ($tags as $tag) {
1088        $label = $lang[$tag['langkey']];
1089        if (!$label) $label = $tag['langkey'] . ':';
1090
1091        echo '<dt>' . $label . '</dt><dd>';
1092        if ($tag['type'] == 'date') {
1093            echo dformat($tag['value']);
1094        } else {
1095            echo hsc($tag['value']);
1096        }
1097        echo '</dd>';
1098    }
1099    echo '</dl>';
1100}
1101
1102/**
1103 * Returns metadata as configured in mediameta config file, ready for creating html
1104 *
1105 * @return array with arrays containing the entries:
1106 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1107 *   - string type     type of value
1108 *   - string value    tag value (unescaped)
1109 */
1110function tpl_get_img_meta()
1111{
1112
1113    $config_files = getConfigFiles('mediameta');
1114    foreach ($config_files as $config_file) {
1115        if (file_exists($config_file)) {
1116            include($config_file);
1117        }
1118    }
1119    $tags = [];
1120    foreach ($fields as $tag) {
1121        $t = [];
1122        if (!empty($tag[0])) {
1123            $t = [$tag[0]];
1124        }
1125        if (isset($tag[3]) && is_array($tag[3])) {
1126            $t = array_merge($t, $tag[3]);
1127        }
1128        $value = tpl_img_getTag($t);
1129        if ($value) {
1130            $tags[] = ['langkey' => $tag[1], 'type' => $tag[2], 'value' => $value];
1131        }
1132    }
1133    return $tags;
1134}
1135
1136/**
1137 * Prints the image with a link to the full sized version
1138 *
1139 * Only allowed in: detail.php
1140 *
1141 * @triggers TPL_IMG_DISPLAY
1142 * @param int $maxwidth - maximal width of the image
1143 * @param int $maxheight - maximal height of the image
1144 * @param bool $link - link to the orginal size?
1145 * @param array $params - additional image attributes
1146 * @return bool Result of TPL_IMG_DISPLAY
1147 */
1148function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null)
1149{
1150    global $IMG;
1151    /** @var Input $INPUT */
1152    global $INPUT;
1153    global $REV;
1154    $w = (int)tpl_img_getTag('File.Width');
1155    $h = (int)tpl_img_getTag('File.Height');
1156
1157    //resize to given max values
1158    $ratio = 1;
1159    if ($w >= $h) {
1160        if ($maxwidth && $w >= $maxwidth) {
1161            $ratio = $maxwidth / $w;
1162        } elseif ($maxheight && $h > $maxheight) {
1163            $ratio = $maxheight / $h;
1164        }
1165    } elseif ($maxheight && $h >= $maxheight) {
1166        $ratio = $maxheight / $h;
1167    } elseif ($maxwidth && $w > $maxwidth) {
1168        $ratio = $maxwidth / $w;
1169    }
1170    if ($ratio) {
1171        $w = floor($ratio * $w);
1172        $h = floor($ratio * $h);
1173    }
1174
1175    //prepare URLs
1176    $url = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV], true, '&');
1177    $src = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV, 'w' => $w, 'h' => $h], true, '&');
1178
1179    //prepare attributes
1180    $alt = tpl_img_getTag('Simple.Title');
1181    if (is_null($params)) {
1182        $p = [];
1183    } else {
1184        $p = $params;
1185    }
1186    if ($w) $p['width'] = $w;
1187    if ($h) $p['height'] = $h;
1188    $p['class'] = 'img_detail';
1189    if ($alt) {
1190        $p['alt'] = $alt;
1191        $p['title'] = $alt;
1192    } else {
1193        $p['alt'] = '';
1194    }
1195    $p['src'] = $src;
1196
1197    $data = ['url' => ($link ? $url : null), 'params' => $p];
1198    return Event::createAndTrigger('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1199}
1200
1201/**
1202 * Default action for TPL_IMG_DISPLAY
1203 *
1204 * @param array $data
1205 * @return bool
1206 */
1207function _tpl_img_action($data)
1208{
1209    global $lang;
1210    $p = buildAttributes($data['params']);
1211
1212    if ($data['url']) echo '<a href="' . hsc($data['url']) . '" title="' . $lang['mediaview'] . '">';
1213    echo '<img ' . $p . '/>';
1214    if ($data['url']) echo '</a>';
1215    return true;
1216}
1217
1218/**
1219 * This function inserts a small gif which in reality is the indexer function.
1220 *
1221 * Should be called somewhere at the very end of the main.php template
1222 *
1223 * @return bool
1224 */
1225function tpl_indexerWebBug()
1226{
1227    global $ID;
1228
1229    $p = [];
1230    $p['src'] = DOKU_BASE . 'lib/exe/taskrunner.php?id=' . rawurlencode($ID) .
1231        '&' . time();
1232    $p['width'] = 2; //no more 1x1 px image because we live in times of ad blockers...
1233    $p['height'] = 1;
1234    $p['alt'] = '';
1235    $att = buildAttributes($p);
1236    echo "<img $att />";
1237    return true;
1238}
1239
1240/**
1241 * tpl_getConf($id)
1242 *
1243 * use this function to access template configuration variables
1244 *
1245 * @param string $id name of the value to access
1246 * @param mixed $notset what to return if the setting is not available
1247 * @return mixed
1248 */
1249function tpl_getConf($id, $notset = false)
1250{
1251    global $conf;
1252    static $tpl_configloaded = false;
1253
1254    $tpl = $conf['template'];
1255
1256    if (!$tpl_configloaded) {
1257        $tconf = tpl_loadConfig();
1258        if ($tconf !== false) {
1259            foreach ($tconf as $key => $value) {
1260                if (isset($conf['tpl'][$tpl][$key])) continue;
1261                $conf['tpl'][$tpl][$key] = $value;
1262            }
1263            $tpl_configloaded = true;
1264        }
1265    }
1266
1267    return $conf['tpl'][$tpl][$id] ?? $notset;
1268}
1269
1270/**
1271 * tpl_loadConfig()
1272 *
1273 * reads all template configuration variables
1274 * this function is automatically called by tpl_getConf()
1275 *
1276 * @return false|array
1277 */
1278function tpl_loadConfig()
1279{
1280
1281    $file = tpl_incdir() . '/conf/default.php';
1282    $conf = [];
1283
1284    if (!file_exists($file)) return false;
1285
1286    // load default config file
1287    include($file);
1288
1289    return $conf;
1290}
1291
1292// language methods
1293
1294/**
1295 * tpl_getLang($id)
1296 *
1297 * use this function to access template language variables
1298 *
1299 * @param string $id key of language string
1300 * @return string
1301 */
1302function tpl_getLang($id)
1303{
1304    static $lang = [];
1305
1306    if (count($lang) === 0) {
1307        global $conf, $config_cascade; // definitely don't invoke "global $lang"
1308
1309        $path = tpl_incdir() . 'lang/';
1310
1311        $lang = [];
1312
1313        // don't include once
1314        @include($path . 'en/lang.php');
1315        foreach ($config_cascade['lang']['template'] as $config_file) {
1316            if (file_exists($config_file . $conf['template'] . '/en/lang.php')) {
1317                include($config_file . $conf['template'] . '/en/lang.php');
1318            }
1319        }
1320
1321        if ($conf['lang'] != 'en') {
1322            @include($path . $conf['lang'] . '/lang.php');
1323            foreach ($config_cascade['lang']['template'] as $config_file) {
1324                if (file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
1325                    include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
1326                }
1327            }
1328        }
1329    }
1330    return $lang[$id] ?? '';
1331}
1332
1333/**
1334 * Retrieve a language dependent file and pass to xhtml renderer for display
1335 * template equivalent of p_locale_xhtml()
1336 *
1337 * @param string $id id of language dependent wiki page
1338 * @return  string     parsed contents of the wiki page in xhtml format
1339 */
1340function tpl_locale_xhtml($id)
1341{
1342    return p_cached_output(tpl_localeFN($id));
1343}
1344
1345/**
1346 * Prepends appropriate path for a language dependent filename
1347 *
1348 * @param string $id id of localized text
1349 * @return string wiki text
1350 */
1351function tpl_localeFN($id)
1352{
1353    $path = tpl_incdir() . 'lang/';
1354    global $conf;
1355    $file = DOKU_CONF . 'template_lang/' . $conf['template'] . '/' . $conf['lang'] . '/' . $id . '.txt';
1356    if (!file_exists($file)) {
1357        $file = $path . $conf['lang'] . '/' . $id . '.txt';
1358        if (!file_exists($file)) {
1359            //fall back to english
1360            $file = $path . 'en/' . $id . '.txt';
1361        }
1362    }
1363    return $file;
1364}
1365
1366/**
1367 * prints the "main content" in the mediamanager popup
1368 *
1369 * Depending on the user's actions this may be a list of
1370 * files in a namespace, the meta editing dialog or
1371 * a message of referencing pages
1372 *
1373 * Only allowed in mediamanager.php
1374 *
1375 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1376 * @param bool $fromajax - set true when calling this function via ajax
1377 * @param string $sort
1378 *
1379 * @author Andreas Gohr <andi@splitbrain.org>
1380 */
1381function tpl_mediaContent($fromajax = false, $sort = 'natural')
1382{
1383    global $IMG;
1384    global $AUTH;
1385    global $INUSE;
1386    global $NS;
1387    global $JUMPTO;
1388    /** @var Input $INPUT */
1389    global $INPUT;
1390
1391    $do = $INPUT->extract('do')->str('do');
1392    if (in_array($do, ['save', 'cancel'])) $do = '';
1393
1394    if (!$do) {
1395        if ($INPUT->bool('edit')) {
1396            $do = 'metaform';
1397        } elseif (is_array($INUSE)) {
1398            $do = 'filesinuse';
1399        } else {
1400            $do = 'filelist';
1401        }
1402    }
1403
1404    // output the content pane, wrapped in an event.
1405    if (!$fromajax) echo '<div id="media__content">';
1406    $data = ['do' => $do];
1407    $evt = new Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1408    if ($evt->advise_before()) {
1409        $do = $data['do'];
1410        if ($do == 'filesinuse') {
1411            media_filesinuse($INUSE, $IMG);
1412        } elseif ($do == 'filelist') {
1413            media_filelist($NS, $AUTH, $JUMPTO, false, $sort);
1414        } elseif ($do == 'searchlist') {
1415            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1416        } else {
1417            msg('Unknown action ' . hsc($do), -1);
1418        }
1419    }
1420    $evt->advise_after();
1421    unset($evt);
1422    if (!$fromajax) echo '</div>';
1423}
1424
1425/**
1426 * Prints the central column in full-screen media manager
1427 * Depending on the opened tab this may be a list of
1428 * files in a namespace, upload form or search form
1429 *
1430 * @author Kate Arzamastseva <pshns@ukr.net>
1431 */
1432function tpl_mediaFileList()
1433{
1434    global $AUTH;
1435    global $NS;
1436    global $JUMPTO;
1437    global $lang;
1438    /** @var Input $INPUT */
1439    global $INPUT;
1440
1441    $opened_tab = $INPUT->str('tab_files');
1442    if (!$opened_tab || !in_array($opened_tab, ['files', 'upload', 'search'])) $opened_tab = 'files';
1443    if ($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1444
1445    echo '<h2 class="a11y">' . $lang['mediaselect'] . '</h2>' . NL;
1446
1447    media_tabs_files($opened_tab);
1448
1449    echo '<div class="panelHeader">' . NL;
1450    echo '<h3>';
1451    $tabTitle = $NS ?: '[' . $lang['mediaroot'] . ']';
1452    printf($lang['media_' . $opened_tab], '<strong>' . hsc($tabTitle) . '</strong>');
1453    echo '</h3>' . NL;
1454    if ($opened_tab === 'search' || $opened_tab === 'files') {
1455        media_tab_files_options();
1456    }
1457    echo '</div>' . NL;
1458
1459    echo '<div class="panelContent">' . NL;
1460    if ($opened_tab == 'files') {
1461        media_tab_files($NS, $AUTH, $JUMPTO);
1462    } elseif ($opened_tab == 'upload') {
1463        media_tab_upload($NS, $AUTH, $JUMPTO);
1464    } elseif ($opened_tab == 'search') {
1465        media_tab_search($NS, $AUTH);
1466    }
1467    echo '</div>' . NL;
1468}
1469
1470/**
1471 * Prints the third column in full-screen media manager
1472 * Depending on the opened tab this may be details of the
1473 * selected file, the meta editing dialog or
1474 * list of file revisions
1475 *
1476 * @param string $image
1477 * @param boolean $rev
1478 *
1479 * @author Kate Arzamastseva <pshns@ukr.net>
1480 */
1481function tpl_mediaFileDetails($image, $rev)
1482{
1483    global $conf, $DEL, $lang;
1484    /** @var Input $INPUT */
1485    global $INPUT;
1486
1487    $removed = (
1488        !file_exists(mediaFN($image)) &&
1489        file_exists(mediaMetaFN($image, '.changes')) &&
1490        $conf['mediarevisions']
1491    );
1492    if (!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1493    if ($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1494    $ns = getNS($image);
1495    $do = $INPUT->str('mediado');
1496
1497    $opened_tab = $INPUT->str('tab_details');
1498
1499    $tab_array = ['view'];
1500    [, $mime] = mimetype($image);
1501    if ($mime == 'image/jpeg') {
1502        $tab_array[] = 'edit';
1503    }
1504    if ($conf['mediarevisions']) {
1505        $tab_array[] = 'history';
1506    }
1507
1508    if (!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1509    if ($INPUT->bool('edit')) $opened_tab = 'edit';
1510    if ($do == 'restore') $opened_tab = 'view';
1511
1512    media_tabs_details($image, $opened_tab);
1513
1514    echo '<div class="panelHeader"><h3>';
1515    [$ext] = mimetype($image, false);
1516    $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1517    $class = 'select mediafile mf_' . $class;
1518
1519    $attributes = $rev ? ['rev' => $rev] : [];
1520    $tabTitle = sprintf(
1521        '<strong><a href="%s" class="%s" title="%s">%s</a></strong>',
1522        ml($image, $attributes),
1523        $class,
1524        $lang['mediaview'],
1525        $image
1526    );
1527    if ($opened_tab === 'view' && $rev) {
1528        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1529    } else {
1530        printf($lang['media_' . $opened_tab], $tabTitle);
1531    }
1532
1533    echo '</h3></div>' . NL;
1534
1535    echo '<div class="panelContent">' . NL;
1536
1537    if ($opened_tab == 'view') {
1538        media_tab_view($image, $ns, null, $rev);
1539    } elseif ($opened_tab == 'edit' && !$removed) {
1540        media_tab_edit($image, $ns);
1541    } elseif ($opened_tab == 'history' && $conf['mediarevisions']) {
1542        media_tab_history($image, $ns);
1543    }
1544
1545    echo '</div>' . NL;
1546}
1547
1548/**
1549 * prints the namespace tree in the mediamanager popup
1550 *
1551 * Only allowed in mediamanager.php
1552 *
1553 * @author Andreas Gohr <andi@splitbrain.org>
1554 */
1555function tpl_mediaTree()
1556{
1557    global $NS;
1558    echo '<div id="media__tree">';
1559    media_nstree($NS);
1560    echo '</div>';
1561}
1562
1563/**
1564 * Print a dropdown menu with all DokuWiki actions
1565 *
1566 * Note: this will not use any pretty URLs
1567 *
1568 * @param string $empty empty option label
1569 * @param string $button submit button label
1570 *
1571 * @author Andreas Gohr <andi@splitbrain.org>
1572 * @deprecated 2017-09-01 see devel:menus
1573 */
1574function tpl_actiondropdown($empty = '', $button = '&gt;')
1575{
1576    dbg_deprecated('see devel:menus');
1577    $menu = new MobileMenu();
1578    echo $menu->getDropdown($empty, $button);
1579}
1580
1581/**
1582 * Print a informational line about the used license
1583 *
1584 * @param string $img print image? (|button|badge)
1585 * @param bool $imgonly skip the textual description?
1586 * @param bool $return when true don't print, but return HTML
1587 * @param bool $wrap wrap in div with class="license"?
1588 * @return string
1589 *
1590 * @author Andreas Gohr <andi@splitbrain.org>
1591 */
1592function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true)
1593{
1594    global $license;
1595    global $conf;
1596    global $lang;
1597    if (!$conf['license']) return '';
1598    if (!is_array($license[$conf['license']])) return '';
1599    $lic = $license[$conf['license']];
1600    $target = ($conf['target']['extern']) ? ' target="' . $conf['target']['extern'] . '"' : '';
1601
1602    $out = '';
1603    if ($wrap) $out .= '<div class="license">';
1604    if ($img) {
1605        $src = license_img($img);
1606        if ($src) {
1607            $out .= '<a href="' . $lic['url'] . '" rel="license"' . $target;
1608            $out .= '><img src="' . DOKU_BASE . $src . '" alt="' . $lic['name'] . '" /></a>';
1609            if (!$imgonly) $out .= ' ';
1610        }
1611    }
1612    if (!$imgonly) {
1613        $out .= $lang['license'] . ' ';
1614        $out .= '<bdi><a href="' . $lic['url'] . '" rel="license" class="urlextern"' . $target;
1615        $out .= '>' . $lic['name'] . '</a></bdi>';
1616    }
1617    if ($wrap) $out .= '</div>';
1618
1619    if ($return) return $out;
1620    echo $out;
1621    return '';
1622}
1623
1624/**
1625 * Includes the rendered HTML of a given page
1626 *
1627 * This function is useful to populate sidebars or similar features in a
1628 * template
1629 *
1630 * @param string $pageid The page name you want to include
1631 * @param bool $print Should the content be printed or returned only
1632 * @param bool $propagate Search higher namespaces, too?
1633 * @param bool $useacl Include the page only if the ACLs check out?
1634 * @return bool|null|string
1635 */
1636function tpl_include_page($pageid, $print = true, $propagate = false, $useacl = true)
1637{
1638    if ($propagate) {
1639        $pageid = page_findnearest($pageid, $useacl);
1640    } elseif ($useacl && auth_quickaclcheck($pageid) == AUTH_NONE) {
1641        return false;
1642    }
1643    if (!$pageid) return false;
1644
1645    global $TOC;
1646    $oldtoc = $TOC;
1647    $html = p_wiki_xhtml($pageid, '', false);
1648    $TOC = $oldtoc;
1649
1650    if ($print) echo $html;
1651    return $html;
1652}
1653
1654/**
1655 * Display the subscribe form
1656 *
1657 * @author Adrian Lang <lang@cosmocode.de>
1658 * @deprecated 2020-07-23
1659 */
1660function tpl_subscribe()
1661{
1662    dbg_deprecated(Subscribe::class . '::show()');
1663    (new Subscribe())->show();
1664}
1665
1666/**
1667 * Tries to send already created content right to the browser
1668 *
1669 * Wraps around ob_flush() and flush()
1670 *
1671 * @author Andreas Gohr <andi@splitbrain.org>
1672 */
1673function tpl_flush()
1674{
1675    if (ob_get_level() > 0) ob_flush();
1676    flush();
1677}
1678
1679/**
1680 * Tries to find a ressource file in the given locations.
1681 *
1682 * If a given location starts with a colon it is assumed to be a media
1683 * file, otherwise it is assumed to be relative to the current template
1684 *
1685 * @param string[] $search locations to look at
1686 * @param bool $abs if to use absolute URL
1687 * @param array    &$imginfo filled with getimagesize()
1688 * @param bool $fallback use fallback image if target isn't found or return 'false' if potential
1689 *                                false result is required
1690 * @return string
1691 *
1692 * @author Andreas  Gohr <andi@splitbrain.org>
1693 */
1694function tpl_getMediaFile($search, $abs = false, &$imginfo = null, $fallback = true)
1695{
1696    $img = '';
1697    $file = '';
1698    $ismedia = false;
1699    // loop through candidates until a match was found:
1700    foreach ($search as $img) {
1701        if (str_starts_with($img, ':')) {
1702            $file = mediaFN($img);
1703            $ismedia = true;
1704        } else {
1705            $file = tpl_incdir() . $img;
1706            $ismedia = false;
1707        }
1708
1709        if (file_exists($file)) break;
1710    }
1711
1712    // manage non existing target
1713    if (!file_exists($file)) {
1714        // give result for fallback image
1715        if ($fallback) {
1716            $file = DOKU_INC . 'lib/images/blank.gif';
1717            // stop process if false result is required (if $fallback is false)
1718        } else {
1719            return false;
1720        }
1721    }
1722
1723    // fetch image data if requested
1724    if (!is_null($imginfo)) {
1725        $imginfo = getimagesize($file);
1726    }
1727
1728    // build URL
1729    if ($ismedia) {
1730        $url = ml($img, '', true, '', $abs);
1731    } else {
1732        $url = tpl_basedir() . $img;
1733        if ($abs) $url = DOKU_URL . substr($url, strlen(DOKU_REL));
1734    }
1735
1736    return $url;
1737}
1738
1739/**
1740 * PHP include a file
1741 *
1742 * either from the conf directory if it exists, otherwise use
1743 * file in the template's root directory.
1744 *
1745 * The function honours config cascade settings and looks for the given
1746 * file next to the ´main´ config files, in the order protected, local,
1747 * default.
1748 *
1749 * Note: no escaping or sanity checking is done here. Never pass user input
1750 * to this function!
1751 *
1752 * @param string $file
1753 *
1754 * @author Andreas Gohr <andi@splitbrain.org>
1755 * @author Anika Henke <anika@selfthinker.org>
1756 */
1757function tpl_includeFile($file)
1758{
1759    global $config_cascade;
1760    foreach (['protected', 'local', 'default'] as $config_group) {
1761        if (empty($config_cascade['main'][$config_group])) continue;
1762        foreach ($config_cascade['main'][$config_group] as $conf_file) {
1763            $dir = dirname($conf_file);
1764            if (file_exists("$dir/$file")) {
1765                include("$dir/$file");
1766                return;
1767            }
1768        }
1769    }
1770
1771    // still here? try the template dir
1772    $file = tpl_incdir() . $file;
1773    if (file_exists($file)) {
1774        include($file);
1775    }
1776}
1777
1778/**
1779 * Returns <link> tag for various icon types (favicon|mobile|generic)
1780 *
1781 * @param array $types - list of icon types to display (favicon|mobile|generic)
1782 * @return string
1783 *
1784 * @author Anika Henke <anika@selfthinker.org>
1785 */
1786function tpl_favicon($types = ['favicon'])
1787{
1788
1789    $return = '';
1790
1791    foreach ($types as $type) {
1792        switch ($type) {
1793            case 'favicon':
1794                $look = [':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico'];
1795                $return .= '<link rel="shortcut icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1796                break;
1797            case 'mobile':
1798                $look = [':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png'];
1799                $return .= '<link rel="apple-touch-icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1800                break;
1801            case 'generic':
1802                // ideal world solution, which doesn't work in any browser yet
1803                $look = [':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg'];
1804                $return .= '<link rel="icon" href="' . tpl_getMediaFile($look) . '" type="image/svg+xml" />' . NL;
1805                break;
1806        }
1807    }
1808
1809    return $return;
1810}
1811
1812/**
1813 * Prints full-screen media manager
1814 *
1815 * @author Kate Arzamastseva <pshns@ukr.net>
1816 */
1817function tpl_media()
1818{
1819    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1820    $fullscreen = true;
1821    require_once DOKU_INC . 'lib/exe/mediamanager.php';
1822
1823    $rev = '';
1824    $image = cleanID($INPUT->str('image'));
1825    if (isset($IMG)) $image = $IMG;
1826    if (isset($JUMPTO)) $image = $JUMPTO;
1827    if (isset($REV) && !$JUMPTO) $rev = $REV;
1828
1829    echo '<div id="mediamanager__page">' . NL;
1830    echo '<h1>' . $lang['btn_media'] . '</h1>' . NL;
1831    html_msgarea();
1832
1833    echo '<div class="panel namespaces">' . NL;
1834    echo '<h2>' . $lang['namespaces'] . '</h2>' . NL;
1835    echo '<div class="panelHeader">';
1836    echo $lang['media_namespaces'];
1837    echo '</div>' . NL;
1838
1839    echo '<div class="panelContent" id="media__tree">' . NL;
1840    media_nstree($NS);
1841    echo '</div>' . NL;
1842    echo '</div>' . NL;
1843
1844    echo '<div class="panel filelist">' . NL;
1845    tpl_mediaFileList();
1846    echo '</div>' . NL;
1847
1848    echo '<div class="panel file">' . NL;
1849    echo '<h2 class="a11y">' . $lang['media_file'] . '</h2>' . NL;
1850    tpl_mediaFileDetails($image, $rev);
1851    echo '</div>' . NL;
1852
1853    echo '</div>' . NL;
1854}
1855
1856/**
1857 * Return useful layout classes
1858 *
1859 * @return string
1860 *
1861 * @author Anika Henke <anika@selfthinker.org>
1862 */
1863function tpl_classes()
1864{
1865    global $ACT, $conf, $ID, $INFO;
1866    /** @var Input $INPUT */
1867    global $INPUT;
1868
1869    $classes = [
1870        'dokuwiki',
1871        'mode_' . $ACT,
1872        'tpl_' . $conf['template'],
1873        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1874        (isset($INFO['exists']) && $INFO['exists']) ? '' : 'notFound',
1875        ($ID == $conf['start']) ? 'home' : ''
1876    ];
1877    return implode(' ', $classes);
1878}
1879
1880/**
1881 * Create event for tools menues
1882 *
1883 * @param string $toolsname name of menu
1884 * @param array $items
1885 * @param string $view e.g. 'main', 'detail', ...
1886 *
1887 * @author Anika Henke <anika@selfthinker.org>
1888 * @deprecated 2017-09-01 see devel:menus
1889 */
1890function tpl_toolsevent($toolsname, $items, $view = 'main')
1891{
1892    dbg_deprecated('see devel:menus');
1893    $data = ['view' => $view, 'items' => $items];
1894
1895    $hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
1896    $evt = new Event($hook, $data);
1897    if ($evt->advise_before()) {
1898        foreach ($evt->data['items'] as $html) echo $html;
1899    }
1900    $evt->advise_after();
1901}
1902