<?php 
/**
 * Provide navigation sidebar functionality to Dokuwiki Templates
 *
 * @author Christopher Smith <chris@jalakai.co.uk>
 * @author Esther Brunner <wikidesign@gmail.com>
 */

/**
 * Recursive function to establish best sidebar file to be used
 */
function getSidebarFN($ns, $file){

	// check for wiki page = $ns:$file (or $file where no namespace)
	$nsFile = ($ns) ? "$ns:$file" : $file;
	if (@file_exists(wikiFN($nsFile)) && auth_quickaclcheck($nsFile)) return $nsFile;
	
  // remove deepest namespace level and call function recursively
	
	// no namespace left, exit with no file found	
	if (!$ns) return '';
	
	$i = strrpos($ns, ":");
	$ns = ($i) ? substr($ns, 0, $i) : false;	
	return getSidebarFN($ns, $file);
}

/**
 * Display the sidebar
 */
function tpl_sidebar(){
	global $ID, $REV, $conf;
	
	// save globals
	$saveID = $ID;
	$saveREV = $REV;

	// discover file to be displayed in navigation sidebar	
  $fileSidebar = getSidebarFN(getNS($ID), tpl_getConf('sidebar_page'));

	// determine what to display
	if ($fileSidebar){
		$ID = $fileSidebar;
		$REV = '';
		print p_wiki_xhtml($ID,$REV,false);
	} else {
    global $IDX;
    html_index($IDX);
	}
		
	// restore globals
	$ID = $saveID;
	$REV = $saveREV;
}

/**
 * Return the correct ID for <div class="dokuwiki">
 */
function tpl_classID(){
  echo 'minima__'.tpl_getConf('width').'_'.tpl_getConf('sidebar_position');
}

/**
 * Checks if the color scheme has changed
 */
function tpl_checkColor(){
  $color = tpl_getConf('color');
  $file  = DOKU_TPLINC.'style.ini';
  $file2 = DOKU_TPLINC.'style_'.$color.'.ini';
  $ini   = parse_ini_file($file);
  
  if ($ini['__theme__'] != '_'.$color){
    if ((@file_exists($file2)) && (@unlink($file)) && (@copy($file2, $file))){
      global $conf;
      if ($conf['fperm']) chmod($file, $conf['fperm']);
    } else {
      msg('Could not set correct style.ini file for your chosen color scheme.', -1);
    }
  }
}

/**
 * Display tabs for easy navigation
 */
function tpl_tabs(){
  global $ID;
  
  $out = '';
  $ns = getNS($ID);
  $tabsFile = wikiFN(($ns).':'.tpl_getConf('tabs_page'));
  if ((@file_exists($tabsFile)) && (auth_quickaclcheck($tabs))){
    $ins = p_cached_instructions($tabsFile);
    
    foreach ($ins as $in){
      if ($in[0] == 'internallink'){
        list($id, $hash) = explode('#', $in[1][0], 2);
        resolve_pageid(getNS($ID), $id, $exists);
        if (getNS($id) != $ns) continue; // ignore links to other namespaces
        if (!$exists) continue;          // ignore links to non-existent pages
        
        // determine link title
        $title = hsc($in[1][1]);
        if (!$title) $title = hsc(p_get_first_heading($id));
        if (!$title) $title = hsc(ucwords(noNS($id)));
        
        // now construct the output link
        if ($id == $ID) $out .= '<span class="activetab">'.$title.'</span> ';
        else $out .= '<a href="'.wl($id).'" class="tab">'.$title.'</a> ';
      }
    }
    echo '<div class="tabs">'.$out.'</div>';
  }
}
