<?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 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'))
  {
    if (checkdnsrr(array_pop(explode("@",$email)),"MX")) 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 emptyDirectory ($strDir)
{
  //echo $strDir.'<br />';
  $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: Cache NOT cleared! ('.$strFile.')</span><br />';
        }
      }
      else
      {
        if(is_dir($strDir.$strFile))
        {
          //echo $strDir.'<br />';
          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 writeToCache ( $Filename, $Content)
{
  echo $Content;
  global $GigKalenderPath;
  $path = 'cache/';
  $datei = $path.$Filename;
  $fp=fopen($datei,"w+");
  fwrite($fp,$Content);
}
function getArrayForAutoSuggest ( $Field )
{
  global $prefix;
  global $db;

  $sql = "SELECT DISTINCT `".$Field."` FROM `".$prefix."gigs` ORDER BY `".$Field."` ASC";
  $result = mysqli_query($db, $sql);
  $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 getFrontendURL ( $Var ) {
// 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 $SetupGalleryURL;
  // Get url defined in gigkalender.ini.php
  $URL = ${$Var};
  // Get url from currently running script
  if (isset($_SERVER['REQUEST_URI'])) $REQUEST_URI=$_SERVER['REQUEST_URI'];
    else $REQUEST_URI = '';
  // Check if url is defined in gigkalender.ini.php
  if ( $URL=='' ) $URL = $REQUEST_URI;
    else $URL = $URL;
  // Split URL into Path and Query
  $URLArray = parse_url ( $URL );
  $Path = $URLArray['path'];
  // calculate the URL to return
  if ( $Var=='SetupFrontendCalendarGigDetailsURL' ) {
    global $Timestamp;
    $URL = $Path.'?Timestamp='.$Timestamp; }
  elseif ( $Var=='SetupFrontendCalendarCurrentMonthURL' ) {
      $URL = $Path.'?'; }
  elseif ( $Var=='SetupGuestbookEmailURL' ) {
    if ( preg_match ( '|\?|', $URL ) ) $URL = $URL.'&amp;';
      else $URL = $URL.'?';
    global $GuestbookID;
    $URL = $URL.'id='.$GuestbookID.'&amp;page=mail'; }
  elseif ( $Var=='SetupGalleryURL' ) {
    $URL = $Path; }
  // return calculated URL
  return $URL; }
 
function getGoogleMapsURL ( $GigCountry, $GigDistrict, $GigPostalCode, $GigCity )
{
  global $BrowserLanguageShort;
  if ($GigPostalCode == "0") {$GigPostalCode = "";}
  $Location = "";
  if ( $GigCountry!='') { $Location = $Location.$GigCountry;}
  if ( $GigCountry!='' && $GigPostalCode!='') { $Location = $Location.'-';}
  if ( $GigPostalCode!='') { $Location = $Location.$GigPostalCode;}
  if ( $GigCountry!='' && $GigPostalCode=='' && $GigCity!='' ) { $Location = $Location.' ';}
  if ( $GigPostalCode!='' && $GigCity!='') { $Location = $Location.' ';}
  if ( $GigCity!='') { $Location = $Location.$GigCity;}
  if ( $GigDistrict!='' AND $GigCity=='') $Location .= $GigDistrict;
  // if ( $GigDistrict!='') { $Location .= ' '.$GigDistrict; }
  //$Location = 'http://maps.google.de/maps?f=q&amp;hl=de&amp;geocode=&amp;q='.rawurlencode($Location);
  // READ http://mapki.com/wiki/Google_Map_Parameters
  $Location = 'http://maps.google.com/maps?f=q&amp;hl='.$BrowserLanguageShort.'&amp;source=s_q&amp;geocode=&amp;q='.rawurlencode($Location);
  return $Location;
}
 
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;

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

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

  $SQL_Befehl = "SELECT * FROM ".$prefix."gigs WHERE GigDate = ".$Timestamp." AND (GigStatus = 'Gig'";
  if ( getSetup('SetupFrontendAllowOptionalGigs') ) $SQL_Befehl .= " OR GigStatus = 'Option'";
  $SQL_Befehl .= ")";
  if ( !getSetup('SetupFrontendAllowPrivateGigs') ) $SQL_Befehl .= " AND GigIsPrivate = 0";
  $SQL_Befehl .= " AND GigPublish = 1";
  $SQL_Befehl .= " LIMIT 1";
  $resultat = mysqli_query($db, $SQL_Befehl);
  if ( mysqli_num_rows($resultat)==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 AnzahlGigsMitGleichemDatum ( $GigDate )
{
  global $prefix;
  global $db;

  $sql = "SELECT count(*) as zahl  FROM ".$prefix."gigs WHERE GigDate=".$GigDate;
  $result = mysqli_query($db, $sql);
  $row = mysqli_fetch_array($result);
  return $row['zahl'];
}
 
function getGigVarFromGigDate ($GigDate, $Var)
{
  global $db;
  global $prefix;
  $SQL_Befehl = "SELECT ".$Var."
    FROM ".$prefix."gigs
    WHERE GigDate='".$GigDate."'
    LIMIT 1";
  $result = mysqli_query($db, $SQL_Befehl);
  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;
  $SQL_Befehl = "SELECT ".$Var."
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $result = mysqli_query($db, $SQL_Befehl);
  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
  $sql = "SELECT GigIsPrivate
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $result = mysqli_query($db, $sql);
  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");
  $sql = "UPDATE ".$prefix."gigs SET 
    GigIsPrivate = '".$neuerGigStatus."',
    GigDateOfLastEdit = '".$DateOfLastEdit."',
    GigLastEditor = '".getCurrentUserVar('UserName')."'
    WHERE GigID = '".$GigID."' LIMIT 1";
  $resultat = mysqli_query($db, $sql);
  if ($resultat) { return true; }
    else {return false;}
}
 
function changeGigPublishing ( $GigID )
{
  global $prefix;
  global $db;
  
  // aktuellen GigStatus abfragen
  $sql = "SELECT GigPublish
    FROM ".$prefix."gigs
    WHERE GigID='".$GigID."'
    LIMIT 1";
  $result = mysqli_query($db, $sql);
  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");
  $sql = "UPDATE ".$prefix."gigs SET 
    GigPublish = '".$neuerGigStatus."',
    GigDateOfLastEdit = '".$DateOfLastEdit."',
    GigLastEditor = '".getCurrentUserVar('UserName')."'
    WHERE GigID = '".$GigID."' LIMIT 1";
  $resultat = mysqli_query($db, $sql);
  if ($resultat) { return true; }
    else {return false;}
}
 
function CheckGigPublish ($GigID)
{
  global $prefix;
  global $db;

  $GigPublish = "";
  $GigStatus = "";
  $SQL_Befehl = "SELECT * FROM ".$prefix."gigs WHERE GigID = ".$GigID." LIMIT 1";
  $resultat = mysqli_query($db, $SQL_Befehl);
  while ($row = mysqli_fetch_array($resultat)) 
  { 
    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 logoutInactiveUser ()
{
  global $prefix;
  global $db;
  
  $SetupUserMaximumInactivityTime = getSetup('SetupUserMaximumInactivityTime');
  if ( $SetupUserMaximumInactivityTime<1 ) { $SetupUserMaximumInactivityTime = 1;}
  $Diff = time()-($SetupUserMaximumInactivityTime*60);
  
    $sql="UPDATE ".$prefix."user SET
      UserSession=NULL
      WHERE UserLastActivityTimestamp<'".$Diff."'";
      mysqli_query($db, $sql);
}  

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

  $sql = "SELECT count(*) as zahl  FROM ".$prefix."gigs";
  $result = mysqli_query($db, $sql);
  $row = mysqli_fetch_array($result);
  return $row['zahl'];
} 
 
function GigNavigation ()
{
  global $AnzahlSeiten;
  if ( $AnzahlSeiten>'1' )
  {
    global $aktuelleSeite;
    global $L_111;
  
    $temp = '<div class="GigNavigation">'.$L_111.': ';
    $i = '1';
    while ($i <= $AnzahlSeiten)
    {
      if ($aktuelleSeite == $i) { $temp = $temp.'<b>'.$i.'</b> '; }
      else { $temp = $temp.'<a href="index.php?submenue=calendar&amp;inhalt=backend_showAllGigs&amp;page='.$i.'">'.$i.'</a> '; }
      $i++;
    }
   $temp = $temp.'</div>';
  }
  else $temp = '';
  return $temp;
} 
 
function AnzahlGigsImZeitraum ( $Zeitraum, $GigStatus )
{
    global $prefix;
    global $db;
    
    $TimestampVonHeute = TimestampAusDatum(date("d"), date("m"), date("y"));
    $sql = "SELECT count(*) as zahl  FROM ".$prefix."gigs";
    if ( $Zeitraum!='all' OR $GigStatus!='all' ) { $sql = $sql." WHERE"; }
    if ( $Zeitraum =="future" ) { $sql = $sql." GigDate>=".$TimestampVonHeute; }
    if ( $Zeitraum =="past" ) { $sql = $sql." GigDate<=".$TimestampVonHeute; }    
    if ( $Zeitraum!='all' && $GigStatus!='all' ) { $sql = $sql." AND"; }
    if ( $GigStatus!='all' ) { $zweiterFilter = " GigStatus='".$GigStatus."'"; }
    else { $zweiterFilter = ""; }
    $sql = $sql.$zweiterFilter;
    $result = mysqli_query($db, $sql);
    $row = mysqli_fetch_array($result);
    return $row['zahl'];
}
 
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);

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

function checkURL ($url)
{ 
  if ( !stristr($url, "http://") ) $url = "http://".$url;
  if ( preg_match('#^http\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url) OR ($url == "http://") ) return true;
}

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 getCurrentUserVar ($Var)
{
  global $db;
  global $prefix;

  if ($Var>0 OR $Var!='')
  {
    $SQL_Befehl = "SELECT ".$Var." FROM ".$prefix."user WHERE UserSession='".session_id()."' LIMIT 1";
    $result = mysqli_query($db, $SQL_Befehl);
    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 checkGigDatum ($GigDateDay, $GigDateMonth, $GigDateYear)
{
  if ( checkdate($GigDateMonth, $GigDateDay, $GigDateYear) ) { return true; }
}

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

  $TimestampVonHeute = TimestampAusDatum(date("d"), date("m"), date("y"));
  $zukuenftigeTermineEingetragen = false;

  $sql="SELECT GigDate
    FROM ".$prefix."gigs
    WHERE GigStatus='Gig' 
      OR GigStatus='Blocked' 
      OR GigStatus='Option' 
      OR GigStatus='Rehearsal'";
  $result = mysqli_query($db, $sql);
  while($row = mysqli_fetch_row($result))
  {
    if (strtolower($row[0]) >= $TimestampVonHeute) { $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 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))
    return true;
}

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

  $SQL_Befehl = "SELECT * FROM " .$prefix."gigs WHERE GigDate = ".$Timestamp;
  $resultat = mysqli_query($db, $SQL_Befehl);
  while ($row = mysqli_fetch_array($resultat))
  {
    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 GigsPublished( $Zeitraum )
{
  global $prefix;
  global $db;
  $TimestampVonHeute = TimestampAusDatum(date("d"), date("m"), date("y"));

  $SQL_Befehl = "SELECT * FROM ".$prefix."gigs WHERE GigStatus='Gig' OR GigStatus='Option' AND GigPublish=1";
  $resultat = mysqli_query($db, $SQL_Befehl);
  $temp=0;
  while ($row = mysqli_fetch_array($resultat))
  {
    extract($row);
    if ( $Zeitraum == 'future' )
    {
      if ($GigDate >= $TimestampVonHeute ) { $temp=1; break; }
    }
    if ( $Zeitraum == 'past' )
    {
      if ($GigDate < $TimestampVonHeute ) { $temp=1; break; }
    }
    if ( $Zeitraum == 'all' )
    {
      if ($GigDate > '0' ) { $temp=1; break; }
    }
  }
  if ($temp==1) return true;
  else return false;
}

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";

  $sql = "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";
  $resultat = mysqli_query($db, $sql);
  if ($resultat) { return true; }
  else {return false;}
}

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

function transformPassword ($Password)
{
  $anzahlZeichen = strlen($Password);
  for ($i=0; $i<$anzahlZeichen; $i++)
  {
    echo "*";
  }
}

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

  $sql = 'SELECT * FROM ' .$prefix."gigs";
  $result = mysqli_query($db, $sql);
  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;

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

function IsUserAdmin ()
{ 
  global $db;
  global $prefix;
  $sql='SELECT UserStatus FROM '.$prefix.'user WHERE UserSession="'.session_id().'"';
  $result = mysqli_query($db, $sql);
  $temp = mysqli_fetch_assoc($result);
  if ($temp['UserStatus'] == "Admin") { return true; }
  else { return false; }
}

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

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

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

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

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

function getUID ( $UserName, $UserCurrentPassword )
{
  global $db;
  global $prefix;

  $SQL_Befehl="SELECT UserId
    FROM ".$prefix."user
    WHERE UserName='".$UserName."' AND UserCurrentPassword='".$UserCurrentPassword."'
    LIMIT 1";
  $result = mysqli_query($db, $SQL_Befehl);
  if ($result)
  {
    if ( mysqli_num_rows($result)==1)
    {
      $user=mysqli_fetch_assoc($result);
      return $user['UserId'];
    }
    else return false;
  }
  else return false;
}

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

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

function addUser ($UserName, $UserStatus, $UserCurrentPassword, $UserEmailadress, $UserSession, $UserLanguage, $UserLastActivityTimestamp, $UserBackendCalenderListCols, $UserRightEmail, $UserRightAddNews, $UserRightEditNews, $UserRightDeleteNews)
{
  global $prefix;
  global $db;
  
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserName = mysqli_real_escape_string($db, $UserName);
    $UserCurrentPassword = mysqli_real_escape_string($db, $UserCurrentPassword);
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
  
  // 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))
  {
    $SQL_Befehl =
      "INSERT INTO ".$prefix."user
      (UserName, UserStatus, UserCurrentPassword, UserEmailadress, UserSession, UserLanguage, UserLastActivityTimestamp, UserBackendCalenderListCols, UserRightEmail, UserRightAddNews, UserRightEditNews, UserRightDeleteNews)
      VALUES
      ('$UserName', '$UserStatus', '$UserCurrentPassword', '$UserEmailadress', '$UserSession', '$UserLanguage', $UserLastActivityTimestamp, '$UserBackendCalenderListCols', $UserRightEmail, $UserRightAddNews,  $UserRightEditNews, $UserRightDeleteNews)";
    $resultat = mysqli_query($db, $SQL_Befehl);
    if ($resultat) { return true; }
    else {return false;}
  }
  else { return false; }
}

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

  $string = strtolower($Username);
  $sql = 'SELECT * FROM ' .$prefix."user";
  $result = mysqli_query($db, $sql);
  $doppelteVorhanden = false;
  $result = mysqli_query($db, $sql);
  $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 TimestampAusDatum ($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 != '' )
  {
    $Tag = date('d', $Timestamp);
    $Monat = date('m', $Timestamp);
    $Jahr = date('Y', $Timestamp);
    return $Tag.".".$Monat.".".$Jahr;
  }
  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 = TimestampAusDatum ($GigDateDay, $GigDateMonth, $GigDateYear);

  if ( $Job=="add" )
  {
    if ($GigDateNew != -1)
    {
        $SQL_Befehl = "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
        )";
        $resultat = mysqli_query($db, $SQL_Befehl);
        if ($resultat) { 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");
      $SQL_Befehl = "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";
      $resultat = mysqli_query($db, $SQL_Befehl);
      if ($resultat) { deleteFileInCache($GigDateNew); return true; }
      else {return false;}
    }
    else
    {
      $GigDateOld = getGigVarFromGigID ($GigID, 'GigDate');
      $SQL_Befehl = "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";
      $resultat = mysqli_query($db, $SQL_Befehl);
      if ($resultat)
      {
        deleteFileInCache($GigDateOld);
        deleteFileInCache($GigDateNew);
        echo $L_107."<br />";
        return true;
      }
      else { return false; }
  }
}
}

function editUser ($UserName, $UserStatus, $UserCurrentPassword, $UserEmailadress, $UserNameOld, $UserLanguage, $UserBackendCalenderListCols, $UserRightEmail, $UserRightAddNews, $UserRightEditNews, $UserRightDeleteNews)
{
  global $prefix;
  global $db;
  
  // HTML-Tags entfernen
    $UserName = strip_tags($UserName);
    $UserCurrentPassword = strip_tags($UserCurrentPassword);
    $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);
    $UserCurrentPassword = mysqli_real_escape_string($db, $UserCurrentPassword);
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
    $UserNameOld = mysqli_real_escape_string($db, $UserNameOld);

  // 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;

  $SQL_Befehl = "UPDATE ".$prefix."user SET
    UserName = '$UserName',
    UserStatus = '$UserStatus',
    UserCurrentPassword = '$UserCurrentPassword',
    UserEmailadress = '$UserEmailadress',
    UserLanguage = '$UserLanguage',
    UserBackendCalenderListCols = '$UserBackendCalenderListCols',
    UserRightEmail = $UserRightEmail,
    UserRightAddNews = $UserRightAddNews,
    UserRightEditNews = $UserRightEditNews,
    UserRightDeleteNews = $UserRightDeleteNews
    WHERE UserName = '$UserNameOld'
    LIMIT 1";
  $resultat = mysqli_query($db, $SQL_Befehl);
  if ($resultat) { return true; }
  else {return false;}
}

function editCurrentUser ($UserCurrentPassword, $UserEmailadress, $UserLanguage, $UserBackendCalenderListCols)
{
  global $prefix;
  global $db;

   // HTML- und PHP-Tags entfernen
     $UserCurrentPassword = strip_tags($UserCurrentPassword);
     $UserEmailadress = strip_tags($UserEmailadress);
     $UserLanguage = strip_tags($UserLanguage);
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
    $UserCurrentPassword = mysqli_real_escape_string($db, $UserCurrentPassword);
    $UserEmailadress = mysqli_real_escape_string($db, $UserEmailadress);
    
  $SQL_Befehl = "UPDATE ".$prefix."user SET
    UserCurrentPassword = '$UserCurrentPassword',
    UserEmailadress = '$UserEmailadress',
    UserLanguage = '$UserLanguage',
    UserBackendCalenderListCols = '$UserBackendCalenderListCols'
    WHERE UserName = '".getCurrentUser()."'
    LIMIT 1";
  $resultat = mysqli_query($db, $SQL_Befehl);
  if ($resultat) { return true; }
  else {return false;}
}

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

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

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

function AnzahlTagedesMonats ($Monat, $Jahr)
{
  $unixtimestamp = mktime(0, 0, 0, $Monat, 1 , $Jahr);
  return date('t', $unixtimestamp);
}

function WochentagsNameVonDatum ($Tag, $Monat, $Jahr)
{
  $wochentage = Array ( 'Sunday', 'Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday' );
  $unixtimestamp = mktime(0, 0, 0, $Monat, $Tag, $Jahr);
  $wochentag = date('w', $unixtimestamp);
  return $wochentage[$wochentag];
}

function WochentagVonDatum ($Tag, $Monat, $Jahr)
{
  $unixtimestamp = mktime(0, 0, 0, $Monat, $Tag, $Jahr);
  $wochentag = date('w', $unixtimestamp);
  if($wochentag == 0) {$wochentag = 7;}
  return $wochentag;
}

function MonatsNameVonDatum ($Monat)
{
  if($Monat == 1) {global $L_January; $Monatsname = $L_January;}
  if($Monat == 2) {global $L_February; $Monatsname = $L_February;}
  if($Monat == 3) {global $L_March; $Monatsname = $L_March;}
  if($Monat == 4) {global $L_April; $Monatsname = $L_April;}
  if($Monat == 5) {global $L_May; $Monatsname = $L_May;}
  if($Monat == 6) {global $L_June;  $Monatsname = $L_June;}
  if($Monat == 7) {global $L_July; $Monatsname = $L_July;}
  if($Monat == 8) {global $L_August; $Monatsname = $L_August;}
  if($Monat == 9) {global $L_September; $Monatsname = $L_September;}
  if($Monat == 10) {global $L_October; $Monatsname = $L_October;}
  if($Monat == 11) {global $L_November; $Monatsname = $L_November;}
  if($Monat == 12) {global $L_December; $Monatsname = $L_December;}
  return $Monatsname;
}
?>