<?php
/******************************************************************************
* my little guestbook                                                         *
* Copyright (C) 2007 mylittlehomepage.net                                     *
* http://mylittlehomepage.net/                                                *
******************************************************************************/

/*******************************************************************************
* 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, either version 3 of the License, or            *
* (at your option) any later version.                                          *
*                                                                              *
* 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, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************/

// Settings:

// Name of guestbook:
$settings['guestbook_title'] = 'G&auml;stebuch';

// Administration password:
$settings['admin_password'] = 'admin';
#$settings['admin_password'] = '21232f297a57a5a743894a0e4a801fc3'; // md5

// Method with that the password is encoded
// (e.g. md5, sha1 or base64_encode; empty if not encoded):
$settings['admin_password_encodation'] = '';

// File in which the entries will be saved (requires CHMOD 666):
$settings['data_file'] = 'gaestebuch.dat';

// How many entries per page?
$settings['entries_per_page'] = 10;

// Admin E-mail for notifications (optional):
$settings['admin_email'] = '';

// BB-Codes on?
$settings['bbcode'] = true;

// Make links clickable:
$settings['autolink'] = true;

// Block IP address after made entry for how many minutes (0=off):
$settings['block_ip'] = 3;

// Length limitations:
$settings['name_maxlength'] = 40;
$settings['name_word_maxlength'] = 25;
$settings['email_hp_maxlength'] = 50;
$settings['location_maxlength'] = 40;
$settings['location_word_maxlength'] = 25;
$settings['text_maxlength'] = 3000;
$settings['text_minlength'] = 5;
$settings['text_word_maxlength'] = 50;

// If you want to use smilies you can define them here (comment out or delete
// these lines if not used):
$smilies[0]['code'] =  ':-)';
$smilies[0]['image'] = 'smilies/smile.png';
$smilies[1]['code'] =  ';-)';
$smilies[1]['image'] = 'smilies/wink.png';
$smilies[2]['code'] =  ':-D';
$smilies[2]['image'] = 'smilies/biggrin.png';
$smilies[3]['code'] =  ':-P';
$smilies[3]['image'] = 'smilies/tongue.png';
$smilies[4]['code'] =  ':-|';
$smilies[4]['image'] = 'smilies/neutral.png';
$smilies[5]['code'] =  ':-(';
$smilies[5]['image'] = 'smilies/frown.png';

// Language settings:
$lang['lang'] =                     'de';
$lang['charset'] =                  'iso-8859-1';
$lang['locale'] =                   array('de', 'de_DE@euro', 'deu');
$lang['time_format'] =              "%d. %B %Y, %H:%M";
$lang['new_entry'] =                'neuer Eintrag';
$lang['back'] =                     'zur�ck';
$lang['preview'] =                  'Vorschau';
$lang['bold_button'] =              'fett';
$lang['bold_button_title'] =        'fett formatieren: [b]text[/b]';
$lang['italic_button'] =            'kursiv';
$lang['italic_button_title'] =      'kursiv formatieren: [i]text[/i]';
$lang['link_button'] =              'Link';
$lang['link_button_title'] =        'Link einf�gen: [link=http://example.com/]Linktext[/link]';
$lang['insert_link_text'] =         'Linktext (optional):';
$lang['insert_link_url'] =          'Link-Adresse (URL):';
$lang['insert_smiley'] =            'Smiley einf�gen';
$lang['error'] =                    'Fehler:';
$lang['optional'] =                 '(optional)';
$lang['optional_email_hp'] =        '(optional, E-Mail wird nicht angezeigt)';
$lang['name'] =                     'Name:';
$lang['email_hp'] =                 'E-Mail oder Homepage:';
$lang['location'] =                 'Ort:';
$lang['message'] =                  'Nachricht:';
$lang['comment'] =                  'Kommentar:';
$lang['spam_protection'] =          'Spam-Schutz:';
$lang['spam_protection_sum'] =      'Bitte die beiden Zahlen addieren:';
$lang['password'] =                 'Passwort:';
$lang['password_wrong'] =           'Passwort falsch!';
$lang['submit_button'] =            'OK - Eintragen';
$lang['preview_button'] =           'Vorschau';
$lang['error_no_name'] =            'kein Name';
$lang['error_no_text'] =            'keine Nachricht';
$lang['error_email_hp_invalid'] =   'E-Mail/Homepage ung�ltig';
$lang['error_email_hp_too_long'] =  'E-Mail/Homepage zu lang';
$lang['error_text_too_long'] =      'Nachricht zu lang ([characters] Zeichen) - nur [max_characters] Zeichen m�glich';
$lang['error_text_too_short'] =     'Nachricht zu kurz';
$lang['error_word_too_long'] =      'Das Wort "[word]" ist zu lang';
$lang['error_already_made_entry'] = 'Es ist gerade ein Eintrag von der selben IP-Adresse gemacht worden - bitte kurz warten.';
$lang['error_spam'] =               'Spam-Schutz: Summe falsch';
$lang['error_invalid_request'] =    'Ung�ltige anfrage';
$lang['admin_login'] =              'Admin Login';
$lang['admin_logout'] =             'Log out';
$lang['log_in'] =                   'Log in';
$lang['edit_link'] =                'bearbeiten';
$lang['delete_link'] =              'l�schen';
$lang['delete_confirm'] =           'Eintrag l�schen?';
$lang['previous_page'] =            'vorige Seite';
$lang['next_page'] =                'n�chste Seite';
$lang['no_entries_yet'] =           'Es sind noch keine Eintr�ge vorhanden.';
$lang['mail_subject'] =             'Neuer G�stebuch-Eintrag';

##############################################################################

session_start();

// functions:

function bbcode($string)
 {
  $string = preg_replace("#\[b\](.+?)\[/b\]#is", "<b>\\1</b>", $string);
  $string = preg_replace("#\[i\](.+?)\[/i\]#is", "<i>\\1</i>", $string);
  $string = preg_replace("#\[u\](.+?)\[/u\]#is", "<u>\\1</u>", $string);
  $string = preg_replace("#\[link\]www\.(.+?)\[/link\]#is", "<a href=\"http://www.\\1\">www.\\1</a>", $string);
  $string = preg_replace("#\[link\](.+?)\[/link\]#is", "<a href=\"\\1\">\\1</a>", $string);
  $string = preg_replace("#\[link=(.+?)\](.+?)\[/link\]#is", "<a href=\"\\1\">\\2</a>", $string);
  $string = preg_replace("#\[url\]www\.(.+?)\[/url\]#is", "<a href=\"http://www.\\1\">www.\\1</a>", $string);
  $string = preg_replace("#\[url\](.+?)\[/url\]#is", "<a href=\"\\1\">\\1</a>", $string);
  $string = preg_replace("#\[url=(.+?)\](.+?)\[/url\]#is", "<a href=\"\\1\">\\2</a>", $string);
  return $string;
 }

function smilies($string)
 {
  global $smilies;
  foreach($smilies as $smiley)
   {
    $string = str_replace($smiley['code'], '<img src="'.$smiley['image'].'" alt="'.$smiley['code'].'" />', $string);
   }
  return $string;
 }

function autolink($string)
 {
  $string = ' ' . $string;
  $string = preg_replace("#(^|[\n ])([\w]+?://.*?[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\">\\2</a>", $string);
  $string = preg_replace("#(^|[\n ])((www|ftp)\.[\w\-]+\.[\w\-.\~]+(?:/[^ \"\t\n\r<]*)?)#is", "\\1<a href=\"http://\\2\">\\2</a>", $string);
  $string = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $string);
  $string = substr($string, 1);
  return $string;
 }

function browse()
 {
  global $settings, $lang, $p, $entry_count;

  if ($entry_count > $settings['entries_per_page'])
  {
   $new_index_before = $p - 1;
   $new_index_after = $p + 1;
   $site_count = ceil($entry_count / $settings['entries_per_page']);
   ?><p class="gb-browse"><?php
   if ($new_index_before >= 0) { ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?p=<?php echo $new_index_before; ?>" title="<?php echo $lang['previous_page']; ?>">&laquo;</a>&nbsp;<?php }
   if ($new_index_before >= 0 && $new_index_before < $site_count) echo "";
   if ($p==0) { ?><span class="caution">1</span>&nbsp;<?php } else { ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?p=0">1</a>&nbsp;<?php }
   for($x=$p-3; $x<$p+4; $x++)
    {
     if ($x > 0 && $x < $site_count) { if ($x==$p) { ?><span class="caution"><?php echo $x+1; ?></span>&nbsp;<?php } else { ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?p=<?php echo $x; ?>"><?php echo $x+1; ?></a>&nbsp;<?php } }
    }
   if ($new_index_after < $site_count) { ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?p=<?php echo $new_index_after; ?>" title="<?php echo $lang['next_page']; ?>">&raquo;</a><?php }
   ?></p><?php
  }
 }

function get_spam_check_numbers()
 {
  $number[0] = rand(1,10);
  $number[1] = rand(0,10);
  $number[2] = $number[0] + $number[1];
  return $number;
 }

function spam_check($result, $entered_result)
 {
  if(intval($result) == intval($entered_result)) return true;
  else return false;
 }

// get current action:
if(isset($_REQUEST['action'])) $action = $_REQUEST['action'];

// admin login:
if(isset($_POST['login_password']))
 {
  if($settings['admin_password_encodation']=='')
   {
    if($_POST['login_password'] == $settings['admin_password'])
     {
      $login_ok = true;
     }
   }
  else
   {
    if($settings['admin_password_encodation']($_POST['login_password']) == $settings['admin_password'])
     {
      $login_ok = true;
     }
   }
  if(isset($login_ok))
   {
    $_SESSION['admin'] = true;
    header("location: ".basename($_SERVER["PHP_SELF"]));
    exit;
   }
  else 
   { 
    $action='login';
    $login_failed=true;
   }
 }

// edit entry:
if(isset($_SESSION['admin']) && isset($_GET['edit']))
 {
  $data = file($settings['data_file']);
  $row_count = count($data);
  for($row = 0; $row < $row_count; $row++)
   {
    $parts = explode('|', $data[$row]);
    if($parts[0] == $_GET['edit'])
     {
      $edit = $parts[0];
      $time = $parts[1];
      $ip = $parts[2];
      $name = urldecode($parts[3]);
      $email_hp = base64_decode(urldecode($parts[4]));
      $location = urldecode($parts[5]);
      $text = urldecode($parts[6]);
      $comment = urldecode($parts[7]);
      break;
     }
   }
  $action='entry';
 }

// delete entry:
if(isset($_SESSION['admin']) && isset($_GET['delete']))
 {
  $data = file($settings['data_file']);
  $row_count = count($data);
  $fp = fopen($settings['data_file'], 'w+');
  flock($fp, 2);
  for($row = 0; $row < $row_count; $row++)
   {
    $parts = explode("|", $data[$row]);
    if($parts[0] != $_GET['delete']) 
     { 
      fwrite($fp, trim($data[$row])."\n"); 
     }
   }
  flock($fp, 3);
  fclose($fp);
  header("location: ".basename($_SERVER["PHP_SELF"]));
  exit;
 }

// form submitted:
if(isset($_POST['entry']) || isset($_POST['preview']))
{
 // import posted data
 if(isset($_POST['time'])) $time = $_POST['time'];
 if(isset($_POST['edit'])) $edit = $_POST['edit'];
 $name = trim($_POST['name']);
 $text = trim($_POST['text']);

 // remove empty lines:
 $text_array = explode("\n", $text);
 $text = '';
 foreach($text_array as $text_line)
  {
   $text_line = trim($text_line);
   if($text_line!='') $text .= $text_line."\n";
  }

 $location = trim($_POST['location']);
 $email_hp = trim($_POST['email_hp']);
 if(isset($_POST['comment']) && isset($_SESSION['admin'])) $comment = trim($_POST['comment']);
 else $comment='-';

 // Ckeck if IP already posted recently:
 if($settings['block_ip']>0 && empty($_SESSION['admin']))
  {
   $data = file($settings['data_file']);
   foreach($data as $line)
    {
     if(trim($line)!='')
      {
       $parts = explode("|", $line);
       $saved_time = (int)$parts[1];
       if(time() < $saved_time+($settings['block_ip']*60) && $_SERVER["REMOTE_ADDR"] == $parts[2] && !isset($_SESSION['admin']))
        {
         $errors[] = $lang['error_already_made_entry'];
         break;
        }
      }
    }
  }
  
 if ($name == '') $errors[] = $lang['error_no_name'];
 if ($text == '') $errors[] = $lang['error_no_text'];
 if(isset($email_hp) && $email_hp != '')
  { 
   if(strlen($email_hp) > $settings['email_hp_maxlength']) $errors[] = $lang['error_email_hp_too_long'];
   if(!preg_match("/^[^@]+@.+\.\D{2,5}$/", $email_hp) && strpos($email_hp,'.')===false) $errors[] = $lang['error_email_hp_invalid'];
  }
 if(strlen($text) > $settings['text_maxlength']) { $lang['error_text_too_long'] = str_replace("[characters]", strlen($text), $lang['error_text_too_long']); $lang['error_text_too_long'] = str_replace("[max_characters]", $settings['text_maxlength'], $lang['error_text_too_long']); $errors[] = $lang['error_text_too_long']; }
 if($text != "" && strlen($text) < $settings['text_minlength']) $errors[] = $lang['error_text_too_short'];
 
 // check for too long words:
 $text_arr = explode(" ",$name); for ($i=0;$i<count($text_arr);$i++) { trim($text_arr[$i]); $laenge = strlen($text_arr[$i]); if ($laenge > $settings['name_word_maxlength']) {
 $error_word_too_long_x = str_replace("[word]", htmlspecialchars(stripslashes(substr($text_arr[$i],0,$settings['name_word_maxlength'])))."...", $lang['error_word_too_long']); $errors[] = $error_word_too_long_x; } }
 $text_arr = explode(" ",$location); for ($i=0;$i<count($text_arr);$i++) { trim($text_arr[$i]); $laenge = strlen($text_arr[$i]); if ($laenge > $settings['location_word_maxlength']) {
 $error_word_too_long_x = str_replace("[word]", htmlspecialchars(stripslashes(substr($text_arr[$i],0,$settings['location_word_maxlength'])))."...", $lang['error_word_too_long']); $errors[] = $error_word_too_long_x; } }
 $text_arr = str_replace("\n", " ", $text);
 if ($settings['bbcode'] == true); { $text_arr = preg_replace("#\[b\](.+?)\[/b\]#is", "\\1", $text_arr); $text_arr = preg_replace("#\[i\](.+?)\[/i\]#is", "\\1", $text_arr); $text_arr = preg_replace("#\[u\](.+?)\[/u\]#is", "\\1", $text_arr); $text_arr = preg_replace("#\[link\](.+?)\[/link\]#is", "\\1", $text_arr); $text_arr = preg_replace("#\[link=(.+?)\](.+?)\[/link\]#is", "\\2", $text_arr); }
 $text_arr = explode(" ",$text_arr); for ($i=0;$i<count($text_arr);$i++) { trim($text_arr[$i]); $laenge = strlen($text_arr[$i]); if ($laenge > $settings['text_word_maxlength']) {
 $error_word_too_long_x = str_replace("[word]", htmlspecialchars(stripslashes(substr($text_arr[$i],0,$settings['text_word_maxlength'])))."...", $lang['error_word_too_long']);$errors[] = $error_word_too_long_x; } }

  if(isset($_POST['entry']) && empty($_SESSION['admin']))
   {
    if(empty($_SESSION['spam_check_session'])) $errors[] = $lang['error_invalid_request'];
    if(spam_check($_SESSION['spam_check_session'][2],$_POST['spam_check'])!=true) $errors[] = $lang['error_spam'];
   } 

 // save new entry:
 if(empty($errors) && isset($_POST['entry']) && empty($edit))
  {
   $time = time();
   $text = urlencode($text);
   $name = urlencode($name);
   $email_hp = urlencode(base64_encode($email_hp));
   $location = urlencode($location);
   if($settings['block_ip']>0) $ip = $_SERVER["REMOTE_ADDR"];
   else $ip = '-';
   $comment = urlencode($comment);
   $entry = uniqid("")."|".$time."|".$ip."|".$name."|".$email_hp."|".$location."|".$text."|".$comment."\n";
   $data = file($settings['data_file']);
   $c = count($data);
   //$fp = fopen($settings['data_file'], 'w+');
   //flock($fp, 2);
   //fwrite($fp, $entry);
   //for ($i = 0; $i < $c; $i++) { fwrite($fp, trim($data[$i])."\n"); }
   //flock($fp, 3);
   //fclose($fp);

   // e-mail notification:
   if (isset($settings['admin_email']) && $settings['admin_email'] != "")
   {
    $emailbody = urldecode($text);
    $absender = urldecode($name);
    if ($email != "") $absender_email = base64_decode(urldecode($email)); else $absender_email = "no@ema.il";
    $header= "From: ".$absender."<".$absender_email.">\n";    $header .= "X-Mailer: PHP/" . phpversion(). "\n";
    $header .= "X-Sender-IP: ".$_SERVER['REMOTE_ADDR']."\n";
    $header .= "Content-Type: text/plain";
    @mail($settings['admin_email'], $lang['mail_subject'], $emailbody, $header);
   }
   header("location: ".basename($_SERVER["PHP_SELF"]));
   exit;
  }

 // save edited entry: 
 elseif(isset($_SESSION['admin']) && empty($errors) && isset($_POST['entry']) && isset($edit))
  {
   $entry_uniqid = $_POST['edit'];
   $name = urlencode($name);
   $email_hp = urlencode(base64_encode($email_hp));
   $location = urlencode($location);
   $text = urlencode($text);
   $comment = urlencode($comment);
   $data = file($settings['data_file']);
   $row_count = count($data);
   $fp = fopen($settings['data_file'], "w+");
   flock($fp, 2);
   for ($row = 0; $row < $row_count; $row++)
    {
     $parts = explode("|", $data[$row]);
     if ($parts[0] == $entry_uniqid) { fwrite($fp, $parts[0]."|".$parts[1]."|".$parts[2]."|".$name."|".$email_hp."|".$location."|".$text."|".$comment."\n"); }
     else { fwrite($fp, trim($data[$row])."\n"); }
    }
   flock($fp, 3);
   fclose($fp);
   header("location: ".basename($_SERVER["PHP_SELF"]));
   exit;
  }
}

if(empty($action)) $action='main';

// actions before HTML:
switch($action)
 {
  case 'login':
   if(isset($_SESSION['admin']))
    {
     session_destroy();
     header("location: ".basename($_SERVER["PHP_SELF"]));
     exit;
    }
   break;
 } 

setlocale(LC_ALL, $lang['locale']);
header('Content-Type: text/html; charset='.$lang['charset']);

################################################################################
// Begin HTML output
################################################################################

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $lang['lang']; ?>">
<head>
<title><?php echo $settings['guestbook_title']; ?></title>
<meta http-equiv="content-type" content="text/html; charset=<?php echo $lang['charset']; ?>" />
<style type="text/css">
<!--
body          { color:#000; background:#fff; margin:20px; padding:0px; font-family:verdana,arial,sans-serif; font-size:100.1%; }
h1            { font-family: verdana, arial, sans-serif; font-size: 1.25em; font-weight: bold; }
p, ul         { font-family: verdana, arial, sans-serif; font-size:0.82em; line-height:1.45em; }
#nav          { margin-bottom:2em; }
p.author      { font-style:italic; margin-top:0; margin-bottom:0.4em; padding-bottom:0.2em; border-bottom:1px solid #d5d5d5; max-width:50em; }
p.entry       { margin-top:0; padding-top:0; margin-bottom:2em; max-width:50em; }
p.comment     { font-style:italic; margin-top:-1.7em; padding:0 0 0 2em; margin-bottom:2em; max-width:50em; color:#606060; }
p.admin       { margin-top:-1.7em; text-align:right; max-width:50em;}
p.admin span  { font-size:0.82em; }
.caution      { font-weight:bold; color:red; }
.small        { font-size:0.69em; line-height:1.19em; }
p .small      { font-size:0.82em; }
h2.preview-hl { font-size:0.82em; line-height:1.45em; font-weight:bold; color:red; margin-bottom:0; }
input.button  { width:45px;  font-size: 11px; font-weight:normal; margin: 0px 0px 5px 0px; }
#preview      { border:1px dotted red; max-width:41em; padding:10px 10px 0 10px; }
#footer       { margin-top:3em; font-size:0.69em; line-height:1.19em; color:#808080; }
#footer a     { color:#808080; }
a:link        { color: #0000cc; text-decoration: none; }
a:visited     { color: #0000cc; text-decoration: none; }
a:hover       { color: #0000cc; text-decoration: underline; }
a:active      { color: #bb0000; text-decoration: none; }
-->
</style><?php
if(($settings['bbcode']==true || isset($smilies)) && $action=='entry') 
{ ?><script type="text/javascript">/* <![CDATA[ */
function bbcode(form,field,v)
 {
 if (document.selection) // for IE
   {
    var str = document.selection.createRange().text;
    document.forms[form].elements[field].focus();
    var sel = document.selection.createRange();
    sel.text = "[" + v + "]" + str + "[/" + v + "]";
    return;
   }
  else if ((typeof document.forms[form].elements[field].selectionStart) != 'undefined') // for Mozilla
   {
    var txtarea = document.forms[form].elements[field];
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    var oldScrollTop = txtarea.scrollTop;
    var s1 = (txtarea.value).substring(0,selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd)
    var s3 = (txtarea.value).substring(selEnd, selLength);
    txtarea.value = s1 + '[' + v + ']' + s2 + '[/' + v + ']' + s3;
    txtarea.selectionStart = s1.length;
    txtarea.selectionEnd = s1.length + 5 + s2.length + v.length * 2;
    txtarea.scrollTop = oldScrollTop;
    txtarea.focus();
    return;
   }
  else insert(form,field,'[' + v + '][/' + v + '] ');
 }

function insert(form,field,what)
 {
  if (document.forms[form].elements[field].createTextRange)
   {
    document.forms[form].elements[field].focus();
    document.selection.createRange().duplicate().text = what;
   }
  else if ((typeof document.forms[form].elements[field].selectionStart) != 'undefined') // f�r Mozilla
   {
    var tarea = document.forms[form].elements[field];
    var selEnd = tarea.selectionEnd;
    var txtLen = tarea.value.length;
    var txtbefore = tarea.value.substring(0,selEnd);
    var txtafter =  tarea.value.substring(selEnd, txtLen);
    var oldScrollTop = tarea.scrollTop;
    tarea.value = txtbefore + what + txtafter;
    tarea.selectionStart = txtbefore.length + what.length;
    tarea.selectionEnd = txtbefore.length + what.length;
    tarea.scrollTop = oldScrollTop;
    tarea.focus();
   }
  else
   {
    document.forms[form].elements[field].value += what;
    document.forms[form].elements[field].focus();
   }
 }

function insert_link(form,field)
 {
 var link_text='<?php echo addslashes($lang['insert_link_text']); ?>';
 var link_target='<?php echo addslashes($lang['insert_link_url']); ?>';

 if (document.selection) // for IE
   {
    var str = document.selection.createRange().text;
    document.forms[form].elements[field].focus();
    var sel = document.selection.createRange();
    var insert_link = prompt(link_target,'http://');
    if(sel.text=='' && insert_link!='' && insert_link!=null) str = prompt(link_text,'');

    if(insert_link && str!=null)
     {
      if(str!='')
       {
        sel.text = "[link=" + insert_link + "]" + str + "[/link]";
       }
      else
       {
        sel.text = "[link]" + insert_link + "[/link]";
       }
     }
    return;
   }
  else if ((typeof document.forms[form].elements[field].selectionStart) != 'undefined') // for Mozilla
   {
    var txtarea = document.forms[form].elements[field];
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    var oldScrollTop = txtarea.scrollTop;
    var s1 = (txtarea.value).substring(0,selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd);
    var s3 = (txtarea.value).substring(selEnd, selLength);
    
    var insert_link = prompt(link_target,'http://');
    if(selEnd-selStart==0 && insert_link!='' && insert_link!=null) s2 = prompt(link_text,'');
    if(insert_link && s2!=null)
     {
      if(s2!='')
       {
        txtarea.value = s1 + '[link=' + insert_link + ']' + s2 + '[/link]' + s3;
        var codelength = 14 + insert_link.length + s2.length;
       }
      else
       {
        txtarea.value = s1 + '[link]' + insert_link + '[/link]' + s3;
        var codelength = 13 + insert_link.length;
       }
      txtarea.selectionStart = s1.length;
      txtarea.selectionEnd = s1.length + codelength;
      txtarea.scrollTop = oldScrollTop;
      txtarea.focus();
      return;
     }
   }
  else insert('[link=http://www.domain.tld/]Link[/link]');
 }
/* ]]> */</script><?php 
}
if(isset($_SESSION['admin'])) 
{ ?><script type="text/javascript">/* <![CDATA[ */
function confirm_link(this_link)
 {
  var confirmed = confirm('<?php echo addslashes($lang['delete_confirm']); ?>');
  return confirmed;
 }
/* ]]> */</script><?php 
}
?></head>

<body>

<h1><?php echo $settings['guestbook_title']; ?></h1>
<p id="nav"><?php if ($action=='main') 
 { 
  ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?action=entry">&raquo; <?php echo $lang['new_entry']; ?></a><?php 
 }
else 
 { 
  ?><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>">&laquo; <?php echo $lang['back']; ?></a><?php 
 }
?></p>
<?php

// actions within HTML output:

switch($action)
 {
  case 'main':
  if(isset($_GET['p'])) $p = $_GET['p'];
  $data = file($settings['data_file']);
  $entry_count = count($data);
  if (empty($p)) $p = 0;
  $last = ($p+1) * $settings['entries_per_page'];
  if ($last > $entry_count) $last = $entry_count;
  
  if($entry_count == 0) 
   { 
    ?><p><em><?php echo $lang['no_entries_yet']; ?></em></p><?php
   }

  for ($i = $p*$settings['entries_per_page']; $i < $last; $i++)
   {
    unset($email);
    unset($hp);
    if(trim($data[$i]) != '')
     {
      $nr = $entry_count -$i;
      $parts = explode("|", $data[$i]);
      $name = urldecode($parts[3]);
      $email_hp = base64_decode(urldecode($parts[4]));
      if(preg_match("/^[^@]+@.+\.\D{2,5}$/", $email_hp)) $email = $email_hp;
      elseif(trim($email_hp!='')) 
       {
        if(substr($email_hp,0,7) != "http://" && substr($email_hp,0,8) != "https://" && substr($email_hp,0,6) != "ftp://" && substr($email_hp,0,9) != "gopher://" && substr($email_hp,0,7) != "news://") $hp = "http://".$email_hp;
        else $hp = $email_hp;
       } 
      $location = urldecode($parts[5]);
      $text = urldecode($parts[6]);
      if(trim($parts[7])!='-')
       {
        $comment = urldecode($parts[7]);
        $comment = trim(htmlspecialchars(stripslashes($comment)));
        $comment = nl2br($comment);
        if($settings['autolink'] == true) $comment = autolink($comment);
        if($settings['bbcode'] == true) $comment = bbcode($comment);
        if(isset($smilies)) $comment = smilies($comment);
       }
      else $comment = '';
      $text = trim(htmlspecialchars(stripslashes($text)));
      $text = nl2br($text);
      if($settings['autolink'] == true) $text = autolink($text);
      if($settings['bbcode'] == true) $text = bbcode($text);
      if(isset($smilies)) $text = smilies($text);
      ?><p class="author"><b><?php if(isset($hp)) { ?><a href="<?php echo htmlspecialchars(stripslashes($hp)); ?>"><?php } echo htmlspecialchars(stripslashes($name)); if(isset($hp)) { ?></a><?php } ?></b>, <?php
      if($location != "") { echo htmlspecialchars(stripslashes($location)) . ", "; }
      echo strftime($lang['time_format'], $parts[1]);
      ?></p>
      <p class="entry"><?php echo $text; ?></p><?php
      if($comment!='') 
       {
        ?><p class="comment"><?php echo $comment; ?></p><?php 
       }
      if(isset($_SESSION['admin'])) 
       { 
        ?><p class="admin"><span>[ <a href="<?php echo basename($_SERVER['PHP_SELF']); ?>?edit=<?php echo $parts[0]; ?>" /><?php echo $lang['edit_link']; ?></a> | <a href="<?php echo basename($_SERVER['PHP_SELF']); ?>?delete=<?php echo $parts[0]; ?>" onclick="return confirm_link(this)" /><?php echo $lang['delete_link']; ?></a> ]</span></p><?php 
       }
      }
    }
   browse();
   break;

  case 'entry':
   if(isset($errors))
    {
     ?><p class="caution"><?php echo $lang['error']; ?></p><ul><?php foreach($errors as $f) { ?><li><?php echo $f; ?></li><?php } ?></ul><br /><?php
    }
   elseif(empty($errors) && isset($_POST['preview']))
    {
     $pr_text = htmlspecialchars(stripslashes($text));
     $pr_text = nl2br($pr_text);
     if($settings['autolink']==true) $pr_text = autolink($pr_text);
     if($settings['bbcode']==true) $pr_text = bbcode($pr_text);
     if(isset($smilies)) $pr_text = smilies($pr_text);
     $pr_comment = htmlspecialchars(stripslashes($comment));
     $pr_comment = nl2br($pr_comment);
     if($settings['autolink'] == true) $pr_comment = autolink($pr_comment);
     if($settings['bbcode'] == true) $pr_comment = bbcode($pr_comment);
     if(isset($smilies)) $pr_comment = smilies($pr_comment);

     if(preg_match("/^[^@]+@.+\.\D{2,5}$/", $email_hp)) $email = $email_hp;
     elseif(trim($email_hp!='')) 
      {
       if(substr($email_hp,0,7) != "http://" && substr($email_hp,0,8) != "https://" && substr($email_hp,0,6) != "ftp://" && substr($email_hp,0,9) != "gopher://" && substr($email_hp,0,7) != "news://") $hp = "http://".$email_hp;
       else $hp = $email_hp;
      } 
     ?><h2 class="preview-hl"><?php echo $lang['preview']; ?></h2>
     <div id="preview">
     <p class="author"><b><?php if(isset($hp)) { ?><a href="<?php echo htmlspecialchars(stripslashes($hp)); ?>"><?php } echo htmlspecialchars(stripslashes($name)); if(isset($hp)) { ?></a><?php } ?></b>, <?php
     if ($location != "") { echo htmlspecialchars(stripslashes($location)) . ", "; }
     if ($action=="edit") echo strftime($lang['time_format'], $_POST['time']);
     else echo strftime($lang['time_format']);
     ?></p>
     <p class="entry"><?php echo $pr_text; ?></p>
     <?php if(trim($pr_comment)!='-') { ?><p class="comment"><?php echo $pr_comment; ?></p><?php }
     ?></div><?php
    }
   ?><form id="entryform" method="post" action="<?php echo basename($_SERVER["PHP_SELF"]); ?>"><div>
   <input type="hidden" name="<?php echo session_name(); ?>" value="<?php echo session_id(); ?>" />
   <input type="hidden" name="action" value="<?php echo $action; ?>" />
   <?php if(isset($edit)) { ?><input type="hidden" name="edit" value="<?php echo $edit; ?>" /><input type="hidden" name="time" value="<?php echo $time; ?>" /><?php } ?>
   <p><b><?php echo $lang['name']; ?></b><br />
   <input type="text" name="name" value="<?php if(isset($name)) echo htmlspecialchars(stripslashes($name)); else echo ''; ?>" size="40" maxlength="<?php echo $settings['name_maxlength']; ?>" /></p>
   <p><b><?php echo $lang['email_hp']; ?></b><br />
   <input type="text" name="email_hp" value="<?php if (isset($email_hp)) echo htmlspecialchars(stripslashes($email_hp)); else echo ''; ?>" size="40" maxlength="<?php echo $settings['email_hp_maxlength']; ?>" />&nbsp;<span class="small"><?php echo $lang['optional_email_hp']; ?></span></p>
   <p><b><?php echo $lang['location']; ?></b><br />
   <input type="text" name="location" value="<?php if (isset($location)) echo htmlspecialchars(stripslashes($location)); else echo ''; ?>" size="40" maxlength="<?php echo $settings['location_maxlength']; ?>" />&nbsp;<span class="small"><?php echo $lang['optional']; ?></span></p>
   <p style="margin-bottom:0;padding-bottom:0;"><b><?php echo $lang['message']; ?></b></p>
   <table><tr><td>
   <textarea id="text" style="float:left;" name="text" cols="65" rows="14"><?php if (isset($text)) echo htmlspecialchars(stripslashes($text)); else echo ""; ?></textarea>
   </td>
   <td style="vertical-align:top;">
   <?php
   if($settings['bbcode']==true) 
    {
     ?><p style="margin-top:0;"><input class="button" style="font-weight:bold;" type="button" name="bbcode-button" title="<?php echo $lang['bold_button_title']; ?>" value="<?php echo $lang['bold_button']; ?>" onclick="bbcode('entryform','text','b');" /><br />
     <input class="button" style="font-style:italic;" type="button" name="bbcode-button" title="<?php echo $lang['italic_button_title']; ?>" value="<?php echo $lang['italic_button']; ?>" onclick="bbcode('entryform','text','i');" /><br />
     <input class="button" style="color: #0000ff; text-decoration: underline;" type="button" name="bbcode-button" title="<?php echo $lang['link_button_title']; ?>" value="<?php echo $lang['link_button']; ?>" onclick="insert_link('entryform','text');" /></p><?php 
    }
   if(isset($smilies))
    {
     ?><p><?php
     $i=0;
     foreach($smilies as $smiley)
      {
       ?><button style="padding:0;" name="smiley" type="button" value="smile" title="<?php echo $lang['insert_smiley']; ?>" onclick="insert('entryform','text','<?php echo $smiley['code']; ?> ');"><img class="smiley" src="<?php echo $smiley['image']; ?>" alt="<?php echo $smiley['code']; ?>" /></button><?php if($i % 2 == 1) echo '<br />';
       ++$i;
      } 
     ?></p><?php
    }
   
   
   else
    {
     ?>&nbsp;<?php
    }
   ?></td></tr></table><?php
   if(empty($edit))
    {
     $_SESSION['spam_check_session'] = get_spam_check_numbers();
     ?><p><b><?php echo $lang['spam_protection']; ?></b><br />
     <?php echo $lang['spam_protection_sum']; ?> <?php echo $_SESSION['spam_check_session'][0]; ?> + <?php echo $_SESSION['spam_check_session'][1]; ?> = <input type="text" name="spam_check" value="" size="5" /></p><?php
    }
   if(isset($edit)) 
    {
     ?><p><b><?php echo $lang['comment']; ?></b><br /><textarea name="comment" cols="65" rows="6"><?php if (isset($comment) && trim($comment)!='-') echo htmlspecialchars(stripslashes($comment)); ?></textarea></p><?php 
    }
   ?><p><input type="submit" name="entry" value="<?php echo $lang['submit_button']; ?>" />&nbsp;<input type="submit" name="preview" value="<?php echo $lang['preview_button']; ?>" /></p>
   </div></form><?php
   break;
  case 'login':
   if(isset($login_failed))
    {
     ?><p class="caution"><?php echo $lang['password_wrong']; ?></p><?php
    } 
   ?><form action="<?php echo basename($_SERVER["PHP_SELF"]); ?>" method="post">
   <p><b><?php echo $lang['password']; ?></b><br /><input id="login" type="password" name="login_password" />&nbsp;<input type="submit" value="<?php echo $lang['log_in']; ?>" /></p>
   </form>
   <script type="text/javascript">/* <![CDATA[ */
   document.getElementById('login').focus();
   /* ]]> */</script>   
   <?php
   break;
 }

?><p id="footer"><a href="<?php echo basename($_SERVER["PHP_SELF"]); ?>?action=login"><?php if(isset($_SESSION['admin'])) echo $lang['admin_logout']; else echo $lang['admin_login']; ?></a></p>
</body>
</html>
