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