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