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