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