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