xref: /dokuwiki/inc/template.php (revision 14f6676a2200c77f0183cf9433e43bfcc16cb772)
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
9  if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_CONF.'dokuwiki.php');
11
12/**
13 * Returns the path to the given template, uses
14 * default one if the custom version doesn't exist.
15 *
16 * @author Andreas Gohr <andi@splitbrain.org>
17 */
18function template($tpl){
19  global $conf;
20
21  if(@is_readable(DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl))
22    return DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl;
23
24  return DOKU_INC.'lib/tpl/default/'.$tpl;
25}
26
27/**
28 * Print the content
29 *
30 * This function is used for printing all the usual content
31 * (defined by the global $ACT var) by calling the appropriate
32 * outputfunction(s) from html.php
33 *
34 * Everything that doesn't use the main template file isn't
35 * handled by this function. ACL stuff is not done here either.
36 *
37 * @author Andreas Gohr <andi@splitbrain.org>
38 */
39function tpl_content($prependTOC=true) {
40    global $ACT;
41    global $INFO;
42    $INFO['prependTOC'] = $prependTOC;
43
44    ob_start();
45    trigger_event('TPL_ACT_RENDER',$ACT,'tpl_content_core');
46    $html_output = ob_get_clean();
47    trigger_event('TPL_CONTENT_DISPLAY',$html_output,'ptln');
48
49    return !empty($html_output);
50}
51
52function tpl_content_core(){
53  global $ACT;
54  global $TEXT;
55  global $PRE;
56  global $SUF;
57  global $SUM;
58  global $IDX;
59
60  switch($ACT){
61    case 'show':
62      html_show();
63      break;
64    case 'preview':
65      html_edit($TEXT);
66      html_show($TEXT);
67      break;
68    case 'recover':
69      html_edit($TEXT);
70      break;
71    case 'edit':
72      html_edit();
73      break;
74    case 'draft':
75      html_draft();
76      break;
77    case 'wordblock':
78      html_edit($TEXT,'wordblock');
79      break;
80    case 'search':
81      html_search();
82      break;
83    case 'revisions':
84      $first = is_numeric($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
85      html_revisions($first);
86      break;
87    case 'diff':
88      html_diff();
89      break;
90    case 'recent':
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 'locked':
105      html_locked();
106      break;
107    case 'login':
108      html_login();
109      break;
110    case 'register':
111      html_register();
112      break;
113    case 'resendpwd':
114      html_resendpwd();
115      break;
116    case 'denied':
117      print p_locale_xhtml('denied');
118      break;
119    case 'profile' :
120      html_updateprofile();
121      break;
122    case 'admin':
123      tpl_admin();
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    $toc = array();
151
152    if(is_array($TOC)){
153        // if a TOC was prepared in global scope, always use it
154        $toc = $TOC;
155    }elseif(($ACT == 'show' || substr($ACT,0,6) == 'export') && !$REV && $INFO['exists']){
156        // get TOC from metadata, render if neccessary
157        $meta = p_get_metadata($ID, false, true);
158        if(isset($meta['internal']['toc'])){
159            $tocok = $meta['internal']['toc'];
160        }else{
161            $tocok = true;
162        }
163        $toc   = $meta['description']['tableofcontents'];
164        if(!$tocok || !is_array($toc) || count($toc) < 3){
165            $toc = array();
166        }
167    }elseif($ACT == 'admin'){
168        // try to load admin plugin TOC FIXME: duplicates code from tpl_admin
169        $plugin = null;
170        if (!empty($_REQUEST['page'])) {
171            $pluginlist = plugin_list('admin');
172            if (in_array($_REQUEST['page'], $pluginlist)) {
173                // attempt to load the plugin
174                $plugin =& plugin_load('admin',$_REQUEST['page']);
175            }
176        }
177        if ( ($plugin !== null) &&
178             (!$plugin->forAdminOnly() || $INFO['isadmin']) ){
179            $toc = $plugin->getTOC();
180            $TOC = $toc; // avoid later rebuild
181        }
182    }
183
184    $html = html_TOC($toc);
185    if($return) return $html;
186    echo $html;
187}
188
189/**
190 * Handle the admin page contents
191 *
192 * @author Andreas Gohr <andi@splitbrain.org>
193 */
194function tpl_admin(){
195    global $INFO;
196    global $TOC;
197
198    $plugin = null;
199    if (!empty($_REQUEST['page'])) {
200        $pluginlist = plugin_list('admin');
201
202        if (in_array($_REQUEST['page'], $pluginlist)) {
203
204          // attempt to load the plugin
205          $plugin =& plugin_load('admin',$_REQUEST['page']);
206        }
207    }
208
209    if ($plugin !== null){
210        if($plugin->forAdminOnly() && !$INFO['isadmin']){
211            msg('For admins only',-1);
212            html_admin();
213        }else{
214            if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
215            if($INFO['prependTOC']) tpl_toc();
216            $plugin->html();
217        }
218    }else{
219        html_admin();
220    }
221    return true;
222}
223
224/**
225 * Print the correct HTML meta headers
226 *
227 * This has to go into the head section of your template.
228 *
229 * @triggers TPL_METAHEADER_OUTPUT
230 * @param  boolean $alt Should feeds and alternative format links be added?
231 * @author Andreas Gohr <andi@splitbrain.org>
232 */
233function tpl_metaheaders($alt=true){
234  global $ID;
235  global $REV;
236  global $INFO;
237  global $ACT;
238  global $QUERY;
239  global $lang;
240  global $conf;
241  $it=2;
242
243  // prepare the head array
244  $head = array();
245
246
247  // the usual stuff
248  $head['meta'][] = array( 'name'=>'generator', 'content'=>'DokuWiki '.getVersion() );
249  $head['link'][] = array( 'rel'=>'search', 'type'=>'application/opensearchdescription+xml',
250                           'href'=>DOKU_BASE.'lib/exe/opensearch.php', 'title'=>$conf['title'] );
251  $head['link'][] = array( 'rel'=>'start', 'href'=>DOKU_BASE );
252  $head['link'][] = array( 'rel'=>'contents', 'href'=> wl($ID,'do=index',false,'&'),
253                           'title'=>$lang['btn_index'] );
254
255  if($alt){
256    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
257                             'title'=>'Recent Changes', 'href'=>DOKU_BASE.'feed.php');
258    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
259                             'title'=>'Current Namespace',
260                             'href'=>DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']);
261    if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']){
262        $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/wiki',
263                                 'title'=>$lang['btn_edit'],
264                                 'href'=> wl($ID,'do=edit',false,'&'));
265    }
266
267    if($ACT == 'search'){
268      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
269                               'title'=>'Search Result',
270                               'href'=>DOKU_BASE.'feed.php?mode=search&q='.$QUERY);
271    }
272
273    if(actionOK('export_xhtml')){
274      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/html', 'title'=>'Plain HTML',
275                               'href'=>exportlink($ID, 'xhtml', '', false, '&'));
276    }
277
278    if(actionOK('export_raw')){
279      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/plain', 'title'=>'Wiki Markup',
280                               'href'=>exportlink($ID, 'raw', '', false, '&'));
281    }
282  }
283
284  // setup robot tags apropriate for different modes
285  if( ($ACT=='show' || $ACT=='export_xhtml') && !$REV){
286    if($INFO['exists']){
287      //delay indexing:
288      if((time() - $INFO['lastmod']) >= $conf['indexdelay']){
289        $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
290      }else{
291        $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
292      }
293    }else{
294      $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,follow');
295    }
296  }elseif(defined('DOKU_MEDIADETAIL')){
297    $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
298  }else{
299    $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
300  }
301
302  // set metadata
303  if($ACT == 'show' || $ACT=='export_xhtml'){
304    // date of modification
305    if($REV){
306      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$REV));
307    }else{
308      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$INFO['lastmod']));
309    }
310
311    // keywords (explicit or implicit)
312    if(!empty($INFO['meta']['subject'])){
313      $head['meta'][] = array( 'name'=>'keywords', 'content'=>join(',',$INFO['meta']['subject']));
314    }else{
315      $head['meta'][] = array( 'name'=>'keywords', 'content'=>str_replace(':',',',$ID));
316    }
317  }
318
319  // load stylesheets
320  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'all', 'type'=>'text/css',
321                          'href'=>DOKU_BASE.'lib/exe/css.php?s=all&t='.$conf['template']);
322  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'screen', 'type'=>'text/css',
323                          'href'=>DOKU_BASE.'lib/exe/css.php?t='.$conf['template']);
324  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'print', 'type'=>'text/css',
325                          'href'=>DOKU_BASE.'lib/exe/css.php?s=print&t='.$conf['template']);
326
327  // load javascript
328  $js_edit  = ($ACT=='edit' || $ACT=='preview' || $ACT=='recover' || $ACT=='wordblock' ) ? 1 : 0;
329  $js_write = ($INFO['writable']) ? 1 : 0;
330  if(defined('DOKU_MEDIAMANAGER')){
331    $js_edit  = 1;
332    $js_write = 0;
333  }
334  if(($js_edit && $js_write) || defined('DOKU_MEDIAMANAGER')){
335    $script = "NS='".$INFO['namespace']."';";
336    if($conf['useacl'] && $_SERVER['REMOTE_USER']){
337      require_once(DOKU_INC.'inc/toolbar.php');
338      $script .= "SIG='".toolbar_signature()."';";
339    }
340    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8',
341                               '_data'=> $script);
342  }
343  $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
344                             'src'=>DOKU_BASE.'lib/exe/js.php?edit='.$js_edit.'&write='.$js_write);
345
346  // trigger event here
347  trigger_event('TPL_METAHEADER_OUTPUT',$head,'_tpl_metaheaders_action',true);
348  return true;
349}
350
351/**
352 * prints the array build by tpl_metaheaders
353 *
354 * $data is an array of different header tags. Each tag can have multiple
355 * instances. Attributes are given as key value pairs. Values will be HTML
356 * encoded automatically so they should be provided as is in the $data array.
357 *
358 * For tags having a body attribute specify the the body data in the special
359 * attribute '_data'. This field will NOT BE ESCAPED automatically.
360 *
361 * @author Andreas Gohr <andi@splitbrain.org>
362 */
363function _tpl_metaheaders_action($data){
364  foreach($data as $tag => $inst){
365    foreach($inst as $attr){
366      echo '<',$tag,' ',buildAttributes($attr);
367      if(isset($attr['_data'])){
368          if($tag == 'script' && $attr['_data'])
369            $attr['_data'] = "<!--//--><![CDATA[//><!--\n".
370                             $attr['_data'].
371                             "\n//--><!]]>";
372
373          echo '>',$attr['_data'],'</',$tag,'>';
374      }else{
375        echo '/>';
376      }
377      echo "\n";
378    }
379  }
380}
381
382/**
383 * Print a link
384 *
385 * Just builds a link.
386 *
387 * @author Andreas Gohr <andi@splitbrain.org>
388 */
389function tpl_link($url,$name,$more=''){
390  print '<a href="'.$url.'" ';
391  if ($more) print ' '.$more;
392  print ">$name</a>";
393  return true;
394}
395
396/**
397 * Prints a link to a WikiPage
398 *
399 * Wrapper around html_wikilink
400 *
401 * @author Andreas Gohr <andi@splitbrain.org>
402 */
403function tpl_pagelink($id,$name=NULL){
404  print html_wikilink($id,$name);
405  return true;
406}
407
408/**
409 * get the parent page
410 *
411 * Tries to find out which page is parent.
412 * returns false if none is available
413 *
414 * @author Andreas Gohr <andi@splitbrain.org>
415 */
416function tpl_getparent($id){
417  global $conf;
418  $parent = getNS($id).':';
419  resolve_pageid('',$parent,$exists);
420  if($parent == $id) {
421    $pos = strrpos (getNS($id),':');
422    $parent = substr($parent,0,$pos).':';
423    resolve_pageid('',$parent,$exists);
424    if($parent == $id) return false;
425  }
426  return $parent;
427}
428
429/**
430 * Print one of the buttons
431 *
432 * Available Buttons are
433 *
434 *  edit        - edit/create/show/draft button
435 *  history     - old revisions
436 *  recent      - recent changes
437 *  login       - login/logout button - if ACL enabled
438 *  profile     - user profile button (if logged in)
439 *  index       - The index
440 *  admin       - admin page - if enough rights
441 *  top         - a back to top button
442 *  back        - a back to parent button - if available
443 *  backlink    - links to the list of backlinks
444 *  subscription- subscribe/unsubscribe button
445 *
446 * @author Andreas Gohr <andi@splitbrain.org>
447 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
448 */
449function tpl_button($type){
450  global $ACT;
451  global $ID;
452  global $REV;
453  global $NS;
454  global $INFO;
455  global $conf;
456  global $auth;
457
458  // check disabled actions and fix the badly named ones
459  $ctype = $type;
460  if($type == 'history') $ctype='revisions';
461  if(!actionOK($ctype)) return false;
462
463  switch($type){
464    case 'edit':
465      #most complicated type - we need to decide on current action
466      if($ACT == 'show' || $ACT == 'search'){
467        if($INFO['writable']){
468          if(!empty($INFO['draft'])){
469            echo html_btn('draft',$ID,'e',array('do' => 'draft'),'post');
470          }else{
471            if($INFO['exists']){
472              echo html_btn('edit',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
473            }else{
474              echo html_btn('create',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
475            }
476          }
477        }else{
478          if(!actionOK('source')) return false; //pseudo action
479          echo html_btn('source',$ID,'v',array('do' => 'edit','rev' => $REV),'post');
480        }
481      }else{
482          echo html_btn('show',$ID,'v',array('do' => 'show'));
483      }
484      return true;
485    case 'history':
486      print html_btn('revs',$ID,'o',array('do' => 'revisions'));
487      return true;
488    case 'recent':
489      print html_btn('recent','','r',array('do' => 'recent'));
490      return true;
491    case 'index':
492      print html_btn('index',$ID,'x',array('do' => 'index'));
493      return true;
494    case 'back':
495      if ($parent = tpl_getparent($ID)) {
496        print html_btn('back',$parent,'b',array('do' => 'show'));
497        return true;
498      }
499      return false;
500    case 'top':
501      print html_topbtn();
502      return true;
503    case 'login':
504      if($conf['useacl'] && $auth){
505        if($_SERVER['REMOTE_USER']){
506          print html_btn('logout',$ID,'',array('do' => 'logout', 'sectok' => getSecurityToken()));
507        }else{
508          print html_btn('login',$ID,'',array('do' => 'login', 'sectok' => getSecurityToken()));
509        }
510        return true;
511      }
512      return false;
513    case 'admin':
514      if($INFO['ismanager']){
515        print html_btn('admin',$ID,'',array('do' => 'admin'));
516        return true;
517      }
518      return false;
519    case 'subscribe':
520    case 'subscription':
521      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
522        if($_SERVER['REMOTE_USER']){
523          if($INFO['subscribed']){
524            print html_btn('unsubscribe',$ID,'',array('do' => 'unsubscribe',));
525          } else {
526            print html_btn('subscribe',$ID,'',array('do' => 'subscribe',));
527          }
528          if($type == 'subscribe') return true;
529        }
530      }
531      if($type == 'subscribe') return false;
532      // fall through for backward compatibility
533    case 'subscribens':
534      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
535        if($_SERVER['REMOTE_USER']){
536          if($INFO['subscribedns']){
537            print html_btn('unsubscribens',$ID,'',array('do' => 'unsubscribens',));
538          } else {
539            print html_btn('subscribens',$ID,'',array('do' => 'subscribens',));
540          }
541          return true;
542        }
543      }
544      return false;
545    case 'backlink':
546      print html_btn('backlink',$ID,'',array('do' => 'backlink'));
547      return true;
548    case 'profile':
549      if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $auth &&
550         $auth->canDo('Profile') && ($ACT!='profile')){
551        print html_btn('profile',$ID,'',array('do' => 'profile'));
552        return true;
553      }
554      return false;
555    default:
556      print '[unknown button type]';
557      return true;
558  }
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=''){
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  switch($type){
597    case 'edit':
598      #most complicated type - we need to decide on current action
599      if($ACT == 'show' || $ACT == 'search'){
600        if($INFO['writable']){
601          if(!empty($INFO['draft'])) {
602            tpl_link(wl($ID,'do=draft'),
603                       $pre.(($inner)?$inner:$lang['btn_draft']).$suf,
604                       'class="action edit" accesskey="e" rel="nofollow"');
605          } else {
606            if($INFO['exists']){
607              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
608                       $pre.(($inner)?$inner:$lang['btn_edit']).$suf,
609                       'class="action edit" accesskey="e" rel="nofollow"');
610            }else{
611              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
612                       $pre.(($inner)?$inner:$lang['btn_create']).$suf,
613                       'class="action create" accesskey="e" rel="nofollow"');
614            }
615          }
616        }else{
617          if(!actionOK('source')) return false; //pseudo action
618          tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
619                   $pre.(($inner)?$inner:$lang['btn_source']).$suf,
620                   'class="action source" accesskey="v" rel="nofollow"');
621        }
622      }else{
623          tpl_link(wl($ID,'do=show'),
624                   $pre.(($inner)?$inner:$lang['btn_show']).$suf,
625                   'class="action show" accesskey="v" rel="nofollow"');
626      }
627      return true;
628    case 'history':
629      tpl_link(wl($ID,'do=revisions'),
630               $pre.(($inner)?$inner:$lang['btn_revs']).$suf,
631               'class="action revisions" accesskey="o" rel="nofollow"');
632      return true;
633    case 'recent':
634      tpl_link(wl('','do=recent'),
635               $pre.(($inner)?$inner:$lang['btn_recent']).$suf,
636              'class="action recent" accesskey="r" rel="nofollow"');
637      return true;
638    case 'index':
639      tpl_link(wl($ID,'do=index'),
640               $pre.(($inner)?$inner:$lang['btn_index']).$suf,
641              'class="action index" accesskey="x" rel="nofollow"');
642      return true;
643    case 'top':
644      print '<a href="#dokuwiki__top" class="action top" accesskey="x">'.
645            $pre.(($inner)?$inner:$lang['btn_top']).$suf.'</a>';
646      return true;
647    case 'back':
648      if ($parent = tpl_getparent($ID)) {
649        tpl_link(wl($parent,'do=show'),
650        $pre.(($inner)?$inner:$lang['btn_back']).$suf,
651        'class="action back" accesskey="b" rel="nofollow"');
652        return true;
653      }
654      return false;
655    case 'login':
656      if($conf['useacl'] && $auth){
657        if($_SERVER['REMOTE_USER']){
658          tpl_link(wl($ID,'do=logout&amp;sectok='.getSecurityToken()),
659                   $pre.(($inner)?$inner:$lang['btn_logout']).$suf,
660                   'class="action logout" rel="nofollow"');
661        }else{
662          tpl_link(wl($ID,'do=login&amp;sectok='.getSecurityToken()),
663                   $pre.(($inner)?$inner:$lang['btn_login']).$suf,
664                   'class="action login" rel="nofollow"');
665        }
666        return true;
667      }
668      return false;
669    case 'admin':
670      if($INFO['ismanager']){
671        tpl_link(wl($ID,'do=admin'),
672                 $pre.(($inner)?$inner:$lang['btn_admin']).$suf,
673                 'class="action admin" rel="nofollow"');
674        return true;
675      }
676      return false;
677   case 'subscribe':
678   case 'subscription':
679      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
680        if($_SERVER['REMOTE_USER']){
681          if($INFO['subscribed']) {
682            tpl_link(wl($ID,'do=unsubscribe'),
683                     $pre.(($inner)?$inner:$lang['btn_unsubscribe']).$suf,
684                     'class="action unsubscribe" rel="nofollow"');
685          } else {
686            tpl_link(wl($ID,'do=subscribe'),
687                     $pre.(($inner)?$inner:$lang['btn_subscribe']).$suf,
688                     'class="action subscribe" rel="nofollow"');
689          }
690          return true;
691        }
692      }
693      return false;
694    case 'subscribens':
695      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
696        if($_SERVER['REMOTE_USER']){
697          if($INFO['subscribedns']) {
698            tpl_link(wl($ID,'do=unsubscribens'),
699                     $pre.(($inner)?$inner:$lang['btn_unsubscribens']).$suf,
700                     'class="action unsubscribens" rel="nofollow"');
701          } else {
702            tpl_link(wl($ID,'do=subscribens'),
703                     $pre.(($inner)?$inner:$lang['btn_subscribens']).$suf,
704                     'class="action subscribens" rel="nofollow"');
705          }
706          return true;
707        }
708      }
709      return false;
710    case 'backlink':
711      tpl_link(wl($ID,'do=backlink'),
712               $pre.(($inner)?$inner:$lang['btn_backlink']).$suf,
713               'class="action backlink" rel="nofollow"');
714      return true;
715    case 'profile':
716      if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
717         $auth->canDo('Profile') && ($ACT!='profile')){
718        tpl_link(wl($ID,'do=profile'),
719                 $pre.(($inner)?$inner:$lang['btn_profile']).$suf,
720                 'class="action profile" rel="nofollow"');
721        return true;
722      }
723      return false;
724    default:
725      print '[unknown link type]';
726      return true;
727  }
728}
729
730/**
731 * Print the search form
732 *
733 * If the first parameter is given a div with the ID 'qsearch_out' will
734 * be added which instructs the ajax pagequicksearch to kick in and place
735 * its output into this div. The second parameter controls the propritary
736 * attribute autocomplete. If set to false this attribute will be set with an
737 * value of "off" to instruct the browser to disable it's own built in
738 * autocompletion feature (MSIE and Firefox)
739 *
740 * @author Andreas Gohr <andi@splitbrain.org>
741 */
742function tpl_searchform($ajax=true,$autocomplete=true){
743  global $lang;
744  global $ACT;
745
746  // don't print the search form if search action has been disabled
747  if (!actionOk('search')) return false;
748
749  print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
750  print '<input type="hidden" name="do" value="search" />';
751  print '<input type="text" ';
752  if($ACT == 'search') print 'value="'.htmlspecialchars($_REQUEST['id']).'" ';
753  if(!$autocomplete) print 'autocomplete="off" ';
754  print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[ALT+F]" />';
755  print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
756  if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
757  print '</div></form>';
758  return true;
759}
760
761/**
762 * Print the breadcrumbs trace
763 *
764 * @author Andreas Gohr <andi@splitbrain.org>
765 */
766function tpl_breadcrumbs($sep='&raquo;'){
767  global $lang;
768  global $conf;
769
770  //check if enabled
771  if(!$conf['breadcrumbs']) return false;
772
773  $crumbs = breadcrumbs(); //setup crumb trace
774
775  //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
776  if($lang['direction'] == 'rtl') {
777    $crumbs = array_reverse($crumbs,true);
778    $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
779  } else {
780    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
781  }
782
783  //render crumbs, highlight the last one
784  print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
785  $last = count($crumbs);
786  $i = 0;
787  foreach ($crumbs as $id => $name){
788    $i++;
789    echo $crumbs_sep;
790    if ($i == $last) print '<span class="curid">';
791    tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
792    if ($i == $last) print '</span>';
793  }
794  return true;
795}
796
797/**
798 * Hierarchical breadcrumbs
799 *
800 * This code was suggested as replacement for the usual breadcrumbs.
801 * It only makes sense with a deep site structure.
802 *
803 * @author Andreas Gohr <andi@splitbrain.org>
804 * @author Nigel McNie <oracle.shinoda@gmail.com>
805 * @author Sean Coates <sean@caedmon.net>
806 * @link   http://wiki.splitbrain.org/wiki:tipsandtricks:hierarchicalbreadcrumbs
807 * @todo   May behave strangely in RTL languages
808 */
809function tpl_youarehere($sep=' &raquo; '){
810  global $conf;
811  global $ID;
812  global $lang;
813
814  // check if enabled
815  if(!$conf['youarehere']) return false;
816
817  $parts = explode(':', $ID);
818  $count = count($parts);
819
820  echo '<span class="bchead">'.$lang['youarehere'].': </span>';
821
822  // always print the startpage
823  $title = p_get_first_heading($conf['start']);
824  if(!$title) $title = $conf['start'];
825  tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
826
827  // print intermediate namespace links
828  $part = '';
829  for($i=0; $i<$count - 1; $i++){
830    $part .= $parts[$i].':';
831    $page = $part;
832    resolve_pageid('',$page,$exists);
833    if ($page == $conf['start']) continue; // Skip startpage
834
835    // output
836    echo $sep;
837    if($exists){
838      $title = p_get_first_heading($page);
839      if(!$title) $title = $parts[$i];
840      tpl_link(wl($page),hsc($title),'title="'.$page.'"');
841    }else{
842      tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
843    }
844  }
845
846  // print current page, skipping start page, skipping for namespace index
847  if(isset($page) && $page==$part.$parts[$i]) return;
848  $page = $part.$parts[$i];
849  if($page == $conf['start']) return;
850  echo $sep;
851  if(page_exists($page)){
852    $title = p_get_first_heading($page);
853    if(!$title) $title = $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($_SERVER['REMOTE_USER']){
873    print $lang['loggedinas'].': '.$INFO['userinfo']['name'];
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 */
884function tpl_pageinfo($ret=false){
885  global $conf;
886  global $lang;
887  global $INFO;
888  global $REV;
889  global $ID;
890
891  // return if we are not allowed to view the page
892  if (!auth_quickaclcheck($ID)) { return false; }
893
894  // prepare date and path
895  $fn = $INFO['filepath'];
896  if(!$conf['fullpath']){
897    if($REV){
898      $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
899    }else{
900      $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
901    }
902  }
903  $fn = utf8_decodeFN($fn);
904  $date = strftime($conf['dformat'],$INFO['lastmod']);
905
906  // print it
907  if($INFO['exists']){
908    $out = '';
909    $out .= $fn;
910    $out .= ' &middot; ';
911    $out .= $lang['lastmod'];
912    $out .= ': ';
913    $out .= $date;
914    if($INFO['editor']){
915      $out .= ' '.$lang['by'].' ';
916      $out .= $INFO['editor'];
917    }else{
918      $out .= ' ('.$lang['external_edit'].')';
919    }
920    if($INFO['locked']){
921      $out .= ' &middot; ';
922      $out .= $lang['lockedby'];
923      $out .= ': ';
924      $out .= $INFO['locked'];
925    }
926    if($ret){
927        return $out;
928    }else{
929        echo $out;
930        return true;
931    }
932  }
933  return false;
934}
935
936/**
937 * Prints or returns the name of the given page (current one if none given).
938 *
939 * If useheading is enabled this will use the first headline else
940 * the given ID is used.
941 *
942 * @author Andreas Gohr <andi@splitbrain.org>
943 */
944function tpl_pagetitle($id=null, $ret=false){
945  global $conf;
946  if(is_null($id)){
947    global $ID;
948    $id = $ID;
949  }
950
951  $name = $id;
952  if ($conf['useheading']) {
953    $title = p_get_first_heading($id);
954    if ($title) $name = $title;
955  }
956
957  if ($ret) {
958      return hsc($name);
959  } else {
960      print hsc($name);
961      return true;
962  }
963}
964
965/**
966 * Returns the requested EXIF/IPTC tag from the current image
967 *
968 * If $tags is an array all given tags are tried until a
969 * value is found. If no value is found $alt is returned.
970 *
971 * Which texts are known is defined in the functions _exifTagNames
972 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
973 * to the names of the latter one)
974 *
975 * Only allowed in: detail.php
976 *
977 * @author Andreas Gohr <andi@splitbrain.org>
978 */
979function tpl_img_getTag($tags,$alt='',$src=null){
980  // Init Exif Reader
981  global $SRC;
982
983  if(is_null($src)) $src = $SRC;
984
985  static $meta = null;
986  if(is_null($meta)) $meta = new JpegMeta($src);
987  if($meta === false) return $alt;
988  $info = $meta->getField($tags);
989  if($info == false) return $alt;
990  return $info;
991}
992
993/**
994 * Prints the image with a link to the full sized version
995 *
996 * Only allowed in: detail.php
997 */
998function tpl_img($maxwidth=0,$maxheight=0){
999  global $IMG;
1000  $w = tpl_img_getTag('File.Width');
1001  $h = tpl_img_getTag('File.Height');
1002
1003  //resize to given max values
1004  $ratio = 1;
1005  if($w >= $h){
1006    if($maxwidth && $w >= $maxwidth){
1007      $ratio = $maxwidth/$w;
1008    }elseif($maxheight && $h > $maxheight){
1009      $ratio = $maxheight/$h;
1010    }
1011  }else{
1012    if($maxheight && $h >= $maxheight){
1013      $ratio = $maxheight/$h;
1014    }elseif($maxwidth && $w > $maxwidth){
1015      $ratio = $maxwidth/$w;
1016    }
1017  }
1018  if($ratio){
1019    $w = floor($ratio*$w);
1020    $h = floor($ratio*$h);
1021  }
1022
1023  //prepare URLs
1024  $url=ml($IMG,array('cache'=>$_REQUEST['cache']));
1025  $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h));
1026
1027  //prepare attributes
1028  $alt=tpl_img_getTag('Simple.Title');
1029  $p = array();
1030  if($w) $p['width']  = $w;
1031  if($h) $p['height'] = $h;
1032         $p['class']  = 'img_detail';
1033  if($alt){
1034    $p['alt']   = $alt;
1035    $p['title'] = $alt;
1036  }else{
1037    $p['alt'] = '';
1038  }
1039  $p = buildAttributes($p);
1040
1041  print '<a href="'.$url.'">';
1042  print '<img src="'.$src.'" '.$p.'/>';
1043  print '</a>';
1044  return true;
1045}
1046
1047/**
1048 * This function inserts a 1x1 pixel gif which in reality
1049 * is the inexer function.
1050 *
1051 * Should be called somewhere at the very end of the main.php
1052 * template
1053 */
1054function tpl_indexerWebBug(){
1055  global $ID;
1056  global $INFO;
1057  if(!$INFO['exists']) return false;
1058
1059  if(isHiddenPage($ID)) return false; //no need to index hidden pages
1060
1061  $p = array();
1062  $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1063                 '&'.time();
1064  $p['width']  = 1;
1065  $p['height'] = 1;
1066  $p['alt']    = '';
1067  $att = buildAttributes($p);
1068  print "<img $att />";
1069  return true;
1070}
1071
1072// configuration methods
1073/**
1074 * tpl_getConf($id)
1075 *
1076 * use this function to access template configuration variables
1077 */
1078function tpl_getConf($id){
1079  global $conf;
1080  global $tpl_configloaded;
1081
1082  $tpl = $conf['template'];
1083
1084  if (!$tpl_configloaded){
1085    $tconf = tpl_loadConfig();
1086    if ($tconf !== false){
1087      foreach ($tconf as $key => $value){
1088        if (isset($conf['tpl'][$tpl][$key])) continue;
1089        $conf['tpl'][$tpl][$key] = $value;
1090      }
1091      $tpl_configloaded = true;
1092    }
1093  }
1094
1095  return $conf['tpl'][$tpl][$id];
1096}
1097
1098/**
1099 * tpl_loadConfig()
1100 * reads all template configuration variables
1101 * this function is automatically called by tpl_getConf()
1102 */
1103function tpl_loadConfig(){
1104
1105  $file = DOKU_TPLINC.'/conf/default.php';
1106  $conf = array();
1107
1108  if (!@file_exists($file)) return false;
1109
1110  // load default config file
1111  include($file);
1112
1113  return $conf;
1114}
1115
1116/**
1117 * prints the "main content" in the mediamanger popup
1118 *
1119 * Depending on the user's actions this may be a list of
1120 * files in a namespace, the meta editing dialog or
1121 * a message of referencing pages
1122 *
1123 * Only allowed in mediamanager.php
1124 *
1125 * @author Andreas Gohr <andi@splitbrain.org>
1126 */
1127function tpl_mediaContent(){
1128  global $IMG;
1129  global $AUTH;
1130  global $INUSE;
1131  global $NS;
1132  global $JUMPTO;
1133
1134  ptln('<div id="media__content">');
1135  if($_REQUEST['edit']){
1136    media_metaform($IMG,$AUTH);
1137  }elseif(is_array($INUSE)){
1138    media_filesinuse($INUSE,$IMG);
1139  }else{
1140    media_filelist($NS,$AUTH,$JUMPTO);
1141  }
1142  ptln('</div>');
1143}
1144
1145/**
1146 * prints the namespace tree in the mediamanger popup
1147 *
1148 * Only allowed in mediamanager.php
1149 *
1150 * @author Andreas Gohr <andi@splitbrain.org>
1151 */
1152function tpl_mediaTree(){
1153  global $NS;
1154
1155  ptln('<div id="media__tree">');
1156  media_nstree($NS);
1157  ptln('</div>');
1158}
1159
1160//Setup VIM: ex: et ts=4 enc=utf-8 :
1161