<?php
/**
 * Display page index
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Otto Vainio <plugins@valjakko.net>
 */


if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'../../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',realpath(dirname(__FILE__).'../').'/');
if(!defined('NL')) define('NL',"\n");

require_once(DOKU_INC.'inc/html.php');
require_once(DOKU_INC.'inc/search.php');

$thislang=array();
setupLocale();

function getPluginName() {
    $basename = preg_replace( '/^.+[\\\\\\/]/', '', dirname(__FILE__));
    return $basename;
}

function myhtml_index(){
  global $NS;
  global $conf;
  global $ID;
  $dir = $conf['datadir'];
  $ns  = cleanID($NS);
  #fixme use appropriate function
  if(empty($ns)){
    $ns = dirname(str_replace(':','/',$ID));
    if($ns == '.') $ns ='';
  }
  $dir  = utf8_encodeFN(str_replace(':','/',$ns));

  print p_locale_xhtml('index');

  $data = array();
  search($data,$conf['datadir'],'linkpage_search_index',array('ns' => $ns),$dir);
  print html_buildlist($data,'idx','html_list_index','html_li_index');
}

function linkpage_filelist($ns,$auth=null,$jump=''){
    global $conf;
    global $lang;
    global $thislang;
    $ns = cleanID($ns);

    // check auth our self if not given (needed for ajax calls)
    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");

    echo '<h1 id="linkpage__ns">:'.hsc($ns).'</h1>'.NL;

    if($auth < AUTH_READ){
        // FIXME: print permission warning here instead?
        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
        return;
    }


    $dir = utf8_encodeFN(str_replace(':','/',$ns));
    $data = array();
    search($data,$conf['datadir'],'linkpage_search_index',array('ns' => $ns),$dir);
  
    if(!count($data)){
        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
        return;
    }
    linkpage_newpage($ns);
    echo $thislang['clicktosort'].NL;
    echo '<table class="sortable" id="linkpage__sortable"><thead><tr>';
    echo '<th>'.$thislang['id'].'</th><th>'.$thislang['title'].'</th>';
    echo '</tr></thead><tbody>';
    foreach($data as $item){
        linkpage_printfile($item,$auth,$jump);
    }
    echo '</tbody></table>';
}


function linkpage_fileContent(){
  global $AUTH;
  global $NS;
  global $JUMPTO;

  ptln('<div id="linkpage__content">');
  linkpage_filelist($NS,$AUTH,$JUMPTO);
  ptln('</div>');
}


/**
 * Formats and prints one file in the list
 */
function linkpage_printfile($item,$auth,$jump){
    if ($item['type']=='d') return;
    global $lang;
    // Prepare zebra coloring
    // I always wanted to use this variable name :-D
    static $twibble = 1;
    $twibble *= -1;
    $zebra = ($twibble == -1) ? 'odd' : 'even';

    // Automatically jump to recent action
    if($jump == $item['id']) {
        $jump = ' id="scroll__here" ';
    }else{
        $jump = '';
    }

    // Prepare fileicons
    list($ext,$mime) = mimetype($item['file']);
    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
    $class = 'select linkpagefile mf_'.$class;

    // Prepare filename
    $file = utf8_decodeFN($item['id']);
    $title = $item['title'];
    $pgsplt=explode(':',$item['id']);
    $pagename = array_pop($pgsplt);
    if (!$title) $title=$pagename;

    // Prepare info
    $info = '';
    
    // output
    echo '<tr><td>';
    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
    echo '<a name="h_'.$item['id'].'" class="'.$class.'">'.$pagename.'</a>';
    echo '</div></td>'.NL;
    echo '<td>';
    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
    echo $title;
    echo '<div class="example" id="ex_'.$item['id'].'">';
    echo $lang['mediausage'].' <code>[[:'.$item['id'].']]</code>';
    echo '</div>';
    echo '</div>';
    echo '</td></tr>';
}

function linkpage_mediaTree(){
  global $NS;

  ptln('<div id="linkpage__tree">');
  linkpage_nstree($NS);
  ptln('</div>');
}


/**
 * Build a tree outline of available media namespaces
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author  Otto Vainio <plugins@valjakko.net>
 */
function linkpage_nstree($ns){
    global $conf;
    global $lang;

    // currently selected namespace
    $ns  = cleanID($ns);
    if(empty($ns)){
        $ns = dirname(str_replace(':','/',$ID));
        if($ns == '.') $ns ='';
    }
    $ns  = utf8_encodeFN(str_replace(':','/',$ns));

    $data = array();
    search($data,$conf['datadir'],'linkpage_search_index',array('ns' => $ns, 'nofiles' => true));

    // wrap a list with the root level around the other namespaces
    $item = array( 'level' => 0, 'id' => '',
                   'open' =>'true', 'label' => '['.$lang['mediaroot'].']');

    echo '<ul class="idx">';
    echo linkpage_nstree_li($item);
    echo linkpage_nstree_item($item);
    echo html_buildlist($data,'idx','linkpage_nstree_item','linkpage_nstree_li');
    echo '</li>';
    echo '</ul>';
}

/**
 * Userfunction for html_buildlist
 *
 * Prints a linkpage namespace tree item
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author  Otto Vainio <plugins@valjakko.net>
 */
function linkpage_nstree_item($item){
    $pos   = strrpos($item['id'], ':');
    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
    if(!$item['label']) $item['label'] = $label;

    $ret  = '';
    $ret .= '<a href="'.DOKU_BASE.'lib/plugins/'.getPluginName().'/exe/filemanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
    $ret .= $item['label'];
    $ret .= '</a>';
    return $ret;
}

/**
 * Userfunction for html_buildlist
 *
 * Prints a linkpage namespace tree item opener
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author  Otto Vainio <plugins@valjakko.net>
 */
function linkpage_nstree_li($item){
    $class='linkpage level'.$item['level'];
    if($item['open']){
        $class .= ' open';
        $img   = DOKU_BASE.'lib/images/minus.gif';
        $alt   = '&minus;';
    }else{
        $class .= ' closed';
        $img   = DOKU_BASE.'lib/images/plus.gif';
        $alt   = '+';
    }
    return '<li class="'.$class.'">'.
           '<img src="'.$img.'" alt="'.$alt.'" />';
}
/**
 * Build the browsable index of pages
 *
 * $opts['ns'] is the current namespace
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 * @author  Otto Vainio <plugins@valjakko.net>
 */
function linkpage_search_index(&$data,$base,$file,$type,$lvl,$opts){
  $return = true;

  $item = array();
  if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
    //add but don't recurse
    $return = false;
  }elseif($type == 'f' && ($opts['nofiles'] || !preg_match('#\.txt$#',$file))){
    //don't add
    return false;
  }

  $id = pathID($file);
  $title = p_get_metadata($id, 'title');

  //check hidden
  if(isHiddenPage($id)){
    return false;
  }

  //check ACL
  if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
    return false;
  }

  $data[]=array( 'id'    => $id,
                 'type'  => $type,
                 'level' => $lvl,
                 'title' => $title,
                 'open'  => $return );
  return $return;
}


/**
 * Print the Add new page form
 *
 */
function linkpage_newpage($ns){
    global $lang;
    global $thislang;
    global $conf;
    $sepa='0';
    if ($conf['plugin']['linkmanager']['usetitleseparator']) {$sepa='1';}
    ?>
    <form action="" method="post">
        <input type="hidden" name="newpage__ns" id="newpage__ns" value="<?php echo hsc($ns)?>" />
        <input type="hidden" name="conf__use_sepa" id="conf__use_sepa" value="<?php echo $sepa ?>" />
        <p>
          <label for="newpage__name"><?php echo $thislang['txt_newpage']?>:</label>
          <span class="nowrap">
          <input type="text" name="newpage__name" class="newpage__name" id="newpage__name" />
          <a name="newpage" class="newpage__submit">submit</a>
          </span>
        </p>
    </form>
    <?php
}

/**
 *  setupLocale() 
 *  reads all the plugins language dependent strings into $this->lang
 *  this function is automatically called by getLang()
 */
function setupLocale() {
  if ($localised) return;
  global $thislang;

  global $conf;            // definitely don't invoke "global $lang"
  $path = DOKU_PLUGIN.getPluginName().'/lang/';
//  echo "polku:$path";

  $lang = array();

  // don't include once, in case several plugin components require the same language file
  @include($path.'en/lang.php');    
  if ($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
  
  $thislang = $lang;
  $localised = true;
}
?>