<?PHP

// some function to power my small guestbook

/*

    This file was written by Thorsten Gunkel <tgunkel@gmx.de> for
    his guestbook on <url:http://www.tgunkel.de>.
    Copyright (C) 2004 Thorsten Gunkel

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation version 2 of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

//calc threat depth of an entry by counting the number of '_' its filename
function thread_depth($string)
{
  return 
substr_count($string,"_");
}


// read a file into an array and replace linebreaks
function file_read($name)
{
  
$lines=array();
  
$fp = @fopen($name"r");
  while (
$line fgets($fp1024))
    {
      
//$line = preg_replace('/\r\n|\r|\n/', '', $line);
      
$line=replace_line_break($line,'');
      
$lines[]=$line;
    }
  
fclose($fp);
  return 
$lines;
}

//get a list of all files in a directory which names match symbol_NR.png
function symbol_list($config)
{
  
$dp opendir($config['picsdatapath']);
  
$dateien = array();
  while(
$datei readdir($dp))
      {
    
// symbol_1234.png
    
if (preg_match('/^symbol_\d\d\d\d\.png$/'$datei))
      {
        
$dateien[] = $datei;
      }
      }
  
closedir($dp);
  
sort($dateien);
  return 
$dateien;
}


//get a of all files in a directory which names match text_NR_NR_NR....txt
function file_list($config)
{
  
$letzteaenderung=0;
  
$dp opendir($config['savedatapath']);
  
$dateien = array();
  while(
$datei readdir($dp))
      {
    
// text_1234_1234.txt
    
if (preg_match('/^text(_\d\d\d\d)*\.txt$/'$datei))
      {
        
$dateien[count($dateien)] = $datei;
        
// Letzte Aenderung bestimmen
        
access_lastmod("update","global","",$config['savedatapath']."/".$datei);
      }
      }
  
closedir($dp);
  
sort($dateien);
  return 
$dateien;
}

//get a sting that contains a nr (multiple chars wide) and do nr+1;
function string_succ($string)
{
  
$wert=array();
  
// split string to array
  
$i1=0;
  while (
preg_match('/\d/',substr($string,$i1,1)))
    {
      
$wert[$i1]=substr($string,$i1,1);
      
$i1=$i1+1;
    }
  
$string="";
  
//add 1 to most most left nr
  
$wert[count($wert)-1]++;
  for (
$i1=count($wert)-1$i1>=0$i1--)
    {
      
//shift 1 to left
      
if ($wert[$i1]>9)
    {
      
//overflow?
      
if ($i1>0)
        {
          
$wert[$i1]=0;
          
$wert[$i1-1]++;
        }
      else
        {
          
$wert[0]="x";
        }
    }
      
//rebuild string
      
$string=$wert[$i1].$string;
    }
  return 
$string;
}

//calculate a new file name
function file_newname($fname,$config)
{
  
$dateien=file_list($config);
  
//test if name is a valid one and calc prefix of name
  
if (preg_match('/^text(_\d\d\d\d)*\.txt$/'$fname))
    {
      
$pre=preg_replace('/\.txt$/','_',$fname);
    }
  else
    {
      
$pre="text_";
    }
  
$nr_max="0000";
  for (
$i1=0$i1 count($dateien); $i1++)
    {
      if (
preg_match("/^$pre\d\d\d\d(_\d\d\d\d)*\.txt/"$dateien[$i1]))
    {
      
$nr_tmp=preg_replace("/^$pre/",'',$dateien[$i1]);
      
$nr_tmp=preg_replace('/(_\d\d\d\d)*\.txt$/','',$nr_tmp);
      if (
$nr_max<$nr_tmp$nr_max=$nr_tmp;
    }
    }
  
$nr_max=string_succ($nr_max);
  if (
preg_match("/\d\d\d\d/"$nr_max))
    {
      return 
$pre.$nr_max.".txt";
    }
  else
    {
      return 
"";
    }
}

// check all parameters, saves and mails them
function save_comment($f_fname$f_name$f_symbol$f_email$f_url$f_comment$f_spamcheck$config)
{
  
$result=false;
  
$f_name=my_nl2br($f_name);      $f_name=htmlspecialchars($f_name);        $f_name=substr($f_name030);
  
$f_email=my_nl2br($f_email);    $f_email=htmlspecialchars($f_email);      $f_email=substr($f_email030);
  
$f_url=my_nl2br($f_url);        $f_url=htmlspecialchars($f_url);          $f_url=substr($f_url0100);
  
$f_comment=htmlspecialchars($f_comment);
  
$f_comment=my_nl2br($f_comment);
  
$f_comment=substr($f_comment0500);
  
// enforce valid symbol nr
  
$f_symbol=(int)$f_symbol;
  if (((
$f_symbol<0) || ($f_symbol>=count(symbol_list($config)))) ||
      ((
$f_symbol<1) && (!session_is_admin())))
    {
      
$f_symbol=1;
    }
  if (
thread_depth(file_newname($f_fname,$config))<=$config['threadmaxdepth'])
    {
      
$destfile=$config['savedatapath'].file_newname($f_fname,$config);
      if (
$destfile!="")
        {
                 if(
$f_spamcheck!=17)
                 {
                  
header("HTTP/1.0 403 Spambot Forbidden");                  
                  
/*
                  mail ($config['destmailaddress'], "Spammer Gaestebucheintrag", "--------
Name:        $f_name\n
Email:       $f_email\n
Homepage:    $f_url\n
Sender-IP:   $_SERVER[REMOTE_ADDR]\n
Sender-Host: $_SERVER[REMOTE_HOST]\n
Kommentar:   $f_comment\n
-----");
                 */
                 
}
                 else
                 {
          
$fp=fopen($destfile,"w");
          
fwrite($fp$f_name."\n");
          
fwrite($fp$f_email."\n");
          
fwrite($fp$f_url."\n");
          
fwrite($fp$f_symbol."\n");
          
fwrite($fpdate("d.m.Y")."\n");
          
fwrite($fp$_SERVER["REMOTE_ADDR"]."\n");
          
fwrite($fp$_SERVER["REMOTE_HOST"]."\n");
          
fwrite($fp$f_comment."\n");
          
fclose($fp);
          
mail ($config['destmailaddress'], "Gaestebucheintrag""--------
Name:        $f_name\n
Email:       $f_email\n
Homepage:    $f_url\n
Sender-IP:   $_SERVER[REMOTE_ADDR]\n
Sender-Host: $_SERVER[REMOTE_HOST]\n
Kommentar:   $f_comment\n
-----"
);
                  
$result=true;
        }
               }
    }
 return 
$result;
}

// resort the files if one was deleted
function file_resort($config)
{
  
$resort_txt="";
  
//check each possible thread depth
  
for ($i1=0$i1<$config['threadmaxdepth']; $i1++)
    {
      
//echo "Thread: ",$i1+1,"<br />";
      //get thread pretext
      
$threadtxt="'^text";
      for (
$i2=0$i2<$i1$i2++)
    {
      
$threadtxt .='_\d\d\d\d';
    }
      
//$threadtxt .="'";
      
$dateien=file_list($config);
      
//list all of the current thread depth
      
$nr_pre="0000";
      
$matches_pre="";
      for (
$i3=0$i3<count($dateien); $i3++)
    {
      if (
preg_match($threadtxt."_\d\d\d\d'"$dateien[$i3]))
        {
          
//echo $nr_pre," ",$dateien[$i3],"<br />";
          //Reset nr?
          //left part is different
          
preg_match($threadtxt."'"$dateien[$i3],$matches_now);
          if (
$matches_pre!=$matches_now)
        {
          
$nr_pre="0000";
        }
          
$matches_pre=$matches_now;
          
//id in the current thread depth
          
$nr_now=preg_replace($threadtxt."_'" ,''$dateien[$i3]);
          
$nr_now=preg_replace('/.txt$/' ,''$nr_now);
          
$nr_now=preg_replace('/_.*$/' ,''$nr_now);
          
//has the id changed?
          
if ($nr_pre!=$nr_now)
        {
          
//is the id the next possible one?
          
if (string_succ($nr_pre)==$nr_now)
            {
              
$nr_pre=$nr_now;
            }
          else
            {
              
//How has the name to change?
              
preg_match($threadtxt."'"$dateien[$i3], $matches);
              
$pretext="'".$matches[0]."_".$nr_now."'";
              
$posttext=$matches[0]."_".string_succ($nr_pre);
              
//Move files down
              
for ($i4=0$i4<count($dateien); $i4++)
            {
              if (
preg_match($pretext$dateien[$i4]))
                {
                  if (!
file_exists($config['savedatapath'].preg_replace($pretext,$posttext,$dateien[$i4])))
                {
                  
rename($config['savedatapath'].$dateien[$i4],$config['savedatapath'].preg_replace($pretext,$posttext,$dateien[$i4]));
                }
                  else
                {
                  
$resort_txt.="Error on resort!";
                }
                }
            }
              
$dateien=file_list($config);
              
$nr_pre=string_succ($nr_pre);
            }
        }
        }
    }
    }
  return 
$resort_txt;
}

//remove a file
function file_remove($name,$config)
{
  if (
session_is_admin())
    {
      
$dateien=file_list($config);
      
$i1=0;
      while ((
$i1<count($dateien)) && $name!=$dateien[$i1])
    {
      
$i1++;
    }
      if ((
$name!="") && $name==$dateien[$i1])
    {
      
$name=$config['savedatapath'].$dateien[$i1];
      
$lines=file_read($config['savedatapath'].$dateien[$i1]);
      
$line=$name."\n";
      for (
$i1=0$i1<count($lines); $i1++)
        {
          
$line.=$lines[$i1]."\n";
        }
      
unlink($name);
      
mail($config['destmailaddress'], "Gaestebucheintrag geloescht"$line);
      echo 
file_resort($config);
    }
    }
}

// function to replace @ with a picture (for spam protection)
function replace_at_with_pic($txt)
{
  
$txt=preg_replace('/@/','<img src="./pics/at" alt="@" title="@" />',$txt);
  return 
$txt;
}

?>