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