<?php

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

class PageNews extends Page
{
  var $FullTitle = 'Aktualní informace';
  var $ShortTitle = 'Aktuality';
  var $ParentClass = 'PagePortal';
  var $UploadedFilesFolder = 'uploads/';

  function Show()
  {
    if(count($this->System->PathItems) > 1)
    { 
      if($this->System->PathItems[1] == 'subscription') return($this->ShowSubscription());
        else if($this->System->PathItems[1] == 'rss') return($this->ShowRSS());
        else return(PAGE_NOT_FOUND);
    } else return($this->ShowMain());
  }
  
  function ShowView()
  {
    $Output = '';
    if(!$this->System->User->CheckPermission('News', 'Display', 'Item')) $Output .= 'Nemáte oprávnění';
    else
    {
      $Category = $this->GetCategory();
      if(array_key_exists('id', $_GET)) $Id = $_GET['id'] * 1;
      $DbResult = $this->Database->query('SELECT `News`.*, `User`.`Name` FROM `News` '.
        'LEFT JOIN `User` ON `User`.`Id`=`News`.`User` WHERE `News`.`Id`='.$Id);
      if($DbResult->num_rows > 0)
      {
        $Row = $DbResult->fetch_array();
        if($Row['Name'] == '') $Author = $Row['Author'];
          else $Author = $Row['Name'];
        $Output .= '<div class="Panel"><div class="Title">'.$Row['Title'].' ('.HumanDate($Row['Date']).', '.$Author.')';
        if(($this->System->User->User['Id'] == $Row['User']) and ($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id'])))
        {
          $Output .= '<div class="Action">';
          $Output .= '&nbsp;<a href="?action=del&amp;category='.$Category['Id'].'&amp;id='.$Row['Id'].'">Smazat</a>';
          $Output .= '&nbsp;<a href="?action=edit&amp;category='.$Category['Id'].'&amp;id='.$Row['Id'].'">Upravit</a>';
          $Output .= '</div>';
        }
        $Output .= '</div><div class="Content">'.$this->System->ModuleManager->Modules['News']->ModifyContent($Row['Content']).'<br />';
        if($Row['Link'] != '') $Output .= '<br/><a href="'.$Row['Link'].'">Odkaz</a>';
        if($Row['Enclosure'] != '')
        {
          $Output .= '<br />Přílohy: ';
          $Enclosures = explode(';', $Row['Enclosure']);
          foreach($Enclosures as $Enclosure)
          {
            if(file_exists($this->UploadedFilesFolder.$Enclosure)) 
              $Output .= ' <a href="'.$this->System->Link('/'.$this->UploadedFilesFolder.$Enclosure).'">'.$Enclosure.'</a>';
          }
        }
        $Output .= '</div></div>';
      } else $Output .= 'Položka nenalezena.';
    }
    return($Output);
  }
  
  function ShowAdd()
  {
    $Output = '';
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id']))
    {
      $Output = '<strong>Vložení nové aktuality:</strong><br />';
      // TODO: Static reference to dynamic category item
      if($Category['Id'] == 2) $Output .= 'U inzerátů uvádějte co nejvíce informací ať případný zájemce ví co kupuje. Uvádějte kontaktní údaje jako Jméno, email, tel. číslo, ICQ. Dále navrženou cenu, detajlní popis předmětu nejlépe s odkazem na stránky výrobce. Pokud váš inzerát již není platný, připište do něj např. "Prodáno" pomocí editace.';
      $Output .= '<form enctype="multipart/form-data" action="?action=add2" method="post">'.
        'Kategorie: <select name="category">';
      $DbResult = $this->Database->select('NewsCategory', '*');
      while($DbRow = $DbResult->fetch_array())
      {
        if($this->System->User->CheckPermission('News', 'Insert', 'Group', $DbRow['Id']))
        {
          if($DbRow['Id'] == $Category['Id']) $Selected = ' selected="1"'; 
            else $Selected = '';
          $Output .= '<option value="'.$DbRow['Id'].'"'.$Selected.'>'.$DbRow['Caption'].'</option>';
        }
      }
      $Output .= '</select><br />'.
        'Nadpis:<br /><input type="text" size="54" name="title"><br />'.
        'Obsah:<br /><textarea name="content" rows="20" cols="40"></textarea><br />'.
        'Odkaz:<br /><input type="text" size="54" name="link"><br />'.
        'Přílohy (Max. velikost souboru 1 MB):<br /><input type="hidden" name="MAX_FILE_SIZE" value="1000000">'.
        '<input name="enclosure1" size="38" type="file"><br />'.
        '<input name="enclosure2" size="38" type="file"><br />'.
        '<input name="enclosure3" size="38" type="file"><br />'.
        '<input type="submit" value="Vložit">'.
        '</form>';
    } else $Output .= 'Do této kategorie nemůžete vkládat aktuality!';
    return($Output);
  }
  
  function ShowAdd2()
  {
    $Output = '';
    $RemoteAddr = GetRemoteAddress();
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id']))
    {
      // Process uploaded file
      // TODO: Make upload using general File class
      $EnclosureFileNames = array('enclosure1', 'enclosure2', 'enclosure3');
      $Enclosures = '';
      foreach($EnclosureFileNames as $EnclosureName)
        if(array_key_exists($EnclosureName, $_FILES) and ($_FILES[$EnclosureName]['name'] != ''))
        {
          $UploadedFilePath = $this->UploadedFilesFolder.basename($_FILES[$EnclosureName]['name']);
          if(move_uploaded_file($_FILES[$EnclosureName]['tmp_name'], $UploadedFilePath))
          {
            $Output .= 'Soubor '.basename($_FILES[$EnclosureName]['name']).' byl uložen na serveru.<br />';
            $Enclosures = $Enclosures.';'.basename($_FILES[$EnclosureName]['name']);
          } else
          {
            $Output .= 'Soubor '.basename($_FILES[$EnclosureName]['name']).' se nepodařilo nahrát na server.<br />';
          }
        }
        $Enclosures = substr($Enclosures, 1);
    
        $_POST['content'] = str_replace("\n",'<br />',$_POST['content']);
        $this->Database->insert('News', array('Category' => $Category['Id'], 'Title' => $_POST['title'],
          'Content' => $_POST['content'], 'Date' => 'NOW()', 'IP' => $RemoteAddr,
          'Enclosure' => $Enclosures, 'Author' => $this->System->User->User['Name'], 
          'User' => $this->System->User->User['Id'], 'Link' => $_POST['link']));
        $Output .= 'Aktualita přidána!<br />Pokud budete chtít vaši aktualitu smazat, klikněte na odkaz Smazat v seznamu všech aktualit v kategorii.<br /><br />';
        $Output .= '<a href="?category='.$_POST['category'].'">Zpět na seznam aktualit</a>';
        $this->System->ModuleManager->Modules['Log']->NewRecord('News', 'Aktualita přidána', $this->Database->insert_id);
    } else $Output .= 'Do této kategorie nemůžete vkládat aktuality!';
    return($Output);
  }
  
  function ShowEdit()
  {
    $Output = '';
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id']))
    {
      $DbResult = $this->Database->query('SELECT * FROM `News` WHERE `Id`='.$_GET['id']);
      $Row = $DbResult->fetch_array();
      if(($this->System->User->User['Id'] == $Row['User']))
      {
        $Row['Content'] = str_replace('<br />', '', $Row['Content']);
        $Output .= '<strong>Editace aktuality v kategorii '.$Category['Caption'].':</strong><br />';
        $Output .= '<form action="?action=update" method="post">'.
        '<input type="hidden" value="'.$_GET['id'].'" name="id">'.
        'Nadpis:<br /><input type="text" size="54" name="title" value="'.$Row['Title'].'"><br />'.
        'Obsah:<br /><textarea name="content" rows="20" cols="40">'.$Row['Content'].'</textarea><br />'.
        'Odkaz:<br /><input type="text" size="54" name="link" value="'.$Row['Link'].'"><br />'.
        '<input type="hidden" name="category" value="'.$Category['Id'].'"><br />'.
        '<input type="submit" value="Uložit">'.
        '</form>';
      } else $Output .= 'Nepovolená operace!';
    } else $Output .= 'Do této kategorie nemůžete vkládat aktuality!';
    return($Output);
  }
  
  function ShowUpdate()
  {
    $Output = '';
    $RemoteAddr = GetRemoteAddress();  
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id']))
    {
      $_POST['id'] = $_POST['id'] * 1;
      $DbResult = $this->Database->select('News', '*', '`Id`='.$_POST['id']);
      if($DbResult->num_rows > 0)
      {
        $Row = $DbResult->fetch_array();
        if($this->System->User->User['Id'] == $Row['User'])
        {
          $_POST['content'] = str_replace("\n", '<br />', $_POST['content']);
          $this->Database->update('News', 'Id='.$_POST['id'], array('Title' => $_POST['title'], 
            'Content' => $_POST['content'], 'Link' => $_POST['link']));
          $Output .= 'Aktualita uložena!<br />';
          $Output .= '<a href="?category='.$Category['Id'].'">Zpět na seznam aktualit</a>';
        } else $Output .= 'Nelze měnit cizí aktualitu!<br />';
      } else $Output .= 'ID nenalezeno!';
    } else $Output .= 'Do této kategorie nemůžete vkládat aktuality!';
    return($Output);
  }
  
  function ShowDelete()
  {
    $Output = '';
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id']))
    {
      $DbResult = $this->Database->query('SELECT * FROM `News` WHERE `Id`='.$_GET['id']);
      $Row = $DbResult->fetch_array();
      if($this->System->User->User['Id'] == $Row['User'])
      {
        // TODO: Make upload using general File class
        if($Row['Enclosure'] != '')
        { 
          $Output .= '<br />Přílohy: ';
          $Enclosures = explode(';', $Row['Enclosure']);
          foreach($Enclosures as $Enclosure)
          {
            if(file_exists($this->UploadedFilesFolder.$Enclosure)) unlink($this->UploadedFilesFolder.$Enclosure);
          }
        }
        $this->Database->query('DELETE FROM `News` WHERE `Id`='.$_GET['id']);
        $Output .= 'Aktualita smazána!<br /><a href="?category='.$Category['Id'].'">Zpět na seznam aktualit</a>';
      } else $Output .= 'Nemáte oprávnění.';
    } else $Output .= 'Do této kategorie nemůžete vkládat aktuality!';
    return($Output);
  }
  
  function ShowList()
  {
    $Output = '';
    $Category = $this->GetCategory();
    if($this->System->User->CheckPermission('News', 'Display', 'Group', $Category['Id']))
    {
      $PerPage = 20;
      $DbResult = $this->Database->select('News', 'COUNT(*)', ' `Category`='.$Category['Id']);
      $RowTotal = $DbResult->fetch_array();
      $PageMax = $RowTotal[0];
      if(array_key_exists('page', $_GET)) $Page = $_GET['page'];
        else $Page = 0; //round($PageMax/$PerPage);
      $Output .= '<strong>Seznam aktualit kategorie '.$Category['Caption'].':</strong><div style="font-size: small;">';
      $Output .= PagesList('?category='.$Category['Id'].'&amp;page=', $Page, $PageMax, $PerPage);
    
      $DbResult = $this->Database->query('SELECT `News`.*, `User`.`Name` FROM `News` '.
        'LEFT JOIN `User` ON `User`.`Id`=`News`.`User` WHERE `Category`='.$Category['Id'].' ORDER BY `News`.`Id` DESC LIMIT '.($Page * $PerPage).','.$PerPage);
      while($Row = $DbResult->fetch_array())
      {
        if($Row['Name'] == '') $Author = $Row['Author'];
          else $Author = $Row['Name'];
        $Output .= '<div class="Panel"><div class="Title"><a href="?action=view&amp;id='.$Row['Id'].'">'.$Row['Title'].'</a> ('.HumanDate($Row['Date']).', '.$Author.')';
        if(($this->System->User->User['Id'] == $Row['User']) and ($this->System->User->CheckPermission('News', 'Insert', 'Group', $Category['Id'])))
        {
          $Output .= '<div class="Action">';
          $Output .= '&nbsp;<a href="?action=del&amp;category='.$Category['Id'].'&amp;id='.$Row['Id'].'">Smazat</a>';
          $Output .= '&nbsp;<a href="?action=edit&amp;category='.$Category['Id'].'&amp;id='.$Row['Id'].'">Upravit</a>';
          $Output .= '</div>';
        }
        $Output .= '</div><div class="Content">'.$this->System->ModuleManager->Modules['News']->ModifyContent($Row['Content']).'<br />';
        if($Row['Link'] != '') $Output .= '<br/><a href="'.$Row['Link'].'">Odkaz</a>';
        if($Row['Enclosure'] != '')
        {
          $Output .= '<br />Přílohy: ';
          $Enclosures = explode(';', $Row['Enclosure']);
          foreach($Enclosures as $Enclosure)
          {
            if(file_exists($this->UploadedFilesFolder.$Enclosure)) 
              $Output .= ' <a href="'.$this->System->Link('/'.$this->UploadedFilesFolder.$Enclosure).'">'.$Enclosure.'</a>';
          }
        }
        $Output .= '</div></div>';
      }
      $Output .= PagesList('?category='.$Category['Id'].'&amp;page=', $Page, $PageMax, $PerPage);
      $Output .= '</div>';
    } else $Output .= 'Nemáte oprávnění.';
    return($Output);
  }
  
  function GetCategory()
  {
    $Category = array('Id' => 1); // Default category
    if(array_key_exists('category', $_GET)) $Category['Id'] = $_GET['category'] * 1;
    if(array_key_exists('category', $_POST)) $Category['Id'] = $_POST['category'] * 1;
    //if(is_null($Category)) throw new Exception('Kategorie neurčena');
    else 
    {
      $DbResult = $this->Database->select('NewsCategory', '*', '`Id`='.$Category['Id'].' ORDER BY `Sequence`');
      if($DbResult->num_rows > 0) $Category = $DbResult->fetch_array();
        else $Category = array('Id' => 0); //throw new Exception('Kategorie nenalezena');
    }
    return($Category);
  }
  
  function ShowMain()
  {
    $Output = '';    
    if(array_key_exists('action',$_GET)) $Action = $_GET['action'];
      else $Action = '';
    if($Action == 'view') $Output .= $this->ShowView();
    else if($Action == 'add') $Output .= $this->ShowAdd();
    else if($Action == 'add2') $Output .= $this->ShowAdd2();
    else if($Action == 'edit') $Output .= $this->ShowEdit();
    else if($Action == 'update') $Output .= $this->ShowUpdate();
    else if($Action == 'del') $Output .= $this->ShowDelete();
    else $Output .= $this->ShowList();
    return($Output);
  }
  
  function ShowSubscription()
  {	
    if(array_key_exists('build', $_GET))
    {
      $Select = '';
      foreach($_POST as $Index => $Item)
      {
        if(substr($Index, 0, 8) == 'category') $Select .= '-'.substr($Index, 8);
      }
      $Select = $this->System->Config['Web']['RootFolder'].'/aktuality/rss/?select='.substr($Select, 1);
      $Output = 'Výsledný RSS kanál: <a href="'.$Select.'">'.$Select.'</a>';
    } else 
    {
      $Output = 'Vytvořte si vlastní RSS kanál, díky kterému budete moci automaticky sledovat novinky pomocí vaší RSS čtečky. Informace o technologii RSS a programech pro čtení kanálů najdete např. <a href="http://www.lupa.cz/clanky/prehled-rss-ctecek/">zde</a><br />'.
      '<br />Kategorie:<br />';
      $Output .= '<form action="?build=1" method="post">';
      $DbResult = $this->Database->select('NewsCategory', '*', '1 ORDER BY `Caption`');
      while($Category = $DbResult->fetch_array())
      {
        $Output .= '<input type="checkbox" name="category'.$Category['Id'].'" />'.$Category['Caption'].'<br />';
      }
      $Output.= '<input type="submit" value="Sestavit"/>'.
        '</form>';
    }  
    return($Output);
  }
  
  function ShowRSS()
  {
    $this->ClearPage = true;
    $this->FormatHTML = false;
    Header('Content-Type: text/xml');

    $NewsCount = 15;

    $Items = array();
    $Category = '';
    $CategoryOption = '';
    $CategoryOptionURL = '';
    $CategoryName = '';

    // Prepare WHERE condition 
    if(array_key_exists('select', $_GET)) 
    {
      $Where = '';
      $Parts = explode('-', $_GET['select']);
      foreach($Parts as $Part)
      {
        $Where .= 'OR (`Category`='.($Part * 1).')'; 
      }
      $Where = substr($Where, 2);
    } else $Where = 1;

    // Get category names
    $Categories = array();
    $DbResult = $this->Database->select('NewsCategory', '*');
    while($Category = $DbResult->fetch_array())
    {
      $Categories[$Category['Id']] = $Category['Caption'];
    }

    // Update news from discussion forum
    /*
    $ForumCategory = 4;   
    $Database->select_db('forum');
    $DbResult = $Database->query('SELECT posts.post_time, posts_text.post_subject, posts_text.post_text, users.username, topics.topic_title FROM posts JOIN posts_text ON posts.post_id = posts_text.post_id JOIN users ON users.user_id = posts.poster_id JOIN topics ON topics.topic_id= posts.topic_id ORDER BY post_time DESC LIMIT '.$NewsCount);
    $Index = 0;
    //echo(DB_NumRows().',');
    while($Row = $DbResult->fetch_array())
    {
      $Row['post_text'] = StrTr($Row['post_text'], "\x8A\x8D\x8E\x9A\x9D\x9E", "\xA9\xAB\xAE\xB9\xBB\xBE"); 
      $Row['post_text'] = str_replace("\n","<br>", $Row['post_text']); 
      $Row['post_subject'] = StrTr($Row['post_subject'], "\x8A\x8D\x8E\x9A\x9D\x9E", "\xA9\xAB\xAE\xB9\xBB\xBE"); 
      $Row['topic_title'] = StrTr($Row['topic_title'], "\x8A\x8D\x8E\x9A\x9D\x9E", "\xA9\xAB\xAE\xB9\xBB\xBE"); 
      $Index = $Index + 1;    
      
      $Title = $Row['topic_title'].'-'.$Row['post_subject'];
      $Content = $Row['post_text'];
      $Date = date('Y-m-d H:i:s', $Row['post_time']);
      $Author = $Row['username'];
      $Database->select_db('is');
      //echo('category='.$ForumCategory.' AND title="'.addslashes($Title).'" AND content="'.addslashes($Content).'" AND author="'.addslashes($Author).'" AND date="'.$Date.'"');
      $DbResult2 = $Database->select('news', '*', 'category='.$ForumCategory.' AND title="'.addslashes($Title).'" AND content="'.addslashes($Content).'" AND author="'.addslashes($Author).'" AND date="'.$Date.'"');
      if($DbResult2->num_rows == 0) //echo('.'); else echo('x'); 
        $Database->insert('news', array('category' => $ForumCategory, 'title' => $Title, 'content' => $Content, 'author' => $Author, 'date' => $Date));
        //echo($Date);  
      $Database->select_db('forum');
    }
    $Database->select_db('is');
    */

    // Get news from database by selected categories
    $UploadedFilesFolder = 'uploads/';
    $DbResult = $this->Database->query('SELECT *, UNIX_TIMESTAMP(`Date`) AS `UnixTime` FROM `News` LEFT JOIN `User` ON `User`.`Id`=`News`.`User` WHERE '.$Where.' ORDER BY News.Date DESC LIMIT 0,'.$NewsCount);
    while($Row = $DbResult->fetch_assoc())
    {
      $EnclosuresText = '';
      if($Row['Enclosure'] != '')
      { 
        $EnclosuresText .= '<br />Přílohy: ';
        $Enclosures = explode(';', $Row['Enclosure']);
        foreach($Enclosures as $Enclosure)
        {
          if(file_exists($UploadedFilesFolder.$Enclosure)) 
            $EnclosuresText .= ' <a href="'.$this->System->Link('/aktuality/'.$UploadedFilesFolder.$Enclosure).'">'.$Enclosure.'</a>';
        }
      }
      if($Row['Name'] == '') $Author = $Row['Author'];
        else $Author = $Row['Name'];
      $Items[] = array(
        'Title' => $Categories[$Row['Category']].' - '.$Row['Title'],
        'Link' => 'http://'.$this->System->Config['Web']['Host'].'/aktuality/?category='.$Row['Category'],
        'Description' => $Row['Content'].' ('.$Author.')'.$EnclosuresText,
        'Time' => $Row['UnixTime'],
      );
    }

    $RSS = new RSS();
    $RSS->Title = $this->System->Config['Web']['Title'].' - Aktuality';
    $RSS->Link = 'http://'.$this->System->Config['Web']['Host'].'/'; 
    $RSS->Description = 'Aktuality '.$this->System->Config['Web']['Description']; 
    $RSS->WebmasterEmail = $this->System->Config['Web']['AdminEmail']; 
    $RSS->Items = $Items;
    return($RSS->Generate());      
  }  
}
