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