


<?php
/**
 * Functions derived from html.php
 * Modified to generate the dropdown index
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 * @author     Modified Paul Minifie
 */


 //#TODO
 //highlight current page
 //highlight visitied pages - does a record exist? how does trace work?


/**
 * Display page index
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Paul Minifie
 * from html.php
 */

function html_index_mod ($ns){
  require_once(DOKU_INC.'inc/search.php');
  global $conf;
  global $ID;
  //added for debug
  global $ACT;
  global $debug;

  $dir = $conf['datadir'];
  $ns  = cleanID($ns);
  #fixme use appropriate function
  if(empty($ns)){
    $ns = dirname(str_replace(':','/',$ID));
    if($ns == '.') $ns ='';
  }
  $ns  = utf8_encodeFN(str_replace(':','/',$ns));

//search_index_title returns an array of arrays, a tree for each of the nodes in the IDX
//so split the IDX into components, each of which have level 0, and add each tree to them, before building the list
  $data =array();
  $data1=array();
  $pageid=array();
  search($data,$conf['datadir'],'search_index_title',array('ns' => $ns));
  $IDdisplay=$ID;
  //TODO obsolete - modify to hide pages with a given suffix
  //test to see if pagename is a descriptor of an NS and if so, truncate to NS
  //only happens if 'nspages' is set in local.php and mod is done and flagged in doku.php
  //if ($conf['amanuensis']['dokunsmod'] and $conf['amanuensis']['nspages']){
  //  $IDdisplay=$ID;
  //  if (test_nsdescriptor(noNS($ID))==true){
  //    $IDdisplay = getNS($ID);
  //  }
  //}
  //remove pages named the same as the NS
  //if 'nspages' is set in local.php and mod is done and flagged in doku.php
  if ($conf['amanuensis']['dokunsmod'] and $conf['amanuensis']['nspages']=='true'){
      $data =stripNSdescriptors($data);
  }
  //$debug['data'] = $data;
  $data = build_subindex($data,$IDdisplay);
  $pageid = diceID($IDdisplay);
  //$debug['iddice']=$pageid;
  //sets the spacer that appears in the title of the dropdowns
  $spacer= array ('id' => ".", 'type' => d, 'level' => 0, 'open' => 1);
  $pageid = index_dicedID ($pageid);
  $data1 = array_shift ($data);
  array_unshift($data1, array_shift($pageid));
  $arrlent = count($pageid);
  $nn=0;
  while ($nn < $arrlent){
      if (($arrlent - $nn) >0){array_push($data1, $spacer);}
      array_push ($data1, $pageid[$nn] );
      $data1 = array_merge ($data1, $data[$nn]);

   $nn++;
  }
 if ($ACT =='edit'){
  print html_buildlist_mod($data1,'idx','html_list_index_edit','html_li_index_mod');
  }else{
  print html_buildlist_mod($data1,'idx','html_list_index_mod','html_li_index_mod');
  }
}

  /**
   * test to see if name is a namespace descriptor ie, is suffixed with '$conf['amanuensis']['nssuffix']'
   * FIXME make suffix a variable (set in doku.php??)
   * @author Paul Minifie
   */
 function test_nsdescriptor ($name){
   global $conf;
   if (strpos(strrev($name),strrev($conf['amanuensis']['nssuffix']))===0) {
       $return=true;
   }else {$return=false;
   }
   return $return;
 }


   /**
   * removes files with the same name as the directory they are in from the dropdown menu
   *
   * @author  Paul Minifie
   */
function stripNSdescriptors($data){
  //global $debug;
  $level = 0;
  $ret=array();
  $count=array();
  $nslist=array();
     //assumes all directories always come before files at a given level, so only does list once
     //so names of directories added to array. if filenames match, they are discarded
     //starts by giving each directory an index
  while ($data){
  $item=array_shift($data);
       $l=$item['level'];
       if( $l > $level ){
          $count[$l]++;
     }
    //$item['index']=$count[$l];
    if ($item['type']=='d'){
      $nslist[$l][$count[$l]][] = noNS($item['id']);
      array_push($ret,$item);
     }elseif($item['type']=='f'){
//$debug['count']=$count;
//$debug['nslist'] = $nslist;
       if (is_array ($nslist[$l][$count[$l]])){
         if (!in_array(noNS($item['id']),$nslist[$l][$count[$l]])){
         array_push($ret,$item);
         }
       }else{
         array_push($ret,$item);
       }
     }
    //remember current level
    $level = $l;
    }
  return $ret;
}

  /**
   * takes an index file, array()as returned by
   * and the IDX, and creates submenus, corresponding to the namespaces
   * in form array(array(rootnamespace), array(nextlevelnamespace),....array(deepestnamespace)
   * and marks the namespaces of the current name
   *
   * @author  Paul Minifie
   */
function build_subindex($index, $id){
  $iddice=array();
  $return[0]=$index;
  $temp = diceID($id);
  while ($temp){
    $iddice[]=noNS(array_shift($temp));
  }
  $level=1;
  $search  = array_shift($iddice).':';
  while ($iddice){
    $return[$level]=array();
    foreach ($return[$level-1] as $item){
       //set second bit as component of name
       if ($search == $item['id']){
           $item['open']=$item['open'] & 2;
       }
       //reduce level for submenu items
       if (0 === strpos( $item['id'],$search)){
         $item['level']= $item['level']-1;
         //add item to submenu
         array_push($return[$level],$item);
       }
    }
  $search .= array_shift($iddice).':';
  $level++;
  }
  return $return;
}


  /**
   * dices $ID into array of form that can be output by html_buildlist_mod
   * Function passed to the search function
   *
   * @author  Paul Minifie
   */
function diceID ($id){
    $dice = array();
    while ($id){
     $dice[]=$id;
     $id=getNS($id);
    }
    return  array_reverse($dice);
}


  /**NOTUSED
   * dices $ID into array of form that can be output by html_buildlist_mod
   * Function passed to the search function
   *
   * @author  Paul Minifie
   */
function diceID_old ($id){
    $dice = array();
    $colon = true;
    while ($colon) {
      $colon=strpos($id, ':' );
      if ($colon){
        $dice[]= substr($id, 0,  strpos($id,':'));
        $id=substr($id, $colon+1);
      }else{
        $dice[]= $id;
      }
    }
    return  $dice;
}

  /**
   * formats a diced $ID into a form that can be built into an index
   *
   * @author  Paul Minifie
   */
function index_dicedID ($dicedID){
  $return=array();
  //FIX_ME this identifies a file as a directory when top level (so the menus work)
  array_unshift ($return, array('id'=>array_pop($dicedID), 'type'=>'d','level'=>0,'open'=>1));
  while ($dicedID){
    array_unshift($return, array('id'=>array_pop($dicedID), 'type'=>'d','level'=>0,'open'=>1));
  }
  return $return;
}


  /**
 * Build the browsable index of pages
 *
 * $opts['ns'] is the current namespace
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 * @author  Paul Minifie
 */
function search_index_title(&$data,$base,$file,$type,$lvl,$opts){
  global $conf;
  $return = true;
  $item = array();

  if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
    //add but don't recurse
    $return = true;
  }elseif($type == 'f' && !preg_match('#\.txt$#',$file)){
    //don't add
    //modified from andreas' function so return value changed to true in this case, to return the entire index
    // #FIXME may be possible to do this with the original function if the namespace is not passed
    return false;
  }
  //check ACL
  $id = pathID($file);
  if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
    return false;
  }
  // dont add namespace descriptors to the list
  //but only if 'nspages' is set in local.php and mod is done and flagged in doku.php                                                                                                       	;
  if (!($conf['amanuensis']['dokunsmod'] and $conf['amanuensis']['nspages'] and test_nsdescriptor($id))){
    $data[]=array( 'id'    => $id,
                   'type'  => $type,
                   'level' => $lvl,
                   'open'  => $return );
  }
  return $return;
}



/**
 * Build an unordered list
 *
 * Build an unordered list from the given $data array
 * Each item in the array has to have a 'level' property
 * the item itself gets printed by the given $func user
 * function. The second and optional function is used to
 * print the <li> tag. Both user function need to accept
 * a single item.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 . @author Paul Minifie
 */
function html_buildlist_mod($data,$class,$func,$lifunc='html_li_default',$menuid='menu-h',$menuclass='horizontal'){
//$level set at -1, changed from 0 -pm
  $level = -1;
  $level_init= -1;
  $opens = 0;
  $ret   = '';
  $firstul = 1;

  foreach ($data as $item){
     if( $item['level'] > $level ){
      //open new list
       for($i=0; $i<($item['level'] - $level); $i++){
          if ($i) $ret .= "<li class=\"clear\">\n";
          //$changed to set class name to level -pm
          if ($firstul){
                       	$ret .= "<ul id=\"$menuid\" class=\"$menuclass\">\n";
                       	$firstul =NULL;
          }else{
          $ret .= "<ul>\n";   //  class=\"lev$level\">\n";
          }
       }
     }
     elseif( $item['level'] < $level ){
        //close last item
        $ret .= "</li>\n";
        for ($i=0; $i<($level - $item['level']); $i++){
        //close higher lists
        $ret .= "</ul>\n</li>\n";
    }
    }else{
      //close last item
      $ret .= "</li>\n";
    }

    //remember current level 
    $level = $item['level'];

    //print item
    $ret .= $lifunc($item); //user function
    //$ret .= '<span>';// class="li">';
    $ret .= $func($item); //user function
    //$ret .= '</span>';
  }

  //close remaining items and lists
  for ($i=0; $i < $level; $i++){
    $ret .= "</li>\n</ul>\n";
  }

  return $ret;
}


function html_list_index_mod($item){
  $ret = '';
  $base = ':'.$item['id'];
  $base = substr($base,strrpos($base,':')+1);
  if($item['type']=='d'){
    $ret .= '<a href="'.wl($ID,'idx='.$item['id']).'" class="subpages">';
    $ret .= $base;
    $ret .= '</a>';
  }else{
    $ret .= html_wikilink(':'.$item['id']);
  }
  return $ret;
}

/**
 * In edit mode, builds the links with
 *
 * User function for html_buildlist()
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Paul Minifie
 */

function html_list_index_edit($item){
  $ret = '';
  $base = ':'.$item['id'];
  $base = substr($base,strrpos($base,':')+1);
  if($item['type']=='d'){
    $ret .= '<a href="javascript:insertIntLink(\''.idfilter($item['id']).'\')" class="subpages_edit" >'.noNS($item['id']).'</a>';
    //$ret .= '<a href="'.wl($ID,'idx='.$item['id']).'" class="subpages">';
    //$ret .= $base;
    //$ret .= '</a>';
  }else{
    $ret .= '<a href="javascript:insertIntLink(\''.idfilter($item['id']).'\')" class="wikilink1_edit" >'.noNS($item['id']).'</a>';

  }
  return $ret;
}

/**
  * NOT USED
 * Index item formatter
 *
 * User function for html_buildlist()
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
 function html_list_index_mod_old($item){
  $ret = '';
  $base = ':'.$item['id'];
  $base = substr($base,strrpos($base,':')+1);
  if($item['type']=='d'){
    $ret .= '<a href="'.wl($ID,'idx='.$item['id']) .'">'; //.'" class="idx_dir">';
    $ret .= $base;
    $ret .= '</a>';
  }else{
    $ret .= html_wikilink(':'.$item['id']);
  }
  return $ret;
}




/**
 * NOT USED
 * Index List item
 *
 * This user function is used in html_build_list to build the
 * <li> tags for namespaces when displaying the page index
 * it gives different classes to opened or closed "folders"
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
 
function html_li_index_mod($item){
  if($item['type'] == "f"){
    return '<li>'; // class="level'.$item['level'].'">';
  }elseif($item['open']){
    return '<li>';// class="open">';
  }else{
    return '<li>';// class="closed">';
  }
}


/**
 * Default List item, modified to insert a link in edit mode
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Paul Minifie
 */
function html_li_edit($item){
  return '<li class="level'.$item['level'].'">';
}


?>
