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