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