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