<?php

include_once(dirname(__FILE__).'/RSS.php');

class ModuleNews extends AppModule
{
  var $RSSChannels;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'News';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Web site annoucements management';
    $this->Dependencies = array();
    $this->RSSChannels = array();
  }

  function DoStart()
  {
    $this->System->RegisterPage('news', 'PageNews');
    $this->System->RegisterPage('rss', 'PageRSS');
    $this->RegisterRSS(array('Title' => T('News'), 'Channel' => 'news',
      'Callback' => array('PageNews', 'ShowRSS'), 'Permission' => LICENCE_ANONYMOUS));
  }

  function ShowBox()
  {
    $Output = '<strong><a href="'.$this->System->Link('/news/').'">'.T('News').':</a></strong><div class="NewsBox">';
    $DbResult = $this->Database->query('SELECT `News`.`Time`, `User`.`Name`, `News`.`Text`,`News`.`Title`, `News`.`Id` '.
      ' FROM `News` JOIN `User` ON `User`.`ID` = `News`.`User` ORDER BY `Time` DESC LIMIT 10');
    while($DbRow = $DbResult->fetch_assoc())
    {
      $Output .= '<h4><a href="'.$this->System->Link('/news/?a=item&amp;i='.$DbRow['Id']).'">'.$DbRow['Title'].'</a> ('.HumanDate($DbRow['Time']).')</h4>'.
        ' <div>'.$DbRow['Text'].' ('.$DbRow['Name'].')</div>';
    }
    $Output .= '</div>';
    return($Output);
  }

  function RegisterRSS($Channel, $Pos = NULL, $Callback = NULL)
  {
    $this->RSSChannels[$Channel['Channel']] = $Channel;

    if(is_null($Pos)) $this->RSSChannelsPos[] = $Channel['Channel'];
    else {
      array_splice($this->RSSChannelsPos, $Pos, 0, $Channel['Channel']);
    }
  }

  function ShowRSSHeader()
  {
    $Output = '';
    foreach($this->RSSChannels as $Channel)
    {
      if($this->System->User->Licence($Channel['Permission']))
        $Output .= ' <link rel="alternate" title="'.$Channel['Title'].'" href="'.
          $this->System->Link('/rss/?channel='.$Channel['Channel']).'" type="application/rss+xml" />';
    }
    return($Output);
  }
}

class PageNews extends Page
{
  function Show()
  {
    $this->Title = T('News');
    if(array_key_exists('a', $_POST)) $Action = $_POST['a'];
      else if(array_key_exists('a', $_GET)) $Action = $_GET['a'];
      else $Action = '';
    if($Action == 'add2') $Output = $this->SaveNew();
    else if($Action == 'add') $Output = $this->ShowAddForm();
    else if($Action == 'item') $Output = $this->ShowItem();
    else $Output = $this->ShowList();
    return($Output);
  }

  function ShowList()
  {
    $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `News`');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $Output = '<h3>'.T('News').'</h3>'.$PageList['Output'];
    if($this->System->User->Licence(LICENCE_ADMIN))
      $Output .= ' <a href="?a=add">'.T('Add').'</a>';
    $Output .= '<div class="shoutbox">';
    $DbResult = $this->System->Database->query('SELECT `News`.`Time`, `News`.`Text`, `News`.`Title`, `News`.`Id`, '.
        '`User`.`Name` AS `User` FROM `News` JOIN `User` ON `User`.`Id`=`News`.`User` ORDER BY `News`.`Time` DESC '.$PageList['SQLLimit']);
    while($Line = $DbResult->fetch_assoc())
    {
      $Output .= '<h4><a href="?a=item&amp;i='.$Line['Id'].'">'.$Line['Title'].'</a> ('.HumanDate($Line['Time']).')</h4><div>'.$Line['Text'].' ('.$Line['User'].')</div>';
    }
    $Output .= '</div>'.$PageList['Output'];
    return($Output);
  }

  function ShowItem()
  {
    if(array_key_exists('i', $_GET))
    {
      $Output = '<h3>'.T('News').'</h3>';
      $DbResult = $this->System->Database->query('SELECT `News`.`Time`, `News`.`Text`, `News`.`Title`, `News`.`Id`, '.
        '`User`.`Name` AS `User` FROM `News` JOIN `User` ON `User`.`Id`=`News`.`User` WHERE `News`.`Id` = '.($_GET['i'] * 1));
      if($DbResult->num_rows == 1)
      {
        $Line = $DbResult->fetch_assoc();
        $Output .= '<h4>'.$Line['Title'].' ('.HumanDate($Line['Time']).')</h4><div>'.$Line['Text'].' ('.$Line['User'].')</div>';
      } else $Output = ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
    $Output .= '<br/><a href="'.$this->System->Link('/news/').'">'.T('All news').'</a>';
    return($Output);
  }

  function ShowAddForm()
  {
    if($this->System->User->Licence(LICENCE_ADMIN))
    {
      $Output = '<form action="?" method="POST">'.
        T('User').': '.$this->System->User->Name.'('.$this->System->User->Id.')<br/> '.
        T('Title').': <input type="text" name="title" size="40"/><br/>'.
        T('Content').': <textarea rows="8" cols="40" onkeydown="ResizeTextArea(this)" class="textedit" id="Text" name="text"></textarea><br/>'.
        '<input type="hidden" name="a" value="add2"/>'.
        '<input type="submit" value="'.T('Save').'"/><br/>'.
        '</form>';
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function SaveNew()
  {
    if($this->System->User->Licence(LICENCE_ADMIN))
    {
      if(array_key_exists('text', $_POST) and array_key_exists('title', $_POST))
      {
        $querty = 'INSERT INTO `News` (`Title`, `Time` ,`User` ,`Text`) VALUES ( "'.$_POST['title'].'", NOW( ) , '.
           $this->System->User->Id.', "'.$_POST['text'].'")';
        $this->System->Database->query($querty);
        $Output = ShowMessage(T('News added'));
        $this->System->ModuleManager->Modules['Log']->WriteLog('Vložena nová aktualita', LOG_TYPE_ADMINISTRATION);
        $Output .= $this->ShowList();
      } else $Output = ShowMessage(T('Data not specified'), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function ShowRSS()
  {
    $Items = array();
    $DbResult = $this->Database->query('SELECT UNIX_TIMESTAMP(`News`.`Time`) AS `UnixTime`, '.
      '`News`.`Title`, `News`.`Time`, `User`.`Name`, `News`.`Text`, `News`.`Id` '.
      'FROM `News` JOIN `User` ON `User`.`ID` = `News`.`User` ORDER BY `Time` DESC LIMIT 10');
    while($DbRow = $DbResult->fetch_assoc())
    {
     $Items[] = array
     (
       'Title' => $DbRow['Title'],
       'Link' =>  'http://'.$this->System->Config['Web']['Host'].$this->System->Link('/news/?a=item&amp;i='.$DbRow['Id']),
       'Description' => $DbRow['Text'].' ('.$DbRow['Name'].')',
       'Time' => $DbRow['UnixTime'],
     );
    }
    $Output = GenerateRSS(array
    (
      'Title' => $this->System->Config['Web']['Title'].' - '.T('System changes'),
      'Link' => 'http://'.$this->System->Config['Web']['Host'].$this->System->Link('/news/'),
      'Description' => $this->System->Config['Web']['Description'],
      'WebmasterEmail' => $this->System->Config['Web']['AdminEmail'],
      'Items' => $Items,
    ));
    return($Output);
  }
}