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