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