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