<?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 editCurrentPassword($UserNewPassword):bool {
  global $prefix, $db;
  $hashedPassword = password_hash($UserNewPassword, PASSWORD_BCRYPT);
  $SQLQuery = "UPDATE ".$prefix."user SET
    UserCurrentPassword = '$hashedPassword'
    WHERE UserName = '".getCurrentUser()."'
    LIMIT 1";
  if (mysqli_query($db, $SQLQuery))
    return true;
  else
    return false; }

function editCurrentUser($UserEmailadress, $UserLanguage,
  $UserBackendCalenderListCols):bool {
  global $prefix, $db;
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
  $SQLQuery = "UPDATE ".$prefix."user SET
    UserEmailadress = '$UserEmailadress',
    UserLanguage = '$UserLanguage',
    UserBackendCalenderListCols = '$UserBackendCalenderListCols'
    WHERE UserName = '".getCurrentUser()."'
    LIMIT 1";
  if (mysqli_query($db, $SQLQuery))
    return true;
  else
    return false; }

function addUser($UserName, $UserStatus, $UserCurrentPassword, $UserEmailadress, $UserSession, $UserLanguage, $UserLastActivityTimestamp, $UserBackendCalenderListCols, $UserRightEmail, $UserRightAddNews, $UserRightEditNews, $UserRightDeleteNews):bool {
  global $prefix, $db;
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserName = mysqli_real_escape_string($db, $UserName);
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
  if (password_needs_rehash($UserCurrentPassword, PASSWORD_BCRYPT))
    /* When adding a new user from the back end or imporing from an older
    Gigkalender versions, the password requires hashing! */
    $hashedPassword = password_hash($UserCurrentPassword, PASSWORD_BCRYPT);
  else
    // Passwords from imported users are already hashed, so no hashing required!
    $hashedPassword = $UserCurrentPassword;
  // Leere numerische Variablen als NULL definieren
    if ($UserLastActivityTimestamp=='') $UserLastActivityTimestamp="NULL";
    if ($UserRightEmail=='') $UserRightEmail=0;
    if ($UserRightAddNews=='') $UserRightAddNews=0;
    if ($UserRightEditNews=='') $UserRightEditNews=0;
    if ($UserRightDeleteNews=='') $UserRightDeleteNews=0;
  if (!testDoppelteUser($UserName)) {
    $SQLQuery = "INSERT INTO ".$prefix."user
      (UserName, UserStatus, UserCurrentPassword, UserEmailadress, UserSession, UserLanguage, UserLastActivityTimestamp, UserBackendCalenderListCols, UserRightEmail, UserRightAddNews, UserRightEditNews, UserRightDeleteNews)
      VALUES
      ('$UserName', '$UserStatus', '$hashedPassword', '$UserEmailadress', '$UserSession', '$UserLanguage', $UserLastActivityTimestamp, '$UserBackendCalenderListCols', $UserRightEmail, $UserRightAddNews,  $UserRightEditNews, $UserRightDeleteNews)";
    $Result = mysqli_query($db, $SQLQuery);
    if ($Result)
      return true;
    else
      return false; }
  else
    return false; }

function editUser($UserName, $UserStatus, $UserCurrentPassword, $UserEmailadress,
  $UserNameOld, $UserLanguage, $UserBackendCalenderListCols, $UserRightEmail,
  $UserRightAddNews, $UserRightEditNews, $UserRightDeleteNews) {
  global $prefix, $db;
  // HTML-Tags entfernen
    $UserName = strip_tags($UserName);
    $UserEmailadress = strip_tags($UserEmailadress);
    $UserNameOld = strip_tags($UserNameOld);
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserName = mysqli_real_escape_string($db, $UserName);
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
    $UserNameOld = mysqli_real_escape_string($db, $UserNameOld);
  $hashedPassword = password_hash($UserCurrentPassword, PASSWORD_BCRYPT);
  // Leere numerische Variablen als NULL definieren
    //if ( $UserLastActivityTimestamp=='' ) $UserLastActivityTimestamp="NULL";
    if ( $UserRightEmail=='' ) $UserRightEmail=0;
    if ( $UserRightAddNews=='' ) $UserRightAddNews=0;
    if ( $UserRightEditNews=='' ) $UserRightEditNews=0;
    if ( $UserRightDeleteNews=='' ) $UserRightDeleteNews=0;
  $SQLQuery = "UPDATE ".$prefix."user SET
    UserName = '$UserName',
    UserStatus = '$UserStatus',
    UserCurrentPassword = '$hashedPassword',
    UserEmailadress = '$UserEmailadress',
    UserLanguage = '$UserLanguage',
    UserBackendCalenderListCols = '$UserBackendCalenderListCols',
    UserRightEmail = $UserRightEmail,
    UserRightAddNews = $UserRightAddNews,
    UserRightEditNews = $UserRightEditNews,
    UserRightDeleteNews = $UserRightDeleteNews
    WHERE UserName = '$UserNameOld'
    LIMIT 1";
  if (mysqli_query($db, $SQLQuery)) {
    return true; }
  else {
    return false; }}

function getUID($UserName, $UserCurrentPassword) {
  global $db, $prefix;
  // Sicherstellen, dass keine Sonderzeichen im Benutzername die Query beeinflussen
  $UserName = addslashes($UserName);  // Optional, sicherer wäre es auch hier ein Prepared Statement zu verwenden
  // Prepared Statement für sichereren Zugriff
  $SQLQuery = "SELECT UserId, UserCurrentPassword FROM ".$prefix."user WHERE UserName = ? LIMIT 1";
  $stmt = mysqli_prepare($db, $SQLQuery);
  // Benutzername binden
  mysqli_stmt_bind_param($stmt, "s", $UserName);
  mysqli_stmt_execute($stmt);
  $result = mysqli_stmt_get_result($stmt);
  if ($result) {
      if (mysqli_num_rows($result) == 1) {
          $user = mysqli_fetch_assoc($result);
          // Debug-Ausgabe
          //echo "Benutzername: " . $UserName . "<br>";
          //echo "Benutzer-ID: " . $user['UserId'] . "<br>";
          //echo "Gespeichertes Passwort (Hash): " . $user['UserCurrentPassword'] . "<br>";

          // Passwort überprüfen
          if (password_verify($UserCurrentPassword, $user['UserCurrentPassword'])) {
              return $user['UserId']; // Passwort stimmt überein, gebe die UserID zurück
          } else {
              return false; // Passwort falsch
          }
      } else {
          //echo "Benutzer nicht gefunden!<br>"; // Debug-Ausgabe
          return false; // Benutzer nicht gefunden
        }
  } else {
      echo "ERROR: Fehler bei der Abfrage: " . mysqli_error($db); // Debug-Ausgabe
      return false; // Fehler bei der Abfrage
  }}

function convertGigDates():void {
  // WIP - not in use yet!!!
  // Function converts values in GigBeginning into a proper 24 h time formats
  // e.g. 01:00 pm SLT => 13:00:00
  global $db, $prefix;
  // Add table column "GigBeginning24h" of type TIME
  $sql = "ALTER TABLE ".$prefix."gigs ADD COLUMN GigBeginning24h TIME";
  //mysqli_query($db, $sql);
  // Vorhandene Daten aktualisieren
  // WHEN GigBeginning LIKE '__:__ Uhr' THEN STR_TO_DATE(GigBeginning, '%H:%i Uhr')
  // WHEN GigBeginning LIKE '__:__ SLT' THEN STR_TO_DATE(GigBeginning, '%H:%i')
  // WHEN GigBeginning LIKE '' THEN NULL
  // WHEN GigBeginning LIKE '__:__ pm SLT' THEN STR_TO_DATE(GigBeginning, '%l:%i %p SLT')
  $sql = "UPDATE ".$prefix."gigs
    SET GigBeginning24h = CASE
      WHEN GigBeginning LIKE '__:__ Uhr' THEN STR_TO_DATE(REPLACE(GigBeginning, ' Uhr', ''), '%h:%i')
      WHEN GigBeginning LIKE '__:__Uhr' THEN STR_TO_DATE(REPLACE(GigBeginning, ' Uhr', ''), '%h:%i')
      WHEN GigBeginning LIKE '__:__ am' THEN STR_TO_DATE(REPLACE(GigBeginning, ' am', ''), '%h:%i')
      WHEN GigBeginning LIKE '__:__ am SLT' THEN STR_TO_DATE(REPLACE(GigBeginning, ' am SLT', ''), '%h:%i')
      WHEN GigBeginning LIKE '__:__ pm' THEN STR_TO_DATE(GigBeginning, '%l:%i %p')
      WHEN GigBeginning LIKE '__:__ pm SLT' THEN STR_TO_DATE(REPLACE(GigBeginning, ' pm SLT', ''), '%h:%i') + INTERVAL 12 HOUR
      WHEN GigBeginning LIKE '__:__' THEN STR_TO_DATE(GigBeginning, '%H:%i %p')
      ELSE GigBeginning24h
    END";
  mysqli_query($db, $sql); }

function blockIP($IP):void {
  global $db, $prefix, $SetupFrontendGuestbookBlockedIPsLimit;
  $IPArray = explode (', ', getSetup('SetupGuestbookSpamIPs'));
  if (in_array($IP, $IPArray)) { // IP already blocked
    echo 'IP is already blocked!<br>';
    // Move IP to the end of the array
    unset($IPArray[$IP]);
    $IPArray[] = $IP; }
  else { // IP not blocked yet
    $IPArray[] = $IP; }
  $IPArray = array_unique ($IPArray);
  // Limit count of IPs in database to 100
  $IPcount = count($IPArray);
  if ($IPcount>$SetupFrontendGuestbookBlockedIPsLimit)
    $IPArray = array_slice($IPArray, $IPcount-$SetupFrontendGuestbookBlockedIPsLimit);
  // Write back to database
  $newIPs = implode (', ', $IPArray);
  $SQLQuery = "UPDATE ".$prefix."setup SET SetupGuestbookSpamIPs = '$newIPs'";
  if (mysqli_query($db, $SQLQuery))
    echo 'IP address blocked!<br>';
  else
    echo '<span class="Fehlermeldung">ERROR: Blocking IP failed!</span><br>'; }

function logoutInactiveUsers():void {
  global $db, $prefix;
  $SetupUserMaximumInactivityTime = getSetup('SetupUserMaximumInactivityTime');
  if ($SetupUserMaximumInactivityTime<1)
    $SetupUserMaximumInactivityTime = 1;
  $Diff = time() - ($SetupUserMaximumInactivityTime*60);
  $SQLQuery = "UPDATE ".$prefix."user SET
    UserSession=NULL
    WHERE UserLastActivityTimestamp<'".$Diff."'";
  mysqli_query($db, $SQLQuery); }

function getShortenedString2($String, $Length):string {
// Function to shorten a string shown in back end table cells
  if ($String!=NULL AND isset($String)) { // Bugfix v1.2.83_028
    $String = strip_tags($String);
    $Title = htmlspecialchars($String, ENT_QUOTES);
    $NumberOfCharacters = mb_strlen($String, 'UTF-8');
    $Output = '<span title="'.$Title .'">';
    if ($NumberOfCharacters > $Length) {
      $String = mb_substr($String, 0, $Length, 'UTF-8');
      $String = trim($String).'…'; }
    return $Output.$String.'</span>'; }
  else
    return ''; }

function getShortenedString($String):string {
// Function to shorten a string shown in back end table cells
  global $CharsCalenderListFields;
  $String = strip_tags($String);
  $Title = str_replace('"', '', $String);
    $NumberOfCharacters = mb_strlen($String, 'UTF-8');
  $Output = '<span title="'.$Title .'">';
  if ($NumberOfCharacters > $CharsCalenderListFields) {
    $String = mb_substr($String, 0, $CharsCalenderListFields, 'UTF-8');
    $String = trim($String)."…"; }
  return $Output.$String.'</span>'; }

function getSetup($Var) {
  global $db, $prefix;
  $SQLQuery = "SELECT ".$Var." FROM ".$prefix."setup WHERE SetupID=1 LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) {
    if (mysqli_num_rows($Result)==1) {
      $temp=mysqli_fetch_assoc($Result);
      return $temp[$Var]; }
    else
      return false; }
  else
    return false; }

function getFrontendURL($Var):string {
// Function to get frontend urls either from running script or the settings in gigkalender.ini.php, to define correct links.
  global $SetupFrontendCalendarCurrentMonthURL;
  global $SetupFrontendCalendarGigDetailsURL;
  global $SetupGuestbookEmailURL;
  global $SetupGuestbookFormURL; // Bugfix v1.2.80_003
  global $SetupGuestbookURL;
  global $SetupGalleryURL;
  // Get url from setup
  if ($Var!='SetupFrontendCalendarCurrentMonthURL' // Bugfix v1.2.83_016
      AND $Var!='SetupFrontendCalendarGigDetailsURL'
      AND $Var!='SetupGuestbookEmailURL'
      AND $Var!='SetupGuestbookFormURL'
      AND $Var!='SetupGuestbookURL'
      AND $Var!='SetupGalleryURL')
    $setupURL = getSetup($Var);
  else
    $setupURL = '';
  // Get url defined in gigkalender.ini.php
  $iniURL = @${$Var};
  // Get url from currently running script
  if (isset($_SERVER['REQUEST_URI'])) $REQUEST_URI = $_SERVER['REQUEST_URI'];
    else $REQUEST_URI = '';
  // Check if set in Setup or gigkalender.ini.php, otherwise set REQUEST_URI
  if ($setupURL!='') $URL = $setupURL;
  elseif ($iniURL!='') $URL = $iniURL;
    else $URL = $REQUEST_URI;
  // Split URL into Path and Query
  $URLArray = parse_url($URL);
  //make new query string
  if (isset($URLArray['query'])) {
    $Path = str_replace("?".$URLArray['query'], "", $URL);
    $Query = @$URLArray['query'];
    // Save query vars in an array
    parse_str($Query, $QueryArray);
    // Remove GigKalender vars from Query
    unset($QueryArray['news_page']);
    unset($QueryArray['gb_page']);
    unset($QueryArray['album']);
    unset($QueryArray['image']);
    if (count($QueryArray)>0) {
      $Query = http_build_query($QueryArray, '', '&amp;');
      $Query = '?'.$Query; }
    else $Query = ''; }
  else {
    $Path = $URL;
    $Query = ''; }
  // calculate the URL to return
  if ($Var=='SetupFrontendCalendarGigDetailsURL') {
    global $Timestamp;
    if ($Timestamp!='') { // for month view
      $URL = $Path;
      if (preg_match('|\?|', $URL)) $URL .= '&timestamp='.$Timestamp;
        else $URL .= '?timestamp='.$Timestamp; }
    else { // for list view
      $URL = $Path.$Query;
      if (preg_match ( '|\?|', $URL )) $URL .= '&GigID=';
        else $URL .= '?GigID='; }}
  elseif ($Var=='SetupFrontendCalendarCurrentMonthURL') {
      $URL = $Path; }
  elseif ($Var=='SetupGalleryURL') {
    $URL = $Path; }
  elseif ($Var=='SetupGuestbookURL') {
    $URL = $Path.$Query; }
  elseif ($Var=='SetupGuestbookFormURL') {
    $URL = $Path.$Query;
    if (preg_match('|\?|', $URL)) $URL .= '&gb_page=form';
      else $URL .= '?gb_page=form'; }
  elseif ($Var=='SetupGuestbookEmailURL') {
    $URL .= $Query;
    if (preg_match('|\?|', $URL)) $URL .= '&amp;';
      else $URL .= '?'; }
  elseif ($Var=='SetupNewsChannelURL') {
    $URL = $Path.$Query; }
  if ($URL=="")
    echo "ERROR: Empty URL from getFrontendURL().";
  return $URL; }

function getPagination ($URL, $NumberPages, $CurrentPage, $Sorting, $PageVar):string {
  $maxNumberPageButtons = 9; // 9, uneven, greater 5
  // If even, then increment
  if ($maxNumberPageButtons%2==0) $maxNumberPageButtons++;
  // If too few buttons defined, set maximum number to 7
  if ($maxNumberPageButtons < 7) $maxNumberPageButtons = 7;
  if ($CurrentPage=="") {
    if ($Sorting="ASC") $CurrentPage = 1;
    elseif ($Sorting="DESC") $CurrentPage = $NumberPages; }
  $Result = '<div class="pagination">';
  $ButtonsHTML = array(); // Holds HTML for each button, for later sorting
  // Prepare a new URL for query strings
    if (preg_match('|\?|', $URL)) $newURL = $URL.'&'.$PageVar."=";
      else $newURL = $URL.'?'.$PageVar."=";
  // Check whether short or long pagination
  if ($NumberPages <= $maxNumberPageButtons) { // Short Pagination, e.g. [1 2 3 4 5 6 7]
      // Page Buttons
      $index = $NumberPages;
      while ($index > 0) {
        if ($index==$NumberPages) { // First Page Button
          if ($Sorting=="ASC")
            $shortPaginationURL = $newURL.$index;
          else
            $shortPaginationURL = $URL; }
        elseif ($index==1) { // Last Page Button
          if ($Sorting=="ASC")
            $shortPaginationURL = $URL;
          else
            $shortPaginationURL = $newURL."1"; }
        // Center Buttons
        else $shortPaginationURL = $newURL.$index;
        if ($CurrentPage!=$index)
          array_push($ButtonsHTML, '<a href="'.$shortPaginationURL.'">'.$index--.'</a>');
        else
          array_push($ButtonsHTML, '<a class="current">'.$index--.'</a>'); }}
  else { // Long Pagination, e.g. [1 … 5 6 7 … 11]
      $maxNumberPageButtons = $maxNumberPageButtons-4;
      $index = $maxNumberPageButtons;
      // First Page Button
        if ($CurrentPage==$NumberPages)
          array_push($ButtonsHTML, '<a class="current">'.$NumberPages--.'</a>');
        else
          if ($Sorting=="ASC")
            array_push($ButtonsHTML, '<a href="'.$newURL.$NumberPages.'">'.$NumberPages--.'</a>');
          else
            array_push($ButtonsHTML, '<a href="'.$URL.'">'.$NumberPages--.'</a>');
      // Hidden Buttons on Left side
        $hiddenButtons = ($NumberPages-$CurrentPage)-(($maxNumberPageButtons-1)/2);
        if ($hiddenButtons>1) {
          array_push($ButtonsHTML, '<a class="passive">…</a>');
          $NumberPages = $NumberPages-$hiddenButtons; }
        else {
          if ($CurrentPage!=$NumberPages)
            array_push($ButtonsHTML, '<a href="'.$newURL.$NumberPages.'">'.$NumberPages--.'</a>');
          else
            array_push($ButtonsHTML, '<a class="current">'.$NumberPages--.'</a>');}
      // Center Buttons
      if ($hiddenButtons > 1 AND $NumberPages<$maxNumberPageButtons+2) $NumberPages = $maxNumberPageButtons+2;
      while ($NumberPages > 0 AND $index > 0) {
        if ($CurrentPage!=$NumberPages)
          array_push($ButtonsHTML, '<a href="'.$newURL.$NumberPages.'">'.$NumberPages--.'</a>');
        else
          array_push($ButtonsHTML, '<a class="current">'.$NumberPages--.'</a>');
        $index--; }
      // Hidden Buttons on Right side
        $hiddenButtons = $NumberPages-1;
        if ($hiddenButtons>1)
          array_push($ButtonsHTML, '<a class="passive">…</a>');
        else {
          if ($CurrentPage!=$NumberPages)
            array_push($ButtonsHTML, '<a href="'.$newURL.$NumberPages.'">'.$NumberPages--.'</a>');
          else
            array_push($ButtonsHTML, '<a class="current">'.$NumberPages--.'</a>'); }
      // Last Page Button
        if ($CurrentPage!=1)
          if ($Sorting=="ASC")
            array_push($ButtonsHTML, '<a href="'.$URL.'">1</a>');
          else
            array_push($ButtonsHTML, '<a href="'.$newURL.'1">1</a>');
        else
          array_push($ButtonsHTML, '<a class="current">1</a>'); }
  if ($Sorting=="ASC") $ButtonsHTML = array_reverse($ButtonsHTML);
  $Result .= implode("", $ButtonsHTML); // array to string
  return $Result.'</div>'; }

function formatFileSize($bytes, $decimals):String {
  // http://php.net/manual/de/function.filesize.php#106569
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  if ($factor==0) $appendix = '';
  else $appendix = 'iB';
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .' '. @$sz[$factor].$appendix; }

function IsUserAdmin():bool {
  global $db;
  global $prefix;
  $SQLQuery='SELECT UserStatus FROM '.$prefix.'user WHERE UserSession="'.session_id().'"';
  $Result = mysqli_query($db, $SQLQuery);
  $temp = mysqli_fetch_assoc($Result);
  if (isset($temp['UserStatus']) AND $temp['UserStatus']==='Admin') // Bugfix: v1.2.80_172
    return true;
  else
    return false; }

function getCurrentURL():string {
  // Taken from https://stackoverflow.com/questions/6768793/get-the-full-url-in-php
  return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; }

function getNumberOfGigsAtSameDay($GigDate):int {
  global $prefix;
  global $db;
  $SQLQuery = "SELECT count(*) as number FROM ".$prefix."gigs WHERE GigDate=".$GigDate;
  $Result = mysqli_query($db, $SQLQuery);
  $row = mysqli_fetch_array($Result);
  return $row['number']; }

function getRealIP():string {
  //whether ip is from share internet
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      $ip_address = $_SERVER['HTTP_CLIENT_IP']; }
  //whether ip is from proxy
  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR']; }
  //whether ip is from remote address
  else {
      $ip_address = $_SERVER['REMOTE_ADDR']; }
  return $ip_address; }

function getMapURL($GigCountry, $GigDistrict, $GigPostalCode, $GigCity):string {
  global $BrowserLanguageShort;
  if ($GigPostalCode=="0")
    $GigPostalCode = "";
  $Location = "";
  if ($GigCountry!='')
    $Location = $Location.$GigCountry;
  if ($GigCountry!='' AND $GigPostalCode!='')
    $Location = $Location.'-';
  if ($GigPostalCode!='')
    $Location = $Location.$GigPostalCode;
  if ($GigCountry!='' AND $GigPostalCode=='' AND $GigCity!='')
    $Location = $Location.' ';
  if ($GigPostalCode!='' AND $GigCity!='')
    $Location = $Location.' ';
  if ($GigCity!='')
    $Location = $Location.$GigCity;
  if ($GigDistrict!='' AND $GigCity=='')
    $Location .= $GigDistrict;
  return 'https://www.openstreetmap.org/search?query='.rawurlencode($Location); }

function writeToCache($Filename, $Content) {
  echo $Content;
  global $GigKalenderPath;
  $Path = 'cache/';
  if (!is_dir($Path))
    mkdir($Path, 0755);
  $fp = fopen($Path.$Filename, "w+");
  fwrite($fp, $Content); }

function getWeekdayFromDate($Day, $Month, $Year) {
  $UnixTimestamp = mktime(0, 0, 0, $Month, $Day, $Year);
  $Weekday = date('w', $UnixTimestamp);
  if ($Weekday == 0)
    $Weekday = 7;
  return $Weekday; }

function getCurrentUserVar($Var) {
  global $db;
  global $prefix;
  if ($Var>0 OR $Var!='') {
    $SQLQuery = "SELECT ".$Var." FROM ".$prefix."user WHERE UserSession='".session_id()."' LIMIT 1";
    $Result = mysqli_query($db, $SQLQuery);
    if ($Result) {
      if (mysqli_num_rows($Result)==1) {
        $temp = mysqli_fetch_assoc($Result);
        return $temp[$Var]; }
      else return false; }
    else return false; }
  else return false; }

function getDaysOfAMonth ($Month, $Year):int {
  $UnixTimestamp = mktime(0, 0, 0, $Month, 1 , $Year);
  return date('t', $UnixTimestamp); }

function emptyDirectory ($strDir) {
  $strDir .= '/'; // v1.2.77_023
  if (is_dir($strDir)) {
    $oDir = dir( $strDir );
    while (false!==($strFile=$oDir->read())) {
      if ($strFile!='.' && $strFile!='..' && !is_link($strDir.$strFile)) {
        if (is_file($strDir.$strFile)) {
          if (@unlink($strDir.$strFile))      {
          }
          else {
            print '<span class="Fehlermeldung">ERROR: File NOT deleted! ('.$strFile.')</span><br />'; }}
        else {
          if(is_dir($strDir.$strFile)) {
            emptyDirectory($strDir.$strFile.'/');
            rmdir($strDir.$strFile); }}}}
    $oDir->close(); }}

function clearCache () {
  $Path = str_replace('\\','/', __FILE__);
  $Path = str_replace('functions/standard.php', '', $Path);
  emptyDirectory($Path.'cache/'); }

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

function getNameOfMonthFromNumberOfMonth ($Month):String {
  switch ($Month) {
    case 1: return $GLOBALS['L_January'];
    case 2: return $GLOBALS['L_February'];
    case 3: return $GLOBALS['L_March'];
    case 4: return $GLOBALS['L_April'];
    case 5: return $GLOBALS['L_May'];
    case 6: return $GLOBALS['L_June'];
    case 7: return $GLOBALS['L_July'];
    case 8: return $GLOBALS['L_August'];
    case 9: return $GLOBALS['L_September'];
    case 10: return $GLOBALS['L_October'];
    case 11: return $GLOBALS['L_November'];
    case 12: return $GLOBALS['L_December'];
    default: return 'ERROR'; }}

function getFileNames($directory, $fileTypes="/*.*"):Array {
  // returns just the files names of all files in a directory
  // optionally results can get filtered by filetypes via regular expression
  $files = array();
  $files = glob( $directory.$fileTypes, GLOB_BRACE);
  $count = count($files); // Dateien zählen
  for ($i=0; $i<$count; $i++)
    $files[$i] = basename($files[$i]); // remove paths
  array_multisort($files);
  return $files; }

function getAnonymIp($ip) {
  // Taken from http://www.selfphp.de/code_snippets/code_snippet.php?id=134
  return preg_replace('/[0-9]+\z/', 'x', $ip); }

function checkEmail ($email) {
  //$email = strtolower($email);
  //if (preg_match('/^[a-z0-9\._-]+@+[a-z0-9\._-]+\.+[a-z]{2,4}$/', $email)
    //AND isEmailTLDValid($email)
    //AND isEmailDomainValid($email))
  if (filter_var($email, FILTER_VALIDATE_EMAIL))
     return true;
  else
     return false; }

function checkURL ($url) {
  return filter_var($url, FILTER_VALIDATE_URL); }

function token ()
{
  if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token'])
  {
    unset($_SESSION['token']);
    exit;
    echo 'I got you!';
  }
  unset($_SESSION['token']);
  $_SESSION['token'] = md5(md5(uniqid().uniqid().mt_rand()));
}

function getToken ()
{
    return md5(md5(uniqid().uniqid().mt_rand()));
}

function getURLWithoutFinalSlash ($url)
{
  if (substr( $url, strlen($url)-1 )=="/" AND $url!='http://') return substr( $url, 0, strlen($url)-1 );
    else return $url;
}

function isEmailDomainValid ($email)
{
  if (function_exists('checkdnsrr'))
  {
    $tempArray = explode("@",$email); // because array_pop() requires a var
    if (checkdnsrr(array_pop($tempArray))) return true;
  }
  else return true;
}

function isEmailTLDValid($email)
{
  $tld = array('ac', 'ad', 'ae', 'aero', 'af', 'ag', 'ai', 'al', 'am', 'an',
    'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'az', 'ba', 'bb', 'bd', 'be',
    'bf', 'bg', 'bh', 'bi', 'biz', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt',
    'bv', 'bw', 'by', 'bz', 'ca', 'cat', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci',
    'ck', 'cl', 'cm', 'cn', 'co', 'com', 'coop', 'cr', 'cu', 'cv', 'cx', 'cy',
    'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'edu', 'ee', 'eg', 'er',
    'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd',
    'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gov', 'gp', 'gq', 'gr',
    'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id',
    'ie', 'il', 'im', 'in', 'info', 'int', 'io', 'iq', 'ir', 'is', 'it', 'je',
    'jm', 'jo', 'jobs', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kr', 'kw',
    'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
    'ly', 'ma', 'mc', 'md', 'mg', 'mh', 'mil', 'mk', 'ml', 'mm', 'mn', 'mo',
    'mobi', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'museum', 'mv', 'mw', 'mx',
    'my', 'mz', 'na', 'name', 'nc', 'ne', 'net', 'nf', 'ng', 'ni', 'nl', 'no',
    'np', 'nr', 'nu', 'nz', 'om', 'org', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk',
    'pl', 'pm', 'pn', 'pr', 'pro', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro',
    'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk',
    'sl', 'sm', 'sn', 'so', 'sr', 'st', 'su', 'sv', 'sy', 'sz', 'tc', 'td',
    'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tp', 'tr', 'travel',
    'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'um', 'us', 'uy', 'uz', 'va',
    'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'yu', 'za', 'zm');
  $email = rtrim($email);
  $email = substr($email, strrpos($email, '.') + 1);
  if (!$email) return false;
  if (in_array(strtolower($email), $tld)) return true;
  return false;
}

function deleteFileInCache ( $Timestamp )
{
  $Year = date('Y', $Timestamp);
  $Month = date('n', $Timestamp);
  $FileName1 = 'admin-'.$Year.'-'.$Month.'.php';
  $FileName2 = 'user-'.$Year.'-'.$Month.'.php';
  $Path = 'cache/';
  if ( !is_link( $Path . $FileName1 ) AND is_file ( $Path . $FileName1 ) )
  {
    if ( @ !unlink ( $Path . $FileName1 ) )
    {
      print '<span class="Fehlermeldung">ERROR: Cache NOT cleared! ('.$FileName1.')</span><br />';
    }
  }
  if ( !is_link( $Path . $FileName2 ) AND is_file ( $Path . $FileName2 ) )
  {
    if ( @ !unlink ( $Path . $FileName2 ) )
    {
      print '<span class="Fehlermeldung">ERROR: Cache NOT cleared! ('.$FileName2.')</span><br />';
    }
  }
}

function getArrayForAutoSuggest ( $Field )
{
  global $prefix;
  global $db;

  $SQLQuery = "SELECT DISTINCT `".$Field."` FROM `".$prefix."gigs` ORDER BY `".$Field."` ASC";
  $Result = mysqli_query($db, $SQLQuery);
  $ArrayForAutoSuggest = array();
  while ($daten = mysqli_fetch_assoc($Result))
  {
    $temp = $daten[$Field];
    if ($temp!='' OR $temp!=0) array_push($ArrayForAutoSuggest, $temp);
  }
  $String = implode ("|", $ArrayForAutoSuggest);
  $String = str_replace('"', '\"',$String);
  return $String;
}

function translateLanguageVarString ( $String )
{
  $Array = explode( ', ', $String);
  for ($i=0; $i<count($Array); $i++)
  {
    global ${'L_'.$Array[$i]};
    $Array[$i] = ${'L_'.$Array[$i]};
  }
  return implode( ', ', $Array);
}
 
function setSetupVar ( $Var, $Value )
{
  global $prefix;
  global $db;

  $SQLQuery = "UPDATE ".$prefix."setup SET
    $Var = '$Value'";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { return true; }
  else {return false;}
}
 
function setUserVar ( $Var, $Value )
{
  global $prefix;
  global $db;

  $SQLQuery = "UPDATE ".$prefix."user SET
    $Var = '$Value'";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { return true; }
  else {return false;}
}
 
function publishedGigOnTimestamp ( $Timestamp )
{
  global $prefix;
  global $db;

  $SQLQuery = "SELECT * FROM ".$prefix."gigs WHERE GigDate = ".$Timestamp." AND (GigStatus = 'Gig'";
  if ( getSetup('SetupFrontendAllowOptionalGigs') ) $SQLQuery .= " OR GigStatus = 'Option'";
  $SQLQuery .= ")";
  if ( !getSetup('SetupFrontendAllowPrivateGigs') ) $SQLQuery .= " AND GigIsPrivate = 0";
  $SQLQuery .= " AND GigPublish = 1";
  $SQLQuery .= " LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    return true;
  }
  else return false;
}

function convertISO8601ToTimestamp ($ISO8601)
{
  global $L_ERROR_Invalid_date;
  if ( $ISO8601>0)
  {
    $eregStr =  '/([0-9]{4})-'. // centuries & years CCYY-
                '([0-9]{2})-'. // months MM-
                '([0-9]{2})'.  // days DD
                'T'.           // separator T
                '([0-9]{2}):'. // hours hh:
                '([0-9]{2}):'. // minutes mm:
                '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
                '(Z|[+\-][0-9]{2}:?[0-9]{2})?/'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
              if(preg_match($eregStr,$ISO8601,$regs))
              {
              $temp = strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
              // not utc
                if($regs[8] != 'Z')
                {
                  $op = substr($regs[8],0,1);
                  $h = substr($regs[8],1,2);
                  $m = substr($regs[8],strlen($regs[8])-2,2);
                  if($op == '-')
                  {
                    $temp = $temp+($h*3600+$m*60);
                  }
                  elseif($op == '+')
                  {
                    $temp = $temp-($h*3600+$m*60);
                  }
                }
              return $temp;
              }
            else // OpenOffice JJJJ-MM-TT HH:MM:SSZ
            {
              $eregStr =  '/([0-9]{4})-'. // centuries & years CCYY-
                          '([0-9]{2})-'. // months MM-
                          '([0-9]{2})'.  // days DD
                          ' '.           // separator ' '
                          '([0-9]{2}):'. // hours hh:
                          '([0-9]{2}):'. // minutes mm:
                          '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
                          '(Z|[+\-][0-9]{2}:?[0-9]{2})?/'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
              if(preg_match($eregStr,$ISO8601,$regs))
              {

              $temp = strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
              // not utc
                if($regs[8] != 'Z')
                {
                  $op = substr($regs[8],0,1);
                  $h = substr($regs[8],1,2);
                  $m = substr($regs[8],strlen($regs[8])-2,2);
                  if($op == '-')
                  {
                    $temp = $temp+($h*3600+$m*60);
                  }
                  elseif($op == '+')
                  {
                    $temp = $temp-($h*3600+$m*60);
                  }
                }
              return $temp;
              }
            else // OpenOffice JJJJ-MM-TT
            {
              $eregStr =  '/([0-9]{4})-'. // centuries & years CCYY-
                          '([0-9]{2})-'. // months MM-
                          '([0-9]{2})/';  // days DD
              if(preg_match($eregStr,$ISO8601,$regs))
              {
                $temp = strtotime("$regs[1]-$regs[2]-$regs[3] 0:0:0Z");
                return $temp;
              }
              else // Timestamp
              {
                $eregStr =  '/([0-9]{9,10})/'; // Timestamp
                if(preg_match($eregStr,$ISO8601,$regs))
                {
                  return $regs[0];
                }
                else { echo '<span class="ErrorMessage">'.$L_ERROR_Invalid_date.' ('.$ISO8601.')</span><br />'; return false; }
              }
            }
              
            }
  }
  else return '';

}
 
function convertTimestampToISO8601 ($Timestamp)
{ 
  if ( $Timestamp>0 )
  {
    // PHP4
      $temp = date('Y-m-d\TH:i:sO', $Timestamp);
      $String = substr ( $temp, 0, 22 ).':'.substr ( $temp, 22 );
      return $String;
    // PHP5
      // return date('c',$Timestamp);
  }
  else return '';
}

function getGigVarFromGigDate ($GigDate, $Var)
{
  global $db;
  global $prefix;
  $SQLQuery = "SELECT ".$Var."
    FROM ".$prefix."gigs
    WHERE GigDate='".$GigDate."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    return $temp[$Var];
  }
  else {echo '_'; return false;}
}
 
function getGigVarFromGigID ($GigID, $Var)
{
  global $db;
  global $prefix;
  $SQLQuery = "SELECT ".$Var."
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    return $temp[$Var];
  }
  else return false;
}
 
function changeGigIsPrivate ( $GigID )
{
  global $prefix;
  global $db;
  
  // aktuellen GigStatus abfragen
  $SQLQuery = "SELECT GigIsPrivate
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    $aktuellerGigStatus = $temp['GigIsPrivate'];
  }
  // neuen GigStatus setzen
  if ( $aktuellerGigStatus=='0' ) $neuerGigStatus = '1';
  if ( $aktuellerGigStatus=='1' ) $neuerGigStatus = '0';
  $DateOfLastEdit = date("U");
  $SQLQuery = "UPDATE ".$prefix."gigs SET 
    GigIsPrivate = '".$neuerGigStatus."',
    GigDateOfLastEdit = '".$DateOfLastEdit."',
    GigLastEditor = '".getCurrentUserVar('UserName')."'
    WHERE GigID = '".$GigID."' LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { return true; }
    else {return false;}
}
 
function changeGigPublishing ( $GigID )
{
  global $prefix;
  global $db;
  
  // aktuellen GigStatus abfragen
  $SQLQuery = "SELECT GigPublish
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    $aktuellerGigStatus = $temp['GigPublish'];
  }
  // neuen GigStatus setzen
  if ( $aktuellerGigStatus=='0' ) $neuerGigStatus = '1';
  if ( $aktuellerGigStatus=='1' ) $neuerGigStatus = '0';
  $DateOfLastEdit = date("U");
  $SQLQuery = "UPDATE ".$prefix."gigs SET 
    GigPublish = '".$neuerGigStatus."',
    GigDateOfLastEdit = '".$DateOfLastEdit."',
    GigLastEditor = '".getCurrentUserVar('UserName')."'
    WHERE GigID = '".$GigID."' LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { return true; }
    else {return false;}
}
 
function CheckGigPublish ($GigID)
{
  global $prefix;
  global $db;

  $GigPublish = "";
  $GigStatus = "";
  $SQLQuery = "SELECT * FROM ".$prefix."gigs WHERE GigID = ".$GigID." LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  while ($row = mysqli_fetch_array($Result))
  { 
    extract($row);    
  }
  if  (
        ( 
          $GigStatus == 'Gig' 
          OR 
          ( $GigStatus == 'Option' AND getSetup('SetupFrontendAllowOptionalGigs') )
        ) 
        AND 
        ( !$GigIsPrivate OR getSetup('SetupFrontendAllowPrivateGigs') )
        AND
        $GigPublish == '1' 
     ) 
  { return true; }
  else { return false;} 
} 
 
function DatumMitUhrzeitAusTimestamp ($Timestamp)
{ 
  if ( $Timestamp != '0' AND $Timestamp != '' )
  {
    global $SetupBackendDateFormat;
    global $SetupBackendTimeFormat;
    return date($SetupBackendDateFormat, $Timestamp).' - '.date($SetupBackendTimeFormat, $Timestamp);
  }
  else { return '-'; }
} 
 
function checkICQNumber ($ICQNumber)
{ 
  if (preg_match('/^([0-9]{5,9}$)/', $ICQNumber)) return true;
    else return false;
} 
 
function getNameOfWeekday ( $Timestamp )
{ 
  global $L_Mo;
  global $L_Tu;
  global $L_We;
  global $L_Th;
  global $L_Fr;
  global $L_Sa;
  global $L_Su;
  
  $Weekday = date('w', $Timestamp);
  switch ($Weekday) 
  {
    case 0: $temp = $L_Su; break;
    case 1: $temp = $L_Mo; break;
    case 2: $temp = $L_Tu; break;
    case 3: $temp = $L_We; break;
    case 4: $temp = $L_Th; break;
    case 5: $temp = $L_Fr; break;
    case 6: $temp = $L_Sa; break;
    default: echo "ERROR: Could not calculate name of weekday!<br />";
  }
  return $temp;
}

function updateUserActivity ()
{
  global $db;
  global $prefix;
  
  $SQLQuery="UPDATE ".$prefix."user SET
    UserLastActivityTimestamp=".time()."
    WHERE UserName='".getCurrentUser()."' LIMIT 1";
  mysqli_query($db, $SQLQuery);
} 
 
function AnzahlAllerGigsInDatenbank ()
{
  global $db;
  global $prefix;

  $SQLQuery = "SELECT count(*) as number FROM ".$prefix."gigs";
  $Result = mysqli_query($db, $SQLQuery);
  $row = mysqli_fetch_array($Result);
  return $row['number'];
} 
 
function AnzahlGigsImZeitraum ( $Zeitraum, $GigStatus )
{
    global $prefix;
    global $db;
    
    $TimestampOfToday = getTimestampFromDate(date("d"), date("m"), date("y"));
    $SQLQuery = "SELECT count(*) as number FROM ".$prefix."gigs";
    if ( $Zeitraum!='all' OR $GigStatus!='all' ) { $SQLQuery = $SQLQuery." WHERE"; }
    if ( $Zeitraum =="future" ) { $SQLQuery = $SQLQuery." GigDate>=".$TimestampOfToday; }
    if ( $Zeitraum =="past" ) { $SQLQuery = $SQLQuery." GigDate<=".$TimestampOfToday; }
    if ( $Zeitraum!='all' && $GigStatus!='all' ) { $SQLQuery = $SQLQuery." AND"; }
    if ( $GigStatus!='all' ) { $zweiterFilter = " GigStatus='".$GigStatus."'"; }
    else { $zweiterFilter = ""; }
    $SQLQuery = $SQLQuery.$zweiterFilter;
    $Result = mysqli_query($db, $SQLQuery);
    $row = mysqli_fetch_array($Result);
    return $row['number'];
}
 
function getUserVar ($UserName, $Var)
{
  global $db;
  global $prefix;
  
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserName = mysqli_real_escape_string($db, $UserName);

  $SQLQuery = "SELECT ".$Var."
    FROM ".$prefix."user
    WHERE UserName='".$UserName."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    return $temp[$Var];
  }
  else return false;
}

function getLocationString ( $GigCountry, $GigDistrict, $GigPostalCode, $GigCity )
{
  global $SetupCalendarLocationShowCountry;
  global $SetupCalendarLocationShowDistrict;
  global $SetupCalendarLocationShowPostalCode;
  global $SetupCalendarLocationShowCity;

  if ($GigPostalCode=="0") $GigPostalCode = "";
  $Location = "";
  if ($SetupCalendarLocationShowCountry)
    if ($GigCountry!='') $Location = $Location.$GigCountry;
  if ($SetupCalendarLocationShowCountry AND $SetupCalendarLocationShowPostalCode)
    if ( $GigCountry!='' AND $GigPostalCode!='') $Location = $Location.'-';
  if ($SetupCalendarLocationShowPostalCode)
    if ( $GigPostalCode!='') $Location = $Location.$GigPostalCode;
  if ($SetupCalendarLocationShowCountry AND $SetupCalendarLocationShowPostalCode AND $SetupCalendarLocationShowCity)
    if ( $GigCountry!='' AND $GigPostalCode=='' AND $GigCity!='' ) $Location = $Location.' ';
  if ($SetupCalendarLocationShowPostalCode AND $SetupCalendarLocationShowCity)
    if ( $GigPostalCode!='' AND $GigCity!='') $Location = $Location.' ';
  if ($SetupCalendarLocationShowCity)
    if ( $GigCity!='') $Location = $Location.$GigCity;
  if ($SetupCalendarLocationShowDistrict)
  if ( $GigDistrict!='') $Location = $Location.' ('.$GigDistrict.')';
  return $Location;
}

function checkGigDatum ($GigDateDay, $GigDateMonth, $GigDateYear)
{
  if ( checkdate($GigDateMonth, $GigDateDay, $GigDateYear) ) { return true; }
}

function zukuenftigeTermineEingetragen()
{
  global $prefix;
  global $db;
  global $L_GigStatusGig;

  $TimestampOfToday = getTimestampFromDate(date("d"), date("m"), date("y"));
  $zukuenftigeTermineEingetragen = false;

  $SQLQuery="SELECT GigDate
    FROM ".$prefix."gigs
    WHERE GigStatus='Gig' 
      OR GigStatus='Blocked'
      OR GigStatus='Option' 
      OR GigStatus='Rehearsal'";
  $Result = mysqli_query($db, $SQLQuery);
  while($row = mysqli_fetch_row($Result))
  {
    if (strtolower($row[0]) >= $TimestampOfToday) { $zukuenftigeTermineEingetragen = true; }
  }
  if ($zukuenftigeTermineEingetragen) return true;
  else return false;
}

function startTime()
{
  $timeExplode = explode(" ", microtime());
  $time = $timeExplode[1] + $timeExplode[0];
  return $time;
}

function endTime($timer)
{
  $timeExplode = explode(" ", microtime());
  $time = $timeExplode[1] + $timeExplode[0];
  $finish = $time - $timer;
  $endTime = sprintf("%4.3f", $finish);
  return $endTime;
}

function getTooltip($Timestamp)
{
  global $prefix;
  global $db;
  $Tooltip = "";

  $SQLQuery = "SELECT * FROM " .$prefix."gigs WHERE GigDate = ".$Timestamp;
  $Result = mysqli_query($db, $SQLQuery);
  while ($row = mysqli_fetch_array($Result))
  {
    extract($row);
    $Tooltip = getLocationString($GigCountry, $GigDistrict, $GigPostalCode, $GigCity);
    if ( $GigArtist != '') { $Tooltip .= '&#10;'.$GigArtist; }
    if ( $GigEvent != '') { $Tooltip .= '&#10;'.$GigEvent; }
    if ( $GigNotes != '') { $Tooltip .= $GigNotes; }
  }
  $Tooltip = str_replace('"', '&quot;', $Tooltip);
  $Tooltip = str_replace('<p>', '&#10;', $Tooltip);
  $Tooltip = preg_replace("/\r|\n/s", "", $Tooltip);
  $Tooltip = strip_tags($Tooltip);
  return $Tooltip;
}

function editSetup ( $SetupRefreshtime,
                     $SetupRowsTextareas,
                     $SetupExportSeparator,
                     $SetupFrontendLanguage,
                     $SetupGuestbookEntriesPerPage,
                     $SetupGuestbookMail,
                     $SetupFrontendCssFile,
                     $SetupGuestbookEntriesUnlock,
                     $SetupGuestbookSpamDomains,
                     $SetupGuestbookSpamIPs,
                     $SetupGuestbookSpamWords,
                     $SetupUserMaximumInactivityTime,
                     $SetupNewsEntriesPerPage,
                     $SetupFrontendAllowOptionalGigs,
                     $SetupFrontendAllowPrivateGigs,
                     $SetupAllowDoubleDates,
                     $SetupCalendarAttributeInAddGigForm,
                     $SetupFrontendAttributes,
                     $SetupFrontendDetailAttributes,
                     $SetupNewsChannelTitle,
                     $SetupNewsChannelURL,
                     $SetupNewsChannelDescription,
                     $SetupNewsChannelLanguage,
                     $SetupNewsChannelCopyright,
                     $SetupFrontendCalendarCharsInFields,
                     $SetupFrontendCalendarShowTableHeads,
                     $SetupFrontendCalendarSelector,
                     $SetupFrontendCalendarMaxAmountOfGigs,
                     $SetupFrontendCalendarPeriodSelector,
                     $SetupFrontendCalendarShowMonthlySeparator,
                     $SetupShowEditorInAddGigForm)
{
  global $prefix;
  global $db;
  
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $SetupRefreshtime = mysqli_real_escape_string($db, $SetupRefreshtime);
    $SetupRowsTextareas = mysqli_real_escape_string($db, $SetupRowsTextareas);
    $SetupExportSeparator = mysqli_real_escape_string($db, $SetupExportSeparator);
    $SetupGuestbookMail = mysqli_real_escape_string($db, $SetupGuestbookMail);
    $SetupFrontendCssFile = mysqli_real_escape_string($db, $SetupFrontendCssFile);
    $SetupGuestbookSpamDomains = mysqli_real_escape_string($db, $SetupGuestbookSpamDomains);
    $SetupGuestbookSpamIPs = mysqli_real_escape_string($db, $SetupGuestbookSpamIPs);
    $SetupGuestbookSpamWords = mysqli_real_escape_string($db, $SetupGuestbookSpamWords);
    $SetupUserMaximumInactivityTime = mysqli_real_escape_string($db, $SetupUserMaximumInactivityTime);
    $SetupNewsEntriesPerPage = mysqli_real_escape_string($db, $SetupNewsEntriesPerPage);
    $SetupCalendarAttributeInAddGigForm = mysqli_real_escape_string($db, $SetupCalendarAttributeInAddGigForm);
    $SetupFrontendAttributes = mysqli_real_escape_string($db, $SetupFrontendAttributes);
    $SetupFrontendDetailAttributes = mysqli_real_escape_string($db, $SetupFrontendDetailAttributes);
    $SetupNewsChannelTitle = mysqli_real_escape_string($db, $SetupNewsChannelTitle);
    $SetupNewsChannelURL = mysqli_real_escape_string($db, $SetupNewsChannelURL);
    $SetupNewsChannelDescription = mysqli_real_escape_string($db, $SetupNewsChannelDescription);
    $SetupNewsChannelLanguage = mysqli_real_escape_string($db, $SetupNewsChannelLanguage);
    $SetupNewsChannelCopyright = mysqli_real_escape_string($db, $SetupNewsChannelCopyright);
    $SetupFrontendCalendarCharsInFields = mysqli_real_escape_string($db, $SetupFrontendCalendarCharsInFields);
    $SetupFrontendCalendarMaxAmountOfGigs = mysqli_real_escape_string($db, $SetupFrontendCalendarMaxAmountOfGigs);

  // Leere numerische Variablen als NULL definieren
    if ( $SetupRefreshtime=='' ) $SetupRefreshtime="NULL";
    if ( $SetupRowsTextareas=='' ) $SetupRowsTextareas="NULL";
    if ( $SetupGuestbookEntriesPerPage=='' ) $SetupGuestbookEntriesPerPage="NULL";
    if ( $SetupGuestbookEntriesUnlock=='' ) $SetupGuestbookEntriesUnlock="NULL";
    if ( $SetupUserMaximumInactivityTime=='' ) $SetupUserMaximumInactivityTime="NULL";
    if ( $SetupNewsEntriesPerPage=='' ) $SetupNewsEntriesPerPage="NULL";
    if ( $SetupFrontendAllowOptionalGigs=='' ) $SetupFrontendAllowOptionalGigs="NULL";
    if ( $SetupFrontendAllowPrivateGigs=='' ) $SetupFrontendAllowPrivateGigs="NULL";
    if ( $SetupAllowDoubleDates=='' ) $SetupAllowDoubleDates="NULL";
    if ( $SetupFrontendCalendarCharsInFields=='' ) $SetupFrontendCalendarCharsInFields="NULL";
    if ( $SetupFrontendCalendarShowTableHeads=='' ) $SetupFrontendCalendarShowTableHeads="NULL";
    if ( $SetupFrontendCalendarMaxAmountOfGigs=='' ) $SetupFrontendCalendarMaxAmountOfGigs="NULL";
    if ( $SetupFrontendCalendarShowMonthlySeparator=='' ) $SetupFrontendCalendarShowMonthlySeparator="NULL";
    if ( $SetupShowEditorInAddGigForm=='' ) $SetupShowEditorInAddGigForm="NULL";

  $SQLQuery = "UPDATE ".$prefix."setup SET
    SetupRefreshtime = $SetupRefreshtime,
    SetupRowsTextareas = $SetupRowsTextareas,
    SetupExportSeparator = '$SetupExportSeparator',
    SetupFrontendLanguage = '$SetupFrontendLanguage',
    SetupGuestbookEntriesPerPage = $SetupGuestbookEntriesPerPage,
    SetupGuestbookMail = '$SetupGuestbookMail',
    SetupFrontendCssFile = '$SetupFrontendCssFile',
    SetupGuestbookEntriesUnlock = $SetupGuestbookEntriesUnlock,
    SetupGuestbookSpamDomains = '$SetupGuestbookSpamDomains',
    SetupGuestbookSpamIPs = '$SetupGuestbookSpamIPs',
    SetupGuestbookSpamWords = '$SetupGuestbookSpamWords',
    SetupUserMaximumInactivityTime = $SetupUserMaximumInactivityTime,
    SetupNewsEntriesPerPage = $SetupNewsEntriesPerPage,
    SetupFrontendAllowOptionalGigs = $SetupFrontendAllowOptionalGigs,
    SetupFrontendAllowPrivateGigs = $SetupFrontendAllowPrivateGigs,
    SetupAllowDoubleDates = $SetupAllowDoubleDates,
    SetupCalendarAttributeInAddGigForm = '$SetupCalendarAttributeInAddGigForm',
    SetupFrontendAttributes = '$SetupFrontendAttributes',
    SetupFrontendDetailAttributes = '$SetupFrontendDetailAttributes',
    SetupNewsChannelTitle = '$SetupNewsChannelTitle',
    SetupNewsChannelURL = '$SetupNewsChannelURL',
    SetupNewsChannelDescription = '$SetupNewsChannelDescription',
    SetupNewsChannelLanguage = '$SetupNewsChannelLanguage',
    SetupNewsChannelCopyright = '$SetupNewsChannelCopyright',
    SetupFrontendCalendarCharsInFields = $SetupFrontendCalendarCharsInFields,
    SetupFrontendCalendarShowTableHeads = $SetupFrontendCalendarShowTableHeads,
    SetupFrontendCalendarSelector = '$SetupFrontendCalendarSelector',
    SetupFrontendCalendarMaxAmountOfGigs = $SetupFrontendCalendarMaxAmountOfGigs,
    SetupFrontendCalendarPeriodSelector = '$SetupFrontendCalendarPeriodSelector',
    SetupFrontendCalendarShowMonthlySeparator = $SetupFrontendCalendarShowMonthlySeparator,
    SetupShowEditorInAddGigForm = $SetupShowEditorInAddGigForm";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { return true; }
  else {return false;}
}

function testDoppelteGigs ($GigDateDay, $GigDateMonth, $GigDateYear)
{
  global $db;
  global $prefix;
  $Timestamp = getTimestampFromDate($GigDateDay, $GigDateMonth, $GigDateYear);
  $doppelteVorhanden = false;

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

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

  $SQLQuery="SELECT UserStatus
    FROM ".$prefix."user
    WHERE UserSession='".session_id()."'";
  $Result= mysqli_query($db, $SQLQuery);
  $temp = mysqli_fetch_assoc($Result);
  if ($temp['UserStatus'] == "User") { return true; }
  else { return false; }
}

function logout() {
  global $db;
  global $prefix;
  $SQLQuery="UPDATE ".$prefix."user SET UserSession=NULL WHERE UserSession='".session_id()."'";
  mysqli_query($db, $SQLQuery);
  session_destroy(); }

function login ( $userID )
{
  global $db;
  global $prefix;

  $SQLQuery="UPDATE ".$prefix."user SET UserSession='".session_id()."' WHERE UserId=".$userID;
  mysqli_query($db, $SQLQuery);
}

function loggedIn()
{
  global $db;
  global $prefix;
  global $session_id;

  $SQLQuery="SELECT UserID FROM ".$prefix."user
    WHERE UserSession='".$session_id."'
    LIMIT 1";
  $Result= mysqli_query($db, $SQLQuery);
  if ($Result)
  {
    return ( mysqli_num_rows($Result)==1);
  }
  else return false;
}

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

  $SQLQuery="SELECT UserName
    FROM ".$prefix."user
    WHERE UserSession='".session_id()."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp = mysqli_fetch_assoc($Result);
    return $temp['UserName'];
  }
  else return false;  
}

function testDoppelteUser ($Username)
{
  global $db;
  global $prefix;
  global $db;

  $string = strtolower($Username);
  $SQLQuery = 'SELECT * FROM ' .$prefix."user";
  $Result = mysqli_query($db, $SQLQuery);
  $doppelteVorhanden = false;
  $Result = mysqli_query($db, $SQLQuery);
  $menge = mysqli_num_rows($Result);
  while($row = mysqli_fetch_row($Result))
  {
    if (strtolower($row[1]) == $string) { $doppelteVorhanden = true; }
  }
  if ($doppelteVorhanden) return true;
  else return false;
}

function getTimestampFromDate($Day, $Month, $Year)
{
  //date_default_timezone_set('Europe/Berlin');
  //echo strtotime($Year."-".$Month."-".$Day);
  return strtotime($Year."-".$Month."-".$Day);
  //return mktime(0, 0, 0, $Month, $Day, $Year);
}

function DatumAusTimestamp ($Timestamp)
{ 
  if ( $Timestamp != '' )
  {
    $Day = date('d', $Timestamp);
    $Month = date('m', $Timestamp);
    $Year = date('Y', $Timestamp);
    return $Day.".".$Month.".".$Year;
  }
  else { return '-'; }
}

function isDatabasePresent ()
{
  global $db;
  global $db_name;
  if (mysqli_select_db($db, $db_name)) return true;
    else return false;
}

function addGig ( $Gig, $Job )
{
  global $prefix;
  global $db;
  global $L_042;
  global $L_107;

  for ($i=0; $i<count($Gig); $i++)
  {
    if ( $i!=23 ) // Notizen werden ausgeklammert
    {
      // Entfernt HTML- und PHP-Tags aus einer Zeichenkette
      $Gig[$i]=strip_tags($Gig[$i]);
      // Wandelt bestimmte Sonderzeichen in HTML-Code um
      //$Gig[$i]=htmlspecialchars($Gig[$i], ENT_QUOTES);
      // Wandelt in UTF-8 um
        //$Gig[$i]=utf8_decode($Gig[$i]);
      // tinyMCE-URL-Escapes entfernen
        $Gig[23] = str_replace('\"','"',$Gig[23]);
    }
  }
  for ($i=0; $i<count($Gig); $i++)
  {
    // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
      $Gig[$i] = mysqli_real_escape_string($db, $Gig[$i]);
  }
  list( $GigID,
        $GigDateDay,
        $GigDateMonth,
        $GigDateYear,
        $GigCountry,
        $GigDistrict,
        $GigPostalCode,
        $GigCity,
        $GigEvent,
        $GigEventURL,
        $GigEntranceFee,
        $GigVenue,
        $GigVenueURL,
        $GigOrganizer,
        $GigOrganizerURL,
        $GigArtist,
        $GigArtistURL,        
        $GigLineup,
        $GigVisitors,
        $GigStageBuilding,
        $GigBeginning,
        $GigDuration,
        $GigEnding,
        $GigNotes,
        $GigStatus,
        $GigPublish,
        $GigIsPrivate,
        $GigDateOfLastEdit,
        $GigLastEditor,
        $GigAddedFrom,
        $GigDateOfAdding ) = $Gig;
        
  if ( $GigEventURL=='http://' ) { $GigEventURL=''; }
  if ( $GigVenueURL=='http://' ) { $GigVenueURL=''; }
  if ( $GigOrganizerURL=='http://' ) { $GigOrganizerURL=''; }
  if ( $GigArtistURL=='http://' ) { $GigArtistURL=''; }
  
  //if ( $GigEventURL!="" AND !stristr( $GigEventURL, 'http://' ) ) $GigEventURL = 'http://'.$GigEventURL;
  //if ( $GigVenueURL!="" AND !stristr( $GigVenueURL, 'http://' ) ) $GigVenueURL = 'http://'.$GigVenueURL;
  //if ( $GigOrganizerURL!="" AND !stristr( $GigOrganizerURL, 'http://' ) ) $GigOrganizerURL = 'http://'.$GigOrganizerURL;
  //if ( $GigArtistURL!="" AND !stristr( $GigArtistURL, 'http://' ) ) $GigArtistURL = 'http://'.$GigArtistURL;

  // Abschließendes Slash bei URLs entfernen
    //echo $GigEventURL.' ';
    $GigEventURL = getURLWithoutFinalSlash ($GigEventURL);
    $GigVenueURL = getURLWithoutFinalSlash ($GigVenueURL);
    $GigOrganizerURL = getURLWithoutFinalSlash ($GigOrganizerURL);
    $GigArtistURL = getURLWithoutFinalSlash ($GigArtistURL);
  
  // Leere numerische Variablen als NULL definieren
    //if ( $GigDate=='' ) $GigDate="NULL";
    if ( $GigPublish=='' ) $GigPublish="NULL";
    if ( $GigIsPrivate=='' ) $GigIsPrivate="NULL";
    if ( $GigDateOfLastEdit=='' ) $GigDateOfLastEdit="NULL";
    if ( $GigDateOfAdding=='' ) $GigDateOfAdding="NULL";

  // Bugfix v1.2.63_072
    if ( $GigPostalCode=='NULL' ) $GigPostalCode='';

  $GigDateNew = getTimestampFromDate($GigDateDay, $GigDateMonth, $GigDateYear);

  if ( $Job=="add" )
  {
    if ($GigDateNew != -1)
    {
        $SQLQuery = "INSERT INTO ".$prefix."gigs
        (
          GigDate,
          GigCountry,
          GigDistrict,
          GigPostalCode,
          GigCity,
          GigEvent,
          GigEventURL,
          GigEntranceFee,
          GigVenue,
          GigVenueURL,
          GigOrganizer,
          GigOrganizerURL,
          GigArtist,
          GigArtistURL,          
          GigLineup,
          GigVisitors,
          GigStageBuilding,
          GigBeginning,
          GigDuration,
          GigEnding,
          GigNotes,
          GigStatus,
          GigPublish,
          GigIsPrivate,
          GigDateOfLastEdit,
          GigLastEditor,
          GigAddedFrom,
          GigDateOfAdding
        )
        VALUES
        (
          '$GigDateNew',
          '$GigCountry',
          '$GigDistrict',
          '$GigPostalCode',
          '$GigCity',
          '$GigEvent',
          '$GigEventURL',
          '$GigEntranceFee',
          '$GigVenue',
          '$GigVenueURL',
          '$GigOrganizer',
          '$GigOrganizerURL',
          '$GigArtist',
          '$GigArtistURL',          
          '$GigLineup',
          '$GigVisitors',
          '$GigStageBuilding',
          '$GigBeginning',
          '$GigDuration',
          '$GigEnding',
          '$GigNotes',
          '$GigStatus',
          $GigPublish,
          $GigIsPrivate,
          $GigDateOfLastEdit,
          '$GigLastEditor',
          '$GigAddedFrom',
          $GigDateOfAdding
        )";
        $Result = mysqli_query($db, $SQLQuery);
        if ($Result) { deleteFileInCache($GigDateNew); return true; }
        else { return false;}
    }
    else {echo "ERROR: The date is wrong! (Timestamp -1) ".DatumAusTimestamp($GigDateNew)."<br />"; return false;}
  }
  if ( $Job=="edit" )
  {
    if (  getGigVarFromGigID ($GigID, 'GigDate') == $GigDateNew)
    {
      $GigLastEditor = getCurrentUserVar("UserName");
      $GigDateOfLastEdit = date("U");
      $SQLQuery = "UPDATE ".$prefix."gigs SET
        GigCountry = '$GigCountry',
        GigDistrict = '$GigDistrict',
        GigPostalCode = '$GigPostalCode',
        GigCity = '$GigCity',
        GigVenue = '$GigVenue',
        GigEvent = '$GigEvent',
        GigEventURL = '$GigEventURL',
        GigEntranceFee = '$GigEntranceFee',
        GigVenueURL = '$GigVenueURL',
        GigOrganizer = '$GigOrganizer',
        GigOrganizerURL = '$GigOrganizerURL',
        GigArtist = '$GigArtist',
        GigArtistURL = '$GigArtistURL',       
        GigLineup = '$GigLineup',
        GigVisitors = '$GigVisitors',
        GigStageBuilding = '$GigStageBuilding',
        GigBeginning = '$GigBeginning',
        GigDuration = '$GigDuration',
        GigEnding = '$GigEnding',
        GigNotes = '$GigNotes',
        GigStatus = '$GigStatus',
        GigPublish = '$GigPublish',
        GigIsPrivate = '$GigIsPrivate',
        GigDateOfLastEdit = $GigDateOfLastEdit,
        GigLastEditor = '".getCurrentUserVar('UserName')."'
        WHERE GigID = '$GigID'
        LIMIT 1";
      $Result = mysqli_query($db, $SQLQuery);
      if ($Result) { deleteFileInCache($GigDateNew); return true; }
      else {return false;}
    }
    else
    {
      $GigDateOld = getGigVarFromGigID ($GigID, 'GigDate');
      $SQLQuery = "UPDATE ".$prefix."gigs SET
        GigDate = '$GigDateNew',
        GigCountry = '$GigCountry',
        GigDistrict = '$GigDistrict',
        GigPostalCode = '$GigPostalCode',
        GigCity = '$GigCity',
        GigVenue = '$GigVenue',
        GigEvent = '$GigEvent',
        GigEventURL = '$GigEventURL',
        GigEntranceFee = '$GigEntranceFee',
        GigVenueURL = '$GigVenueURL',
        GigOrganizer = '$GigOrganizer',
        GigOrganizerURL = '$GigOrganizerURL',
        GigArtist = '$GigArtist',
        GigArtistURL = '$GigArtistURL',        
        GigLineup = '$GigLineup',
        GigVisitors = '$GigVisitors',
        GigStageBuilding = '$GigStageBuilding',
        GigBeginning = '$GigBeginning',
        GigEnding = '$GigEnding',
        GigNotes = '$GigNotes',
        GigStatus = '$GigStatus',
        GigPublish = '$GigPublish',
        GigIsPrivate = '$GigIsPrivate',
        GigDateOfLastEdit = $GigDateOfLastEdit
        WHERE GigID = '$GigID'
        LIMIT 1";
      $Result = mysqli_query($db, $SQLQuery);
      if ($Result)
      {
        deleteFileInCache($GigDateOld);
        deleteFileInCache($GigDateNew);
        echo $L_107."<br />";
        return true;
      }
      else { return false; }
  }
}
}

function DatumInZukunft ($Timestamp)
{
  $TimestampOfToday = getTimestampFromDate(date("d"), date("m"), date("y"));
  if ($Timestamp >= $TimestampOfToday) {return true;}
  else {return false;}
}

function CheckGigStatusDesTages ($Timestamp)
{
  global $prefix;
  global $db;

  $GigStatus = "";
  $SQLQuery = "SELECT * FROM ".$prefix."gigs WHERE GigDate = ".$Timestamp." LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  while ($row = mysqli_fetch_array($Result))
  { 
    extract($row);
  }
  if ($GigStatus!='') { return $GigStatus; }
  else { return 'Normal';} 
}

function WochentagsNameVonDatum ($Day, $Month, $Year)
{
  $wochentage = Array ( 'Sunday', 'Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday' );
  $UnixTimestamp = mktime(0, 0, 0, $Month, $Day, $Year);
  $Weekday = date('w', $UnixTimestamp);
  return $wochentage[$Weekday];
}