<?php

class ModuleShoutBox extends AppModule
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'ShoutBox';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Simple user chat system.';
    $this->Dependencies = array('News');
  }
  
  function Start()
  {
  	$this->System->RegisterPage('shoutbox', 'PageShoutBox');
  	$this->System->ModuleManager->Modules['News']->RegisterRSS(array(
  	  'Title' => T('Shoutbox'), 'Channel' => 'shoutbox', 'Callback' => array('PageShoutBox', 'ShowRSS'), 
  	  'Permission' => LICENCE_ANONYMOUS));  	 
    if(array_key_exists('Search', $this->System->ModuleManager->Modules))
      $this->System->ModuleManager->Modules['Search']->RegisterSearch('shoutbox',
      T('Shoutbox'), array('UserName', 'Text'), '`ShoutBox`', $this->System->Link('/shoutbox/?search='));
  }
  
  function ShowBox()
  {
  	$Output = '<strong><a href="'.$this->System->Link('/shoutbox/').'">'.T('Shoutbox').':</a></strong>';
  	 
  	if($this->System->User->Licence(LICENCE_USER))
  		$Output .= ' <a href="'.$this->System->Link('/shoutbox/?a=add').'">'.T('Add').'</a>';
  	$Output .= '<div class="box"><table>';
  	$DbResult = $this->Database->query('SELECT * FROM `ShoutBox` ORDER BY `ID` DESC LIMIT 30');
  	while($Line = $DbResult->fetch_assoc())
  		$Output .= '<tr><td><strong>'.$Line['UserName'].'</strong>: '.MakeActiveLinks($Line['Text']).'</td></tr>';
  	$Output .= '</table></div>';
  	return($Output);
  }   
}

class PageShoutBox extends Page
{
	function Show()
	{
		$this->Title = T('Shoutbox');
		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->AddFinish();
		if($Action == 'add') $Output = $this->ShowAddForm();
		else $Output = $this->ShowList();
		return($Output);
	}
	
	function ShowList()
	{
		$Output = '';
		if(array_key_exists('search', $_GET)) $_SESSION['search'] = $_GET['search'];
		else if(!array_key_exists('search', $_SESSION)) $_SESSION['search'] = '';
		if(array_key_exists('search', $_GET) and ($_GET['search'] == '')) $_SESSION['search'] = '';
		if($_SESSION['search'] != '')
		{
			$SearchQuery = ' AND (`Text` LIKE "%'.$_SESSION['search'].'%")';
			$Output .= '<div><a href="?search=">'.sprintf(T('Disable filter "%s"'), $_SESSION['search']).'</a></div>';
		} else $SearchQuery = '';			

   	$DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `ShoutBox` WHERE 1'.$SearchQuery);
		$DbRow = $DbResult->fetch_row();
		$PageList = GetPageList($DbRow[0]);	

		$Output .= '<h3>'.T('Shoutbox').'</h3>'.$PageList['Output'];
		if($this->System->User->Licence(LICENCE_USER)) 
			$Output .= ' <a href="'.$this->System->Link('/shoutbox/?a=add').'">'.T('Add').'</a>';
		$Output .= '<div class="shoutbox">';
		$DbResult = $this->System->Database->query('SELECT * FROM `ShoutBox`  WHERE 1'.$SearchQuery.' ORDER BY `ID` DESC '.$PageList['SQLLimit']);
		while($Line = $DbResult->fetch_assoc())
			$Output .= '<div><strong>'.$Line['UserName'].'</strong>: '.MakeActiveLinks($Line['Text']).'</div>';
		$Output .= '</div>'.$PageList['Output'];
		return($Output);
	}
	
	function ShowAddForm()
	{
		$Output = '';
		if($this->System->User->Licence(LICENCE_USER))
		{
				$Output .= '<form action="?" method="post">'.
						'<fieldset><legend>'.T('New message').'</legend>'.
						'Uživatel: ';
				if($this->System->User->Licence(LICENCE_USER)) $Output .= '<b>'.$this->System->User->Name.'</b><br />';
				else $Output .= '<input type="text" name="user" /><br />';
			$Output .= 'Text zprávy: <br/>'.
			'<textarea onkeydown="ResizeTextArea(this)" name="text" cols="40"></textarea> <br/>'.
			'<input type="hidden" name="a" value="add2"/>'.
			'<input type="submit" value="Odeslat" /><br /></fieldset>'.
			'</form>';
		}	else $Output .= ShowMessage('Pro vkládaní zpráv musíte byt registrováni.', MESSAGE_CRITICAL);
		$Output .= $this->ShowList();
	  return($Output);	
	}
	
	function AddFinish()
	{
		$Output = '';
		if($this->System->User->Licence(LICENCE_USER))
		{
			if(array_key_exists('text', $_POST))
			{
				$Text = $_POST['text'];
				if(trim($Text) == '') $Output .= ShowMessage('Nelze vložit prázdnou zprávu.', MESSAGE_WARNING);
				else
				{
					// Protection against mutiple post of same message
					$DbResult = $this->System->Database->query('SELECT `Text` FROM `ShoutBox` WHERE (`User` = "'.
							$this->System->User->Id.'") ORDER BY `Date` DESC LIMIT 1');
					if($DbResult->num_rows > 0)
					{
						$DbRow = $DbResult->fetch_assoc();
					} else $DbRow['Text'] = '';
			
					if($DbRow['Text'] == $Text) $Output .= ShowMessage('Nelze vložit stejnou zprávu vícekrát za sebou.', MESSAGE_WARNING);
					else
					{
						$this->System->Database->query('INSERT INTO `ShoutBox` ( `User`, `UserName` , `Text` , `Date` , `IP` ) '.
								' VALUES ('.$this->System->User->Id.', "'.$this->System->User->Name.
								'", "'.$Text.'", NOW(), "'.$_SERVER['REMOTE_ADDR'].'")');
						$Output .= ShowMessage('Zpráva vložena.');
					}
				}
			} else $Output .= ShowMessage('Nezadán text pro novou zprávu.', MESSAGE_CRITICAL);				
			$Output .= '<br/>';
		} else $Output .= ShowMessage('Pro vkládaní zpráv musíte byt registrováni.', MESSAGE_CRITICAL);
		$Output .= $this->ShowList();
		return($Output);
	}	
	
	function ShowRSS()
	{
		$Items = array();
	  $TitleLength = 50;
	  mb_internal_encoding('utf-8');
	  $DbResult = $this->Database->query('SELECT UNIX_TIMESTAMP(`Date`) AS `UnixDate`, `User`, `UserName`, `Text` FROM `ShoutBox` ORDER BY `ID` DESC LIMIT 20');
	  while($DbRow = $DbResult->fetch_assoc())
	  {
	    $Title = mb_substr($DbRow['Text'], 0, $TitleLength);
	    if(mb_strlen($Title) == $TitleLength) $Title .= '...';
	    $Items[] = array
	    (
	        'Title' => $DbRow['UserName'].': '.$Title,
	        'Link' =>  'http://'.$this->System->Config['Web']['Host'].$this->System->Link('/shoutbox/'),
	        'Description' => $DbRow['Text'],
	        'Time' => $DbRow['UnixDate'],
	    );
	  }
	  $Output = GenerateRSS(array
    (
      'Title' => $this->System->Config['Web']['Title'].' - '.T('Shoutbox'),
      'Link' => 'http://'.$this->System->Config['Web']['Host'].$this->System->Link('/shoutbox/'),
      'Description' => $this->System->Config['Web']['Description'],
      'WebmasterEmail' => $this->System->Config['Web']['AdminEmail'],
      'Items' => $Items,
    ));
    return($Output);
	}
}