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