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