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