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