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