<?php
/**
* Main file for the Netzbrett  
*
* @author	Thomas Weinert	<subjective@subjective.de>
* @version	1.4.7
* @package  Netzbrett
* @modulegroup    Netzbrett_Program
* @module   Netzbrett_Program_Main
* @access public
*/

$daycounts = array(
  1=>"today",
  2=>"one day",
  3=>"two days",
  8=>"one week",
  15=>"two weeks",
  31=>"one month",
  61=>"two months",
  10000=>"all");

/**
* Main function to include the Netzbrett in a page.
*@access public
*/
function netzbrett_main() {

  $GLOBALS["nb_output_buffer"] = "";
  nb_print("<!-- Netzbrett - Copyright 2000-2001 Thomas Weinert (http://www.subjective.de) -->");
  
  if ($GLOBALS["showtime"]) {
    $ms1 = microtime();
  }
  
  $GLOBALS["phrases"] = activate_lng($GLOBALS["nb_lngpath"],$GLOBALS["nb_lng"]);
  $GLOBALS["PHP_SELF_SAVE"] = chk_phpexe();
  switch ($GLOBALS["p_cmd"]) {
    case "entry" : 
      if ($GLOBALS["p_entry"]>0) { 
        print_entry($GLOBALS["p_entry"]); 
      } else {
        print_index();
      }
      break;
    case "save" : save_entry(true); break;
    case "admin" :
      if (($GLOBALS["p_entry"] > 0) and ($GLOBALS["p_pass"] == $GLOBALS["adminpass"])) {
        if (($GLOBALS["p_subcmd"] == "delete") and ($GLOBALS["p_delcheck"])) {
   	      delete_entries($GLOBALS["data_dir"],$GLOBALS["p_entry"]);
	      if ($GLOBALS["p_prev"] > 0) {
            print_entry($GLOBALS["p_prev"]);
	      } else {
	        print_index();
	      }
        } elseif ($GLOBALS["p_subcmd"] == "edit") {
          if (check_inputs()) {
            save_entry();
          } else {
            print_admin(false);
          }      
        } else {
          print_admin();
        }
      } else {
        if ($GLOBALS["p_entry"] > 0) {
          print_entry($GLOBALS["p_entry"]);
        } else {
          print_index();        
        } 
      }
      break;
    case "print" : 
      if ($GLOBALS["p_entry"]>0) { 
        printview($GLOBALS["p_entry"]); 
      } else {
        print_index();
      }
      break;
    default : print_index(); 
  }
  
  if ($GLOBALS["showtime"]) {
    $ms2 = microtime();
    ereg("([0-9\.]+) ([0-9\.]+),([0-9\.]+) ([0-9\.]+)",$ms1.",".$ms2,$regs);
    $out = ($regs[4]-$regs[2])+($regs[3]-$regs[1]);
    nb_print("Time needed: $out");
  }
    
  return $GLOBALS["nb_output_buffer"];
}

/**
* Checks a directory for a ending slash.
*@param string $dir directory to check
*@return string $dir corrected directory
*/
function chk_slash($dir) {
  if (!(ereg("/$",$dir))) {
    return $dir."/";
  } else {
    return $dir;
  }
}

/**
* Tests for php.exe in $GLOBALS["PHP_SELF"].
*/
function chk_phpexe() {
  return eregi_replace("^.*php.exe ","",$GLOBALS["PHP_SELF"]);  
}

/**
* Prepares string before printing.
*@param string $str string to prepare
*@param boolean $chghtml replace HTMLentities
*@param boolean $chgquot replace quotes  
*@return string $result prepared string 
*/
function str2html($str,$chghtml=true,$chgquot=true) {
  if (get_magic_quotes_gpc() == 1) {
    $result = stripslashes($str);  
  } else {
    $result = $str;    
  }
  if ($chgquot) {
    $result = ereg_replace("\"","&quot;",$result);
  }
  if ($chghtml) {
    htmlentities($result);
  }
  return $result;
}

/**
* Prepares date/time before printing.
*@param integer $datetime timestamp to prepare
*@param boolean $withtime include time  
*@return string $result prepared datetime 
*/
function date2html($datetime,$withtime=false) {
  $ThaiMonthAbbrl = array("Á.¤.","¡.¾.","ÁÕ.¤.","àÁ.Â.","¾.¤.","ÁÔ.Â.","¡.¤","Ê.¤.","¡.Â.","µ.¤.","¾.Â.","¸.¤.");
  switch ($GLOBALS["datemode"]) {
    case "THAI" : 
      $result = date("d",$datetime)." ".$ThaiMonthAbbrl[date("n",$datetime)-1]." ".(date("Y",$datetime)+543);
      break;
    case "B.E." : 
      $result = date("d / m / ",$datetime).(date("Y",$datetime)+543);
      break;
    default : 
      $result = date($GLOBALS["datefmt"],$datetime); 
  }
  if ($withtime) { $result .= " "; $result .= date($GLOBALS["timefmt"],$datetime); }
  return $result; 
}

/*  */
/**
* Loading translation table.
*@param string $lngpath path to language files
*@param string $default_lng default language (de, en, ...) 
*@return array $phrases loaded phrases or false 
*/
function activate_lng($lngpath,$default_lng) {  
  if (trim($GLOBALS["p_lng"]) <> '') {
    $i_lng = $GLOBALS["p_lng"];
  } else {
    $i_lng = $default_lng; 
  }
  if (file_exists(chk_slash($lngpath).$i_lng.".txt")) {
    $lines = file(chk_slash($lngpath).$i_lng.".txt"); 
    while (list(,$line) = each($lines)) {
      list($key,$val)= explode("=",$line);
	  $phrases[$key] = $val;
    }
    return $phrases;
  } else {
    return false;
  }  
}

/**
* Translates a phrase.
*@param string $str string to translate
*@param mixed $vals values to include by a sprintf() 
*@return string $i_str translated string 
*/
function translate($str,$vals=false) {
  if ($GLOBALS["phrases"]) {
    $i_str = $GLOBALS["phrases"][$str];
	if ($i_str == "") {
	  $i_str = $str;
	}
  } else {
    $i_str = $str;
  }
  if (gettype($vals)=="array") {
    $i_str = sprintf($i_str,$vals[0],$vals[1],$vals[2],$vals[3],$vals[4],$vals[5],$vals[6],$vals[7],$vals[8],$vals[9]);
  }
  return (trim($i_str));
}

/**
* Connect all childs to the parents build and Array
* of entires with no parents. 
*@param array &$entries entries list 
*/
function optimize_tree(&$entries) {
  $result = false;
  if (is_array($entries)) {
    while(list($key,$val) = each($entries)) {
      if ($val["PREV"] > 0) {
        if (!is_array($entries[$val["PREV"]]["SUBS"])) {
          $entries[$val["PREV"]]["SUBS"] = array($key); 
        } else {
          $entries[$val["PREV"]]["SUBS"][] = $key;
        }
      } else {
        if (!is_array($result)) {
          settype($result,"array");
        }
        $result[] = $key;
      }
    }
  }
  return $result;
}

/**
* Delete all other entries from list (this thread only).
*@param integer $entryno start entry number
*@param array $entries entries list 
*@return array $entries_list corrected entries list 
*/
function optimize_data($entryno,$entries) {
  
  $entries_list = $entries;
  end($entries_list);
  while ($entry = prev($entries_list)) {
    if (! ((ereg(";$entryno;",$entry["PATH"])) || ($entryno == $entry["FILE"]) || ($entryno == $entry["PREV"]))) {
      unset($entries_list[$entry["FILE"]]);
    }    
  }
  return $entries_list;
}

/**
* Delete this thread from list.
*@param integer $entryno start entry number
*@param array $entries entries list 
*@return array $entries_list corrected entries list 
*/
function optimize_data_reverse($entryno,$entries) {
  $entries_list = $entries;
  end($entries_list);
  while ($entry = prev($entries_list)) {
    if (((ereg(";$entryno;",$entry["PATH"])) || ($entryno == $entry["FILE"]) || ($entryno == $entry["PREV"]))) {
      unset($entries_list[$entry["FILE"]]);
    }    
  }
  return $entries_list;
}

/**
* Get all previous entries in this thread (recursive funktion).
*@param integer $entryno start entry number
*@param array $entries entries list 
*@return string $res all numbers of previous entries divided by ; 
*/
function get_prevs($entryno,$entries) {
  $entry = $entries[$entryno];
  $prevno = (integer) $entry["PREV"];
  if (($prevno) > 0) {
    $res = $prevno.";".get_prevs($prevno,$entries);
  }
  return $res;
}

/**
* Check an reformat text, delete/escape htmltags, ...
*@param string $text text to reformat
*@return string $itext reformatted text 
*/
function check_text($text) {

  global $comment_tags, $tags_allowed;
  $itext = $text;
  $i_tags = explode(";",$tags_allowed);
  while (list($ikey,$ival) = each($i_tags)) {
	if ($ival <> '') {
	  $itext = eregi_replace($ival,"### $ikey ###", $itext);
	}
  }
  if (!($comment_tags)) {
    $itext = ereg_replace("<[^<>]*>","",$itext);
    $itext = ereg_replace("<","&lt;",$itext);
    $itext = ereg_replace(">","&gt;",$itext);
  } else {
    $itext = ereg_replace("<","&lt;",$itext);
    $itext = ereg_replace(">","&gt;",$itext);  
  }
  $i_tags = explode(";",$tags_allowed);
  while(list($ikey,$ival) = each($i_tags)) {
	if ($ival <> '') {
	  $itext = eregi_replace("### $ikey ###",$ival, $itext);
	}
  }
  return $itext;
}

/**
* Checks a link and add a param from a global variable if set. 
*@param string $paramname paramname name of global variable
*@param string $linkstr link
*@return string $linkstr link with added param 
*/
function check_queryparam($paramname,$linkstr) {
  if ((isset($GLOBALS[$paramname])) && 
     (!(eregi("[\?\&]$paramname\=",$linkstr)))) {
    if (ereg("\?",$linkstr)) {
      return $linkstr."&".$paramname."=".$GLOBALS[$paramname];
    } else { 
      return $linkstr."?".$paramname."=".$GLOBALS[$paramname];
    }
  } else {
    return $linkstr;
  }
}

/**
* Checks a link for global variables to include
*@param string $linkstr link to check
*@return string $result checked link
*/
function check_link($linkstr) {

  $result = $linkstr;
  $paramlist = explode(";",$GLOBALS["nb_query_params"]);
  while (list(,$val) = each($paramlist)) {
    $result = check_queryparam($val,$result); 
  }
  return $result;
}

/**
* Calls socket function to read entries list (without TEXT)
*@param string $data_dir location of data
*@return array $result entries list or false
*/
function read_entries($data_dir) {
  $result = false;
  switch ($GLOBALS["sck"]) {
    case "mysql" : $result = mysql_read_entries($data_dir); break;
    case "pear" : $result = pear_read_entries($data_dir); break;
    case "text_fast" : $result = fast_text_read_entries($data_dir); break;
    default : $result = text_read_entries($data_dir);
  }
  return $result;  
}

/**
* Calls socket function to read one entry
*@param string $data_dir location of data
*@param integer $entry_no number of entry
*@return array $result entry or false
*/
function read_entry($data_dir,$entry_no) {
  $result = false;
  switch ($GLOBALS["sck"]) {
    case "mysql" : $result = mysql_read_entry($data_dir,$entry_no); break;
    case "pear" : $result = pear_read_entry($data_dir,$entry_no); break;
    case "text_fast" : $result = fast_text_read_entry($data_dir,$entry_no); break;
    default : $result = text_read_entry($data_dir,$entry_no);
  }
  return $result;  
}

/**
* Checks input data
*@return boolean $allok input data correct or not
*/
function check_inputs() {
  global $nb_inputerror;
  $allok = true;
  $GLOBALS["p_subj"] = stripslashes(ereg_replace("\"","&quot;",$GLOBALS["p_subj"]));
  $GLOBALS["p_name"] = stripslashes(ereg_replace("\"","&quot;",$GLOBALS["p_name"]));
  $GLOBALS["p_text"] = stripslashes(ereg_replace("\"","&quot;",$GLOBALS["p_text"]));
  $GLOBALS["p_email"] = stripslashes(ereg_replace("\"","&quot;",$GLOBALS["p_email"]));
  $GLOBALS["p_http"] = stripslashes(ereg_replace("\"","&quot;",$GLOBALS["p_http"]));
  if (ereg("^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$",$GLOBALS["p_http"])) {
    $GLOBALS["p_http"] = "www.".$GLOBALS["p_http"];
  }
  if ($GLOBALS['perform_strongcheck']) {
    if (! chkinput($GLOBALS["p_subj"],"alphanum",true)) { 
      $nb_inputerror['p_subj'] = true; 
      $allok = false;
    };
    if (! chkinput($GLOBALS["p_name"],"alpha",true))  { 
      $nb_inputerror['p_name'] = true; 
      $allok = false;
    };
    if (! chkinput($GLOBALS["p_text"],"chars",true))  { 
      $nb_inputerror['p_text'] = true; 
      $allok = false;
    };
  } else {
    if (! chkinput($GLOBALS["p_subj"],"nohtml",true)) { 
      $nb_inputerror['p_subj'] = true; 
      $allok = false;
    };
    if (! chkinput($GLOBALS["p_name"],"nohtml",true)) { 
      $nb_inputerror['p_name'] = true; 
      $allok = false;
    };
    if (!($GLOBALS['p_text'] != ''))  { 
      $nb_inputerror['p_text'] = true; 
      $allok = false;
    };
  }
  if (! chkinput($GLOBALS["p_email"],"email",false))  { 
    $nb_inputerror['p_email'] = true; 
    $allok = false;
  };
  if (! chkinput($GLOBALS["p_http"],"http",false))  { 
    $nb_inputerror['p_http'] = true; 
    $allok = false;
  };
  return $allok;
}

/**
* Prepares data and calls socket function to save one entry
* Send Mails to Admin(s)
*@param boolean $asnew Save as new entry (or update)
*/
function save_entry($asnew=false) {

  if (check_inputs()) {
    $prev_entry = read_entry($GLOBALS["data_dir"],$GLOBALS["p_prev"]);
    if (is_array($prev_entry)) {
      $i_path = ";".$prev_entry['PREV'].$prev_entry['PATH'];
    }
    if ($asnew) {
      $entry_data = array(
        "SUBJ"=>$GLOBALS["p_subj"],
        "NAME"=>$GLOBALS["p_name"],
        "MAIL"=>$GLOBALS["p_email"],
        "HTTP"=>$GLOBALS["p_http"],
        "DATE"=>time(),
        "PREV"=>$GLOBALS["p_prev"],
        "PATH"=>$i_path,
        "TEXT"=>check_text($GLOBALS["p_text"]));
      $entry_no = $GLOBALS["p_prev"];
    } else {     
      $entry_data = read_entry($GLOBALS["data_dir"],$GLOBALS["p_entry"]);
      $entry_data["SUBJ"] = $GLOBALS["p_subj"];
      $entry_data["NAME"] = $GLOBALS["p_name"];
      $entry_data["MAIL"] = $GLOBALS["p_email"];
      $entry_data["HTTP"] = $GLOBALS["p_http"];
      $entry_data["TEXT"] = check_text($GLOBALS["p_text"]);
      $entry_no = $GLOBALS["p_entry"];
    }
    $newentry = false; 
    switch ($GLOBALS["sck"]) {
      case "mysql" : $newentry = mysql_save_entry($GLOBALS["data_dir"],$asnew,$entry_data,$entry_no); break;
      case "pear" : $newentry = pear_save_entry($GLOBALS["data_dir"],$asnew,$entry_data,$entry_no); break;
      case "text_fast" : $newentry = fast_text_save_entry($GLOBALS["data_dir"],$asnew,$entry_data,$entry_no); break;
      default : $newentry = text_save_entry($GLOBALS["data_dir"],$asnew,$entry_data,$entry_no);
    }
    unset($GLOBALS["p_subj"]);
    unset($GLOBALS["p_text"]);
    if ((!($GLOBALS["backtoindex"])) && ($newentry)) {
      print_entry($newentry);
    } else {
      print_index();
    }
    if (chkinput($entry_data["MAIL"],"email",true)) {
      $mail_from = "From: ".$entry_data["NAME"]." <".$entry_data["MAIL"].">";
    } else {
      $mail_from = ""; 
    }    
    
    $msg_link = "http://".$GLOBALS["SERVER_NAME"].$GLOBALS["PHP_SELF_SAVE"]."?p_cmd=entry&p_entry=".$newentry;
    $mail_msg = $entry_data["SUBJ"]."\n\n".$entry_data["TEXT"]."\n\n".
      translate("Name").": ".$entry_data["NAME"]."\n".
      translate("Date").": ".date2html($entry_data["DATE"],true)."\n".
      translate("Email").": ".$entry_data["MAIL"]."\n".
      translate("Web").": ".$entry_data["HTTP"]."\n\n".
      $msg_link."\r\n";
    if (($GLOBALS["p_cmd"] == "save") || ($GLOBALS["sendchanged"])) {
      if ($GLOBALS["sendnews"]) {
        mail($GLOBALS["sendto"],$GLOBALS["sendsubj"],$mail_msg,$mail_from); 
      }    
      if ($GLOBALS["sendnews_cc"]) {
        mail($GLOBALS["sendto_cc"],$GLOBALS["sendsubj"],$mail_msg,$mail_from); 
      }
    }
  } else {
    print_new(translate("Please check you inputs."), $GLOBALS["p_subj"], $GLOBALS["p_prev"]);
  }
}

/**
* Calls socket function to delete an entry and all answers
*@param string $data_dir location of data
*@param integer $entry_nr number of entry
*@return array $result deleted
*/
function delete_entries($data_dir,$entry_nr) {
  switch ($GLOBALS["sck"]) {
    case "mysql" : $result = mysql_delete_entries($data_dir,$entry_nr); break;
    case "pear" : $result = pear_delete_entries($data_dir,$entry_nr); break;
    case "text_fast" : $result = fast_text_delete_entries($data_dir,$entry_nr); break;
    default : $result = text_delete_entries($data_dir,$entry_nr);
  }
  return $result;  
}

/**
* check date of entry newer like definied days
*@param integer $tocheck timestamp to check
*@param integer $max_days maximum days
*@return array $result newer like
*/
function check_entry_date($tocheck,$max_days) {
  return (($tocheck+($max_days * 86400)) >= time());
}

/**
* check date of thread newer like definied days
*@param integer $prev_file start entry number
*@param integer $entries_list list of entries
*@param integer $max_days maximum days
*@return array $is_new newer like
*/
function check_thread_date($prev_file, $entries_list, $max_days) {
  $is_new = check_entry_date($entries_list[$prev_file]["DATE"],$max_days);
  if (! $is_new) {
    $mainentry = $entries_list[$prev_file];
    if (is_array($mainentry["SUBS"])) {
      while (list(,$key) = each($mainentry["SUBS"])) {
        if ($is_new = check_thread_date($key, $entries_list, $max_days)) {
          break;
        }   
      }
    }
  } 
  return $is_new;
}

/**
* prints the main index view
*/
function print_index() {

  global $data_dir;
  $entries = read_entries($data_dir);
  
  if ($entries) {
    $max_entries = count($entries);
    if (!(strlen($GLOBALS["p_days"]) > 0)) {
      $GLOBALS["p_days"] = $GLOBALS["std_showentry"];
    }
    print_ctrl_header($GLOBALS["p_days"]);
    $printed = 0;
    print_thread_checked (0,$entries,1,"&nbsp;",$GLOBALS["p_days"]);
    print_counter($GLOBALS["printed"], $max_entries);
  }
  print_add_thread();
}

/**
* prints one entry in a thread list
*@param array $entry entry data
*@param integer $level indent level
*@param string $spacer level indent spacer
*@param boolean $color actual color index if color follows indent
*@param integer $nolinkentry index of actual full viewed entry
*/
function print_thread_entry($entry,$level,$spacer, $color, $nolinkentry=0) {

  global $max_entrynew, $color_1, $color_2, $printed, $colorfollow, $p_lng,
    $pic_artikel, $pic_artikel_new, $pic_artikel_sel, $file_index, $p_days, $vmax,
    $tpl_rowstart, $tpl_rowend, $tpl_rowstart_hl, $tpl_rowend_hl,
    $tpl_namestart, $tpl_nameend;

  if ($colorfollow) {
    if ($color) {
      nb_print("<tr bgcolor=\"$color_1\" valign=\"middle\">");
    } else {
      nb_print("<tr bgcolor=\"$color_2\" valign=\"middle\">");
    }
  } else {
    if (($printed % 2)) {
      nb_print("<tr bgcolor=\"$color_1\" valign=\"middle\">");
    } else {
      nb_print("<tr bgcolor=\"$color_2\" valign=\"middle\">");
    }  
  }
  for ($i=1;$i<$level;$i++) {
	nb_print("<td>$spacer</td>");
  }
  $colspan = $vmax - $level;
  if ($nolinkentry == $entry["FILE"]) {
    nb_print("<td colspan=\"$colspan\"><img src=\"$pic_artikel_sel\" border=\"0\" align=\"left\" alt=\"\">$tpl_rowstart_hl");
    nb_print(str2html($entry["SUBJ"]));
    nb_print("$tpl_namestart <nobr>".translate("by")." ".str2html($entry["NAME"])."</nobr>$tpl_nameend$tpl_rowend_hl");
  } else {
    if (check_entry_date($entry["DATE"],$max_entrynew)) {
      nb_print("<td colspan=\"$colspan\"><img src=\"$pic_artikel_new\" border=\"0\" align=\"left\" alt=\"*\">");
    } else {
      nb_print("<td colspan=\"$colspan\"><img src=\"$pic_artikel\" border=\"0\" align=\"left\" alt=\"\">");
    }
    nb_print("$tpl_rowstart<a href=\"");
    nb_print( check_link($GLOBALS["PHP_SELF_SAVE"]."?p_lng=$p_lng&p_days=$p_days&p_cmd=entry&p_entry=".$entry["FILE"]));
    nb_print("\">".str2html($entry["SUBJ"])."</a>");
    nb_print("$tpl_namestart <nobr>".translate("by")." ".str2html($entry["NAME"])."</nobr>$tpl_nameend$tpl_rowend");
  }
  nb_print("</td>\r\n<td align=\"right\">");
  nb_print("<small><nobr>(");
  nb_print(date2html($entry["DATE"]).")</nobr></small></td></tr>\r\n");
  $printed++;
}

/**
* prints actual thread level an calls itself for subthreads
*@param integer $prev_file previous entry number 
*@param array $entries_list entries list 
*@param integer $level indent level
*@param string $spacer level indent spacer
*@param boolean $color actual color index if color follows indent
*@param integer $nolinkentry index of actual full viewed entry
*@result array $entries_list2 entries list without printed entries
*/
function print_thread_list($prev_file, $entries_list, $level, $spacer, $color, $nolinkentry=0) {
  if (gettype($entries_list) == "array") {
    $mainentry = $entries_list[$prev_file];
    if (is_array($mainentry["SUBS"])) {
      while (list(,$key) = each($mainentry["SUBS"])) {
        print_thread_entry($entries_list[$key],$level,$spacer, $color, $nolinkentry);
        //unset($entries_list2[$key]);
        print_thread_list($key, $entries_list, $level+1, $spacer, !($color), $nolinkentry);
      }
    }
  }
}

/**
* optimizes list an prints thread
*@param integer $prev_file previous entry number 
*@param array $entries_list entries list 
*@param integer $level indent level
*@param string $spacer level indent spacer
*@param integer $nolinkentry index of actual full viewed entry
*/
function print_thread($prev_file, $entries_list, $level, $spacer, $nolinkentry=0) {

  global $table_width, $vmax, $printed;
  
 /*  if (gettype($entries_list) == "array") {
    $entries = optimize_data($prev_file,$entries_list);
  } */
  $entries = $entries_list;
  optimize_tree($entries);
  
  if (gettype($entries) == "array") {
    nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"100%\">\r\n");
    print_thread_entry($entries[$prev_file],1,"&nbsp;", 0, $nolinkentry);
    print_thread_list($prev_file, $entries, $level, $spacer, true, $nolinkentry);
    nb_print('</table>');
  }
}

/**
* prints all thread with an entry newer like a maximum of days
*@param integer $prev_file previous entry number 
*@param array &$entries_list pointer to entries list 
*@param integer $level indent level
*@param string $spacer level indent spacer
*@param integer $max_days maximum days
*/
function print_thread_checked($prev_file, &$entries_list, $level, $spacer, $max_days) {

  global $table_width, $pic_trenner, $vmax;
  
  $rootentries = optimize_tree($entries_list);
  if (is_array($rootentries)) {
    nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"$table_width\">\r\n");
    while (list(,$no) = each($rootentries)) {
      $is_new = check_thread_date($no, $entries_list, $max_days);
	  if ($is_new) {
	    nb_print("<tr><td colspan=\"$vmax\"><img src=\"$pic_trenner\" height=\"2\" width=\"2\" border=\"0\"></td></tr>\r\n");
	    print_thread_entry($entries_list[$no],$level,$spacer, true, $printed);
	    print_thread_list($no, $entries_list, $level+1, $spacer, false);
      }  
    }
    nb_print("</table>\r\n\r\n");
  }
}

/**
* prints a form and a combobox to select the time period
*@param integer $daycount actual diplayed time period 
*/
Function print_ctrl_header($daycount) {

  global $max_entrynew, $table_width, $file_index, $daycounts, $pic_refresh,
    $pic_trenner, $pic_artnew;
    
  nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"$table_width\"><tr><td align=\"right\">\r\n");
  nb_print("<form action=\"".check_link($GLOBALS["PHP_SELF_SAVE"])."\" method=\"post\">\r\n");
  nb_print("<input type=\"hidden\" name=\"p_lng\" value=\"".$GLOBALS["p_lng"]."\">");
  nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\">\r\n");
  nb_print("<tr>");
  nb_print("<td><b>".translate("Displayed period").":</b> \r\n");
  nb_print("<select name=\"p_days\">\r\n");
  while (list($key, $val) = each($daycounts)) {
    if ($key == $daycount) {
      nb_print("<option value=\"$key\" selected>".translate($val)."</option>\r\n");
        } else {
      nb_print("<option value=\"$key\">".translate($val)."</option>\r\n");
        }
  }
  nb_print("</select></td><td rowspan=\"2\">&nbsp;&nbsp;</td>\r\n");
  nb_print("<td rowspan=\"2\"><input type=\"image\" src=\"$pic_refresh\" alt=\"".translate("Refresh")."\" border=\"0\"></td></tr>\r\n");
  nb_print("<tr><td>(<img src=\"$pic_artnew\" border=\"0\" alt=\"*\">
    ".translate("= new entry (max %s days old)",array($max_entrynew)).")</td></tr>\r\n");
  nb_print("</table></form>\r\n");
  nb_print("</td></tr>\r\n");
  nb_print("</table>\r\n");

}

/**
* prints the counted entries an the count of all entries
*@param integer $e_printed printed entries
*@param integer $e_all all entries 
*/
function print_counter($e_printed, $e_all) {
  nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"".$GLOBALS["table_width"]."\"><tr><td align=\"right\">\r\n");
  nb_print(translate("Showing %s of %s entries total.", array((integer)$e_printed,$e_all)));
  nb_print("</td></tr>\r\n");
  nb_print("</table>\r\n");
  nb_print("<br clear=\"all\">\r\n");

}

/**
* prints some pictures to navigate on the page an in the thread
*@param integer $i_entrynr viewed entry
*@param integer $i_prevnr previous entry 
*@param integer $i_days time period 
*@param string $alt_write alt text for the local link to the form
*@param string $i_lng actual language
*/
function print_thread_navigation($i_entrynr,$i_prevnr,$i_days,$alt_write,$i_lng) {
  global $pic_printer, $pic_moveup, $pic_moveall, $pic_makenew;
  nb_print("<a href=\"");
  nb_print( check_link($GLOBALS["PHP_SELF_SAVE"]."?p_lng=$i_lng&p_cmd=print&p_days=$i_days&p_entry=$i_entrynr"));
  nb_print("\" target=\"_self\"><img src=\"$pic_printer\" border=\"0\" align=\"right\"alt=\"".translate("Print view")."\"></a>
  ");
  if ($i_prevnr > 0) {
    nb_print("<a href=\"");
    nb_print( check_link($GLOBALS["PHP_SELF_SAVE"]."?p_lng=$i_lng&p_cmd=entry&p_days=$i_days&p_entry=$i_prevnr"));
    nb_print("\"><img src=\"$pic_moveup\" border=\"0\" align=\"right\" alt=\"".translate("Parent entry")."\"></a>");
  }
  nb_print("<a href=\"");
  nb_print(check_link($GLOBALS["PHP_SELF_SAVE"]."?p_lng=$i_lng&p_days=$i_days"));
  nb_print("\"><img src=\"$pic_moveall\" border=\"0\" align=\"right\"alt=\"".translate("Forum mainpage")."\"></a>");
  nb_print("<a href=\"");
  nb_print( check_link($GLOBALS["PHP_SELF_SAVE"]."?p_lng=$i_lng&p_cmd=entry&p_days=$i_days&p_entry=$i_entrynr"));
  nb_print("#write\"><img src=\"$pic_makenew\" border=\"0\" align=\"right\" alt=\"$alt_write\"></a>");
}

/**
* prints the error sign if error var is set
*@param string $paramname paramname
*@param string error sign or empty form
*/
function printErrorSign($paramname) {
  if (isset($GLOBALS['nb_inputerror'][$paramname])) {
    return $GLOBALS['tpl_errorsign'];
  } else {
    return '&nbsp;';
  }
}

/**
* prints the form for a new entry/answer
*@param string $new_caption form caption
*@param string $new_subj entry subject default
*@param string $new_prev previous entry 
*@param boolean $adm_edit admin mode (show delete form)
*/
function print_new($new_caption, $new_subj, $new_prev, $adm_edit = false) {

  global $table_width, $pic_makenew, 
    $pic_delete, $p_entry, $p_days,	$p_pass;

  nb_print("<a name=\"write\"></a>");
  nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"$table_width\">\r\n");
  nb_print("<tr>");
  if ($GLOBALS["lcol_show"]) {
    nb_print("<td width=\"".$GLOBALS["lcol_width"]."\"><img src=\"$pic_makenew\" border=\"0\"></td>\r\n");
  }
  nb_print("<td>\r\n");
  nb_print("<form action=\"".check_link($GLOBALS["PHP_SELF_SAVE"])."\" method=\"POST\">\r\n");
  if (!($adm_edit)) {
    nb_print("<input type=\"hidden\" name=\"p_cmd\" value=\"save\">\r\n");
  } else {
    nb_print("<input type=\"hidden\" name=\"p_cmd\" value=\"admin\">\r\n");
    nb_print("<input type=\"hidden\" name=\"p_subcmd\" value=\"edit\">\r\n");
    nb_print("<input type=\"hidden\" name=\"p_entry\" value=\"$p_entry\">\r\n");
    nb_print("<input type=\"hidden\" name=\"p_pass\" value=\"$p_pass\">\r\n");
  }
  nb_print("<input type=\"hidden\" name=\"p_prev\" value=\"$new_prev\">\r\n");
  nb_print("<input type=\"hidden\" name=\"p_days\" value=\"$p_days\">\r\n");
  nb_print("<input type=\"hidden\" name=\"p_lng\" value=\"$p_lng\">\r\n");
  nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\">\r\n");
  nb_print("<tr><td colspan=\"3\"><b> $new_caption :</b><br><br></td>");
  nb_print("</tr>\r\n");
  nb_print("<tr><td>".translate("Subject").":</td><td><input type=\"text\" size=\"".$GLOBALS["tpl_sizeinput"]."\" maxlength=\"50\" name=\"p_subj\" value=\"$new_subj\"></td><td>".printErrorSign('p_subj')."</td></tr>\r\n");
  nb_print("<tr><td>".translate("Name").":</td><td><input type=\"text\" size=\"".$GLOBALS["tpl_sizeinput"]."\" maxlength=\"50\" name=\"p_name\" value=\"".$GLOBALS["p_name"]."\"></td><td>".printErrorSign('p_name')."</td></tr>\r\n");
  nb_print("<tr><td>".translate("Email").":</td><td><input type=\"text\" size=\"".$GLOBALS["tpl_sizeinput"]."\" maxlength=\"60\" name=\"p_email\" value=\"".$GLOBALS["p_email"]."\"></td><td>".printErrorSign('p_email')."</td></tr>\r\n");
  if (!$GLOBALS['hide_wwwinput']) { 
    nb_print("<tr><td>".translate("Web").":</td><td><input type=\"text\" size=\"".$GLOBALS["tpl_sizeinput"]."\" maxlength=\"60\" name=\"p_http\" value=\"".$GLOBALS["p_http"]."\"></td><td>".printErrorSign('p_http')."</td></tr>\r\n");
  }
  nb_print("<tr valign=\"top\"><td>".translate("Entry").":</td><td><textarea cols=\"".$GLOBALS["tpl_colstextarea"]."\" rows=\"".$GLOBALS["tpl_rowstextarea"]."\" name=\"p_text\" maxlength=\"50\">".$GLOBALS["p_text"]."</textarea></td><td>".printErrorSign('p_text')."</td></tr>\r\n");
  nb_print("<tr><td align=\"right\" colspan=\"2\"><input type=\"submit\" value=\"".translate("Save")."\" ></td><td>&nbsp;</td></tr>\r\n");
  nb_print("</table>\r\n");
  nb_print("</form>\r\n");
  nb_print("</td>\r\n");
  if ($adm_edit) {
    print_delete();
  }
  nb_print("</tr></table>\r\n");
}

/**
* print a entry in full view an it´s answers
*@param integer $entrynr numer of entry
*/
function print_entry($entrynr) {

  global $p_days, $data_dir, $pic_artone, $pic_artmore, $pic_artnew, $pic_moveall, $pic_moveup, 
    $pic_printer, $file_index, $max_entrynew, $table_width, $lcol_width, $printed;
  
  $entries = read_entries($data_dir);
  $entry = read_entry($data_dir,$entrynr);
  $text_out = nl2br($entry["TEXT"]);
  $text_out = eregi_replace("<br>"," <br>",$text_out);
  $text_out = eregi_replace("([[:alnum:]]+)://([^[:space:]'\"]*)([[:alnum:]#?/&=])", 
"<a href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $text_out); 
  $text_out = str2html($text_out, false, false);
  $link_out = $entry["HTTP"];
  if (! ereg("^http://",$link_out)) { $link_out = "http://".$link_out; }
    nb_print("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"$table_width\">\r\n");
  nb_print("<tr>");
  if ($GLOBALS["lcol_show"]) {
    nb_print("<td width=\"$lcol_width\" rowspan=\"3\"><img src=\"$pic_artone\" border=\"0\"></td>\r\n");
  }
  nb_print("<td>");
  if ($GLOBALS["navontop"]) {
    print_thread_navigation($entrynr,$entry["PREV"],$p_days,translate("Write an answer"),$GLOBALS["p_lng"]);
  }
  nb_print("<b>".str2html($entry["SUBJ"])."</b></td></tr>\r\n");
  nb_print("<tr><td><p>".$text_out."</p></td></tr>\r\n");
  nb_print("<tr><td><br><table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"left\">");
  nb_print( "<tr><td><small>".translate("Name").":</small></td><td><small>".str2html($entry["NAME"])."</small></td>");
  nb_print("<tr><td><small>".translate("Email").":</small></td><td><small><a href=\"mailto:".$entry["MAIL"]."\">".$entry["MAIL"]."</a></small></td>");
  nb_print( "<tr><td><small>".translate("Date").":</small></td><td><small>".date2html($entry["DATE"],true)."</small></td>");
  if (!$GLOBALS['hide_wwwinput']) { 
    nb_print("<tr><td><small>".translate("Web").":</small></td><td><small><a href=\"".$link_out."\" target=\"_top\">".$entry["HTTP"]."</small>");
  }
  nb_print("</td></tr>\r\n");
  nb_print("</table><br clear=\"all\">\r\n");
  nb_print("</td></tr>\r\n");
  nb_print("<tr>");
  if ($GLOBALS["lcol_show"]) {
    nb_print("<td width=\"$lcol_width\" rowspan=\"2\"><br><img src=\"$pic_artmore\" border=\"0\"></td>\r\n");
  }
  nb_print("<td colspan=\"2\"><br>");
  if ($GLOBALS["navonbottom"]) {
    print_thread_navigation($entrynr,$entry["PREV"],$p_days,translate("Write an answer"),$GLOBALS["p_lng"]);
  }
  nb_print("(<img src=\"$pic_artnew\" border=\"0\"> ".translate("= new entry (max %s days old)",array($max_entrynew)).")");
  nb_print("</td></tr>\r\n");
  nb_print("<td>");
  $printed = 0;
  if ($entry['PREV'] > 0) {
    $prevs = explode(";",$entry["PATH"]);
    $firstno = end($prevs);
    $firstno = prev($prevs);
    if ($firstno > 0) {
      print_thread($firstno, $entries, 2, "&nbsp;" , $entrynr);
    } else {
      print_thread($entry['PREV'], $entries, 2, "&nbsp;", $entrynr);
    }
  } else {
    print_thread($entrynr, $entries, 2, "&nbsp;", $entrynr);
  }
  if ($printed == 0) {
    nb_print("<br>".translate("No answers to this entry."));
  }
  nb_print("</td></tr>\r\n");
  nb_print("</table><br clear=\"all\">\r\n");

  $new_subj = str2html($entry["SUBJ"]);
  if (!(eregi("^Re:",$new_subj))) {
    $new_subj = "Re: $new_subj";
  }
  print_new(translate("Write an answer"),$new_subj,$entry["FILE"]);
  
  print_login($entry["FILE"]);
}

/**
* prints full entry optimized for printer
*@param integer $entry_nr numer of entry
*/
function printview($entry_nr) {

  global $data_dir, $file_index, $p_days;

  $entries = read_entries($data_dir);
  if ($entries) {
    $entry = read_entry($data_dir,$entry_nr);
	$e_name = str2html($entry["NAME"]);
	$e_mail = $entry["MAIL"];
	$e_http = $entry["HTTP"];
	$e_subj = str2html($entry["SUBJ"]);
	$e_date = date2html($entry["DATE"],true);
	$e_text = nl2br(str2html($entry["TEXT"],false));
	nb_print("
	  <table align=\"center\" width=\"600\">
	  <tr>
	    <th align=\"left\">$e_subj</th>
	  </tr>
	  <tr>
	    <td><hr noshade size=\"1\">
		  <table border=\"0\" align=\"left\" cellpadding=\"3\" cellspacing=\"0\">
		  <tr>
		    <td>".translate("Name").":</td><td>$e_name</td>
		  </tr>
		  <tr>
		    <td>".translate("Email").":</td><td>$e_mail</td>
		  </tr>
      ");
    if (!$GLOBALS['hide_wwwinput']) { 
      nb_print("  
		  <tr>
		    <td>".translate("Web").":</td><td>$e_http</td>
		  </tr>");
    }
    nb_print("
		  </table>
		</td>
	  </tr>
	  <tr>
	    <td><br>
		  <p align=\"justify\">
		    $e_text
		  </p>
		</td>
	  </tr>
	  <tr>
	    <td align=\"center\"><hr noshade size=\"1\">
 	      <a href=\"".check_link($GLOBALS["PHP_SELF_SAVE"]."?p_days=$p_days&p_cmd=entry&p_entry=$entry_nr")."\">".translate("Back")."</a>
		</td>
	  </tr>
	  </table>
	");
  }
}

/**
* prints admin login form
*@param integer $entry_nr numer of entry
*/
function print_login($entry_nr) {

  global $file_index, $pic_pass, $adminmode, $table_width, $p_entry, $p_days;
  
  if ($adminmode) {
    nb_print("
	  <br clear=\"all\">
	  <table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" align=\"center\" width=\"$table_width\">
      <tr><td align=\"right\">
      <form action=\"".check_link($GLOBALS["PHP_SELF_SAVE"])."\" method=\"post\">
	  <input type=\"hidden\" name=\"p_cmd\" value=\"admin\">
	  <input type=\"hidden\" name=\"p_entry\" value=\"$entry_nr\">
	  <input type=\"hidden\" name=\"p_prev\" value=\"$p_entry\">
	  <input type=\"hidden\" name=\"p_days\" value=\"$p_days\">
	  <nobr>
	  ".translate("Admin").":
	  <input type=\"password\" size=\"8\" maxlength=\"15\" name=\"p_pass\">
	  <input type=\"image\" src=\"$pic_pass\" border=\"0\" align=\"absmiddle\">
	  </nobr>
      </form>
	  </td></tr>
	  </table>
    ");
  }
}

/**
* prints admin view
*@param boolean $loadentry load entry or apply post params from form
*/
Function print_admin($loadentry=true) {

  global $p_subj, $p_name, $p_mail, $p_web, $p_text, $p_prev, $p_entry,
    $data_dir;
    
  nb_print("<div align=\"center\"><h3>".translate("Admin Mode")."</h3></div>");
  
  $entry = read_entry($data_dir, $p_entry);
  $p_prev=$entry["PREV"];
  
  if ($loadentry) {
    $p_name=str2html($entry["NAME"]);
    $p_mail=$entry["MAIL"];
    $p_web=$entry["HTTP"];
    $p_subj=str2html($entry["SUBJ"]);
    $p_text= str2html(str_replace("<br>","\r\n",$entry["TEXT"]),false,false);  
  }
  
  print_new(translate("Change entry"),$p_subj,$p_prev,true);
}

/**
* prints delete form for admin view
*/
function print_delete() {

  nb_print("<th valign=\"top\">  
	<nobr><b>".translate("Delete")." :</b></nobr><br><br>
	<form action=\"".check_link($GLOBALS["PHP_SELF_SAVE"])."\" method=\"POST\">
    <input type=\"hidden\" name=\"p_cmd\" value=\"admin\">
	<input type=\"hidden\" name=\"p_subcmd\" value=\"delete\">
	<input type=\"hidden\" name=\"p_entry\" value=\"".$GLOBALS["p_entry"]."\">
	<input type=\"hidden\" name=\"p_prev\" value=\"".$GLOBALS["p_prev"]."\">
	<input type=\"hidden\" name=\"p_days\" value=\"".$GLOBALS["p_days"]."\">
	<input type=\"hidden\" name=\"p_pass\" value=\"".$GLOBALS["p_pass"]."\">
	<div align=\"left\">
	<input type=\"checkbox\" name=\"p_delcheck\" value=\"1\">
	".translate("Yes! Delete this entry and all answers.")."
	</div> <br>
    <input type=\"image\" src=\"".$GLOBALS["pic_delete"]."\" border=\"0\"></th>
	</form>\r\n");

} 

/**
* prints form for a new entry
*/
function print_add_thread() {
  print_new(translate("Write a new entry"),"","");
}

/**
* saves user data(name, email homepage) in a cookie
*@access public
*/
function netzbrett_cookies() {
  global $c_netzbrett,$p_name,$p_email,$p_http;
  if ($GLOBALS["usercookie"]) {
    if ($GLOBALS["p_cmd"] == "save") {
      $c_netzbrett = "$p_name|||$p_email|||$p_http";
      setcookie("c_netzbrett",$c_netzbrett,time()+(86400*$GLOBALS["usercookiedays"]));  
    } else {
      if (!(isset($p_name) || ($p_cmd == 'admin'))) {
        list($p_name,$p_email,$p_http) = explode("|||",$c_netzbrett);
      }
    }
  } 
}

/**
* prints the last entry(short view) with a link to the forum
*@param string $link url to the forum
*@access public
*/
function netzbrett_last($link) {

  $GLOBALS["nb_output_buffer"] = "";
  switch ($GLOBALS["sck"]) {
    case "mysql" : $entry = mysql_read_lastentry($GLOBALS["data_dir"]); break;
    case "pear" : $entry = pear_read_lastentry($GLOBALS["data_dir"]); break;
    case "text_fast" : $entry = fast_text_read_lastentry($GLOBALS["data_dir"]); break;
    default : $entry = text_read_lastentry($GLOBALS["data_dir"]);
  }
  if ($entry) {
    $short_text = $entry["TEXT"];
    if (strlen($short_text) > 230) {
      ereg(".{229}[^\n\r ]*","$short_text ",$found);
      $short_text = $found[0];
    }
    nb_print(date2html($entry["DATE"])." - <i>".$entry["NAME"].":</i><br>");
    nb_print("<b><a href=\"");
    nb_print( check_link($link."?p_cmd=entry&p_entry=".$entry["FILE"])."\">".$entry["SUBJ"]."</a></b> - ".$short_text);
  }
  return $GLOBALS["nb_output_buffer"];
} 

/**
* Output
* param string $str
*/
function nb_print($str) {
  if ($GLOBALS["nb_direct_output"]) {
    echo $str;
  } else {
    $GLOBALS["nb_output_buffer"] .= $str;
  }
}

?>
