<?php
/*
    CREATIVE COMMONS - Attribution-No Derivative Works 3.0 Germany:
    - You may not alter, transform, or build upon this work.
    - Dieses Werk darf nicht bearbeitet oder in anderer Weise verändert werden.
*/

function messageIsSpam($name, $message, $ip, $url, $hiddenURL):String {
  // test for hidden URL
  if (!empty($hiddenURL))
    return 'hidden-url';
  // test for blocked IP
  $BlockedIPs = explode(", ", getSetup('SetupGuestbookSpamIPs'));
  $count = count($BlockedIPs);
  for( $i=0; $i<$count; $i++ )
    if ($ip == trim ($BlockedIPs[$i]))
      return 'blocked-ip';
  // test for "http" in name
  if (stristr($name, 'http')) {
      return 'blocked-word-in-name: http'; }
  // test for blocked words
  $message = str_replace("\r\n", " ", $message);
  $message = str_replace(".", " ", $message);
  $message = str_replace(",", " ", $message);
  $message = str_replace(":", " ", $message);
  $message = str_replace(";", " ", $message);
  $BlockedWords = explode(", ", getSetup('SetupGuestbookSpamWords'));
  $count = count($BlockedWords);
  for( $i=0; $i<$count; $i++ ) {
    $word = trim ($BlockedWords[$i]);
    if (stristr(' '.$message.' ', ' '.$word.' ')) // v1.2.78_019
      return 'blocked-word-in-message: '.$word;
    if (stristr($name, $word)) { // v1.2.80_162
      return 'blocked-word-in-name: '.$word; }}
  // test for blocked domains
  $BlockedDomains = explode(", ", getSetup('SetupGuestbookSpamDomains'));
  $count = count($BlockedDomains);
  for( $i=0; $i<$count; $i++ )
    if (stristr($url, trim ($BlockedDomains[$i])))
      return 'blocked-domain';
  // test for invalid characters
  $re = '[#]';
  if (preg_match($re, $message, $matches, PREG_UNMATCHED_AS_NULL, 0))
    return 'blocked-character: '.implode(", ", $matches);
  return 'noSpam'; }

function getGuestbookFrontendPagination():string {
  global $NumberOfPages;
  global $L_112;
  $URLform = getFrontendURL('SetupGuestbookFormURL');
  // Eintragen-Link
  $output = '<div class="GuestbookNavigation">
          <div class="GuestbookLinkForAddingEntries">[
            <form style="display:inline" method="post" accept-charset="UTF-8">
              <p style="display:inline">
                <input type="hidden" name="page" value="form" />
                  <a href="'.$URLform.'">
                    <img src="'.PATH.'frontend/images/guestbook_form.png" alt="" />'.$L_112.'</a>
              </p>
            </form> ]
          </div>';
  // Pagination
  if ($NumberOfPages>1) {
    global $CurrentPage;
    global $L_111;
    $output .= $L_111.': ';
    $URLgb = getFrontendURL('SetupGuestbookURL');
    $output .= getPagination( $URLgb, $NumberOfPages, $CurrentPage, "DESC", "gb_page"); }
  else
    $output .= "&nbsp;"; // to avoid empty div container
  return $output .= '</div>'; }

function addGuestbookEntry($Name, $Email, $URL, $ICQ, $Nachricht, $IP, $Ort):BOOL {
  $arg_list = get_defined_vars();
  global $prefix;
  global $db;
  $Datum = date("U");
  // Zufällige Zahl erzeugen
    mt_srand((double)microtime() * 1000000);
    $Code = mt_rand();
  // Optimize function arguments
    foreach($arg_list as $key => $value) {
      $$key = html_entity_decode($$key);
      $$key = mysqli_real_escape_string($db, $$key); }
  // Leere numerische Variablen als NULL definieren
    if (empty($ICQ)) $ICQ = "NULL";
  $SQLQuery = "INSERT INTO ".$prefix."guestbook (Datum,Name,Email,URL,ICQ,Nachricht,IP,Code,Ort)
    VALUES ($Datum, '$Name', '$Email', '$URL', $ICQ, '$Nachricht', '$IP', $Code, '$Ort')";
  $Result = mysqli_query($db, $SQLQuery);
  if (!$Result) {
    echo '<span class="ErrorMessage">ERROR:<br>Failed to add this entry to database!<br></span><br><br>';
    $Nachricht = "\nFAILED TO ADD THIS ENTRY TO DATABASE!\n\n".$Nachricht; }
  // send email to administrator
    sendMail($Datum, $Name, $Ort, $Email, $URL, $ICQ, $Nachricht, $IP, $Code);
  return $Result; }

function DatumUndUhrzeitAusTimestamp($Timestamp):string {
  $Day = date('d', $Timestamp);
  $Month = date('m', $Timestamp);
  $Year = date('Y', $Timestamp);
  $Stunde = date('H', $Timestamp);
  $Minute = date('i', $Timestamp);
  return $Day.".".$Month.".".$Year." ".$Stunde.":".$Minute; }

function sendMail($Datum, $Name, $Ort, $Email, $URL, $ICQ, $Nachricht, $IP, $Code) {
  global $L_Date;
  global $L_114;
  global $L_115;
  global $L_116;
  global $L_118;
  global $L_134;
  global $L_119;
  global $L_135;
  global $L_136;
  global $L_137;
  global $L_GuestbookLocation;
  global $L_ERROR_Email_could_not_be_sent;
  global $GigKalenderPath;
  $SetupGuestbookMail = getSetup('SetupGuestbookMail');
  // NULL Werte für anzeige in E-Mail neutralisieren
    if ($ICQ=="NULL") $ICQ = "";
  // Define email message
  $MailMessage = $L_Date.": ".DatumUndUhrzeitAusTimestamp ($Datum);
  $MailMessage = $MailMessage."\n".$L_114.": ".$Name;
  $MailMessage = $MailMessage."\n".$L_GuestbookLocation.": ".$Ort;
  $MailMessage = $MailMessage."\n".$L_115.": ".$Email;
  $MailMessage = $MailMessage."\n".$L_116.": ".$URL;
  $MailMessage = $MailMessage."\n".$L_118.": ".$ICQ;
  $MailMessage = $MailMessage."\n".$L_134.": ".$IP;
  $MailMessage = $MailMessage."\n---";
  $MailMessage = $MailMessage."\n\n".$L_119.": ".$Nachricht;
  $MailMessage = $MailMessage."\n\n---";
  $MailMessage = $MailMessage."\n".$L_136.":\n".$GigKalenderPath."guestbook/guestbook_edit.php?code=".$Code;
  $MailMessage = $MailMessage."\n\n".$L_137.":\n".$GigKalenderPath."guestbook/guestbook_delete.php?code=".$Code;
  // Define email header
    $optheader[] = "From: GigKalender< ".$SetupGuestbookMail." >";
    $optheader[] = "Content-Type: text/plain; Charset=utf-8";
    $Header = implode("\n", $optheader);
  // Send email
    if ( !@mail($SetupGuestbookMail, $L_135, $MailMessage, $Header) )
      echo '<span class="ErrorMessage">'.$L_ERROR_Email_could_not_be_sent.'</span><br /><br />'; }

function getGuestbookBackEndPagination():string {
  global $NumberOfPages;
  if ($NumberOfPages>1) {
    global $CurrentPage;
    $output = '<div class="GigNavigation">';
    $URL = "index.php?submenue=guestbook&content=backend_showAllGuestbookEntries";
    $output .= getPagination ($URL, $NumberOfPages, $CurrentPage, "ASC", "page");
    $output .= '</div>'; }
  else $output = '';
  return $output; }

function editGuestbookEntry($ID, $Name, $Email, $URL, $ICQ, $Nachricht, $Ort, $Kommentar):BOOL {
  $arg_list = get_defined_vars();
  global $prefix;
  global $db;
  // Optimize function arguments
    foreach($arg_list as $key => $value) {
      $$key = html_entity_decode($$key);
      $$key = mysqli_real_escape_string($db, $$key); }
  // Leere numerische Variablen als NULL definieren
    if ($ICQ<1) $ICQ = NULL;
  // Define a prepared statement
  if ($stmt = mysqli_prepare($db, "UPDATE ".$prefix."guestbook SET
            Name = '".$Name."',
            Email = '".$Email."',
            URL = '".$URL."',
            ICQ = ?,
            Nachricht = '".$Nachricht."',
            Kommentar = '".$Kommentar."',
            Ort = '".$Ort."'
            WHERE GuestbookID = '".$ID."'
            LIMIT 1")) {
    mysqli_stmt_bind_param($stmt, "i", $ICQ);
    $Result = mysqli_stmt_execute($stmt); }
  return $Result; }

function isFormReload($gb_name, $gb_text, $gb_ip):BOOL {
  global $db;
  global $prefix;
  // escaping special characters for use in an SQL statement, e.g. 'O\'Connel'
    $gb_name = mysqli_real_escape_string($db, $gb_name);
    $gb_text = mysqli_real_escape_string($db, $gb_text);
  $SQLQuery = "SELECT count(*) as number FROM ".$prefix."guestbook WHERE Name='".$gb_name."' AND Nachricht='".$gb_text."' AND IP='".$gb_ip."'";
  $Result = mysqli_query($db, $SQLQuery);
  $row = mysqli_fetch_array($Result);
  if ($row['number'])
    return true;
  else
    return false; }

  function isGuestbookEntryPresent ( $Code )
  {
    global $db;
    global $prefix;

    $Result = @mysqli_query($db, "SELECT CODE FROM ".$prefix."guestbook WHERE CODE = ".$Code);
    $Result = mysqli_num_rows($Result);
    if ($Result == true) return true;
    else return false;
  }

  function writeSpamLog ( $Name, $Ort, $Email, $EchteURL, $URL, $ICQ, $Nachricht, $IP, $Identifier, $Form )
  {
    global $SetupWriteGuestbookSpamLog;
    if ( $SetupWriteGuestbookSpamLog )
    {
      global $GigKalenderPath;
      global $GigKalenderVersion;
      $path = str_replace("\\","/",dirname(__FILE__));
      $datei = $path."/spam.log";
      $fp=fopen($datei,"a");
$String = '### '.convertTimestampToISO8601(date('U')).' ###
[GigKalender-Version]
'.$GigKalenderVersion.'
[Form]
'.$Form.'
[Reason]
'.$Identifier.'
[Name]
'.$Name.'
[Location]
'.$Ort.'
[Email]
'.$Email.'
[URL]
'.$EchteURL.'
[HiddenURL]
'.$URL.'
[ICQ]
'.$ICQ.'
[Message]
'.$Nachricht.'
[IP]
'.$IP.'


';
      fwrite($fp,$String);
    }
  }
  
  function testDoppelte ($Timestamp)
  {
    global $db;
    global $prefix;    
    
    $SQLQuery = 'SELECT * FROM ' .$prefix. "guestbook";
    $Result = mysqli_query($db, $SQLQuery);
    $doppelteVorhanden = false;
    while($row = mysqli_fetch_row($Result))
    {
      if (strtolower($row[1]) == $Timestamp) { $doppelteVorhanden = true; }
    }
    if ($doppelteVorhanden) return true;
    else return false;
}

  function AltenEintragHinzufuegen ($Day, $Month, $Year, $Stunde, $Minute, $Sekunde, $Name, $Email, $URL, $ICQ, $Nachricht, $Kommentar, $IP, $Code, $Ort)
  {
    global $prefix;
    global $db;

    $Datum = mktime($Stunde, $Minute, $Sekunde, $Month, $Day , $Year);
    if ( $URL=='http://' ) { $URL=''; }
    // HTML & PHP-Tags entfernen
      $Name = strip_tags($Name);
      $Email = strip_tags($Email);
      $ICQ = strip_tags($ICQ);
      $Nachricht = strip_tags($Nachricht);
      $Kommentar = strip_tags($Kommentar);
    // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
      $Name = mysqli_real_escape_string($db, $Name);
      $Email = mysqli_real_escape_string($db, $Email);
      $URL = mysqli_real_escape_string($db, $URL);
      $ICQ = mysqli_real_escape_string($db, $ICQ);
      $Nachricht = mysqli_real_escape_string($db, $Nachricht);
      $Kommentar = mysqli_real_escape_string($db, $Kommentar);
      $Ort = mysqli_real_escape_string($db, $Ort);
    // Leere numerische Variablen als NULL definieren
      if ( $Datum=='' ) $Datum="NULL";
      if ( $ICQ=='' ) $ICQ="NULL";
      if ( $Code=='' ) $Code="NULL";

    if (!testDoppelte($Datum))
    {   
      $SQLQuery = "INSERT INTO ".$prefix."guestbook (Datum,Name,Email,URL,ICQ,Nachricht,Kommentar,IP,Code,Ort)
      VALUES ($Datum, '$Name', '$Email', '$URL', $ICQ, '$Nachricht', '$Kommentar', '$IP', $Code, '$Ort')";
      $Result = mysqli_query($db, $SQLQuery);
      if ($Result) { return true; }
      else {return false;}
    }
    else { echo 'Error: Eintrag schon vorhanden.<br />';}
  }

  function AnzahlEintraege ()
  {
    global $prefix;
    global $db;

    $SQLQuery = "SELECT count(*) as number FROM ".$prefix."guestbook";
    $Result = mysqli_query($db, $SQLQuery);
    $row = mysqli_fetch_array($Result);
    return $row['number'];
  }
?>