<?php

class ModuleForum extends Module
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Forum';
    $this->Version = '1.0';
    $this->Creator = 'Maron';
    $this->License = 'GNU/GPL';
    $this->Description = '';
    $this->Dependencies = array();
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['forum'], 'PageForum');
    $this->System->ModuleManager->Modules['News']->RegisterRSS(array(
      'Title' => T('Forum'), 'Channel' => 'forum', 'Callback' => array('PageForum', 'ShowRSS'),
      'Permission' => LICENCE_ANONYMOUS));

    if (array_key_exists('Search', $this->System->ModuleManager->Modules))
      $this->System->ModuleManager->Modules['Search']->RegisterSearch('forum',
      T('Forum'), array('UserName', 'Text'), '`ForumText`', $this->System->Link('/forum/?search='));
    if (array_key_exists('Search', $this->System->ModuleManager->Modules))
      $this->System->ModuleManager->Modules['Search']->RegisterSearch('forumthread',
      T('Name of thread forum'), array('UserName', 'Text'), '`ForumThread`',
      $this->System->Link('/forum/?search='));

    Core::Cast($this->System)->RegisterMenuItem(array(
      'Title' => T('Forum'),
      'Hint' => T('Forum about translation wow'),
      'Link' => $this->System->Link('/forum/'),
      'Permission' => LICENCE_ANONYMOUS,
      'Icon' => '',
    ), 17);
  }

  function ShowBox()
  {
    $Count = 20;
    $Output = '<strong><a href="'.$this->System->Link('/forum/').'">'.T('Last forum posts').':</a></strong>';
    $Output .= '<div class="box">';

    $Query = 'SELECT `ForumText`.`Text`, `ForumText`.`Date`, `User`.`Name` AS `UserName`, '.
      '`User`.`Id` AS `UserId`, `ForumText`.`Thread` '.
      'FROM `ForumText` '.
      'JOIN `User` ON `User`.`Id` = `ForumText`.`User` '.
      'ORDER BY `Date` DESC LIMIT '.$Count;
    $DbResult = $this->Database->query($Query);
    $Output .= '<table class="MiniTable"><tr><th>'.T('Date').'</th><th>'.T('User').'</th><th>'.T('Post').'</th></tr>';
    while ($DbRow = $DbResult->fetch_assoc())
    {
      $Output .= '<tr>'.
        '<td><a href="'.$this->System->Link('/forum/?Thread='.$DbRow['Thread']).'">'.HumanDate($DbRow['Date']).'</a></td>'.
        '<td><a href="'.$this->System->Link('/user/?user='.$DbRow['UserId']).'">'.$DbRow['UserName'].'</a></td>'.
        '<td>'.ShowBBcodes(htmlspecialchars($DbRow['Text'])).'</td>'.
        '</tr>';
    }
    $Output .= '</table></div>';
    return $Output;
  }
}

class PageForum extends Page
{
  function Show(): string
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    $this->Title = T('Forum');
    if (array_key_exists('a', $_POST)) $Action = $_POST['a'];
      else if (array_key_exists('a', $_GET)) $Action = $_GET['a'];
      else $Action = '';
    if (array_key_exists('Edit', $_GET)) {
      if (array_key_exists('text', $_POST))
        $Output .= $this->Edit();
      $Output .= $this->ShowEditForm();
    } else
    if (array_key_exists('search', $_GET))
      $Output .= $this->ShowSearchForum();
    else
    if (array_key_exists('Thread', $_GET)) {
      $Output .= '<h3>'.T('Forum - Thread').'</h3>';
      if ($Action == 'add2') $Output .= $this->AddFinish();
      if ($User->Licence(LICENCE_USER)) $Output .= $this->ShowAddForm();
      $Output .= $this->ShowList();
    } else {
      $Output .= '<h3>'.T('Forum - List of Thread').'</h3>';
      if ($Action == 'add2') $Output .= $this->AddFinish('ForumThread');
      if ($User->Licence(LICENCE_USER)) $Output .= $this->ShowAddFormThread();
      $Output .= $this->ShowListThread();
    }
    return $Output;
  }

  function Edit()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    $this->System->Database->query('UPDATE `ForumText` SET `Text`="'.$_POST['text'].'" WHERE `User` = '.$User->Id.' AND `ID` = '.$_GET['Edit']);
    $Output .= ShowMessage(T('Text edited.'));
    return $Output;
  }

  function ShowEditForm()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($User->Licence(LICENCE_USER))
    {
      $DbResult = $this->System->Database->query('SELECT * FROM `ForumText`  WHERE `User` = '.$User->Id.' AND `ID` = '.$_GET['Edit']);
      if ( $DbResult->num_rows > 0) {
        $DbRow = $DbResult->fetch_assoc();
        $Output .= '<form action="?Edit='.$_GET['Edit'].'" method="post">'.
            '<fieldset><legend>'.T('Edit message').'</legend>'.
            T('User').': ';
        if ($User->Licence(LICENCE_USER)) $Output .= '<b>'.$User->Name.'</b><br />';
          else $Output .= '<input type="text" name="user" /><br />';
        $Output .= T('Message text').': ('.T('You can use').' <a href="http://www.bbcode.org/reference.php">'.T('BB code').'</a>)<br/>'.
        '<textarea onkeydown="ResizeTextArea(this)" rows="8" name="text" cols="80">'.htmlspecialchars($DbRow['Text']).'</textarea> <br/>'.
        '<input type="hidden" name="a" value="add2"/>'.
        '<input type="submit" value="'.T('Send').'" /><br /></fieldset>'.
        '</form>';
      } else $Output .= ShowMessage(T('You have to be registered for adding message.'), MESSAGE_CRITICAL);
    }   else $Output .= ShowMessage(T('You can edit only your own message.'), MESSAGE_CRITICAL);
    return $Output;
  }

  function ShowSearchForum()
  {
    $Output = '';

    $Output .= '<div class="shoutbox">';
    $where = '`ForumText`.`Text` LIKE "%'.($_GET['search'] ).'%" OR '.
    ' `ForumThread`.`Text` LIKE "%'.($_GET['search'] ).'%" OR `ForumThread`.`UserName` LIKE "%'.($_GET['search'] ).'%" OR '.
    ' `ForumText`.`UserName` LIKE "%'.($_GET['search'] ).'%"';
    $join = ' JOIN `ForumThread` ON `ForumThread`.`ID` = `ForumText`.`Thread`';

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

    $Output .= $PageList['Output'];

    $DbResult = $this->System->Database->query('SELECT `ForumText`.`Text`, `ForumText`.`Date`, `ForumText`.`UserName`,'.
    '`ForumThread`.`Text` as `ThreadName`,`ForumText`.`Thread` FROM `ForumText` '.$join.' WHERE '.$where.' ORDER BY `ForumText`.`Date` DESC '.$PageList['SQLLimit']);
    while ($Line = $DbResult->fetch_assoc())
      $Output .= '<div><a href="'.$this->System->Link('/forum/?Thread='.$Line['Thread']).'">'.
      htmlspecialchars($Line['ThreadName']).'</a><br /><strong>'.$Line['UserName'].
      '</strong> ('.HumanDate($Line['Date']).'): '.ShowBBcodes(htmlspecialchars($Line['Text'])).'</div> ';
    $Output .= '</div>'.$PageList['Output'];
    return $Output;
  }

  function ShowListThread()
  {
    $Output = '';

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

    $Output .= $PageList['Output'];
    $Output .= '<div class="shoutbox">';
    $DbResult = $this->System->Database->query('SELECT * FROM `ForumThread` WHERE 1 ORDER BY `ID` DESC '.$PageList['SQLLimit']);
    while ($Line = $DbResult->fetch_assoc())
    {
      $Output .= '<div><span style="float:right;"><strong>'.$Line['UserName'].
        '</strong> - ('.HumanDate($Line['Date']).')</span> <a href="?Thread='.$Line['ID'].'">'.
        str_replace("\n", '', htmlspecialchars($Line['Text'])).'</a></div>';
    }
    $Output .= '</div>'.$PageList['Output'];
    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"'), $_SESSION['search']).'</a></div>';
    } else $SearchQuery = '';

    $ThreadId = 0;
    if (TryGetUrlParameterInt('Thread', $ThreadId))
    {
      $DbResult = $this->System->Database->query('SELECT * FROM `ForumThread` WHERE ID='.$ThreadId.' LIMIT 1');
      if ($DbResult->num_rows > 0)
      {
        $Thread = $DbResult->fetch_assoc();
        $Output .= '<h3>'.htmlspecialchars($Thread['Text']).'</h3>';

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

        $Output .= $PageList['Output'];
        $Output .= '<div class="shoutbox">';
        $DbResult = $this->System->Database->query('SELECT * FROM `ForumText` WHERE `Thread` = '.
          $ThreadId.' '.$SearchQuery.' ORDER BY `ID` DESC '.$PageList['SQLLimit']);
        while ($Line = $DbResult->fetch_assoc())
        {
          if ($User->Id == $Line['User'])
          {
            $Edit = '<a href="?Edit='.$Line['ID'].'">'.T('edit').'</a>';
          } else $Edit = '';
          $Text = str_replace("\n", '<br />', ShowBBcodes(htmlspecialchars($Line['Text'])));
          $Output .= '<div><span style="float:right;">'.$Edit.' ('.HumanDate($Line['Date']).
            ')</span><strong>'.$Line['UserName'].'</strong>: '.$Text.'  </div> ';
        }
        $Output .= '</div>'.$PageList['Output'];
      } else $Output .= ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
    } else $Output .= ShowMessage(T('Id not found'), MESSAGE_CRITICAL);
    return $Output;
  }

  function ShowAddForm()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($User->Licence(LICENCE_USER))
    {
      $Output .= '<form action="?Thread='.$_GET['Thread'].'" method="post">'.
        '<fieldset><legend>'.T('New Forum Message').'</legend>'.
        T('User').': ';
      if ($User->Licence(LICENCE_USER)) $Output .= '<b>'.$User->Name.'</b><br />';
        else $Output .= '<input type="text" name="user" /><br />';
      $Output .= T('Message text').': ('.T('You can use').' <a href="http://www.bbcode.org/reference.php">'.T('BB code').'</a>)<br/>'.
        '<textarea onkeydown="ResizeTextArea(this)" name="text" cols="80"></textarea> <br/>'.
        '<input type="hidden" name="a" value="add2"/>'.
        '<input type="submit" value="'.T('Send').'" /><br /></fieldset>'.
        '</form>';
    } else $Output .= ShowMessage(T('You have to be registered for adding message.'), MESSAGE_CRITICAL);
    return $Output;
  }

  function ShowAddFormThread()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($User->Licence(LICENCE_USER))
    {
      $Output .= '<form action="?" method="post">'.
        '<fieldset><legend>'.T('New thread').'</legend>'.T('User').': ';
      if ($User->Licence(LICENCE_USER)) $Output .= '<b>'.$User->Name.'</b><br />';
        else $Output .= '<input type="text" name="user" /><br />';
      $Output .= T('Name of thread').': <br />'.
      '<textarea onkeydown="ResizeTextArea(this)" name="text" rows="1" cols="30"></textarea> <br/>'.
      '<input type="hidden" name="a" value="add2"/>'.
      '<input type="submit" value="'.T('Send').'" /><br /></fieldset>'.
      '</form>';
    } else $Output .= ShowMessage(T('You have to be registered for adding message.'), MESSAGE_CRITICAL);
    return $Output;
  }

  function AddFinish($Table = 'ForumText')
  {
    $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
          $Thread = '';
          if ($Table == 'ForumText') $Thread = 'AND `Thread` = '.$_GET['Thread'];
          $DbResult = $this->System->Database->query('SELECT `Text` FROM `'.$Table.'` WHERE 1 '.$Thread.' AND (`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(T('You can\' add same message twice.'), MESSAGE_WARNING);
          else
          {
            if ($Table == 'ForumText') {

              $DbResult = $this->System->Database->query('SELECT * FROM `ForumThread` WHERE ID='.($_GET['Thread']*1).' LIMIT 1');
              if ($DbResult->num_rows > 0)
              {
                $this->System->Database->query('INSERT INTO `'.$Table.'` ( `User`, `UserName` , `Text` , `Date` , `IP` , `Thread` ) '.
                ' VALUES ('.$User->Id.', "'.$User->Name.
                '", "'.$Text.'", NOW(), "'.GetRemoteAddress().'","'.$_GET['Thread'].'")');
              } else $Output .= ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
             } else
            $this->System->Database->query('INSERT INTO `'.$Table.'` ( `User`, `UserName` , `Text` , `Date` , `IP`) '.
                ' VALUES ('.$User->Id.', "'.$User->Name.
                '", "'.$Text.'", NOW(), "'.GetRemoteAddress().'")');
            $Output .= ShowMessage(T('Added.'));
          }
        }
      } else $Output .= ShowMessage(T('You have to specified new message.'), MESSAGE_CRITICAL);
      $Output .= '<br/>';
    } else $Output .= ShowMessage(T('You have to be registered for adding message.'), MESSAGE_CRITICAL);
    return $Output;
  }

  function ShowRSS()
  {
    $Items = array();
    $TitleLength = 50;
    mb_internal_encoding('utf-8');
    $DbResult = $this->Database->query('SELECT `Thread`, `ID`, UNIX_TIMESTAMP(`Date`) AS `UnixDate`, '.
      '`User`, `UserName`, `Text`, ( SELECT `Text` FROM `ForumThread` '.
      'WHERE `ID` = `ForumText`.`Thread`) AS `ThreadText` FROM `ForumText` 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' => htmlspecialchars($DbRow['ThreadText']).' - '.$DbRow['UserName'].': ',
        'Link' => 'https://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/forum/?Thread='.$DbRow['Thread']),
        'Description' => ShowBBcodes(htmlspecialchars($DbRow['Text'])),
        'Time' => $DbRow['UnixDate'],
      );
    }
    $Output = GenerateRSS(array
    (
      'Title' => Core::Cast($this->System)->Config['Web']['Title'].' - '.T('Forum'),
      'Link' => 'https://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/forum/'),
      'Description' => Core::Cast($this->System)->Config['Web']['Description'],
      'WebmasterEmail' => Core::Cast($this->System)->Config['Web']['AdminEmail'],
      'Items' => $Items,
    ));
    return $Output;
  }
}
