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