<?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 getNewsFrontendPagination():string {
  global $NumberOfPages;
  global $CurrentPage;
  global $L_111;
  $URL = getFrontendURL('SetupNewsChannelURL');
  $output = '<div class="NewsNavigation">'.$L_111.': ';
  $output .= getPagination($URL, $NumberOfPages, $CurrentPage, "DESC", "news_page");
  return $output .= '</div>'; }

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

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

function convertString ( $String )
{
  $String = str_replace("<","&lt;",$String);
  $String = str_replace(">","&gt;",$String);
  $String = str_replace("&","&amp;",$String);
  $String = str_replace('"','&quot;',$String);
  $String = str_replace("'","&apos;",$String);
  return $String;
}
  
function getTimeStringRFC3339 ($Timestamp)
{
  // get TimeZone
  $timeZone = date('O', $Timestamp);
  // create first part of AtomTime
  $atomTime[0] = date('Y-m-d\TH:i:s', $Timestamp );
  // build second part of AtomTime
  $atomTime[1] = substr($timeZone,0,3). ':' .substr($timeZone,3,2);
  // merge the 2 parts to one
  $atomTimeString = implode('', $atomTime);
  return $atomTimeString;
}
  
function writeAllFeeds ()
{
  writeAtomFeed();
  writeRSSFeed();
}
  
function writeAtomFeed ()
{
  global $db;
  global $prefix;
  global $GigKalenderPath;
  global $GigKalenderVersion;
  $SetupNewsChannelURL = getSetup('SetupNewsChannelURL');
  $path = str_replace("\\","/",dirname(__FILE__));
  $path = str_replace("/news","/news",$path);
  $CurrentEntry = getNumberOfPublishedNewsEntries();

  $String = '<?xml version="1.0" encoding="utf-8"?>
  <feed xmlns="http://www.w3.org/2005/Atom">
  <title>'.getSetup('SetupNewsChannelTitle').'</title>
  <subtitle type="text">'.getSetup('SetupNewsChannelDescription').'</subtitle>
  <updated>'.getTimeStringRFC3339(time()).'</updated>
  <link href="'.$GigKalenderPath.'news/news.atom" rel="self" />
  <generator>GigKalender '.$GigKalenderVersion.'</generator>
  <rights>'.getSetup('SetupNewsChannelCopyright').'</rights>
  <id>'.getSetup('SetupNewsChannelURL').'</id>';


  // NewsFeed schreiben
    $SQLQuery = "SELECT * FROM ".$prefix."news order by Date DESC";
    $Result = mysqli_query($db, $SQLQuery);
    $datei = $path."/news.atom";
    $fp=fopen($datei,"w+");

    while ($row = mysqli_fetch_array($Result))
    {
      extract($row);
      if ( $Publish=='1' )
      {
        if ( substr_count($SetupNewsChannelURL, '?')) $URL = $SetupNewsChannelURL.'&amp;';
        else $URL = $SetupNewsChannelURL.'?';
        $URL = $URL.'NewsID='.$CurrentEntry.'#news'.$CurrentEntry;

        $AuthorEmailadress = getUserVar ($AddedFrom, 'UserEmailadress');
        if ( $AuthorEmailadress!='' ) $Email = '<email>'.$AuthorEmailadress.'</email>';
        else $Email = '';
        
        $Title = convertString ( $Title );
        
        $String = $String.'
  <entry>
    <title>'.$Title.'</title>
    <content type="xhtml" xml:lang="'.getSetup('SetupNewsChannelLanguage').'">
      <div xmlns="http://www.w3.org/1999/xhtml">'.$Text.'</div>
    </content>
    <author>
      <name>'.$AddedFrom.'</name>
      <uri>'.getSetup('SetupNewsChannelURL').'</uri>
      '.$Email.'
    </author>
    <id>'.$URL.'</id>
    <published>'.getTimeStringRFC3339($Date).'</published>
    <link rel="alternate" href="'.$URL.'" />';
    if ($DateOfLastEdit!=NULL AND $DateOfLastEdit!=0)
    {
      $String .= '
    <updated>'.getTimeStringRFC3339($DateOfLastEdit).'</updated>';
    }
    else
    {
      $String .= '
    <updated>'.getTimeStringRFC3339($Date).'</updated>';
    }
  $String .= '
  </entry>';
      $CurrentEntry--;
      }
    }
    $String = $String.'
</feed>';
    fwrite($fp,$String);
}
  
function writeRSSFeed ()
{
  global $db;
  global $prefix;
  global $GigKalenderPath;
  global $GigKalenderVersion;
  $SetupNewsChannelURL = getSetup('SetupNewsChannelURL');
  $path = str_replace("\\","/",dirname(__FILE__));
  $path = str_replace("/news","/news",$path);
  $CurrentEntry = getNumberOfPublishedNewsEntries();
  
  $String = '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
      <title>'.getSetup('SetupNewsChannelTitle').'</title>
      <link>'.getSetup('SetupNewsChannelURL').'</link>
      <atom:link href="'.$GigKalenderPath.'news/news.rss" rel="self" type="application/rss+xml" />
      <description>'.getSetup('SetupNewsChannelDescription').'</description>
      <language>'.getSetup('SetupNewsChannelLanguage').'</language>
      <copyright>'.getSetup('SetupNewsChannelCopyright').'</copyright>
      <pubDate>'.gmdate ( "D, d M Y H:i:s" ).' GMT</pubDate>
      <lastBuildDate>'.gmdate ( "D, d M Y H:i:s" ).' GMT</lastBuildDate>
      <generator>GigKalender '.$GigKalenderVersion.'</generator>';
  
  // NewsFeed schreiben
    $SQLQuery = "SELECT * FROM ".$prefix."news order by Date DESC";
    $Result = mysqli_query($db, $SQLQuery);
    $datei = $path."/news.rss";
    $fp=fopen($datei,"w+");

    while ($row = mysqli_fetch_array($Result))
    {
      extract($row);
      if ( substr_count($SetupNewsChannelURL, '?')) $URL = $SetupNewsChannelURL.'&amp;';
      else $URL = $SetupNewsChannelURL.'?';
      $URL = $URL.'NewsID='.$CurrentEntry.'#news'.$CurrentEntry;
      
      $AuthorEmailadress = getUserVar ($AddedFrom, 'UserEmailadress');
      if ( $AuthorEmailadress!='' ) $Email = '<author>'.$AuthorEmailadress.' ('.$AddedFrom.')</author>';
      else $Email = '';
      
      $Title = convertString ( $Title );

      if ( $Publish=='1' )
      {
        $String = $String.'
        <item>
          <guid>'.$URL.'</guid>
          <title>'.$Title.'</title>
          <link>'.$URL.'</link>
          <description><![CDATA['.$Text.']]></description>
          '.$Email.'
          <pubDate>'.gmdate ( "D, d M Y H:i:s", $Date ).' GMT</pubDate>
        </item>';
        $CurrentEntry--;
      }
    }
    $String = $String.'</channel>
    </rss>';
    fwrite($fp,$String);
}
  
function importNewsEntry ($Date, $AddedFrom, $Title, $Text, $DateOfLastEdit, $LastEditor, $Publish)
  {
    global $prefix;
    global $db;
    
    // HTML-Tags entfernen
      $Title = strip_tags($Title);
    $Text = str_replace("&","&amp;",$Text);
    // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
      $Title = mysqli_real_escape_string($db, $Title);
      $Text = mysqli_real_escape_string($db, $Text);
    // Leere numerische Variablen als NULL definieren
      if ( $Date=='' ) $Date="NULL";
      if ( $DateOfLastEdit=='' ) $DateOfLastEdit="NULL";
      if ( $Publish=='' ) $Publish="NULL";
    
    $SQLQuery = "INSERT INTO ".$prefix."news (Date, AddedFrom, Title, Text, DateOfLastEdit, LastEditor, Publish)     
      VALUES ($Date, '$AddedFrom', '$Title', '$Text', $DateOfLastEdit, '$LastEditor', $Publish)";
    $Result = mysqli_query($db, $SQLQuery);
    if ($Result) { return true; }
    else {return false;}
}   
  
function editNews ($NewsID, $Title, $Text, $Publish)
{
  global $prefix;
  global $db;
  
  // HTML-Tags entfernen
    $Title = strip_tags($Title);
  $DateOfLastEdit = date("U");
  // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
  $Title = mysqli_real_escape_string($db, $Title);
  $Text = mysqli_real_escape_string($db, $Text);
      
  $SQLQuery = "UPDATE ".$prefix."news SET
        Title = '".$Title."',
        Text = '".$Text."',
        Publish = '".$Publish."',
        DateOfLastEdit = '".$DateOfLastEdit."',
        LastEditor = '".getCurrentUserVar('UserName')."'
        WHERE NewsID = '".$NewsID."'
        LIMIT 1";
      $Result = mysqli_query($db, $SQLQuery);
      if ($Result) { writeAllFeeds(); return true; }
      else {return false;}
}

function  changePublishing ( $Date )
{
  global $prefix;
  global $db;
  
  // aktuellen Status abfragen
  $SQLQuery = "SELECT Publish
    FROM ".$prefix."news
    WHERE Date='".$Date."'
    LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ( mysqli_num_rows($Result)==1)
  {
    $temp=mysqli_fetch_assoc($Result);
    $aktuellerStatus = $temp['Publish'];
  }
  // neuen Status setzen
  if ( $aktuellerStatus=='0' OR $aktuellerStatus=='NULL') $Publish = '1';
  if ( $aktuellerStatus=='1' ) $Publish = '0';
  $DateOfLastEdit = date("U");

  // Leere numerische Variablen als NULL definieren
    if ( $DateOfLastEdit=='' ) $DateOfLastEdit="NULL";
    if ( $Publish=='' ) $Publish="NULL";

  $SQLQuery = "UPDATE ".$prefix."news SET 
    Publish = ".$Publish.",
    DateOfLastEdit = ".$DateOfLastEdit.",
    LastEditor = '".getCurrentUserVar('UserName')."'
    WHERE Date = '".$Date."' LIMIT 1";
  $Result = mysqli_query($db, $SQLQuery);
  if ($Result) { writeAllFeeds(); return true; }
    else {return false;}
}  
  
function addNews ($Title, $Text, $Publish)
  {
    global $prefix;
    global $db;
    /// echo $Title.' '.$Text.' '.$Publish.'<br >';
    // HTML-Tags entfernen
      $Title = strip_tags($Title);
    // Sonderzeichen umwandeln
      //$Title = htmlspecialchars($Title, ENT_QUOTES);
      //$Text = htmlspecialchars($Text, ENT_QUOTES);
    $Text = str_replace("&","&amp;",$Text);
    // tinyMCE-URL-Escapes entfernen
      $Text = str_replace('\"','"',$Text);
    $Date = date("U");
    // Maskieren spezieller Zeichen für die Verwendung in einer SQL-Anweisung
      $Title = mysqli_real_escape_string($db, $Title);
      $Text = mysqli_real_escape_string($db, $Text);

    // Leere numerische Variablen als NULL definieren
      if ( $Date=='' ) $Date="NULL";
      //if ( $DateOfLastEdit=='' ) $DateOfLastEdit="NULL";
      if ( $Publish=='' ) $Publish="NULL";
    
    $SQLQuery = "INSERT INTO ".$prefix."news (Date, AddedFrom, Title, Text, DateOfLastEdit, Publish)      
      VALUES ($Date, '".getCurrentUserVar('UserName')."', '$Title', '$Text', NULL, $Publish)";
    /// echo $SQLQuery.'<br >';
    $Result = mysqli_query($db, $SQLQuery);
    if ($Result) { writeAllFeeds(); return true; }
    else {return false;}
}  

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

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