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