xref: /dokuwiki/inc/template.php (revision 430a27b9c8e4c39ed47bc0671dff896e25f26583)
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
671    // don't print the search form if search action has been disabled
672    if(!actionOK('search')) return false;
673
674    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search" method="get" role="search"><div class="no">';
675    print '<input type="hidden" name="do" value="search" />';
676    print '<input type="text" ';
677    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
678    print 'placeholder="'.$lang['btn_search'].'" ';
679    if(!$autocomplete) print 'autocomplete="off" ';
680    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
681    print '<button type="submit" title="'.$lang['btn_search'].'">'.$lang['btn_search'].'</button>';
682    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
683    print '</div></form>';
684    return true;
685}
686
687/**
688 * Print the breadcrumbs trace
689 *
690 * @author Andreas Gohr <andi@splitbrain.org>
691 *
692 * @param string $sep Separator between entries
693 * @param bool   $return return or print
694 * @return bool|string
695 */
696function tpl_breadcrumbs($sep = null, $return = false) {
697    global $lang;
698    global $conf;
699
700    //check if enabled
701    if(!$conf['breadcrumbs']) return false;
702
703    //set default
704    if(is_null($sep)) $sep = '•';
705
706    $out='';
707
708    $crumbs = breadcrumbs(); //setup crumb trace
709
710    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
711
712    //render crumbs, highlight the last one
713    $out .= '<span class="bchead">'.$lang['breadcrumb'].'</span>';
714    $last = count($crumbs);
715    $i    = 0;
716    foreach($crumbs as $id => $name) {
717        $i++;
718        $out .= $crumbs_sep;
719        if($i == $last) $out .= '<span class="curid">';
720        $out .= '<bdi>' . tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="'.$id.'"', true) .  '</bdi>';
721        if($i == $last) $out .= '</span>';
722    }
723    if($return) return $out;
724    print $out;
725    return $out ? true : false;
726}
727
728/**
729 * Hierarchical breadcrumbs
730 *
731 * This code was suggested as replacement for the usual breadcrumbs.
732 * It only makes sense with a deep site structure.
733 *
734 * @author Andreas Gohr <andi@splitbrain.org>
735 * @author Nigel McNie <oracle.shinoda@gmail.com>
736 * @author Sean Coates <sean@caedmon.net>
737 * @author <fredrik@averpil.com>
738 * @todo   May behave strangely in RTL languages
739 *
740 * @param string $sep Separator between entries
741 * @param bool   $return return or print
742 * @return bool|string
743 */
744function tpl_youarehere($sep = null, $return = false) {
745    global $conf;
746    global $ID;
747    global $lang;
748
749    // check if enabled
750    if(!$conf['youarehere']) return false;
751
752    //set default
753    if(is_null($sep)) $sep = ' » ';
754
755    $out = '';
756
757    $parts = explode(':', $ID);
758    $count = count($parts);
759
760    $out .= '<span class="bchead">'.$lang['youarehere'].' </span>';
761
762    // always print the startpage
763    $out .= '<span class="home">' . tpl_pagelink(':'.$conf['start'], null, true) . '</span>';
764
765    // print intermediate namespace links
766    $part = '';
767    for($i = 0; $i < $count - 1; $i++) {
768        $part .= $parts[$i].':';
769        $page = $part;
770        if($page == $conf['start']) continue; // Skip startpage
771
772        // output
773        $out .= $sep . tpl_pagelink($page, null, true);
774    }
775
776    // print current page, skipping start page, skipping for namespace index
777    resolve_pageid('', $page, $exists);
778    if(isset($page) && $page == $part.$parts[$i]) return true;
779    $page = $part.$parts[$i];
780    if($page == $conf['start']) return true;
781    $out .= $sep;
782    $out .= tpl_pagelink($page, null, true);
783    if($return) return $out;
784    print $out;
785    return $out ? true : false;
786}
787
788/**
789 * Print info if the user is logged in
790 * and show full name in that case
791 *
792 * Could be enhanced with a profile link in future?
793 *
794 * @author Andreas Gohr <andi@splitbrain.org>
795 *
796 * @return bool
797 */
798function tpl_userinfo() {
799    global $lang;
800    /** @var Input $INPUT */
801    global $INPUT;
802
803    if($INPUT->server->str('REMOTE_USER')) {
804        print $lang['loggedinas'].' '.userlink();
805        return true;
806    }
807    return false;
808}
809
810/**
811 * Print some info about the current page
812 *
813 * @author Andreas Gohr <andi@splitbrain.org>
814 *
815 * @param bool $ret return content instead of printing it
816 * @return bool|string
817 */
818function tpl_pageinfo($ret = false) {
819    global $conf;
820    global $lang;
821    global $INFO;
822    global $ID;
823
824    // return if we are not allowed to view the page
825    if(!auth_quickaclcheck($ID)) {
826        return false;
827    }
828
829    // prepare date and path
830    $fn = $INFO['filepath'];
831    if(!$conf['fullpath']) {
832        if($INFO['rev']) {
833            $fn = str_replace($conf['olddir'].'/', '', $fn);
834        } else {
835            $fn = str_replace($conf['datadir'].'/', '', $fn);
836        }
837    }
838    $fn   = utf8_decodeFN($fn);
839    $date = dformat($INFO['lastmod']);
840
841    // print it
842    if($INFO['exists']) {
843        $out = '';
844        $out .= '<bdi>'.$fn.'</bdi>';
845        $out .= ' · ';
846        $out .= $lang['lastmod'];
847        $out .= ' ';
848        $out .= $date;
849        if($INFO['editor']) {
850            $out .= ' '.$lang['by'].' ';
851            $out .= '<bdi>'.editorinfo($INFO['editor']).'</bdi>';
852        } else {
853            $out .= ' ('.$lang['external_edit'].')';
854        }
855        if($INFO['locked']) {
856            $out .= ' · ';
857            $out .= $lang['lockedby'];
858            $out .= ' ';
859            $out .= '<bdi>'.editorinfo($INFO['locked']).'</bdi>';
860        }
861        if($ret) {
862            return $out;
863        } else {
864            echo $out;
865            return true;
866        }
867    }
868    return false;
869}
870
871/**
872 * Prints or returns the name of the given page (current one if none given).
873 *
874 * If useheading is enabled this will use the first headline else
875 * the given ID is used.
876 *
877 * @author Andreas Gohr <andi@splitbrain.org>
878 *
879 * @param string $id page id
880 * @param bool   $ret return content instead of printing
881 * @return bool|string
882 */
883function tpl_pagetitle($id = null, $ret = false) {
884    global $ACT, $INPUT, $conf, $lang;
885
886    if(is_null($id)) {
887        global $ID;
888        $id = $ID;
889    }
890
891    $name = $id;
892    if(useHeading('navigation')) {
893        $first_heading = p_get_first_heading($id);
894        if($first_heading) $name = $first_heading;
895    }
896
897    // default page title is the page name, modify with the current action
898    switch ($ACT) {
899        // admin functions
900        case 'admin' :
901            $page_title = $lang['btn_admin'];
902            // try to get the plugin name
903            /** @var $plugin DokuWiki_Admin_Plugin */
904            if ($plugin = plugin_getRequestAdminPlugin()){
905                $plugin_title = $plugin->getMenuText($conf['lang']);
906                $page_title = $plugin_title ? $plugin_title : $plugin->getPluginName();
907            }
908            break;
909
910        // user functions
911        case 'login' :
912        case 'profile' :
913        case 'register' :
914        case 'resendpwd' :
915            $page_title = $lang['btn_'.$ACT];
916            break;
917
918         // wiki functions
919        case 'search' :
920        case 'index' :
921            $page_title = $lang['btn_'.$ACT];
922            break;
923
924        // page functions
925        case 'edit' :
926            $page_title = "✎ ".$name;
927            break;
928
929        case 'revisions' :
930            $page_title = $name . ' - ' . $lang['btn_revs'];
931            break;
932
933        case 'backlink' :
934        case 'recent' :
935        case 'subscribe' :
936            $page_title = $name . ' - ' . $lang['btn_'.$ACT];
937            break;
938
939        default : // SHOW and anything else not included
940            $page_title = $name;
941    }
942
943    if($ret) {
944        return hsc($page_title);
945    } else {
946        print hsc($page_title);
947        return true;
948    }
949}
950
951/**
952 * Returns the requested EXIF/IPTC tag from the current image
953 *
954 * If $tags is an array all given tags are tried until a
955 * value is found. If no value is found $alt is returned.
956 *
957 * Which texts are known is defined in the functions _exifTagNames
958 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
959 * to the names of the latter one)
960 *
961 * Only allowed in: detail.php
962 *
963 * @author Andreas Gohr <andi@splitbrain.org>
964 *
965 * @param array|string $tags tag or array of tags to try
966 * @param string       $alt  alternative output if no data was found
967 * @param null|string  $src  the image src, uses global $SRC if not given
968 * @return string
969 */
970function tpl_img_getTag($tags, $alt = '', $src = null) {
971    // Init Exif Reader
972    global $SRC;
973
974    if(is_null($src)) $src = $SRC;
975
976    static $meta = null;
977    if(is_null($meta)) $meta = new JpegMeta($src);
978    if($meta === false) return $alt;
979    $info = cleanText($meta->getField($tags));
980    if($info == false) return $alt;
981    return $info;
982}
983
984/**
985 * Returns a description list of the metatags of the current image
986 *
987 * @return string html of description list
988 */
989function tpl_img_meta() {
990    global $lang;
991
992    $tags = tpl_get_img_meta();
993
994    echo '<dl>';
995    foreach($tags as $tag) {
996        $label = $lang[$tag['langkey']];
997        if(!$label) $label = $tag['langkey'] . ':';
998
999        echo '<dt>'.$label.'</dt><dd>';
1000        if ($tag['type'] == 'date') {
1001            echo dformat($tag['value']);
1002        } else {
1003            echo hsc($tag['value']);
1004        }
1005        echo '</dd>';
1006    }
1007    echo '</dl>';
1008}
1009
1010/**
1011 * Returns metadata as configured in mediameta config file, ready for creating html
1012 *
1013 * @return array with arrays containing the entries:
1014 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1015 *   - string type     type of value
1016 *   - string value    tag value (unescaped)
1017 */
1018function tpl_get_img_meta() {
1019
1020    $config_files = getConfigFiles('mediameta');
1021    foreach ($config_files as $config_file) {
1022        if(file_exists($config_file)) {
1023            include($config_file);
1024        }
1025    }
1026    /** @var array $fields the included array with metadata */
1027
1028    $tags = array();
1029    foreach($fields as $tag){
1030        $t = array();
1031        if (!empty($tag[0])) {
1032            $t = array($tag[0]);
1033        }
1034        if(is_array($tag[3])) {
1035            $t = array_merge($t,$tag[3]);
1036        }
1037        $value = tpl_img_getTag($t);
1038        if ($value) {
1039            $tags[] = array('langkey' => $tag[1], 'type' => $tag[2], 'value' => $value);
1040        }
1041    }
1042    return $tags;
1043}
1044
1045/**
1046 * Prints the image with a link to the full sized version
1047 *
1048 * Only allowed in: detail.php
1049 *
1050 * @triggers TPL_IMG_DISPLAY
1051 * @param $maxwidth  int - maximal width of the image
1052 * @param $maxheight int - maximal height of the image
1053 * @param $link bool     - link to the orginal size?
1054 * @param $params array  - additional image attributes
1055 * @return bool Result of TPL_IMG_DISPLAY
1056 */
1057function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
1058    global $IMG;
1059    /** @var Input $INPUT */
1060    global $INPUT;
1061    global $REV;
1062    $w = (int) tpl_img_getTag('File.Width');
1063    $h = (int) tpl_img_getTag('File.Height');
1064
1065    //resize to given max values
1066    $ratio = 1;
1067    if($w >= $h) {
1068        if($maxwidth && $w >= $maxwidth) {
1069            $ratio = $maxwidth / $w;
1070        } elseif($maxheight && $h > $maxheight) {
1071            $ratio = $maxheight / $h;
1072        }
1073    } else {
1074        if($maxheight && $h >= $maxheight) {
1075            $ratio = $maxheight / $h;
1076        } elseif($maxwidth && $w > $maxwidth) {
1077            $ratio = $maxwidth / $w;
1078        }
1079    }
1080    if($ratio) {
1081        $w = floor($ratio * $w);
1082        $h = floor($ratio * $h);
1083    }
1084
1085    //prepare URLs
1086    $url = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV), true, '&');
1087    $src = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV, 'w'=> $w, 'h'=> $h), true, '&');
1088
1089    //prepare attributes
1090    $alt = tpl_img_getTag('Simple.Title');
1091    if(is_null($params)) {
1092        $p = array();
1093    } else {
1094        $p = $params;
1095    }
1096    if($w) $p['width'] = $w;
1097    if($h) $p['height'] = $h;
1098    $p['class'] = 'img_detail';
1099    if($alt) {
1100        $p['alt']   = $alt;
1101        $p['title'] = $alt;
1102    } else {
1103        $p['alt'] = '';
1104    }
1105    $p['src'] = $src;
1106
1107    $data = array('url'=> ($link ? $url : null), 'params'=> $p);
1108    return trigger_event('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1109}
1110
1111/**
1112 * Default action for TPL_IMG_DISPLAY
1113 *
1114 * @param array $data
1115 * @return bool
1116 */
1117function _tpl_img_action($data) {
1118    global $lang;
1119    $p = buildAttributes($data['params']);
1120
1121    if($data['url']) print '<a href="'.hsc($data['url']).'" title="'.$lang['mediaview'].'">';
1122    print '<img '.$p.'/>';
1123    if($data['url']) print '</a>';
1124    return true;
1125}
1126
1127/**
1128 * This function inserts a small gif which in reality is the indexer function.
1129 *
1130 * Should be called somewhere at the very end of the main.php
1131 * template
1132 *
1133 * @return bool
1134 */
1135function tpl_indexerWebBug() {
1136    global $ID;
1137
1138    $p           = array();
1139    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1140        '&'.time();
1141    $p['width']  = 2; //no more 1x1 px image because we live in times of ad blockers...
1142    $p['height'] = 1;
1143    $p['alt']    = '';
1144    $att         = buildAttributes($p);
1145    print "<img $att />";
1146    return true;
1147}
1148
1149/**
1150 * tpl_getConf($id)
1151 *
1152 * use this function to access template configuration variables
1153 *
1154 * @param string $id      name of the value to access
1155 * @param mixed  $notset  what to return if the setting is not available
1156 * @return mixed
1157 */
1158function tpl_getConf($id, $notset=false) {
1159    global $conf;
1160    static $tpl_configloaded = false;
1161
1162    $tpl = $conf['template'];
1163
1164    if(!$tpl_configloaded) {
1165        $tconf = tpl_loadConfig();
1166        if($tconf !== false) {
1167            foreach($tconf as $key => $value) {
1168                if(isset($conf['tpl'][$tpl][$key])) continue;
1169                $conf['tpl'][$tpl][$key] = $value;
1170            }
1171            $tpl_configloaded = true;
1172        }
1173    }
1174
1175    if(isset($conf['tpl'][$tpl][$id])){
1176        return $conf['tpl'][$tpl][$id];
1177    }
1178
1179    return $notset;
1180}
1181
1182/**
1183 * tpl_loadConfig()
1184 *
1185 * reads all template configuration variables
1186 * this function is automatically called by tpl_getConf()
1187 *
1188 * @return array
1189 */
1190function tpl_loadConfig() {
1191
1192    $file = tpl_incdir().'/conf/default.php';
1193    $conf = array();
1194
1195    if(!file_exists($file)) return false;
1196
1197    // load default config file
1198    include($file);
1199
1200    return $conf;
1201}
1202
1203// language methods
1204/**
1205 * tpl_getLang($id)
1206 *
1207 * use this function to access template language variables
1208 *
1209 * @param string $id key of language string
1210 * @return string
1211 */
1212function tpl_getLang($id) {
1213    static $lang = array();
1214
1215    if(count($lang) === 0) {
1216        global $conf, $config_cascade; // definitely don't invoke "global $lang"
1217
1218        $path = tpl_incdir() . 'lang/';
1219
1220        $lang = array();
1221
1222        // don't include once
1223        @include($path . 'en/lang.php');
1224        foreach($config_cascade['lang']['template'] as $config_file) {
1225            if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
1226                include($config_file . $conf['template'] . '/en/lang.php');
1227            }
1228        }
1229
1230        if($conf['lang'] != 'en') {
1231            @include($path . $conf['lang'] . '/lang.php');
1232            foreach($config_cascade['lang']['template'] as $config_file) {
1233                if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
1234                    include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
1235                }
1236            }
1237        }
1238    }
1239    return $lang[$id];
1240}
1241
1242/**
1243 * Retrieve a language dependent file and pass to xhtml renderer for display
1244 * template equivalent of p_locale_xhtml()
1245 *
1246 * @param   string $id id of language dependent wiki page
1247 * @return  string     parsed contents of the wiki page in xhtml format
1248 */
1249function tpl_locale_xhtml($id) {
1250    return p_cached_output(tpl_localeFN($id));
1251}
1252
1253/**
1254 * Prepends appropriate path for a language dependent filename
1255 *
1256 * @param string $id id of localized text
1257 * @return string wiki text
1258 */
1259function tpl_localeFN($id) {
1260    $path = tpl_incdir().'lang/';
1261    global $conf;
1262    $file = DOKU_CONF.'template_lang/'.$conf['template'].'/'.$conf['lang'].'/'.$id.'.txt';
1263    if (!file_exists($file)){
1264        $file = $path.$conf['lang'].'/'.$id.'.txt';
1265        if(!file_exists($file)){
1266            //fall back to english
1267            $file = $path.'en/'.$id.'.txt';
1268        }
1269    }
1270    return $file;
1271}
1272
1273/**
1274 * prints the "main content" in the mediamanager popup
1275 *
1276 * Depending on the user's actions this may be a list of
1277 * files in a namespace, the meta editing dialog or
1278 * a message of referencing pages
1279 *
1280 * Only allowed in mediamanager.php
1281 *
1282 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1283 * @param bool $fromajax - set true when calling this function via ajax
1284 * @param string $sort
1285 *
1286 * @author Andreas Gohr <andi@splitbrain.org>
1287 */
1288function tpl_mediaContent($fromajax = false, $sort='natural') {
1289    global $IMG;
1290    global $AUTH;
1291    global $INUSE;
1292    global $NS;
1293    global $JUMPTO;
1294    /** @var Input $INPUT */
1295    global $INPUT;
1296
1297    $do = $INPUT->extract('do')->str('do');
1298    if(in_array($do, array('save', 'cancel'))) $do = '';
1299
1300    if(!$do) {
1301        if($INPUT->bool('edit')) {
1302            $do = 'metaform';
1303        } elseif(is_array($INUSE)) {
1304            $do = 'filesinuse';
1305        } else {
1306            $do = 'filelist';
1307        }
1308    }
1309
1310    // output the content pane, wrapped in an event.
1311    if(!$fromajax) ptln('<div id="media__content">');
1312    $data = array('do' => $do);
1313    $evt  = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1314    if($evt->advise_before()) {
1315        $do = $data['do'];
1316        if($do == 'filesinuse') {
1317            media_filesinuse($INUSE, $IMG);
1318        } elseif($do == 'filelist') {
1319            media_filelist($NS, $AUTH, $JUMPTO,false,$sort);
1320        } elseif($do == 'searchlist') {
1321            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1322        } else {
1323            msg('Unknown action '.hsc($do), -1);
1324        }
1325    }
1326    $evt->advise_after();
1327    unset($evt);
1328    if(!$fromajax) ptln('</div>');
1329
1330}
1331
1332/**
1333 * Prints the central column in full-screen media manager
1334 * Depending on the opened tab this may be a list of
1335 * files in a namespace, upload form or search form
1336 *
1337 * @author Kate Arzamastseva <pshns@ukr.net>
1338 */
1339function tpl_mediaFileList() {
1340    global $AUTH;
1341    global $NS;
1342    global $JUMPTO;
1343    global $lang;
1344    /** @var Input $INPUT */
1345    global $INPUT;
1346
1347    $opened_tab = $INPUT->str('tab_files');
1348    if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
1349    if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1350
1351    echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
1352
1353    media_tabs_files($opened_tab);
1354
1355    echo '<div class="panelHeader">'.NL;
1356    echo '<h3>';
1357    $tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
1358    printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
1359    echo '</h3>'.NL;
1360    if($opened_tab === 'search' || $opened_tab === 'files') {
1361        media_tab_files_options();
1362    }
1363    echo '</div>'.NL;
1364
1365    echo '<div class="panelContent">'.NL;
1366    if($opened_tab == 'files') {
1367        media_tab_files($NS, $AUTH, $JUMPTO);
1368    } elseif($opened_tab == 'upload') {
1369        media_tab_upload($NS, $AUTH, $JUMPTO);
1370    } elseif($opened_tab == 'search') {
1371        media_tab_search($NS, $AUTH);
1372    }
1373    echo '</div>'.NL;
1374}
1375
1376/**
1377 * Prints the third column in full-screen media manager
1378 * Depending on the opened tab this may be details of the
1379 * selected file, the meta editing dialog or
1380 * list of file revisions
1381 *
1382 * @author Kate Arzamastseva <pshns@ukr.net>
1383 *
1384 * @param string $image
1385 * @param boolean $rev
1386 */
1387function tpl_mediaFileDetails($image, $rev) {
1388    global $conf, $DEL, $lang;
1389    /** @var Input $INPUT */
1390    global $INPUT;
1391
1392    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')) && $conf['mediarevisions']);
1393    if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1394    if($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1395    $ns = getNS($image);
1396    $do = $INPUT->str('mediado');
1397
1398    $opened_tab = $INPUT->str('tab_details');
1399
1400    $tab_array = array('view');
1401    list(, $mime) = mimetype($image);
1402    if($mime == 'image/jpeg') {
1403        $tab_array[] = 'edit';
1404    }
1405    if($conf['mediarevisions']) {
1406        $tab_array[] = 'history';
1407    }
1408
1409    if(!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1410    if($INPUT->bool('edit')) $opened_tab = 'edit';
1411    if($do == 'restore') $opened_tab = 'view';
1412
1413    media_tabs_details($image, $opened_tab);
1414
1415    echo '<div class="panelHeader"><h3>';
1416    list($ext) = mimetype($image, false);
1417    $class    = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1418    $class    = 'select mediafile mf_'.$class;
1419    $attributes = $rev ? ['rev' => $rev] : [];
1420    $tabTitle = '<strong><a href="'.ml($image, $attributes).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.$image.'</a>'.'</strong>';
1421    if($opened_tab === 'view' && $rev) {
1422        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1423    } else {
1424        printf($lang['media_'.$opened_tab], $tabTitle);
1425    }
1426
1427    echo '</h3></div>'.NL;
1428
1429    echo '<div class="panelContent">'.NL;
1430
1431    if($opened_tab == 'view') {
1432        media_tab_view($image, $ns, null, $rev);
1433
1434    } elseif($opened_tab == 'edit' && !$removed) {
1435        media_tab_edit($image, $ns);
1436
1437    } elseif($opened_tab == 'history' && $conf['mediarevisions']) {
1438        media_tab_history($image, $ns);
1439    }
1440
1441    echo '</div>'.NL;
1442}
1443
1444/**
1445 * prints the namespace tree in the mediamanager popup
1446 *
1447 * Only allowed in mediamanager.php
1448 *
1449 * @author Andreas Gohr <andi@splitbrain.org>
1450 */
1451function tpl_mediaTree() {
1452    global $NS;
1453    ptln('<div id="media__tree">');
1454    media_nstree($NS);
1455    ptln('</div>');
1456}
1457
1458/**
1459 * Print a dropdown menu with all DokuWiki actions
1460 *
1461 * Note: this will not use any pretty URLs
1462 *
1463 * @author Andreas Gohr <andi@splitbrain.org>
1464 *
1465 * @param string $empty empty option label
1466 * @param string $button submit button label
1467 * @deprecated 2017-09-01 see devel:menus
1468 */
1469function tpl_actiondropdown($empty = '', $button = '&gt;') {
1470    dbg_deprecated('see devel:menus');
1471    $menu = new \dokuwiki\Menu\MobileMenu();
1472    echo $menu->getDropdown($empty, $button);
1473}
1474
1475/**
1476 * Print a informational line about the used license
1477 *
1478 * @author Andreas Gohr <andi@splitbrain.org>
1479 * @param  string $img     print image? (|button|badge)
1480 * @param  bool   $imgonly skip the textual description?
1481 * @param  bool   $return  when true don't print, but return HTML
1482 * @param  bool   $wrap    wrap in div with class="license"?
1483 * @return string
1484 */
1485function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true) {
1486    global $license;
1487    global $conf;
1488    global $lang;
1489    if(!$conf['license']) return '';
1490    if(!is_array($license[$conf['license']])) return '';
1491    $lic    = $license[$conf['license']];
1492    $target = ($conf['target']['extern']) ? ' target="'.$conf['target']['extern'].'"' : '';
1493
1494    $out = '';
1495    if($wrap) $out .= '<div class="license">';
1496    if($img) {
1497        $src = license_img($img);
1498        if($src) {
1499            $out .= '<a href="'.$lic['url'].'" rel="license"'.$target;
1500            $out .= '><img src="'.DOKU_BASE.$src.'" alt="'.$lic['name'].'" /></a>';
1501            if(!$imgonly) $out .= ' ';
1502        }
1503    }
1504    if(!$imgonly) {
1505        $out .= $lang['license'].' ';
1506        $out .= '<bdi><a href="'.$lic['url'].'" rel="license" class="urlextern"'.$target;
1507        $out .= '>'.$lic['name'].'</a></bdi>';
1508    }
1509    if($wrap) $out .= '</div>';
1510
1511    if($return) return $out;
1512    echo $out;
1513    return '';
1514}
1515
1516/**
1517 * Includes the rendered HTML of a given page
1518 *
1519 * This function is useful to populate sidebars or similar features in a
1520 * template
1521 *
1522 * @param string $pageid The page name you want to include
1523 * @param bool $print Should the content be printed or returned only
1524 * @param bool $propagate Search higher namespaces, too?
1525 * @param bool $useacl Include the page only if the ACLs check out?
1526 * @return bool|null|string
1527 */
1528function tpl_include_page($pageid, $print = true, $propagate = false, $useacl = true) {
1529    if($propagate) {
1530        $pageid = page_findnearest($pageid, $useacl);
1531    } elseif($useacl && auth_quickaclcheck($pageid) == AUTH_NONE) {
1532        return false;
1533    }
1534    if(!$pageid) return false;
1535
1536    global $TOC;
1537    $oldtoc = $TOC;
1538    $html   = p_wiki_xhtml($pageid, '', false);
1539    $TOC    = $oldtoc;
1540
1541    if($print) echo $html;
1542    return $html;
1543}
1544
1545/**
1546 * Display the subscribe form
1547 *
1548 * @author Adrian Lang <lang@cosmocode.de>
1549 */
1550function tpl_subscribe() {
1551    global $INFO;
1552    global $ID;
1553    global $lang;
1554    global $conf;
1555    $stime_days = $conf['subscribe_time'] / 60 / 60 / 24;
1556
1557    echo p_locale_xhtml('subscr_form');
1558    echo '<h2>'.$lang['subscr_m_current_header'].'</h2>';
1559    echo '<div class="level2">';
1560    if($INFO['subscribed'] === false) {
1561        echo '<p>'.$lang['subscr_m_not_subscribed'].'</p>';
1562    } else {
1563        echo '<ul>';
1564        foreach($INFO['subscribed'] as $sub) {
1565            echo '<li><div class="li">';
1566            if($sub['target'] !== $ID) {
1567                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1568            } else {
1569                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1570            }
1571            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1572            if(!$sstl) $sstl = hsc($sub['style']);
1573            echo ' ('.$sstl.') ';
1574
1575            echo '<a href="'.wl(
1576                $ID,
1577                array(
1578                     'do'        => 'subscribe',
1579                     'sub_target'=> $sub['target'],
1580                     'sub_style' => $sub['style'],
1581                     'sub_action'=> 'unsubscribe',
1582                     'sectok'    => getSecurityToken()
1583                )
1584            ).
1585                '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'].
1586                '</a></div></li>';
1587        }
1588        echo '</ul>';
1589    }
1590    echo '</div>';
1591
1592    // Add new subscription form
1593    echo '<h2>'.$lang['subscr_m_new_header'].'</h2>';
1594    echo '<div class="level2">';
1595    $ns      = getNS($ID).':';
1596    $targets = array(
1597        $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1598        $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1599    );
1600    $styles  = array(
1601        'every'  => $lang['subscr_style_every'],
1602        'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1603        'list'   => sprintf($lang['subscr_style_list'], $stime_days),
1604    );
1605
1606    $form = new Doku_Form(array('id' => 'subscribe__form'));
1607    $form->startFieldset($lang['subscr_m_subscribe']);
1608    $form->addRadioSet('sub_target', $targets);
1609    $form->startFieldset($lang['subscr_m_receive']);
1610    $form->addRadioSet('sub_style', $styles);
1611    $form->addHidden('sub_action', 'subscribe');
1612    $form->addHidden('do', 'subscribe');
1613    $form->addHidden('id', $ID);
1614    $form->endFieldset();
1615    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1616    html_form('SUBSCRIBE', $form);
1617    echo '</div>';
1618}
1619
1620/**
1621 * Tries to send already created content right to the browser
1622 *
1623 * Wraps around ob_flush() and flush()
1624 *
1625 * @author Andreas Gohr <andi@splitbrain.org>
1626 */
1627function tpl_flush() {
1628    ob_flush();
1629    flush();
1630}
1631
1632/**
1633 * Tries to find a ressource file in the given locations.
1634 *
1635 * If a given location starts with a colon it is assumed to be a media
1636 * file, otherwise it is assumed to be relative to the current template
1637 *
1638 * @param  string[] $search       locations to look at
1639 * @param  bool     $abs           if to use absolute URL
1640 * @param  array   &$imginfo   filled with getimagesize()
1641 * @return string
1642 *
1643 * @author Andreas  Gohr <andi@splitbrain.org>
1644 */
1645function tpl_getMediaFile($search, $abs = false, &$imginfo = null) {
1646    $img     = '';
1647    $file    = '';
1648    $ismedia = false;
1649    // loop through candidates until a match was found:
1650    foreach($search as $img) {
1651        if(substr($img, 0, 1) == ':') {
1652            $file    = mediaFN($img);
1653            $ismedia = true;
1654        } else {
1655            $file    = tpl_incdir().$img;
1656            $ismedia = false;
1657        }
1658
1659        if(file_exists($file)) break;
1660    }
1661
1662    // fetch image data if requested
1663    if(!is_null($imginfo)) {
1664        $imginfo = getimagesize($file);
1665    }
1666
1667    // build URL
1668    if($ismedia) {
1669        $url = ml($img, '', true, '', $abs);
1670    } else {
1671        $url = tpl_basedir().$img;
1672        if($abs) $url = DOKU_URL.substr($url, strlen(DOKU_REL));
1673    }
1674
1675    return $url;
1676}
1677
1678/**
1679 * PHP include a file
1680 *
1681 * either from the conf directory if it exists, otherwise use
1682 * file in the template's root directory.
1683 *
1684 * The function honours config cascade settings and looks for the given
1685 * file next to the ´main´ config files, in the order protected, local,
1686 * default.
1687 *
1688 * Note: no escaping or sanity checking is done here. Never pass user input
1689 * to this function!
1690 *
1691 * @author Anika Henke <anika@selfthinker.org>
1692 * @author Andreas Gohr <andi@splitbrain.org>
1693 *
1694 * @param string $file
1695 */
1696function tpl_includeFile($file) {
1697    global $config_cascade;
1698    foreach(array('protected', 'local', 'default') as $config_group) {
1699        if(empty($config_cascade['main'][$config_group])) continue;
1700        foreach($config_cascade['main'][$config_group] as $conf_file) {
1701            $dir = dirname($conf_file);
1702            if(file_exists("$dir/$file")) {
1703                include("$dir/$file");
1704                return;
1705            }
1706        }
1707    }
1708
1709    // still here? try the template dir
1710    $file = tpl_incdir().$file;
1711    if(file_exists($file)) {
1712        include($file);
1713    }
1714}
1715
1716/**
1717 * Returns <link> tag for various icon types (favicon|mobile|generic)
1718 *
1719 * @author Anika Henke <anika@selfthinker.org>
1720 *
1721 * @param  array $types - list of icon types to display (favicon|mobile|generic)
1722 * @return string
1723 */
1724function tpl_favicon($types = array('favicon')) {
1725
1726    $return = '';
1727
1728    foreach($types as $type) {
1729        switch($type) {
1730            case 'favicon':
1731                $look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
1732                $return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1733                break;
1734            case 'mobile':
1735                $look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
1736                $return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1737                break;
1738            case 'generic':
1739                // ideal world solution, which doesn't work in any browser yet
1740                $look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
1741                $return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
1742                break;
1743        }
1744    }
1745
1746    return $return;
1747}
1748
1749/**
1750 * Prints full-screen media manager
1751 *
1752 * @author Kate Arzamastseva <pshns@ukr.net>
1753 */
1754function tpl_media() {
1755    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1756    $fullscreen = true;
1757    require_once DOKU_INC.'lib/exe/mediamanager.php';
1758
1759    $rev   = '';
1760    $image = cleanID($INPUT->str('image'));
1761    if(isset($IMG)) $image = $IMG;
1762    if(isset($JUMPTO)) $image = $JUMPTO;
1763    if(isset($REV) && !$JUMPTO) $rev = $REV;
1764
1765    echo '<div id="mediamanager__page">'.NL;
1766    echo '<h1>'.$lang['btn_media'].'</h1>'.NL;
1767    html_msgarea();
1768
1769    echo '<div class="panel namespaces">'.NL;
1770    echo '<h2>'.$lang['namespaces'].'</h2>'.NL;
1771    echo '<div class="panelHeader">';
1772    echo $lang['media_namespaces'];
1773    echo '</div>'.NL;
1774
1775    echo '<div class="panelContent" id="media__tree">'.NL;
1776    media_nstree($NS);
1777    echo '</div>'.NL;
1778    echo '</div>'.NL;
1779
1780    echo '<div class="panel filelist">'.NL;
1781    tpl_mediaFileList();
1782    echo '</div>'.NL;
1783
1784    echo '<div class="panel file">'.NL;
1785    echo '<h2 class="a11y">'.$lang['media_file'].'</h2>'.NL;
1786    tpl_mediaFileDetails($image, $rev);
1787    echo '</div>'.NL;
1788
1789    echo '</div>'.NL;
1790}
1791
1792/**
1793 * Return useful layout classes
1794 *
1795 * @author Anika Henke <anika@selfthinker.org>
1796 *
1797 * @return string
1798 */
1799function tpl_classes() {
1800    global $ACT, $conf, $ID, $INFO;
1801    /** @var Input $INPUT */
1802    global $INPUT;
1803
1804    $classes = array(
1805        'dokuwiki',
1806        'mode_'.$ACT,
1807        'tpl_'.$conf['template'],
1808        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1809        $INFO['exists'] ? '' : 'notFound',
1810        ($ID == $conf['start']) ? 'home' : '',
1811    );
1812    return join(' ', $classes);
1813}
1814
1815/**
1816 * Create event for tools menues
1817 *
1818 * @author Anika Henke <anika@selfthinker.org>
1819 * @param string $toolsname name of menu
1820 * @param array $items
1821 * @param string $view e.g. 'main', 'detail', ...
1822 * @deprecated 2017-09-01 see devel:menus
1823 */
1824function tpl_toolsevent($toolsname, $items, $view = 'main') {
1825    dbg_deprecated('see devel:menus');
1826    $data = array(
1827        'view' => $view,
1828        'items' => $items
1829    );
1830
1831    $hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
1832    $evt = new Doku_Event($hook, $data);
1833    if($evt->advise_before()) {
1834        foreach($evt->data['items'] as $k => $html) echo $html;
1835    }
1836    $evt->advise_after();
1837}
1838
1839//Setup VIM: ex: et ts=4 :
1840
1841