xref: /dokuwiki/inc/template.php (revision eaf69d75d9a9a2fee8de9207a076f9126fe6c848)
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    trigger_event('TPL_TOC_RENDER', $toc, NULL, false);
185    $html = html_TOC($toc);
186    if($return) return $html;
187    echo $html;
188}
189
190/**
191 * Handle the admin page contents
192 *
193 * @author Andreas Gohr <andi@splitbrain.org>
194 */
195function tpl_admin(){
196    global $INFO;
197    global $TOC;
198
199    $plugin = null;
200    if (!empty($_REQUEST['page'])) {
201        $pluginlist = plugin_list('admin');
202
203        if (in_array($_REQUEST['page'], $pluginlist)) {
204
205          // attempt to load the plugin
206          $plugin =& plugin_load('admin',$_REQUEST['page']);
207        }
208    }
209
210    if ($plugin !== null){
211        if($plugin->forAdminOnly() && !$INFO['isadmin']){
212            msg('For admins only',-1);
213            html_admin();
214        }else{
215            if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
216            if($INFO['prependTOC']) tpl_toc();
217            $plugin->html();
218        }
219    }else{
220        html_admin();
221    }
222    return true;
223}
224
225/**
226 * Print the correct HTML meta headers
227 *
228 * This has to go into the head section of your template.
229 *
230 * @triggers TPL_METAHEADER_OUTPUT
231 * @param  boolean $alt Should feeds and alternative format links be added?
232 * @author Andreas Gohr <andi@splitbrain.org>
233 */
234function tpl_metaheaders($alt=true){
235  global $ID;
236  global $REV;
237  global $INFO;
238  global $ACT;
239  global $QUERY;
240  global $lang;
241  global $conf;
242  $it=2;
243
244  // prepare the head array
245  $head = array();
246
247
248  // the usual stuff
249  $head['meta'][] = array( 'name'=>'generator', 'content'=>'DokuWiki '.getVersion() );
250  $head['link'][] = array( 'rel'=>'search', 'type'=>'application/opensearchdescription+xml',
251                           'href'=>DOKU_BASE.'lib/exe/opensearch.php', 'title'=>$conf['title'] );
252  $head['link'][] = array( 'rel'=>'start', 'href'=>DOKU_BASE );
253  $head['link'][] = array( 'rel'=>'contents', 'href'=> wl($ID,'do=index',false,'&'),
254                           'title'=>$lang['btn_index'] );
255
256  if($alt){
257    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
258                             'title'=>'Recent Changes', 'href'=>DOKU_BASE.'feed.php');
259    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
260                             'title'=>'Current Namespace',
261                             'href'=>DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']);
262    if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']){
263        $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/wiki',
264                                 'title'=>$lang['btn_edit'],
265                                 'href'=> wl($ID,'do=edit',false,'&'));
266    }
267
268    if($ACT == 'search'){
269      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
270                               'title'=>'Search Result',
271                               'href'=>DOKU_BASE.'feed.php?mode=search&q='.$QUERY);
272    }
273
274    if(actionOK('export_xhtml')){
275      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/html', 'title'=>'Plain HTML',
276                               'href'=>exportlink($ID, 'xhtml', '', false, '&'));
277    }
278
279    if(actionOK('export_raw')){
280      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/plain', 'title'=>'Wiki Markup',
281                               'href'=>exportlink($ID, 'raw', '', false, '&'));
282    }
283  }
284
285  // setup robot tags apropriate for different modes
286  if( ($ACT=='show' || $ACT=='export_xhtml') && !$REV){
287    if($INFO['exists']){
288      //delay indexing:
289      if((time() - $INFO['lastmod']) >= $conf['indexdelay']){
290        $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
291      }else{
292        $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
293      }
294    }else{
295      $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,follow');
296    }
297  }elseif(defined('DOKU_MEDIADETAIL')){
298    $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
299  }else{
300    $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
301  }
302
303  // set metadata
304  if($ACT == 'show' || $ACT=='export_xhtml'){
305    // date of modification
306    if($REV){
307      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$REV));
308    }else{
309      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$INFO['lastmod']));
310    }
311
312    // keywords (explicit or implicit)
313    if(!empty($INFO['meta']['subject'])){
314      $head['meta'][] = array( 'name'=>'keywords', 'content'=>join(',',$INFO['meta']['subject']));
315    }else{
316      $head['meta'][] = array( 'name'=>'keywords', 'content'=>str_replace(':',',',$ID));
317    }
318  }
319
320  // load stylesheets
321  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'all', 'type'=>'text/css',
322                          'href'=>DOKU_BASE.'lib/exe/css.php?s=all&t='.$conf['template']);
323  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'screen', 'type'=>'text/css',
324                          'href'=>DOKU_BASE.'lib/exe/css.php?t='.$conf['template']);
325  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'print', 'type'=>'text/css',
326                          'href'=>DOKU_BASE.'lib/exe/css.php?s=print&t='.$conf['template']);
327
328  // load javascript
329  $js_edit  = ($ACT=='edit' || $ACT=='preview' || $ACT=='recover' || $ACT=='wordblock' ) ? 1 : 0;
330  $js_write = ($INFO['writable']) ? 1 : 0;
331  if(defined('DOKU_MEDIAMANAGER')){
332    $js_edit  = 1;
333    $js_write = 0;
334  }
335  if(($js_edit && $js_write) || defined('DOKU_MEDIAMANAGER')){
336    $script = "NS='".$INFO['namespace']."';";
337    if($conf['useacl'] && $_SERVER['REMOTE_USER']){
338      require_once(DOKU_INC.'inc/toolbar.php');
339      $script .= "SIG='".toolbar_signature()."';";
340    }
341    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8',
342                               '_data'=> $script);
343  }
344  $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
345                             'src'=>DOKU_BASE.'lib/exe/js.php?edit='.$js_edit.'&write='.$js_write);
346
347  // trigger event here
348  trigger_event('TPL_METAHEADER_OUTPUT',$head,'_tpl_metaheaders_action',true);
349  return true;
350}
351
352/**
353 * prints the array build by tpl_metaheaders
354 *
355 * $data is an array of different header tags. Each tag can have multiple
356 * instances. Attributes are given as key value pairs. Values will be HTML
357 * encoded automatically so they should be provided as is in the $data array.
358 *
359 * For tags having a body attribute specify the the body data in the special
360 * attribute '_data'. This field will NOT BE ESCAPED automatically.
361 *
362 * @author Andreas Gohr <andi@splitbrain.org>
363 */
364function _tpl_metaheaders_action($data){
365  foreach($data as $tag => $inst){
366    foreach($inst as $attr){
367      echo '<',$tag,' ',buildAttributes($attr);
368      if(isset($attr['_data'])){
369          if($tag == 'script' && $attr['_data'])
370            $attr['_data'] = "<!--//--><![CDATA[//><!--\n".
371                             $attr['_data'].
372                             "\n//--><!]]>";
373
374          echo '>',$attr['_data'],'</',$tag,'>';
375      }else{
376        echo '/>';
377      }
378      echo "\n";
379    }
380  }
381}
382
383/**
384 * Print a link
385 *
386 * Just builds a link.
387 *
388 * @author Andreas Gohr <andi@splitbrain.org>
389 */
390function tpl_link($url,$name,$more=''){
391  print '<a href="'.$url.'" ';
392  if ($more) print ' '.$more;
393  print ">$name</a>";
394  return true;
395}
396
397/**
398 * Prints a link to a WikiPage
399 *
400 * Wrapper around html_wikilink
401 *
402 * @author Andreas Gohr <andi@splitbrain.org>
403 */
404function tpl_pagelink($id,$name=NULL){
405  print html_wikilink($id,$name);
406  return true;
407}
408
409/**
410 * get the parent page
411 *
412 * Tries to find out which page is parent.
413 * returns false if none is available
414 *
415 * @author Andreas Gohr <andi@splitbrain.org>
416 */
417function tpl_getparent($id){
418  global $conf;
419  $parent = getNS($id).':';
420  resolve_pageid('',$parent,$exists);
421  if($parent == $id) {
422    $pos = strrpos (getNS($id),':');
423    $parent = substr($parent,0,$pos).':';
424    resolve_pageid('',$parent,$exists);
425    if($parent == $id) return false;
426  }
427  return $parent;
428}
429
430/**
431 * Print one of the buttons
432 *
433 * Available Buttons are
434 *
435 *  edit        - edit/create/show/draft button
436 *  history     - old revisions
437 *  recent      - recent changes
438 *  login       - login/logout button - if ACL enabled
439 *  profile     - user profile button (if logged in)
440 *  index       - The index
441 *  admin       - admin page - if enough rights
442 *  top         - a back to top button
443 *  back        - a back to parent button - if available
444 *  backlink    - links to the list of backlinks
445 *  subscription- subscribe/unsubscribe button
446 *
447 * @author Andreas Gohr <andi@splitbrain.org>
448 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
449 */
450function tpl_button($type){
451  global $ACT;
452  global $ID;
453  global $REV;
454  global $NS;
455  global $INFO;
456  global $conf;
457  global $auth;
458
459  // check disabled actions and fix the badly named ones
460  $ctype = $type;
461  if($type == 'history') $ctype='revisions';
462  if(!actionOK($ctype)) return false;
463
464  switch($type){
465    case 'edit':
466      #most complicated type - we need to decide on current action
467      if($ACT == 'show' || $ACT == 'search'){
468        if($INFO['writable']){
469          if(!empty($INFO['draft'])){
470            echo html_btn('draft',$ID,'e',array('do' => 'draft'),'post');
471          }else{
472            if($INFO['exists']){
473              echo html_btn('edit',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
474            }else{
475              echo html_btn('create',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
476            }
477          }
478        }else{
479          if(!actionOK('source')) return false; //pseudo action
480          echo html_btn('source',$ID,'v',array('do' => 'edit','rev' => $REV),'post');
481        }
482      }else{
483          echo html_btn('show',$ID,'v',array('do' => 'show'));
484      }
485      return true;
486    case 'history':
487      print html_btn('revs',$ID,'o',array('do' => 'revisions'));
488      return true;
489    case 'recent':
490      print html_btn('recent','','r',array('do' => 'recent'));
491      return true;
492    case 'index':
493      print html_btn('index',$ID,'x',array('do' => 'index'));
494      return true;
495    case 'back':
496      if ($parent = tpl_getparent($ID)) {
497        print html_btn('back',$parent,'b',array('do' => 'show'));
498        return true;
499      }
500      return false;
501    case 'top':
502      print html_topbtn();
503      return true;
504    case 'login':
505      if($conf['useacl'] && $auth){
506        if($_SERVER['REMOTE_USER']){
507          print html_btn('logout',$ID,'',array('do' => 'logout', 'sectok' => getSecurityToken()));
508        }else{
509          print html_btn('login',$ID,'',array('do' => 'login', 'sectok' => getSecurityToken()));
510        }
511        return true;
512      }
513      return false;
514    case 'admin':
515      if($INFO['ismanager']){
516        print html_btn('admin',$ID,'',array('do' => 'admin'));
517        return true;
518      }
519      return false;
520    case 'subscribe':
521    case 'subscription':
522      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
523        if($_SERVER['REMOTE_USER']){
524          if($INFO['subscribed']){
525            print html_btn('unsubscribe',$ID,'',array('do' => 'unsubscribe',));
526          } else {
527            print html_btn('subscribe',$ID,'',array('do' => 'subscribe',));
528          }
529          if($type == 'subscribe') return true;
530        }
531      }
532      if($type == 'subscribe') return false;
533      // fall through for backward compatibility
534    case 'subscribens':
535      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
536        if($_SERVER['REMOTE_USER']){
537          if($INFO['subscribedns']){
538            print html_btn('unsubscribens',$ID,'',array('do' => 'unsubscribens',));
539          } else {
540            print html_btn('subscribens',$ID,'',array('do' => 'subscribens',));
541          }
542          return true;
543        }
544      }
545      return false;
546    case 'backlink':
547      print html_btn('backlink',$ID,'',array('do' => 'backlink'));
548      return true;
549    case 'profile':
550      if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $auth &&
551         $auth->canDo('Profile') && ($ACT!='profile')){
552        print html_btn('profile',$ID,'',array('do' => 'profile'));
553        return true;
554      }
555      return false;
556    default:
557      print '[unknown button type]';
558      return true;
559  }
560}
561
562/**
563 * Like the action buttons but links
564 *
565 * Available links are
566 *
567 *  edit    - edit/create/show link
568 *  history - old revisions
569 *  recent  - recent changes
570 *  login   - login/logout link - if ACL enabled
571 *  profile - user profile link (if logged in)
572 *  index   - The index
573 *  admin   - admin page - if enough rights
574 *  top     - a back to top link
575 *  back    - a back to parent link - if available
576 *  backlink - links to the list of backlinks
577 *  subscribe/subscription - subscribe/unsubscribe link
578 *
579 * @author Andreas Gohr <andi@splitbrain.org>
580 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
581 * @see    tpl_button
582 */
583function tpl_actionlink($type,$pre='',$suf='',$inner=''){
584  global $ID;
585  global $INFO;
586  global $REV;
587  global $ACT;
588  global $conf;
589  global $lang;
590  global $auth;
591
592  // check disabled actions and fix the badly named ones
593  $ctype = $type;
594  if($type == 'history') $ctype='revisions';
595  if(!actionOK($ctype)) return false;
596
597  switch($type){
598    case 'edit':
599      #most complicated type - we need to decide on current action
600      if($ACT == 'show' || $ACT == 'search'){
601        if($INFO['writable']){
602          if(!empty($INFO['draft'])) {
603            tpl_link(wl($ID,'do=draft'),
604                       $pre.(($inner)?$inner:$lang['btn_draft']).$suf,
605                       'class="action edit" accesskey="e" rel="nofollow"');
606          } else {
607            if($INFO['exists']){
608              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
609                       $pre.(($inner)?$inner:$lang['btn_edit']).$suf,
610                       'class="action edit" accesskey="e" rel="nofollow"');
611            }else{
612              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
613                       $pre.(($inner)?$inner:$lang['btn_create']).$suf,
614                       'class="action create" accesskey="e" rel="nofollow"');
615            }
616          }
617        }else{
618          if(!actionOK('source')) return false; //pseudo action
619          tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
620                   $pre.(($inner)?$inner:$lang['btn_source']).$suf,
621                   'class="action source" accesskey="v" rel="nofollow"');
622        }
623      }else{
624          tpl_link(wl($ID,'do=show'),
625                   $pre.(($inner)?$inner:$lang['btn_show']).$suf,
626                   'class="action show" accesskey="v" rel="nofollow"');
627      }
628      return true;
629    case 'history':
630      tpl_link(wl($ID,'do=revisions'),
631               $pre.(($inner)?$inner:$lang['btn_revs']).$suf,
632               'class="action revisions" accesskey="o" rel="nofollow"');
633      return true;
634    case 'recent':
635      tpl_link(wl('','do=recent'),
636               $pre.(($inner)?$inner:$lang['btn_recent']).$suf,
637              'class="action recent" accesskey="r" rel="nofollow"');
638      return true;
639    case 'index':
640      tpl_link(wl($ID,'do=index'),
641               $pre.(($inner)?$inner:$lang['btn_index']).$suf,
642              'class="action index" accesskey="x" rel="nofollow"');
643      return true;
644    case 'top':
645      print '<a href="#dokuwiki__top" class="action top" accesskey="x">'.
646            $pre.(($inner)?$inner:$lang['btn_top']).$suf.'</a>';
647      return true;
648    case 'back':
649      if ($parent = tpl_getparent($ID)) {
650        tpl_link(wl($parent,'do=show'),
651        $pre.(($inner)?$inner:$lang['btn_back']).$suf,
652        'class="action back" accesskey="b" rel="nofollow"');
653        return true;
654      }
655      return false;
656    case 'login':
657      if($conf['useacl'] && $auth){
658        if($_SERVER['REMOTE_USER']){
659          tpl_link(wl($ID,'do=logout&amp;sectok='.getSecurityToken()),
660                   $pre.(($inner)?$inner:$lang['btn_logout']).$suf,
661                   'class="action logout" rel="nofollow"');
662        }else{
663          tpl_link(wl($ID,'do=login&amp;sectok='.getSecurityToken()),
664                   $pre.(($inner)?$inner:$lang['btn_login']).$suf,
665                   'class="action login" rel="nofollow"');
666        }
667        return true;
668      }
669      return false;
670    case 'admin':
671      if($INFO['ismanager']){
672        tpl_link(wl($ID,'do=admin'),
673                 $pre.(($inner)?$inner:$lang['btn_admin']).$suf,
674                 'class="action admin" rel="nofollow"');
675        return true;
676      }
677      return false;
678   case 'subscribe':
679   case 'subscription':
680      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
681        if($_SERVER['REMOTE_USER']){
682          if($INFO['subscribed']) {
683            tpl_link(wl($ID,'do=unsubscribe'),
684                     $pre.(($inner)?$inner:$lang['btn_unsubscribe']).$suf,
685                     'class="action unsubscribe" rel="nofollow"');
686          } else {
687            tpl_link(wl($ID,'do=subscribe'),
688                     $pre.(($inner)?$inner:$lang['btn_subscribe']).$suf,
689                     'class="action subscribe" rel="nofollow"');
690          }
691          return true;
692        }
693      }
694      return false;
695    case 'subscribens':
696      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
697        if($_SERVER['REMOTE_USER']){
698          if($INFO['subscribedns']) {
699            tpl_link(wl($ID,'do=unsubscribens'),
700                     $pre.(($inner)?$inner:$lang['btn_unsubscribens']).$suf,
701                     'class="action unsubscribens" rel="nofollow"');
702          } else {
703            tpl_link(wl($ID,'do=subscribens'),
704                     $pre.(($inner)?$inner:$lang['btn_subscribens']).$suf,
705                     'class="action subscribens" rel="nofollow"');
706          }
707          return true;
708        }
709      }
710      return false;
711    case 'backlink':
712      tpl_link(wl($ID,'do=backlink'),
713               $pre.(($inner)?$inner:$lang['btn_backlink']).$suf,
714               'class="action backlink" rel="nofollow"');
715      return true;
716    case 'profile':
717      if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
718         $auth->canDo('Profile') && ($ACT!='profile')){
719        tpl_link(wl($ID,'do=profile'),
720                 $pre.(($inner)?$inner:$lang['btn_profile']).$suf,
721                 'class="action profile" rel="nofollow"');
722        return true;
723      }
724      return false;
725    default:
726      print '[unknown link type]';
727      return true;
728  }
729}
730
731/**
732 * Print the search form
733 *
734 * If the first parameter is given a div with the ID 'qsearch_out' will
735 * be added which instructs the ajax pagequicksearch to kick in and place
736 * its output into this div. The second parameter controls the propritary
737 * attribute autocomplete. If set to false this attribute will be set with an
738 * value of "off" to instruct the browser to disable it's own built in
739 * autocompletion feature (MSIE and Firefox)
740 *
741 * @author Andreas Gohr <andi@splitbrain.org>
742 */
743function tpl_searchform($ajax=true,$autocomplete=true){
744  global $lang;
745  global $ACT;
746
747  // don't print the search form if search action has been disabled
748  if (!actionOk('search')) return false;
749
750  print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
751  print '<input type="hidden" name="do" value="search" />';
752  print '<input type="text" ';
753  if($ACT == 'search') print 'value="'.htmlspecialchars($_REQUEST['id']).'" ';
754  if(!$autocomplete) print 'autocomplete="off" ';
755  print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[ALT+F]" />';
756  print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
757  if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
758  print '</div></form>';
759  return true;
760}
761
762/**
763 * Print the breadcrumbs trace
764 *
765 * @author Andreas Gohr <andi@splitbrain.org>
766 */
767function tpl_breadcrumbs($sep='&raquo;'){
768  global $lang;
769  global $conf;
770
771  //check if enabled
772  if(!$conf['breadcrumbs']) return false;
773
774  $crumbs = breadcrumbs(); //setup crumb trace
775
776  //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
777  if($lang['direction'] == 'rtl') {
778    $crumbs = array_reverse($crumbs,true);
779    $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
780  } else {
781    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
782  }
783
784  //render crumbs, highlight the last one
785  print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
786  $last = count($crumbs);
787  $i = 0;
788  foreach ($crumbs as $id => $name){
789    $i++;
790    echo $crumbs_sep;
791    if ($i == $last) print '<span class="curid">';
792    tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
793    if ($i == $last) print '</span>';
794  }
795  return true;
796}
797
798/**
799 * Hierarchical breadcrumbs
800 *
801 * This code was suggested as replacement for the usual breadcrumbs.
802 * It only makes sense with a deep site structure.
803 *
804 * @author Andreas Gohr <andi@splitbrain.org>
805 * @author Nigel McNie <oracle.shinoda@gmail.com>
806 * @author Sean Coates <sean@caedmon.net>
807 * @author <fredrik@averpil.com>
808 * @todo   May behave strangely in RTL languages
809 */
810function tpl_youarehere($sep=' &raquo; '){
811  global $conf;
812  global $ID;
813  global $lang;
814
815  // check if enabled
816  if(!$conf['youarehere']) return false;
817
818  $parts = explode(':', $ID);
819  $count = count($parts);
820
821  echo '<span class="bchead">'.$lang['youarehere'].': </span>';
822
823  // always print the startpage
824  $title = p_get_first_heading($conf['start']);
825  if(!$title) $title = $conf['start'];
826  tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
827
828  // print intermediate namespace links
829  $part = '';
830  for($i=0; $i<$count - 1; $i++){
831    $part .= $parts[$i].':';
832    $page = $part;
833    resolve_pageid('',$page,$exists);
834    if ($page == $conf['start']) continue; // Skip startpage
835
836    // output
837    echo $sep;
838    if($exists){
839      $title = p_get_first_heading($page);
840      if(!$title) $title = $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 = p_get_first_heading($page);
854    if(!$title) $title = $parts[$i];
855    tpl_link(wl($page),hsc($title),'title="'.$page.'"');
856  }else{
857    tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
858  }
859  return true;
860}
861
862/**
863 * Print info if the user is logged in
864 * and show full name in that case
865 *
866 * Could be enhanced with a profile link in future?
867 *
868 * @author Andreas Gohr <andi@splitbrain.org>
869 */
870function tpl_userinfo(){
871  global $lang;
872  global $INFO;
873  if($_SERVER['REMOTE_USER']){
874    print $lang['loggedinas'].': '.$INFO['userinfo']['name'];
875    return true;
876  }
877  return false;
878}
879
880/**
881 * Print some info about the current page
882 *
883 * @author Andreas Gohr <andi@splitbrain.org>
884 */
885function tpl_pageinfo($ret=false){
886  global $conf;
887  global $lang;
888  global $INFO;
889  global $REV;
890  global $ID;
891
892  // return if we are not allowed to view the page
893  if (!auth_quickaclcheck($ID)) { return false; }
894
895  // prepare date and path
896  $fn = $INFO['filepath'];
897  if(!$conf['fullpath']){
898    if($REV){
899      $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
900    }else{
901      $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
902    }
903  }
904  $fn = utf8_decodeFN($fn);
905  $date = strftime($conf['dformat'],$INFO['lastmod']);
906
907  // print it
908  if($INFO['exists']){
909    $out = '';
910    $out .= $fn;
911    $out .= ' &middot; ';
912    $out .= $lang['lastmod'];
913    $out .= ': ';
914    $out .= $date;
915    if($INFO['editor']){
916      $out .= ' '.$lang['by'].' ';
917      $out .= $INFO['editor'];
918    }else{
919      $out .= ' ('.$lang['external_edit'].')';
920    }
921    if($INFO['locked']){
922      $out .= ' &middot; ';
923      $out .= $lang['lockedby'];
924      $out .= ': ';
925      $out .= $INFO['locked'];
926    }
927    if($ret){
928        return $out;
929    }else{
930        echo $out;
931        return true;
932    }
933  }
934  return false;
935}
936
937/**
938 * Prints or returns the name of the given page (current one if none given).
939 *
940 * If useheading is enabled this will use the first headline else
941 * the given ID is used.
942 *
943 * @author Andreas Gohr <andi@splitbrain.org>
944 */
945function tpl_pagetitle($id=null, $ret=false){
946  global $conf;
947  if(is_null($id)){
948    global $ID;
949    $id = $ID;
950  }
951
952  $name = $id;
953  if ($conf['useheading']) {
954    $title = p_get_first_heading($id);
955    if ($title) $name = $title;
956  }
957
958  if ($ret) {
959      return hsc($name);
960  } else {
961      print hsc($name);
962      return true;
963  }
964}
965
966/**
967 * Returns the requested EXIF/IPTC tag from the current image
968 *
969 * If $tags is an array all given tags are tried until a
970 * value is found. If no value is found $alt is returned.
971 *
972 * Which texts are known is defined in the functions _exifTagNames
973 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
974 * to the names of the latter one)
975 *
976 * Only allowed in: detail.php
977 *
978 * @author Andreas Gohr <andi@splitbrain.org>
979 */
980function tpl_img_getTag($tags,$alt='',$src=null){
981  // Init Exif Reader
982  global $SRC;
983
984  if(is_null($src)) $src = $SRC;
985
986  static $meta = null;
987  if(is_null($meta)) $meta = new JpegMeta($src);
988  if($meta === false) return $alt;
989  $info = $meta->getField($tags);
990  if($info == false) return $alt;
991  return $info;
992}
993
994/**
995 * Prints the image with a link to the full sized version
996 *
997 * Only allowed in: detail.php
998 */
999function tpl_img($maxwidth=0,$maxheight=0){
1000  global $IMG;
1001  $w = tpl_img_getTag('File.Width');
1002  $h = tpl_img_getTag('File.Height');
1003
1004  //resize to given max values
1005  $ratio = 1;
1006  if($w >= $h){
1007    if($maxwidth && $w >= $maxwidth){
1008      $ratio = $maxwidth/$w;
1009    }elseif($maxheight && $h > $maxheight){
1010      $ratio = $maxheight/$h;
1011    }
1012  }else{
1013    if($maxheight && $h >= $maxheight){
1014      $ratio = $maxheight/$h;
1015    }elseif($maxwidth && $w > $maxwidth){
1016      $ratio = $maxwidth/$w;
1017    }
1018  }
1019  if($ratio){
1020    $w = floor($ratio*$w);
1021    $h = floor($ratio*$h);
1022  }
1023
1024  //prepare URLs
1025  $url=ml($IMG,array('cache'=>$_REQUEST['cache']));
1026  $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h));
1027
1028  //prepare attributes
1029  $alt=tpl_img_getTag('Simple.Title');
1030  $p = array();
1031  if($w) $p['width']  = $w;
1032  if($h) $p['height'] = $h;
1033         $p['class']  = 'img_detail';
1034  if($alt){
1035    $p['alt']   = $alt;
1036    $p['title'] = $alt;
1037  }else{
1038    $p['alt'] = '';
1039  }
1040  $p = buildAttributes($p);
1041
1042  print '<a href="'.$url.'">';
1043  print '<img src="'.$src.'" '.$p.'/>';
1044  print '</a>';
1045  return true;
1046}
1047
1048/**
1049 * This function inserts a 1x1 pixel gif which in reality
1050 * is the inexer function.
1051 *
1052 * Should be called somewhere at the very end of the main.php
1053 * template
1054 */
1055function tpl_indexerWebBug(){
1056  global $ID;
1057  global $INFO;
1058  if(!$INFO['exists']) return false;
1059
1060  if(isHiddenPage($ID)) return false; //no need to index hidden pages
1061
1062  $p = array();
1063  $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1064                 '&'.time();
1065  $p['width']  = 1;
1066  $p['height'] = 1;
1067  $p['alt']    = '';
1068  $att = buildAttributes($p);
1069  print "<img $att />";
1070  return true;
1071}
1072
1073// configuration methods
1074/**
1075 * tpl_getConf($id)
1076 *
1077 * use this function to access template configuration variables
1078 */
1079function tpl_getConf($id){
1080  global $conf;
1081  global $tpl_configloaded;
1082
1083  $tpl = $conf['template'];
1084
1085  if (!$tpl_configloaded){
1086    $tconf = tpl_loadConfig();
1087    if ($tconf !== false){
1088      foreach ($tconf as $key => $value){
1089        if (isset($conf['tpl'][$tpl][$key])) continue;
1090        $conf['tpl'][$tpl][$key] = $value;
1091      }
1092      $tpl_configloaded = true;
1093    }
1094  }
1095
1096  return $conf['tpl'][$tpl][$id];
1097}
1098
1099/**
1100 * tpl_loadConfig()
1101 * reads all template configuration variables
1102 * this function is automatically called by tpl_getConf()
1103 */
1104function tpl_loadConfig(){
1105
1106  $file = DOKU_TPLINC.'/conf/default.php';
1107  $conf = array();
1108
1109  if (!@file_exists($file)) return false;
1110
1111  // load default config file
1112  include($file);
1113
1114  return $conf;
1115}
1116
1117/**
1118 * prints the "main content" in the mediamanger popup
1119 *
1120 * Depending on the user's actions this may be a list of
1121 * files in a namespace, the meta editing dialog or
1122 * a message of referencing pages
1123 *
1124 * Only allowed in mediamanager.php
1125 *
1126 * @author Andreas Gohr <andi@splitbrain.org>
1127 */
1128function tpl_mediaContent(){
1129  global $IMG;
1130  global $AUTH;
1131  global $INUSE;
1132  global $NS;
1133  global $JUMPTO;
1134
1135  ptln('<div id="media__content">');
1136  if($_REQUEST['edit']){
1137    media_metaform($IMG,$AUTH);
1138  }elseif(is_array($INUSE)){
1139    media_filesinuse($INUSE,$IMG);
1140  }else{
1141    media_filelist($NS,$AUTH,$JUMPTO);
1142  }
1143  ptln('</div>');
1144}
1145
1146/**
1147 * prints the namespace tree in the mediamanger popup
1148 *
1149 * Only allowed in mediamanager.php
1150 *
1151 * @author Andreas Gohr <andi@splitbrain.org>
1152 */
1153function tpl_mediaTree(){
1154  global $NS;
1155
1156  ptln('<div id="media__tree">');
1157  media_nstree($NS);
1158  ptln('</div>');
1159}
1160
1161
1162/**
1163 * Print a dropdown menu with all DokuWiki actions
1164 *
1165 * Note: this will not use any pretty URLs
1166 *
1167 * @author Andreas Gohr <andi@splitbrain.org>
1168 */
1169function tpl_actiondropdown($empty='',$button='&gt;'){
1170    global $ID;
1171    global $INFO;
1172    global $REV;
1173    global $ACT;
1174    global $conf;
1175    global $lang;
1176    global $auth;
1177
1178
1179    echo '<form method="post" accept-charset="utf-8">'; #FIXME action
1180    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1181    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1182    echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1183
1184    echo '<select name="do" id="action__selector" class="edit">';
1185    echo '<option value="">'.$empty.'</option>';
1186
1187    echo '<optgroup label=" &mdash; ">';
1188        // 'edit' - most complicated type, we need to decide on current action
1189        if($ACT == 'show' || $ACT == 'search'){
1190            if($INFO['writable']){
1191                if(!empty($INFO['draft'])) {
1192                    echo '<option value="edit">'.$lang['btn_draft'].'</option>';
1193                } else {
1194                    if($INFO['exists']){
1195                        echo '<option value="edit">'.$lang['btn_edit'].'</option>';
1196                    }else{
1197                        echo '<option value="edit">'.$lang['btn_create'].'</option>';
1198                    }
1199                }
1200            }else if(actionOK('source')) { //pseudo action
1201                echo '<option value="edit">'.$lang['btn_source'].'</option>';
1202            }
1203        }else{
1204            echo '<option value="show">'.$lang['btn_show'].'</option>';
1205        }
1206
1207        echo '<option value="revisions">'.$lang['btn_revs'].'</option>';
1208        echo '<option value="backlink">'.$lang['btn_backlink'].'</option>';
1209    echo '</optgroup>';
1210
1211    echo '<optgroup label=" &mdash; ">';
1212        echo '<option value="recent">'.$lang['btn_recent'].'</option>';
1213        echo '<option value="index">'.$lang['btn_index'].'</option>';
1214    echo '</optgroup>';
1215
1216    echo '<optgroup label=" &mdash; ">';
1217        if($conf['useacl'] && $auth){
1218            if($_SERVER['REMOTE_USER']){
1219                echo '<option value="logout">'.$lang['btn_logout'].'</option>';
1220            }else{
1221                echo '<option value="login">'.$lang['btn_login'].'</option>';
1222            }
1223        }
1224
1225        if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
1226             $auth->canDo('Profile') && ($ACT!='profile')){
1227            echo '<option value="profile">'.$lang['btn_profile'].'</option>';
1228        }
1229
1230        if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
1231            if($_SERVER['REMOTE_USER']){
1232                if($INFO['subscribed']) {
1233                    echo '<option value="unsubscribe">'.$lang['btn_unsubscribe'].'</option>';
1234                } else {
1235                    echo '<option value="subscribe">'.$lang['btn_subscribe'].'</option>';
1236                }
1237            }
1238        }
1239
1240        if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
1241            if($_SERVER['REMOTE_USER']){
1242                if($INFO['subscribedns']) {
1243                    echo '<option value="unsubscribens">'.$lang['btn_unsubscribens'].'</option>';
1244                } else {
1245                    echo '<option value="subscribens">'.$lang['btn_subscribens'].'</option>';
1246                }
1247            }
1248        }
1249
1250        if($INFO['ismanager']){
1251            echo '<option value="admin">'.$lang['btn_admin'].'</option>';
1252        }
1253    echo '</optgroup>';
1254
1255    echo '</select>';
1256    echo '<input type="submit" value="'.$button.'" id="action__selectorbtn" />';
1257    echo '</form>';
1258}
1259
1260//Setup VIM: ex: et ts=4 enc=utf-8 :
1261
1262