xref: /dokuwiki/inc/template.php (revision bf413a4e50ea09a0345533c5fb1d07e963bd6368)
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');
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', '_data'=> $script);
348
349    // load external javascript
350    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
351            'src'=>DOKU_BASE.'lib/exe/js.php'.'?tseed='.$tseed);
352
353    // trigger event here
354    trigger_event('TPL_METAHEADER_OUTPUT',$head,'_tpl_metaheaders_action',true);
355    return true;
356}
357
358/**
359 * prints the array build by tpl_metaheaders
360 *
361 * $data is an array of different header tags. Each tag can have multiple
362 * instances. Attributes are given as key value pairs. Values will be HTML
363 * encoded automatically so they should be provided as is in the $data array.
364 *
365 * For tags having a body attribute specify the the body data in the special
366 * attribute '_data'. This field will NOT BE ESCAPED automatically.
367 *
368 * @author Andreas Gohr <andi@splitbrain.org>
369 */
370function _tpl_metaheaders_action($data){
371    foreach($data as $tag => $inst){
372        foreach($inst as $attr){
373            echo '<',$tag,' ',buildAttributes($attr);
374            if(isset($attr['_data']) || $tag == 'script'){
375                if($tag == 'script' && $attr['_data'])
376                    $attr['_data'] = "<!--//--><![CDATA[//><!--\n".
377                        $attr['_data'].
378                        "\n//--><!]]>";
379
380                echo '>',$attr['_data'],'</',$tag,'>';
381            }else{
382                echo '/>';
383            }
384            echo "\n";
385        }
386    }
387}
388
389/**
390 * Print a link
391 *
392 * Just builds a link.
393 *
394 * @author Andreas Gohr <andi@splitbrain.org>
395 */
396function tpl_link($url,$name,$more='',$return=false){
397    $out = '<a href="'.$url.'" ';
398    if ($more) $out .= ' '.$more;
399    $out .= ">$name</a>";
400    if ($return) return $out;
401    print $out;
402    return true;
403}
404
405/**
406 * Prints a link to a WikiPage
407 *
408 * Wrapper around html_wikilink
409 *
410 * @author Andreas Gohr <andi@splitbrain.org>
411 */
412function tpl_pagelink($id,$name=null){
413    print html_wikilink($id,$name);
414    return true;
415}
416
417/**
418 * get the parent page
419 *
420 * Tries to find out which page is parent.
421 * returns false if none is available
422 *
423 * @author Andreas Gohr <andi@splitbrain.org>
424 */
425function tpl_getparent($id){
426    global $conf;
427    $parent = getNS($id).':';
428    resolve_pageid('',$parent,$exists);
429    if($parent == $id) {
430        $pos = strrpos (getNS($id),':');
431        $parent = substr($parent,0,$pos).':';
432        resolve_pageid('',$parent,$exists);
433        if($parent == $id) return false;
434    }
435    return $parent;
436}
437
438/**
439 * Print one of the buttons
440 *
441 * @author Adrian Lang <mail@adrianlang.de>
442 * @see    tpl_get_action
443 */
444function tpl_button($type,$return=false){
445    $data = tpl_get_action($type);
446    if ($data === false) {
447        return false;
448    } elseif (!is_array($data)) {
449        $out = sprintf($data, 'button');
450    } else {
451        extract($data);
452        if ($id === '#dokuwiki__top') {
453            $out = html_topbtn();
454        } else {
455            $out = html_btn($type, $id, $accesskey, $params, $method);
456        }
457    }
458    if ($return) return $out;
459    echo $out;
460    return true;
461}
462
463/**
464 * Like the action buttons but links
465 *
466 * @author Adrian Lang <mail@adrianlang.de>
467 * @see    tpl_get_action
468 */
469function tpl_actionlink($type,$pre='',$suf='',$inner='',$return=false){
470    global $lang;
471    $data = tpl_get_action($type);
472    if ($data === false) {
473        return false;
474    } elseif (!is_array($data)) {
475        $out = sprintf($data, 'link');
476    } else {
477        extract($data);
478        if (strpos($id, '#') === 0) {
479            $linktarget = $id;
480        } else {
481            $linktarget = wl($id, $params);
482        }
483        $caption = $lang['btn_' . $type];
484        $out = tpl_link($linktarget, $pre.(($inner)?$inner:$caption).$suf,
485                        'class="action ' . $type . '" ' .
486                        'accesskey="' . $accesskey . '" rel="nofollow" ' .
487                        'title="' . hsc($caption) . '"', 1);
488    }
489    if ($return) return $out;
490    echo $out;
491    return true;
492}
493
494/**
495 * Check the actions and get data for buttons and links
496 *
497 * Available actions are
498 *
499 *  edit        - edit/create/show/draft
500 *  history     - old revisions
501 *  recent      - recent changes
502 *  login       - login/logout - if ACL enabled
503 *  profile     - user profile (if logged in)
504 *  index       - The index
505 *  admin       - admin page - if enough rights
506 *  top         - back to top
507 *  back        - back to parent - if available
508 *  backlink    - links to the list of backlinks
509 *  subscribe/subscription- subscribe/unsubscribe
510 *
511 * @author Andreas Gohr <andi@splitbrain.org>
512 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
513 * @author Adrian Lang <mail@adrianlang.de>
514 */
515function tpl_get_action($type) {
516    global $ID;
517    global $INFO;
518    global $REV;
519    global $ACT;
520    global $conf;
521    global $auth;
522
523    // check disabled actions and fix the badly named ones
524    if($type == 'history') $type='revisions';
525    if(!actionOK($type)) return false;
526
527    $accesskey = null;
528    $id        = $ID;
529    $method    = 'get';
530    $params    = array('do' => $type);
531    switch($type){
532        case 'edit':
533            // most complicated type - we need to decide on current action
534            if($ACT == 'show' || $ACT == 'search'){
535                $method = 'post';
536                if($INFO['writable']){
537                    $accesskey = 'e';
538                    if(!empty($INFO['draft'])) {
539                        $type = 'draft';
540                        $params['do'] = 'draft';
541                    } else {
542                        $params['rev'] = $REV;
543                        if(!$INFO['exists']){
544                            $type   = 'create';
545                        }
546                    }
547                }else{
548                    if(!actionOK('source')) return false; //pseudo action
549                    $params['rev'] = $REV;
550                    $type = 'source';
551                    $accesskey = 'v';
552                }
553            }else{
554                $params = '';
555                $type = 'show';
556                $accesskey = 'v';
557            }
558            break;
559        case 'revisions':
560            $type = 'revs';
561            $accesskey = 'o';
562            break;
563        case 'recent':
564            $accesskey = 'r';
565            break;
566        case 'index':
567            $accesskey = 'x';
568            break;
569        case 'top':
570            $accesskey = 'x';
571            $params = '';
572            $id = '#dokuwiki__top';
573            break;
574        case 'back':
575            $parent = tpl_getparent($ID);
576            if (!$parent) {
577                return false;
578            }
579            $id = $parent;
580            $params = '';
581            $accesskey = 'b';
582            break;
583        case 'login':
584            if(!$conf['useacl'] || !$auth){
585                return false;
586            }
587            $params['sectok'] = getSecurityToken();
588            if(isset($_SERVER['REMOTE_USER'])){
589                if (!$auth->canDo('logout')) {
590                    return false;
591                }
592                $params['do'] = 'logout';
593                $type = 'logout';
594            }
595            break;
596        case 'register':
597            if($_SERVER['REMOTE_USER']){
598                return false;
599            }
600            break;
601        case 'resendpwd':
602            if($_SERVER['REMOTE_USER']){
603                return false;
604            }
605            break;
606        case 'admin':
607            if(!$INFO['ismanager']){
608                return false;
609            }
610            break;
611        case 'revert':
612            if(!$INFO['ismanager'] || !$REV || !$INFO['writable']) {
613                return false;
614            }
615            $params['rev'] = $REV;
616            $params['sectok'] = getSecurityToken();
617            break;
618        case 'subscription':
619            $type = 'subscribe';
620            $params['do'] = 'subscribe';
621        case 'subscribe':
622            if(!$conf['useacl'] || !$auth  || !$conf['subscribers'] || !$_SERVER['REMOTE_USER']){
623                return false;
624            }
625            break;
626        case 'backlink':
627            break;
628        case 'profile':
629            if(!$conf['useacl'] || !$auth || !isset($_SERVER['REMOTE_USER']) ||
630                    !$auth->canDo('Profile')){
631                return false;
632            }
633            break;
634        case 'subscribens':
635            // Superseeded by subscribe/subscription
636            return '';
637            break;
638        default:
639            return '[unknown %s type]';
640            break;
641    }
642    return compact('accesskey', 'type', 'id', 'method', 'params');
643}
644
645/**
646 * Wrapper around tpl_button() and tpl_actionlink()
647 *
648 * @author Anika Henke <anika@selfthinker.org>
649 */
650function tpl_action($type,$link=0,$wrapper=false,$return=false,$pre='',$suf='',$inner='') {
651    $out = '';
652    if ($link) $out .= tpl_actionlink($type,$pre,$suf,$inner,1);
653    else $out .= tpl_button($type,1);
654    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
655
656    if ($return) return $out;
657    print $out;
658    return $out ? true : false;
659}
660
661/**
662 * Print the search form
663 *
664 * If the first parameter is given a div with the ID 'qsearch_out' will
665 * be added which instructs the ajax pagequicksearch to kick in and place
666 * its output into this div. The second parameter controls the propritary
667 * attribute autocomplete. If set to false this attribute will be set with an
668 * value of "off" to instruct the browser to disable it's own built in
669 * autocompletion feature (MSIE and Firefox)
670 *
671 * @author Andreas Gohr <andi@splitbrain.org>
672 */
673function tpl_searchform($ajax=true,$autocomplete=true){
674    global $lang;
675    global $ACT;
676    global $QUERY;
677
678    // don't print the search form if search action has been disabled
679    if (!actionOk('search')) return false;
680
681    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search" method="get"><div class="no">';
682    print '<input type="hidden" name="do" value="search" />';
683    print '<input type="text" ';
684    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
685    if(!$autocomplete) print 'autocomplete="off" ';
686    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
687    print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
688    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
689    print '</div></form>';
690    return true;
691}
692
693/**
694 * Print the breadcrumbs trace
695 *
696 * @author Andreas Gohr <andi@splitbrain.org>
697 */
698function tpl_breadcrumbs($sep='&bull;'){
699    global $lang;
700    global $conf;
701
702    //check if enabled
703    if(!$conf['breadcrumbs']) return false;
704
705    $crumbs = breadcrumbs(); //setup crumb trace
706
707    //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
708    if($lang['direction'] == 'rtl') {
709        $crumbs = array_reverse($crumbs,true);
710        $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
711    } else {
712        $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
713    }
714
715    //render crumbs, highlight the last one
716    print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
717    $last = count($crumbs);
718    $i = 0;
719    foreach ($crumbs as $id => $name){
720        $i++;
721        echo $crumbs_sep;
722        if ($i == $last) print '<span class="curid">';
723        tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
724        if ($i == $last) print '</span>';
725    }
726    return true;
727}
728
729/**
730 * Hierarchical breadcrumbs
731 *
732 * This code was suggested as replacement for the usual breadcrumbs.
733 * It only makes sense with a deep site structure.
734 *
735 * @author Andreas Gohr <andi@splitbrain.org>
736 * @author Nigel McNie <oracle.shinoda@gmail.com>
737 * @author Sean Coates <sean@caedmon.net>
738 * @author <fredrik@averpil.com>
739 * @todo   May behave strangely in RTL languages
740 */
741function tpl_youarehere($sep=' &raquo; '){
742    global $conf;
743    global $ID;
744    global $lang;
745
746    // check if enabled
747    if(!$conf['youarehere']) return false;
748
749    $parts = explode(':', $ID);
750    $count = count($parts);
751
752    echo '<span class="bchead">'.$lang['youarehere'].': </span>';
753
754    // always print the startpage
755    tpl_pagelink(':'.$conf['start']);
756
757    // print intermediate namespace links
758    $part = '';
759    for($i=0; $i<$count - 1; $i++){
760        $part .= $parts[$i].':';
761        $page = $part;
762        if ($page == $conf['start']) continue; // Skip startpage
763
764        // output
765        echo $sep;
766        tpl_pagelink($page);
767    }
768
769    // print current page, skipping start page, skipping for namespace index
770    resolve_pageid('',$page,$exists);
771    if(isset($page) && $page==$part.$parts[$i]) return;
772    $page = $part.$parts[$i];
773    if($page == $conf['start']) return;
774    echo $sep;
775    tpl_pagelink($page);
776    return true;
777}
778
779/**
780 * Print info if the user is logged in
781 * and show full name in that case
782 *
783 * Could be enhanced with a profile link in future?
784 *
785 * @author Andreas Gohr <andi@splitbrain.org>
786 */
787function tpl_userinfo(){
788    global $lang;
789    global $INFO;
790    if(isset($_SERVER['REMOTE_USER'])){
791        print $lang['loggedinas'].': '.hsc($INFO['userinfo']['name']).' ('.hsc($_SERVER['REMOTE_USER']).')';
792        return true;
793    }
794    return false;
795}
796
797/**
798 * Print some info about the current page
799 *
800 * @author Andreas Gohr <andi@splitbrain.org>
801 */
802function tpl_pageinfo($ret=false){
803    global $conf;
804    global $lang;
805    global $INFO;
806    global $ID;
807
808    // return if we are not allowed to view the page
809    if (!auth_quickaclcheck($ID)) { return false; }
810
811    // prepare date and path
812    $fn = $INFO['filepath'];
813    if(!$conf['fullpath']){
814        if($INFO['rev']){
815            $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
816        }else{
817            $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
818        }
819    }
820    $fn = utf8_decodeFN($fn);
821    $date = dformat($INFO['lastmod']);
822
823    // print it
824    if($INFO['exists']){
825        $out = '';
826        $out .= $fn;
827        $out .= ' &middot; ';
828        $out .= $lang['lastmod'];
829        $out .= ': ';
830        $out .= $date;
831        if($INFO['editor']){
832            $out .= ' '.$lang['by'].' ';
833            $out .= editorinfo($INFO['editor']);
834        }else{
835            $out .= ' ('.$lang['external_edit'].')';
836        }
837        if($INFO['locked']){
838            $out .= ' &middot; ';
839            $out .= $lang['lockedby'];
840            $out .= ': ';
841            $out .= editorinfo($INFO['locked']);
842        }
843        if($ret){
844            return $out;
845        }else{
846            echo $out;
847            return true;
848        }
849    }
850    return false;
851}
852
853/**
854 * Prints or returns the name of the given page (current one if none given).
855 *
856 * If useheading is enabled this will use the first headline else
857 * the given ID is used.
858 *
859 * @author Andreas Gohr <andi@splitbrain.org>
860 */
861function tpl_pagetitle($id=null, $ret=false){
862    global $conf;
863    if(is_null($id)){
864        global $ID;
865        $id = $ID;
866    }
867
868    $name = $id;
869    if (useHeading('navigation')) {
870        $title = p_get_first_heading($id);
871        if ($title) $name = $title;
872    }
873
874    if ($ret) {
875        return hsc($name);
876    } else {
877        print hsc($name);
878        return true;
879    }
880}
881
882/**
883 * Returns the requested EXIF/IPTC tag from the current image
884 *
885 * If $tags is an array all given tags are tried until a
886 * value is found. If no value is found $alt is returned.
887 *
888 * Which texts are known is defined in the functions _exifTagNames
889 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
890 * to the names of the latter one)
891 *
892 * Only allowed in: detail.php
893 *
894 * @author Andreas Gohr <andi@splitbrain.org>
895 */
896function tpl_img_getTag($tags,$alt='',$src=null){
897    // Init Exif Reader
898    global $SRC;
899
900    if(is_null($src)) $src = $SRC;
901
902    static $meta = null;
903    if(is_null($meta)) $meta = new JpegMeta($src);
904    if($meta === false) return $alt;
905    $info = $meta->getField($tags);
906    if($info == false) return $alt;
907    return $info;
908}
909
910/**
911 * Prints the image with a link to the full sized version
912 *
913 * Only allowed in: detail.php
914 *
915 * @param $maxwidth  int - maximal width of the image
916 * @param $maxheight int - maximal height of the image
917 * @param $link bool     - link to the orginal size?
918 * @param $params array  - additional image attributes
919 */
920function tpl_img($maxwidth=0,$maxheight=0,$link=true,$params=null){
921    global $IMG;
922    $w = tpl_img_getTag('File.Width');
923    $h = tpl_img_getTag('File.Height');
924
925    //resize to given max values
926    $ratio = 1;
927    if($w >= $h){
928        if($maxwidth && $w >= $maxwidth){
929            $ratio = $maxwidth/$w;
930        }elseif($maxheight && $h > $maxheight){
931            $ratio = $maxheight/$h;
932        }
933    }else{
934        if($maxheight && $h >= $maxheight){
935            $ratio = $maxheight/$h;
936        }elseif($maxwidth && $w > $maxwidth){
937            $ratio = $maxwidth/$w;
938        }
939    }
940    if($ratio){
941        $w = floor($ratio*$w);
942        $h = floor($ratio*$h);
943    }
944
945    //prepare URLs
946    $url=ml($IMG,array('cache'=>$_REQUEST['cache']),true,'&');
947    $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h),true,'&');
948
949    //prepare attributes
950    $alt=tpl_img_getTag('Simple.Title');
951    if(is_null($params)){
952        $p = array();
953    }else{
954        $p = $params;
955    }
956    if($w) $p['width']  = $w;
957    if($h) $p['height'] = $h;
958    $p['class']  = 'img_detail';
959    if($alt){
960        $p['alt']   = $alt;
961        $p['title'] = $alt;
962    }else{
963        $p['alt'] = '';
964    }
965    $p['src'] = $src;
966
967    $data = array('url'=>($link?$url:null), 'params'=>$p);
968    return trigger_event('TPL_IMG_DISPLAY',$data,'_tpl_img_action',true);
969}
970
971/**
972 * Default action for TPL_IMG_DISPLAY
973 */
974function _tpl_img_action($data, $param=NULL) {
975    $p = buildAttributes($data['params']);
976
977    if($data['url']) print '<a href="'.hsc($data['url']).'">';
978    print '<img '.$p.'/>';
979    if($data['url']) print '</a>';
980    return true;
981}
982
983/**
984 * This function inserts a 1x1 pixel gif which in reality
985 * is the indexer function.
986 *
987 * Should be called somewhere at the very end of the main.php
988 * template
989 */
990function tpl_indexerWebBug(){
991    global $ID;
992    global $INFO;
993    if(!$INFO['exists']) return false;
994
995    $p = array();
996    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
997        '&'.time();
998    $p['width']  = 1;
999    $p['height'] = 1;
1000    $p['alt']    = '';
1001    $att = buildAttributes($p);
1002    print "<img $att />";
1003    return true;
1004}
1005
1006// configuration methods
1007/**
1008 * tpl_getConf($id)
1009 *
1010 * use this function to access template configuration variables
1011 */
1012function tpl_getConf($id){
1013    global $conf;
1014    static $tpl_configloaded = false;
1015
1016    $tpl = $conf['template'];
1017
1018    if (!$tpl_configloaded){
1019        $tconf = tpl_loadConfig();
1020        if ($tconf !== false){
1021            foreach ($tconf as $key => $value){
1022                if (isset($conf['tpl'][$tpl][$key])) continue;
1023                $conf['tpl'][$tpl][$key] = $value;
1024            }
1025            $tpl_configloaded = true;
1026        }
1027    }
1028
1029    return $conf['tpl'][$tpl][$id];
1030}
1031
1032/**
1033 * tpl_loadConfig()
1034 * reads all template configuration variables
1035 * this function is automatically called by tpl_getConf()
1036 */
1037function tpl_loadConfig(){
1038
1039    $file = DOKU_TPLINC.'/conf/default.php';
1040    $conf = array();
1041
1042    if (!@file_exists($file)) return false;
1043
1044    // load default config file
1045    include($file);
1046
1047    return $conf;
1048}
1049
1050// language methods
1051/**
1052 * tpl_getLang($id)
1053 *
1054 * use this function to access template language variables
1055 */
1056function tpl_getLang($id){
1057    static $lang = array();
1058
1059    if (count($lang) === 0){
1060        $path = DOKU_TPLINC.'lang/';
1061
1062        $lang = array();
1063
1064        global $conf;            // definitely don't invoke "global $lang"
1065        // don't include once
1066        @include($path.'en/lang.php');
1067        if ($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
1068    }
1069
1070    return $lang[$id];
1071}
1072
1073/**
1074 * prints the "main content" in the mediamanger popup
1075 *
1076 * Depending on the user's actions this may be a list of
1077 * files in a namespace, the meta editing dialog or
1078 * a message of referencing pages
1079 *
1080 * Only allowed in mediamanager.php
1081 *
1082 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1083 * @param bool $fromajax - set true when calling this function via ajax
1084 * @author Andreas Gohr <andi@splitbrain.org>
1085 */
1086function tpl_mediaContent($fromajax=false){
1087    global $IMG;
1088    global $AUTH;
1089    global $INUSE;
1090    global $NS;
1091    global $JUMPTO;
1092
1093    if(is_array($_REQUEST['do'])){
1094        $do = array_shift(array_keys($_REQUEST['do']));
1095    }else{
1096        $do = $_REQUEST['do'];
1097    }
1098    if(in_array($do,array('save','cancel'))) $do = '';
1099
1100    if(!$do){
1101        if($_REQUEST['edit']){
1102            $do = 'metaform';
1103        }elseif(is_array($INUSE)){
1104            $do = 'filesinuse';
1105        }else{
1106            $do = 'filelist';
1107        }
1108    }
1109
1110    // output the content pane, wrapped in an event.
1111    if(!$fromajax) ptln('<div id="media__content">');
1112    $data = array( 'do' => $do);
1113    $evt = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1114    if ($evt->advise_before()) {
1115        $do = $data['do'];
1116        if($do == 'metaform'){
1117            media_metaform($IMG,$AUTH);
1118        }elseif($do == 'filesinuse'){
1119            media_filesinuse($INUSE,$IMG);
1120        }elseif($do == 'filelist'){
1121            media_filelist($NS,$AUTH,$JUMPTO);
1122        }elseif($do == 'searchlist'){
1123            media_searchlist($_REQUEST['q'],$NS,$AUTH);
1124        }else{
1125            msg('Unknown action '.hsc($do),-1);
1126        }
1127    }
1128    $evt->advise_after();
1129    unset($evt);
1130    if(!$fromajax) ptln('</div>');
1131
1132}
1133
1134/**
1135 * prints the namespace tree in the mediamanger popup
1136 *
1137 * Only allowed in mediamanager.php
1138 *
1139 * @author Andreas Gohr <andi@splitbrain.org>
1140 */
1141function tpl_mediaTree(){
1142    global $NS;
1143
1144    ptln('<div id="media__tree">');
1145    media_nstree($NS);
1146    ptln('</div>');
1147}
1148
1149
1150/**
1151 * Print a dropdown menu with all DokuWiki actions
1152 *
1153 * Note: this will not use any pretty URLs
1154 *
1155 * @author Andreas Gohr <andi@splitbrain.org>
1156 */
1157function tpl_actiondropdown($empty='',$button='&gt;'){
1158    global $ID;
1159    global $INFO;
1160    global $REV;
1161    global $ACT;
1162    global $conf;
1163    global $lang;
1164    global $auth;
1165
1166    echo '<form action="' . DOKU_SCRIPT . '" method="post" accept-charset="utf-8">';
1167    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1168    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1169    echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1170
1171    echo '<select name="do" class="edit quickselect">';
1172    echo '<option value="">'.$empty.'</option>';
1173
1174    echo '<optgroup label=" &mdash; ">';
1175        $act = tpl_get_action('edit');
1176        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1177
1178        $act = tpl_get_action('revisions');
1179        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1180
1181        $act = tpl_get_action('revert');
1182        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1183
1184        $act = tpl_get_action('backlink');
1185        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1186    echo '</optgroup>';
1187
1188    echo '<optgroup label=" &mdash; ">';
1189        $act = tpl_get_action('recent');
1190        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1191
1192        $act = tpl_get_action('index');
1193        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1194    echo '</optgroup>';
1195
1196    echo '<optgroup label=" &mdash; ">';
1197        $act = tpl_get_action('login');
1198        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1199
1200        $act = tpl_get_action('profile');
1201        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1202
1203        $act = tpl_get_action('subscribe');
1204        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1205
1206        $act = tpl_get_action('admin');
1207        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1208    echo '</optgroup>';
1209
1210    echo '</select>';
1211    echo '<input type="submit" value="'.$button.'" />';
1212    echo '</form>';
1213}
1214
1215/**
1216 * Print a informational line about the used license
1217 *
1218 * @author Andreas Gohr <andi@splitbrain.org>
1219 * @param  string $img    - print image? (|button|badge)
1220 * @param  bool   $return - when true don't print, but return HTML
1221 */
1222function tpl_license($img='badge',$imgonly=false,$return=false){
1223    global $license;
1224    global $conf;
1225    global $lang;
1226    if(!$conf['license']) return '';
1227    if(!is_array($license[$conf['license']])) return '';
1228    $lic = $license[$conf['license']];
1229
1230    $out  = '<div class="license">';
1231    if($img){
1232        $src = license_img($img);
1233        if($src){
1234            $out .= '<a href="'.$lic['url'].'" rel="license"';
1235            if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1236            $out .= '><img src="'.DOKU_BASE.$src.'" class="medialeft lic'.$img.'" alt="'.$lic['name'].'" /></a> ';
1237        }
1238    }
1239    if(!$imgonly) {
1240        $out .= $lang['license'];
1241        $out .= ' <a href="'.$lic['url'].'" rel="license" class="urlextern"';
1242        if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1243        $out .= '>'.$lic['name'].'</a>';
1244    }
1245    $out .= '</div>';
1246
1247    if($return) return $out;
1248    echo $out;
1249}
1250
1251
1252/**
1253 * Includes the rendered XHTML of a given page
1254 *
1255 * This function is useful to populate sidebars or similar features in a
1256 * template
1257 */
1258function tpl_include_page($pageid,$print=true){
1259    global $ID;
1260    $oldid = $ID;
1261    $html = p_wiki_xhtml($pageid,'',false);
1262    $ID = $oldid;
1263
1264    if(!$print) return $html;
1265    echo $html;
1266}
1267
1268/**
1269 * Display the subscribe form
1270 *
1271 * @author Adrian Lang <lang@cosmocode.de>
1272 */
1273function tpl_subscribe() {
1274    global $INFO;
1275    global $ID;
1276    global $lang;
1277    global $conf;
1278    $stime_days = $conf['subscribe_time']/60/60/24;
1279
1280    echo p_locale_xhtml('subscr_form');
1281    echo '<h2>' . $lang['subscr_m_current_header'] . '</h2>';
1282    echo '<div class="level2">';
1283    if ($INFO['subscribed'] === false) {
1284        echo '<p>' . $lang['subscr_m_not_subscribed'] . '</p>';
1285    } else {
1286        echo '<ul>';
1287        foreach($INFO['subscribed'] as $sub) {
1288            echo '<li><div class="li">';
1289            if ($sub['target'] !== $ID) {
1290                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1291            } else {
1292                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1293            }
1294            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1295            if(!$sstl) $sstl = hsc($sub['style']);
1296            echo ' ('.$sstl.') ';
1297
1298            echo '<a href="' . wl($ID,
1299                                  array('do'=>'subscribe',
1300                                        'sub_target'=>$sub['target'],
1301                                        'sub_style'=>$sub['style'],
1302                                        'sub_action'=>'unsubscribe',
1303                                        'sectok' => getSecurityToken())) .
1304                 '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'] .
1305                 '</a></div></li>';
1306        }
1307        echo '</ul>';
1308    }
1309    echo '</div>';
1310
1311    // Add new subscription form
1312    echo '<h2>' . $lang['subscr_m_new_header'] . '</h2>';
1313    echo '<div class="level2">';
1314    $ns = getNS($ID).':';
1315    $targets = array(
1316            $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1317            $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1318            );
1319    $styles = array(
1320            'every'  => $lang['subscr_style_every'],
1321            'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1322            'list' => sprintf($lang['subscr_style_list'], $stime_days),
1323            );
1324
1325    $form = new Doku_Form(array('id' => 'subscribe__form'));
1326    $form->startFieldset($lang['subscr_m_subscribe']);
1327    $form->addRadioSet('sub_target', $targets);
1328    $form->startFieldset($lang['subscr_m_receive']);
1329    $form->addRadioSet('sub_style', $styles);
1330    $form->addHidden('sub_action', 'subscribe');
1331    $form->addHidden('do', 'subscribe');
1332    $form->addHidden('id', $ID);
1333    $form->endFieldset();
1334    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1335    html_form('SUBSCRIBE', $form);
1336    echo '</div>';
1337}
1338
1339/**
1340 * Tries to send already created content right to the browser
1341 *
1342 * Wraps around ob_flush() and flush()
1343 *
1344 * @author Andreas Gohr <andi@splitbrain.org>
1345 */
1346function tpl_flush(){
1347    ob_flush();
1348    flush();
1349}
1350
1351
1352/**
1353 * Use favicon.ico from data/media root directory if it exists, otherwise use
1354 * the one in the template's image directory.
1355 *
1356 * @author Anika Henke <anika@selfthinker.org>
1357 */
1358function tpl_getFavicon() {
1359    if (file_exists(mediaFN('favicon.ico')))
1360        return ml('favicon.ico');
1361    return DOKU_TPL.'images/favicon.ico';
1362}
1363
1364
1365//Setup VIM: ex: et ts=4 :
1366
1367