xref: /dokuwiki/inc/template.php (revision 033eb35b208082e0d25132d664962f35869dd3d8)
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        case 'preview' :
964            $page_title = "✎ ".$name;
965            break;
966
967        case 'revisions' :
968            $page_title = $name . ' - ' . $lang['btn_revs'];
969            break;
970
971        case 'backlink' :
972        case 'recent' :
973        case 'subscribe' :
974            $page_title = $name . ' - ' . $lang['btn_'.$ACT];
975            break;
976
977        default : // SHOW and anything else not included
978            $page_title = $name;
979    }
980
981    if($ret) {
982        return hsc($page_title);
983    } else {
984        print hsc($page_title);
985        return true;
986    }
987}
988
989/**
990 * Returns the requested EXIF/IPTC tag from the current image
991 *
992 * If $tags is an array all given tags are tried until a
993 * value is found. If no value is found $alt is returned.
994 *
995 * Which texts are known is defined in the functions _exifTagNames
996 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
997 * to the names of the latter one)
998 *
999 * Only allowed in: detail.php
1000 *
1001 * @author Andreas Gohr <andi@splitbrain.org>
1002 *
1003 * @param array|string $tags tag or array of tags to try
1004 * @param string       $alt  alternative output if no data was found
1005 * @param null|string  $src  the image src, uses global $SRC if not given
1006 * @return string
1007 */
1008function tpl_img_getTag($tags, $alt = '', $src = null) {
1009    // Init Exif Reader
1010    global $SRC;
1011
1012    if(is_null($src)) $src = $SRC;
1013
1014    static $meta = null;
1015    if(is_null($meta)) $meta = new JpegMeta($src);
1016    if($meta === false) return $alt;
1017    $info = cleanText($meta->getField($tags));
1018    if($info == false) return $alt;
1019    return $info;
1020}
1021
1022/**
1023 * Returns a description list of the metatags of the current image
1024 *
1025 * @return string html of description list
1026 */
1027function tpl_img_meta() {
1028    global $lang;
1029
1030    $tags = tpl_get_img_meta();
1031
1032    echo '<dl>';
1033    foreach($tags as $tag) {
1034        $label = $lang[$tag['langkey']];
1035        if(!$label) $label = $tag['langkey'] . ':';
1036
1037        echo '<dt>'.$label.'</dt><dd>';
1038        if ($tag['type'] == 'date') {
1039            echo dformat($tag['value']);
1040        } else {
1041            echo hsc($tag['value']);
1042        }
1043        echo '</dd>';
1044    }
1045    echo '</dl>';
1046}
1047
1048/**
1049 * Returns metadata as configured in mediameta config file, ready for creating html
1050 *
1051 * @return array with arrays containing the entries:
1052 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1053 *   - string type     type of value
1054 *   - string value    tag value (unescaped)
1055 */
1056function tpl_get_img_meta() {
1057
1058    $config_files = getConfigFiles('mediameta');
1059    foreach ($config_files as $config_file) {
1060        if(file_exists($config_file)) {
1061            include($config_file);
1062        }
1063    }
1064    /** @var array $fields the included array with metadata */
1065
1066    $tags = array();
1067    foreach($fields as $tag){
1068        $t = array();
1069        if (!empty($tag[0])) {
1070            $t = array($tag[0]);
1071        }
1072        if(is_array($tag[3])) {
1073            $t = array_merge($t,$tag[3]);
1074        }
1075        $value = tpl_img_getTag($t);
1076        if ($value) {
1077            $tags[] = array('langkey' => $tag[1], 'type' => $tag[2], 'value' => $value);
1078        }
1079    }
1080    return $tags;
1081}
1082
1083/**
1084 * Prints the image with a link to the full sized version
1085 *
1086 * Only allowed in: detail.php
1087 *
1088 * @triggers TPL_IMG_DISPLAY
1089 * @param $maxwidth  int - maximal width of the image
1090 * @param $maxheight int - maximal height of the image
1091 * @param $link bool     - link to the orginal size?
1092 * @param $params array  - additional image attributes
1093 * @return bool Result of TPL_IMG_DISPLAY
1094 */
1095function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
1096    global $IMG;
1097    /** @var Input $INPUT */
1098    global $INPUT;
1099    global $REV;
1100    $w = (int) tpl_img_getTag('File.Width');
1101    $h = (int) tpl_img_getTag('File.Height');
1102
1103    //resize to given max values
1104    $ratio = 1;
1105    if($w >= $h) {
1106        if($maxwidth && $w >= $maxwidth) {
1107            $ratio = $maxwidth / $w;
1108        } elseif($maxheight && $h > $maxheight) {
1109            $ratio = $maxheight / $h;
1110        }
1111    } else {
1112        if($maxheight && $h >= $maxheight) {
1113            $ratio = $maxheight / $h;
1114        } elseif($maxwidth && $w > $maxwidth) {
1115            $ratio = $maxwidth / $w;
1116        }
1117    }
1118    if($ratio) {
1119        $w = floor($ratio * $w);
1120        $h = floor($ratio * $h);
1121    }
1122
1123    //prepare URLs
1124    $url = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV), true, '&');
1125    $src = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV, 'w'=> $w, 'h'=> $h), true, '&');
1126
1127    //prepare attributes
1128    $alt = tpl_img_getTag('Simple.Title');
1129    if(is_null($params)) {
1130        $p = array();
1131    } else {
1132        $p = $params;
1133    }
1134    if($w) $p['width'] = $w;
1135    if($h) $p['height'] = $h;
1136    $p['class'] = 'img_detail';
1137    if($alt) {
1138        $p['alt']   = $alt;
1139        $p['title'] = $alt;
1140    } else {
1141        $p['alt'] = '';
1142    }
1143    $p['src'] = $src;
1144
1145    $data = array('url'=> ($link ? $url : null), 'params'=> $p);
1146    return Event::createAndTrigger('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1147}
1148
1149/**
1150 * Default action for TPL_IMG_DISPLAY
1151 *
1152 * @param array $data
1153 * @return bool
1154 */
1155function _tpl_img_action($data) {
1156    global $lang;
1157    $p = buildAttributes($data['params']);
1158
1159    if($data['url']) print '<a href="'.hsc($data['url']).'" title="'.$lang['mediaview'].'">';
1160    print '<img '.$p.'/>';
1161    if($data['url']) print '</a>';
1162    return true;
1163}
1164
1165/**
1166 * This function inserts a small gif which in reality is the indexer function.
1167 *
1168 * Should be called somewhere at the very end of the main.php
1169 * template
1170 *
1171 * @return bool
1172 */
1173function tpl_indexerWebBug() {
1174    global $ID;
1175
1176    $p           = array();
1177    $p['src']    = DOKU_BASE.'lib/exe/taskrunner.php?id='.rawurlencode($ID).
1178        '&'.time();
1179    $p['width']  = 2; //no more 1x1 px image because we live in times of ad blockers...
1180    $p['height'] = 1;
1181    $p['alt']    = '';
1182    $att         = buildAttributes($p);
1183    print "<img $att />";
1184    return true;
1185}
1186
1187/**
1188 * tpl_getConf($id)
1189 *
1190 * use this function to access template configuration variables
1191 *
1192 * @param string $id      name of the value to access
1193 * @param mixed  $notset  what to return if the setting is not available
1194 * @return mixed
1195 */
1196function tpl_getConf($id, $notset=false) {
1197    global $conf;
1198    static $tpl_configloaded = false;
1199
1200    $tpl = $conf['template'];
1201
1202    if(!$tpl_configloaded) {
1203        $tconf = tpl_loadConfig();
1204        if($tconf !== false) {
1205            foreach($tconf as $key => $value) {
1206                if(isset($conf['tpl'][$tpl][$key])) continue;
1207                $conf['tpl'][$tpl][$key] = $value;
1208            }
1209            $tpl_configloaded = true;
1210        }
1211    }
1212
1213    if(isset($conf['tpl'][$tpl][$id])){
1214        return $conf['tpl'][$tpl][$id];
1215    }
1216
1217    return $notset;
1218}
1219
1220/**
1221 * tpl_loadConfig()
1222 *
1223 * reads all template configuration variables
1224 * this function is automatically called by tpl_getConf()
1225 *
1226 * @return array
1227 */
1228function tpl_loadConfig() {
1229
1230    $file = tpl_incdir().'/conf/default.php';
1231    $conf = array();
1232
1233    if(!file_exists($file)) return false;
1234
1235    // load default config file
1236    include($file);
1237
1238    return $conf;
1239}
1240
1241// language methods
1242/**
1243 * tpl_getLang($id)
1244 *
1245 * use this function to access template language variables
1246 *
1247 * @param string $id key of language string
1248 * @return string
1249 */
1250function tpl_getLang($id) {
1251    static $lang = array();
1252
1253    if(count($lang) === 0) {
1254        global $conf, $config_cascade; // definitely don't invoke "global $lang"
1255
1256        $path = tpl_incdir() . 'lang/';
1257
1258        $lang = array();
1259
1260        // don't include once
1261        @include($path . 'en/lang.php');
1262        foreach($config_cascade['lang']['template'] as $config_file) {
1263            if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
1264                include($config_file . $conf['template'] . '/en/lang.php');
1265            }
1266        }
1267
1268        if($conf['lang'] != 'en') {
1269            @include($path . $conf['lang'] . '/lang.php');
1270            foreach($config_cascade['lang']['template'] as $config_file) {
1271                if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
1272                    include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
1273                }
1274            }
1275        }
1276    }
1277    return $lang[$id];
1278}
1279
1280/**
1281 * Retrieve a language dependent file and pass to xhtml renderer for display
1282 * template equivalent of p_locale_xhtml()
1283 *
1284 * @param   string $id id of language dependent wiki page
1285 * @return  string     parsed contents of the wiki page in xhtml format
1286 */
1287function tpl_locale_xhtml($id) {
1288    return p_cached_output(tpl_localeFN($id));
1289}
1290
1291/**
1292 * Prepends appropriate path for a language dependent filename
1293 *
1294 * @param string $id id of localized text
1295 * @return string wiki text
1296 */
1297function tpl_localeFN($id) {
1298    $path = tpl_incdir().'lang/';
1299    global $conf;
1300    $file = DOKU_CONF.'template_lang/'.$conf['template'].'/'.$conf['lang'].'/'.$id.'.txt';
1301    if (!file_exists($file)){
1302        $file = $path.$conf['lang'].'/'.$id.'.txt';
1303        if(!file_exists($file)){
1304            //fall back to english
1305            $file = $path.'en/'.$id.'.txt';
1306        }
1307    }
1308    return $file;
1309}
1310
1311/**
1312 * prints the "main content" in the mediamanager popup
1313 *
1314 * Depending on the user's actions this may be a list of
1315 * files in a namespace, the meta editing dialog or
1316 * a message of referencing pages
1317 *
1318 * Only allowed in mediamanager.php
1319 *
1320 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1321 * @param bool $fromajax - set true when calling this function via ajax
1322 * @param string $sort
1323 *
1324 * @author Andreas Gohr <andi@splitbrain.org>
1325 */
1326function tpl_mediaContent($fromajax = false, $sort='natural') {
1327    global $IMG;
1328    global $AUTH;
1329    global $INUSE;
1330    global $NS;
1331    global $JUMPTO;
1332    /** @var Input $INPUT */
1333    global $INPUT;
1334
1335    $do = $INPUT->extract('do')->str('do');
1336    if(in_array($do, array('save', 'cancel'))) $do = '';
1337
1338    if(!$do) {
1339        if($INPUT->bool('edit')) {
1340            $do = 'metaform';
1341        } elseif(is_array($INUSE)) {
1342            $do = 'filesinuse';
1343        } else {
1344            $do = 'filelist';
1345        }
1346    }
1347
1348    // output the content pane, wrapped in an event.
1349    if(!$fromajax) ptln('<div id="media__content">');
1350    $data = array('do' => $do);
1351    $evt  = new Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1352    if($evt->advise_before()) {
1353        $do = $data['do'];
1354        if($do == 'filesinuse') {
1355            media_filesinuse($INUSE, $IMG);
1356        } elseif($do == 'filelist') {
1357            media_filelist($NS, $AUTH, $JUMPTO,false,$sort);
1358        } elseif($do == 'searchlist') {
1359            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1360        } else {
1361            msg('Unknown action '.hsc($do), -1);
1362        }
1363    }
1364    $evt->advise_after();
1365    unset($evt);
1366    if(!$fromajax) ptln('</div>');
1367
1368}
1369
1370/**
1371 * Prints the central column in full-screen media manager
1372 * Depending on the opened tab this may be a list of
1373 * files in a namespace, upload form or search form
1374 *
1375 * @author Kate Arzamastseva <pshns@ukr.net>
1376 */
1377function tpl_mediaFileList() {
1378    global $AUTH;
1379    global $NS;
1380    global $JUMPTO;
1381    global $lang;
1382    /** @var Input $INPUT */
1383    global $INPUT;
1384
1385    $opened_tab = $INPUT->str('tab_files');
1386    if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
1387    if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1388
1389    echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
1390
1391    media_tabs_files($opened_tab);
1392
1393    echo '<div class="panelHeader">'.NL;
1394    echo '<h3>';
1395    $tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
1396    printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
1397    echo '</h3>'.NL;
1398    if($opened_tab === 'search' || $opened_tab === 'files') {
1399        media_tab_files_options();
1400    }
1401    echo '</div>'.NL;
1402
1403    echo '<div class="panelContent">'.NL;
1404    if($opened_tab == 'files') {
1405        media_tab_files($NS, $AUTH, $JUMPTO);
1406    } elseif($opened_tab == 'upload') {
1407        media_tab_upload($NS, $AUTH, $JUMPTO);
1408    } elseif($opened_tab == 'search') {
1409        media_tab_search($NS, $AUTH);
1410    }
1411    echo '</div>'.NL;
1412}
1413
1414/**
1415 * Prints the third column in full-screen media manager
1416 * Depending on the opened tab this may be details of the
1417 * selected file, the meta editing dialog or
1418 * list of file revisions
1419 *
1420 * @author Kate Arzamastseva <pshns@ukr.net>
1421 *
1422 * @param string $image
1423 * @param boolean $rev
1424 */
1425function tpl_mediaFileDetails($image, $rev) {
1426    global $conf, $DEL, $lang;
1427    /** @var Input $INPUT */
1428    global $INPUT;
1429
1430    $removed = (
1431        !file_exists(mediaFN($image)) &&
1432        file_exists(mediaMetaFN($image, '.changes')) &&
1433        $conf['mediarevisions']
1434    );
1435    if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1436    if($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1437    $ns = getNS($image);
1438    $do = $INPUT->str('mediado');
1439
1440    $opened_tab = $INPUT->str('tab_details');
1441
1442    $tab_array = array('view');
1443    list(, $mime) = mimetype($image);
1444    if($mime == 'image/jpeg') {
1445        $tab_array[] = 'edit';
1446    }
1447    if($conf['mediarevisions']) {
1448        $tab_array[] = 'history';
1449    }
1450
1451    if(!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1452    if($INPUT->bool('edit')) $opened_tab = 'edit';
1453    if($do == 'restore') $opened_tab = 'view';
1454
1455    media_tabs_details($image, $opened_tab);
1456
1457    echo '<div class="panelHeader"><h3>';
1458    list($ext) = mimetype($image, false);
1459    $class    = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1460    $class    = 'select mediafile mf_'.$class;
1461    $attributes = $rev ? ['rev' => $rev] : [];
1462    $tabTitle = '<strong><a href="'.ml($image, $attributes).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.
1463        $image.'</a>'.'</strong>';
1464    if($opened_tab === 'view' && $rev) {
1465        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1466    } else {
1467        printf($lang['media_'.$opened_tab], $tabTitle);
1468    }
1469
1470    echo '</h3></div>'.NL;
1471
1472    echo '<div class="panelContent">'.NL;
1473
1474    if($opened_tab == 'view') {
1475        media_tab_view($image, $ns, null, $rev);
1476
1477    } elseif($opened_tab == 'edit' && !$removed) {
1478        media_tab_edit($image, $ns);
1479
1480    } elseif($opened_tab == 'history' && $conf['mediarevisions']) {
1481        media_tab_history($image, $ns);
1482    }
1483
1484    echo '</div>'.NL;
1485}
1486
1487/**
1488 * prints the namespace tree in the mediamanager popup
1489 *
1490 * Only allowed in mediamanager.php
1491 *
1492 * @author Andreas Gohr <andi@splitbrain.org>
1493 */
1494function tpl_mediaTree() {
1495    global $NS;
1496    ptln('<div id="media__tree">');
1497    media_nstree($NS);
1498    ptln('</div>');
1499}
1500
1501/**
1502 * Print a dropdown menu with all DokuWiki actions
1503 *
1504 * Note: this will not use any pretty URLs
1505 *
1506 * @author Andreas Gohr <andi@splitbrain.org>
1507 *
1508 * @param string $empty empty option label
1509 * @param string $button submit button label
1510 * @deprecated 2017-09-01 see devel:menus
1511 */
1512function tpl_actiondropdown($empty = '', $button = '&gt;') {
1513    dbg_deprecated('see devel:menus');
1514    $menu = new \dokuwiki\Menu\MobileMenu();
1515    echo $menu->getDropdown($empty, $button);
1516}
1517
1518/**
1519 * Print a informational line about the used license
1520 *
1521 * @author Andreas Gohr <andi@splitbrain.org>
1522 * @param  string $img     print image? (|button|badge)
1523 * @param  bool   $imgonly skip the textual description?
1524 * @param  bool   $return  when true don't print, but return HTML
1525 * @param  bool   $wrap    wrap in div with class="license"?
1526 * @return string
1527 */
1528function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true) {
1529    global $license;
1530    global $conf;
1531    global $lang;
1532    if(!$conf['license']) return '';
1533    if(!is_array($license[$conf['license']])) return '';
1534    $lic    = $license[$conf['license']];
1535    $target = ($conf['target']['extern']) ? ' target="'.$conf['target']['extern'].'"' : '';
1536
1537    $out = '';
1538    if($wrap) $out .= '<div class="license">';
1539    if($img) {
1540        $src = license_img($img);
1541        if($src) {
1542            $out .= '<a href="'.$lic['url'].'" rel="license"'.$target;
1543            $out .= '><img src="'.DOKU_BASE.$src.'" alt="'.$lic['name'].'" /></a>';
1544            if(!$imgonly) $out .= ' ';
1545        }
1546    }
1547    if(!$imgonly) {
1548        $out .= $lang['license'].' ';
1549        $out .= '<bdi><a href="'.$lic['url'].'" rel="license" class="urlextern"'.$target;
1550        $out .= '>'.$lic['name'].'</a></bdi>';
1551    }
1552    if($wrap) $out .= '</div>';
1553
1554    if($return) return $out;
1555    echo $out;
1556    return '';
1557}
1558
1559/**
1560 * Includes the rendered HTML of a given page
1561 *
1562 * This function is useful to populate sidebars or similar features in a
1563 * template
1564 *
1565 * @param string $pageid The page name you want to include
1566 * @param bool $print Should the content be printed or returned only
1567 * @param bool $propagate Search higher namespaces, too?
1568 * @param bool $useacl Include the page only if the ACLs check out?
1569 * @return bool|null|string
1570 */
1571function tpl_include_page($pageid, $print = true, $propagate = false, $useacl = true) {
1572    if($propagate) {
1573        $pageid = page_findnearest($pageid, $useacl);
1574    } elseif($useacl && auth_quickaclcheck($pageid) == AUTH_NONE) {
1575        return false;
1576    }
1577    if(!$pageid) return false;
1578
1579    global $TOC;
1580    $oldtoc = $TOC;
1581    $html   = p_wiki_xhtml($pageid, '', false);
1582    $TOC    = $oldtoc;
1583
1584    if($print) echo $html;
1585    return $html;
1586}
1587
1588/**
1589 * Display the subscribe form
1590 *
1591 * @author Adrian Lang <lang@cosmocode.de>
1592 */
1593function tpl_subscribe() {
1594    global $INFO;
1595    global $ID;
1596    global $lang;
1597    global $conf;
1598    $stime_days = $conf['subscribe_time'] / 60 / 60 / 24;
1599
1600    echo p_locale_xhtml('subscr_form');
1601    echo '<h2>'.$lang['subscr_m_current_header'].'</h2>';
1602    echo '<div class="level2">';
1603    if($INFO['subscribed'] === false) {
1604        echo '<p>'.$lang['subscr_m_not_subscribed'].'</p>';
1605    } else {
1606        echo '<ul>';
1607        foreach($INFO['subscribed'] as $sub) {
1608            echo '<li><div class="li">';
1609            if($sub['target'] !== $ID) {
1610                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1611            } else {
1612                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1613            }
1614            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1615            if(!$sstl) $sstl = hsc($sub['style']);
1616            echo ' ('.$sstl.') ';
1617
1618            echo '<a href="'.wl(
1619                $ID,
1620                array(
1621                     'do'        => 'subscribe',
1622                     'sub_target'=> $sub['target'],
1623                     'sub_style' => $sub['style'],
1624                     'sub_action'=> 'unsubscribe',
1625                     'sectok'    => getSecurityToken()
1626                )
1627            ).
1628                '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'].
1629                '</a></div></li>';
1630        }
1631        echo '</ul>';
1632    }
1633    echo '</div>';
1634
1635    // Add new subscription form
1636    echo '<h2>'.$lang['subscr_m_new_header'].'</h2>';
1637    echo '<div class="level2">';
1638    $ns      = getNS($ID).':';
1639    $targets = array(
1640        $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1641        $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1642    );
1643    $styles  = array(
1644        'every'  => $lang['subscr_style_every'],
1645        'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1646        'list'   => sprintf($lang['subscr_style_list'], $stime_days),
1647    );
1648
1649    $form = new Doku_Form(array('id' => 'subscribe__form'));
1650    $form->startFieldset($lang['subscr_m_subscribe']);
1651    $form->addRadioSet('sub_target', $targets);
1652    $form->startFieldset($lang['subscr_m_receive']);
1653    $form->addRadioSet('sub_style', $styles);
1654    $form->addHidden('sub_action', 'subscribe');
1655    $form->addHidden('do', 'subscribe');
1656    $form->addHidden('id', $ID);
1657    $form->endFieldset();
1658    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1659    html_form('SUBSCRIBE', $form);
1660    echo '</div>';
1661}
1662
1663/**
1664 * Tries to send already created content right to the browser
1665 *
1666 * Wraps around ob_flush() and flush()
1667 *
1668 * @author Andreas Gohr <andi@splitbrain.org>
1669 */
1670function tpl_flush() {
1671    if( ob_get_level() > 0 ) ob_flush();
1672    flush();
1673}
1674
1675/**
1676 * Tries to find a ressource file in the given locations.
1677 *
1678 * If a given location starts with a colon it is assumed to be a media
1679 * file, otherwise it is assumed to be relative to the current template
1680 *
1681 * @param  string[] $search       locations to look at
1682 * @param  bool     $abs           if to use absolute URL
1683 * @param  array   &$imginfo   filled with getimagesize()
1684 * @return string
1685 *
1686 * @author Andreas  Gohr <andi@splitbrain.org>
1687 */
1688function tpl_getMediaFile($search, $abs = false, &$imginfo = null) {
1689    $img     = '';
1690    $file    = '';
1691    $ismedia = false;
1692    // loop through candidates until a match was found:
1693    foreach($search as $img) {
1694        if(substr($img, 0, 1) == ':') {
1695            $file    = mediaFN($img);
1696            $ismedia = true;
1697        } else {
1698            $file    = tpl_incdir().$img;
1699            $ismedia = false;
1700        }
1701
1702        if(file_exists($file)) break;
1703    }
1704
1705    // fetch image data if requested
1706    if(!is_null($imginfo)) {
1707        $imginfo = getimagesize($file);
1708    }
1709
1710    // build URL
1711    if($ismedia) {
1712        $url = ml($img, '', true, '', $abs);
1713    } else {
1714        $url = tpl_basedir().$img;
1715        if($abs) $url = DOKU_URL.substr($url, strlen(DOKU_REL));
1716    }
1717
1718    return $url;
1719}
1720
1721/**
1722 * PHP include a file
1723 *
1724 * either from the conf directory if it exists, otherwise use
1725 * file in the template's root directory.
1726 *
1727 * The function honours config cascade settings and looks for the given
1728 * file next to the ´main´ config files, in the order protected, local,
1729 * default.
1730 *
1731 * Note: no escaping or sanity checking is done here. Never pass user input
1732 * to this function!
1733 *
1734 * @author Anika Henke <anika@selfthinker.org>
1735 * @author Andreas Gohr <andi@splitbrain.org>
1736 *
1737 * @param string $file
1738 */
1739function tpl_includeFile($file) {
1740    global $config_cascade;
1741    foreach(array('protected', 'local', 'default') as $config_group) {
1742        if(empty($config_cascade['main'][$config_group])) continue;
1743        foreach($config_cascade['main'][$config_group] as $conf_file) {
1744            $dir = dirname($conf_file);
1745            if(file_exists("$dir/$file")) {
1746                include("$dir/$file");
1747                return;
1748            }
1749        }
1750    }
1751
1752    // still here? try the template dir
1753    $file = tpl_incdir().$file;
1754    if(file_exists($file)) {
1755        include($file);
1756    }
1757}
1758
1759/**
1760 * Returns <link> tag for various icon types (favicon|mobile|generic)
1761 *
1762 * @author Anika Henke <anika@selfthinker.org>
1763 *
1764 * @param  array $types - list of icon types to display (favicon|mobile|generic)
1765 * @return string
1766 */
1767function tpl_favicon($types = array('favicon')) {
1768
1769    $return = '';
1770
1771    foreach($types as $type) {
1772        switch($type) {
1773            case 'favicon':
1774                $look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
1775                $return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1776                break;
1777            case 'mobile':
1778                $look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
1779                $return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1780                break;
1781            case 'generic':
1782                // ideal world solution, which doesn't work in any browser yet
1783                $look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
1784                $return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
1785                break;
1786        }
1787    }
1788
1789    return $return;
1790}
1791
1792/**
1793 * Prints full-screen media manager
1794 *
1795 * @author Kate Arzamastseva <pshns@ukr.net>
1796 */
1797function tpl_media() {
1798    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1799    $fullscreen = true;
1800    require_once DOKU_INC.'lib/exe/mediamanager.php';
1801
1802    $rev   = '';
1803    $image = cleanID($INPUT->str('image'));
1804    if(isset($IMG)) $image = $IMG;
1805    if(isset($JUMPTO)) $image = $JUMPTO;
1806    if(isset($REV) && !$JUMPTO) $rev = $REV;
1807
1808    echo '<div id="mediamanager__page">'.NL;
1809    echo '<h1>'.$lang['btn_media'].'</h1>'.NL;
1810    html_msgarea();
1811
1812    echo '<div class="panel namespaces">'.NL;
1813    echo '<h2>'.$lang['namespaces'].'</h2>'.NL;
1814    echo '<div class="panelHeader">';
1815    echo $lang['media_namespaces'];
1816    echo '</div>'.NL;
1817
1818    echo '<div class="panelContent" id="media__tree">'.NL;
1819    media_nstree($NS);
1820    echo '</div>'.NL;
1821    echo '</div>'.NL;
1822
1823    echo '<div class="panel filelist">'.NL;
1824    tpl_mediaFileList();
1825    echo '</div>'.NL;
1826
1827    echo '<div class="panel file">'.NL;
1828    echo '<h2 class="a11y">'.$lang['media_file'].'</h2>'.NL;
1829    tpl_mediaFileDetails($image, $rev);
1830    echo '</div>'.NL;
1831
1832    echo '</div>'.NL;
1833}
1834
1835/**
1836 * Return useful layout classes
1837 *
1838 * @author Anika Henke <anika@selfthinker.org>
1839 *
1840 * @return string
1841 */
1842function tpl_classes() {
1843    global $ACT, $conf, $ID, $INFO;
1844    /** @var Input $INPUT */
1845    global $INPUT;
1846
1847    $classes = array(
1848        'dokuwiki',
1849        'mode_'.$ACT,
1850        'tpl_'.$conf['template'],
1851        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1852        (isset($INFO) && $INFO['exists']) ? '' : 'notFound',
1853        ($ID == $conf['start']) ? 'home' : '',
1854    );
1855    return join(' ', $classes);
1856}
1857
1858/**
1859 * Create event for tools menues
1860 *
1861 * @author Anika Henke <anika@selfthinker.org>
1862 * @param string $toolsname name of menu
1863 * @param array $items
1864 * @param string $view e.g. 'main', 'detail', ...
1865 * @deprecated 2017-09-01 see devel:menus
1866 */
1867function tpl_toolsevent($toolsname, $items, $view = 'main') {
1868    dbg_deprecated('see devel:menus');
1869    $data = array(
1870        'view' => $view,
1871        'items' => $items
1872    );
1873
1874    $hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
1875    $evt = new Event($hook, $data);
1876    if($evt->advise_before()) {
1877        foreach($evt->data['items'] as $k => $html) echo $html;
1878    }
1879    $evt->advise_after();
1880}
1881
1882//Setup VIM: ex: et ts=4 :
1883
1884