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