<?php

class ModuleShoutBox extends Module
{
  function __construct(System $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 DoStart(): void
  {
    $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()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '<strong><a href="'.$this->System->Link('/shoutbox/').'">'.T('Shoutbox').':</a></strong>';

    if ($User->Licence(LICENCE_USER))
      $Output .= ' <a href="'.$this->System->Link('/shoutbox/?a=add').'">'.T('Add').'</a>';
    $Output .= '<div class="box"><div class="shoutbox"><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></div>';
    return $Output;
  }
}

class PageShoutBox extends Page
{
  function Show(): string
  {
    $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()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $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"'), htmlentities($_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>';
    if ($User->Licence(LICENCE_USER))
      $Output .= ' <a href="'.$this->System->Link('/shoutbox/?a=add').'">'.T('Add').'</a>';
    $Output .= $PageList['Output'];
    $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()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($User->Licence(LICENCE_USER))
    {
        $Output .= '<form action="?" method="post">'.
            '<fieldset><legend>'.T('New message').'</legend>'.
            'Uživatel: ';
        if ($User->Licence(LICENCE_USER)) $Output .= '<b>'.$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()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($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` = "'.
              $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 ('.$User->Id.', "'.$User->Name.
                '", "'.$Text.'", NOW(), "'.GetRemoteAddress().'")');
            $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()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $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' =>  'https://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/shoutbox/'),
          'Description' => $DbRow['Text'],
          'Time' => $DbRow['UnixDate'],
      );
    }
    $Output = GenerateRSS(array
    (
      'Title' => Core::Cast($this->System)->Config['Web']['Title'].' - '.T('Shoutbox'),
      'Link' => 'https://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/shoutbox/'),
      'Description' => Core::Cast($this->System)->Config['Web']['Description'],
      'WebmasterEmail' => Core::Cast($this->System)->Config['Web']['AdminEmail'],
      'Items' => $Items,
    ));
    return $Output;
  }
}
