<?php
/*Skrypt pochodzi z książki "PHP. 101 praktycznych skryptów"
  autor: Marcin Lis                    http://marcinlis.com*/

$ile = 2;
$rek_size = 5;

function removeTags($str)
{
  return htmlentities($str);
}

function skipRekord($fp, $rek_size)
{
  for($i = 0; $i < $rek_size; $i++){
    fgets($fp);
    if(feof($fp)){
      return false;
    }
  }
  return true;
}

function readGuestBook($from, $ile, $rek_size)
{
  $contents = "";
  if(($fp = fopen("guestbook.txt", "r")) === false)
    return false;
  for($i = 0; $i < $from; $i++){
    if(!skipRekord($fp, $rek_size))
      break;
  }
  for($i = $from * $rek_size; $i < ($from + $ile) * $rek_size; $i++){
    if(feof($fp)){
      break;
    }
    $tempStr = fgets($fp);
    $contents .= $tempStr."<br />";
  }
  fclose($fp);
  return trim($contents);
}

function addToGuestBook($imie, $nazwisko, $email, $contents)
{
  if(($fp = @fopen("guestbook.txt", "r")) === false)
    return false;

  $imie = removeTags($imie);
  $nazwisko = removeTags($nazwisko);
  $email = removeTags($email);
  $contents = removeTags($contents);

  $tempC = fread($fp, filesize("guestbook.txt"));
  fclose($fp);
  $fp = fopen("guestbook.txt", "w");
  fputs($fp, $imie."\r\n");
  fputs($fp, $nazwisko."\r\n");
  fputs($fp, $email."\r\n");
  fputs($fp, $contents."\r\n");
  fputs($fp, "\r\n");
  fputs($fp, $tempC);
  fclose($fp);
}

if(isSet($_GET["from"])){
  $from = $_GET["from"];
}
else{
  $from = 0;
}

if($from <= 0){
  $from = 0;
  $prev = 0;
  $next = $ile;
}
else{
  $prev = $from - $ile;
  $next = $from + $ile;
}

if(isSet($_POST["imie"])){
  $imie = $_POST["imie"];
}
else{
  $imie = "";
}

if(isSet($_POST["nazwisko"])){
  $nazwisko = $_POST["nazwisko"];
}
else{
  $nazwisko = "";
}

if(isSet($_POST["email"])){
  $email = $_POST["email"];
}
else{
  $email = "";
}

if(isSet($_POST["contents"])){
  $contents = $_POST["contents"];
}
else{
  $contents = "";
}

if($imie == "" && $nazwisko == ""
   && $email == "" && $contents == ""){
  $tempStr = readGuestBook($from, $ile, $rek_size);
  if($tempStr == "" || $tempStr == "\r\n"){
    echo("Koniec wpisów"."<br />");
    $next -= $ile;
  }
  else{
    echo($tempStr);
  }
}
else{
  addToGuestBook($imie, $nazwisko, $email, $contents);
  echo(readGuestBook($from, $ile, $rek_size));
}

$code = <<<TEMP
<a href="guestbook.php?from=$prev">Poprzednie</a> 
<a href="guestbook.php?from=$next">Następne</a>
TEMP;
echo("$code");
?>
