<?php

/*
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                     Чат v.:6.0 для JohnCMS v.:4.3.x                        //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                               Автор: k_2                                   //
//                                                                            //
//                Благодарности выражать на: WMR 250322967425.                //
//                                                                            //
//                     Обратная связь: k2022@rambler.ru                       //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
*/

defined('_IN_JOHNCMS') or die('Error: restricted access');

// Проверяем существование идентификатора комнаты или сообщения и авторизацию юзера
if (!$id || !$user_id) {
  header("Location: index.php");
 exit;
}
// Получаем id комнаты
if (!$mod) {
  $id_k = $id;
} else {
  $sql = $rights > 6 ? "" : " AND `tip` != '1'";
  if ($rights != 9)
    $sql .= " AND (`id_s` = '0' OR `id_u` = '$user_id' OR `id_s` = '$user_id')";
  $soob = mysql_query("SELECT * FROM `chat_room_".$id_k."` WHERE `id` = '" . $id . "'".$sql."");
  $s_d = mysql_fetch_array($soob);
  if (!mysql_num_rows($soob) || $s_d['id_u'] == $user_id) {
    header("Location: index.php");
   exit;
  }
  $set_author = array();
  $set_author = unserialize($s_d['author']);
  // Настроки по-умолчанию
  if (!isset($set_author) || empty($set_author))
    $set_author = serialize(array (
      'av' => '',
      'sex' => 'm',
      'status' => '',
      'name' => $lng_chat['ticker'],
      'name_delete' => '',
      'cvet' => '',
      'cvet_n' => '',
      'ip' => '2130706433',
      'soft' => 'k_2_bot',
      'rights' => 0
    ));
}
// Получаем данные комнаты
$kat = mysql_query("SELECT `name`, `tip`, `bot` FROM `chat_rooms` WHERE `id` = '" . $id_k . "'");
// Переадресация при несущ. комнаты
if (!mysql_num_rows($kat)) { 
  header("location: index.php");
 exit;
}
$kat_d = mysql_fetch_assoc($kat);
// Проверяем на бан.
if (($chat_us_d['ban_time'] >= time() || $ban['12']) && $kat_d['tip'] != 'sr') {
  header("location: $home/chat/index.php?id=$id_k");
 exit;
}
// Проверяем на флуд
$old = ($rights) ? 5 : 10;
$flod_time = time() - $old;
if ($datauser['lastpost'] > $flod_time){
  echo functions::display_error($lng['error_flood'] . ' ' . ($datauser['lastpost']-$flod_time) . $lng['sec'], '<a href="?id=' . $id_k . '">' . $lng['back'] . '</a>');
  require('../incfiles/end.php');
 exit;
}
// Определяем тип сообщения
switch ($mod) {
  case 'citata':
    // Запрещаем цитировать анонимов
    if ($kat_d['tip'] == 'an') {
      header("Location: index.php");
     exit;
    }
    if (isset ($_POST['submit'])) {
      /*
      -----------------------------------------------------------------
      Получение сообщения
      -----------------------------------------------------------------
      */ 
      // Проверяем на существование сообщения
      if (empty ($_POST['msg'])) {
        echo functions::display_error($lng['error_empty_message'], '<a href="index.php?id=' . $id_k . '">'.$lng['back'].'</a>');
        require("../incfiles/end.php");
       exit;
      }
      $msg = trim($_POST['msg']); 
      if ($_POST['msgtrans'] == 1)
        $msg = functions::trans($msg);
      // Форматируем и обрабатываем цитату
      $citata = trim($_POST['citata']);
      $citata = preg_replace('#\[c\](.*?)\[/c\]#si', '', $citata);
      $citata = mb_substr($citata, 0, 200);
      $repl = '[c]' . $us_d['name'] . ' (' . date("d.m.Y/H:i", $s_d['time']) . ")\r\n" . $citata . '[/c] ';
      if (intval($_POST['priv']))
        $priv = ($kat_d['tip'] != 'in' && !$s_d['id_bot']) ? $s_d['id_u'] : 0;
      else
        $priv = 0;
      $pas = ($kat_d['tip'] == 'in') ? intval($_SESSION['key']) : 0;        
      $brauser = strtok($agn, ' ');
      $mass_user_post = serialize(array (
        'av' => '',
        'sex' => $datauser['sex'],
        'status' => $datauser['status'],
        'name' => $login,
        'name_delete' => '',
        'cvet' => $set_chat['cvet'],
        'cvet_n' => $set_chat['cvet_n'],
        'ip' => core::$ip,
        'soft' => $brauser,
        'rights' => $chat_us_d['rights']
      ));
      // Заносим сообщение в б.д
      mysql_query("INSERT INTO `chat_room_".$id_k."` SET
        `id_u` = '".$user_id."',
        `id_s` = '".$priv."',
        `time` = '".time()."',
        `text` = '".mysql_real_escape_string($repl.$msg)."',
        `author` = '".mysql_real_escape_string($mass_user_post)."',
        `pas` = '".$pas."'
      ");
      // Изменяем данные автора сообщения
      mysql_query("UPDATE `users` SET `lastpost` = '" . time() . "' WHERE `id` = '" . $user_id . "'");
      mysql_query("UPDATE `chat_users` SET `postchat` = '" . ($chat_us_d['postchat'] + 1) . "' WHERE `id_u` = '" . $user_id . "'");
      header("location: $home/chat/index.php?id=$id_k");
    } else {
      /*
      -----------------------------------------------------------------
      Форма ввода сообщения
      -----------------------------------------------------------------
      */
      $cit = strip_tags($s_d['text']);
      $cit = preg_replace('#\[c\](.*?)\[/c\]#si', '', $cit);
      $cit = preg_replace('#\&#si', '&amp;', $cit);
      echo '<div class="phdr"><b>'.$lng_chat['room'].':</b> ' . $kat_d['name'] . '</div><form name="form" action="index.php?act=messages&amp;mod=citata&amp;id=' . $id . '&amp;id_k=' . $id_k . '" method="post"><div class="gmenu"><p>' .($set_author['cvet_n']  ? "<span style='color: ".$set_author['cvet_n']."'>" : "") .'<b>'.$set_author['name'] .'</b>'. ($set_author['cvet_n'] ? '</span>' : ''). ' <span class="gray">(' . date("d.m.Y/H:i", $s_d['time']) . ')</span></p>';
      echo '<p><h3>'.$lng_chat['quote'].'</h3><textarea rows="' . $set_user['field_h'] . '" name="citata">' . $cit . '</textarea>';
      echo '<br /><small>'.$lng_chat['max_character'].'</small></p>';
      echo '<p><h3>'.$lng['message'].'</h3>';
      if (!$is_mobile)                                 
        echo '</p><p>' . bbcode::auto_bb('form', 'msg').'';
      echo '<textarea rows="' . $set_user['field_h'] . '" name="msg"></textarea></p>';
      if ($set_user['translit'])
        echo '<input type="checkbox" name="msgtrans" value="1" /> '.$lng['translit'].'<br />';
      if ($kat_d['tip'] != 'in' && !$s_d['id_bot'])
        echo '<input type="checkbox" name="priv" value="1"' . ($s_d['id_s'] ? ' checked="checked"' : '') . '/> <span style="color:red">'.$lng_chat['private'].'</span>';
      echo '<p><input type="submit" name="submit" value="'.$lng['save'].'"/></p></div></form>';
      echo '<div class="phdr"><a href="../pages/faq.php?act=trans">'.$lng['translit'].'</a> | <a href="../pages/faq.php?act=smileys">'.$lng['smileys'].'</a></div>';
      if ($kat_d['tip'] != 'in' && !$s_d['id_bot'])
        echo '<a href="../users/pradd.php?act=write&amp;adr=' . $s_d['id_u'] . '">'.$lng_chat['write_in_private'].'</a><br />';
    }
  break;

  case 'txt':
    // Запрещаем цитировать анонимов
    if ($kat_d['tip'] == 'an') {
      header("Location: index.php");
     exit;
    }
    $shift = (core::$system_set['timeshift'] + core::$user_set['timeshift']) * 3600;
    $vr = date("d.m.Y / H:i", $s_d['time'] + $shift);
    if (isset ($_POST['submit'])) {
      /*
      -----------------------------------------------------------------
      Получение сообщения
      -----------------------------------------------------------------
      */ 
      // Проверяем на существование сообщения
      if (empty ($_POST['msg'])) {                  
        echo functions::display_error($lng['error_empty_message'], '<a href="index.php?id=' . $id_k . '">'.$lng['back'].'</a>');
        require("../incfiles/end.php");
       exit;
      }
      $msg = trim($_POST['msg']); 
      if ($_POST['msgtrans'] == 1)
        $msg = functions::trans($msg); 
      // Обрабатываем реплику
      $text = intval($_POST['txt']);
      
      switch ($text) {

        case 2 :
          $repl = $set_author['name'] . ','.$lng_chat['reply_1'].', ';
        break;

        case 3 :
          $repl = $set_author['name'] . ', '.$lng_chat['reply_2'].' ([url=' . $home . '/chat/index.php?act=post&id=' . $id . '&id_k=' . $id_k . ']' . $vr . '[/url]) '.$lng_chat['reply_3'].', ';
        break;

        case 4 :
          $repl = $set_author['name'] . ', '.$lng_chat['reply_4'].' ';
        break;

        default :
          $repl = $set_author['name'] . ', ';    
      }
      if (intval($_POST['priv']))
        $priv = ($kat_d['tip'] != 'in' && !$s_d['id_bot']) ? $s_d['id_u'] : 0;
      else
        $priv = 0;
      $pas = ($kat_d['tip'] == 'in') ? intval($_SESSION['key']) : 0;        
      $brauser = strtok($agn, ' ');
      $mass_user_post = serialize(array (
        'av' => '',
        'sex' => $datauser['sex'],
        'status' => $datauser['status'],
        'name' => $login,
        'name_delete' => '',
        'cvet' => $set_chat['cvet'],
        'cvet_n' => $set_chat['cvet_n'],
        'ip' => core::$ip,
        'soft' => $brauser,
        'rights' => $chat_us_d['rights']
      ));
      // Заносим сообщение в б.д.
      mysql_query("INSERT INTO `chat_room_".$id_k."` SET
        `id_u` = '".$user_id."',
        `id_s` = '".$priv."',
        `time` = '".time()."',
        `text` = '".mysql_real_escape_string($repl.$msg)."',
        `author` = '".mysql_real_escape_string($mass_user_post)."',
        `pas` = '".$pas."'
      ");
      // Изменяем данные автора сообщения
      mysql_query("UPDATE `users` SET `lastpost` = '" . time() . "' WHERE `id` = '" . $user_id . "'");
      mysql_query("UPDATE `chat_users` SET `postchat` = '" . ($chat_us_d['postchat'] + 1) . "' WHERE `id_u` = '" . $user_id . "'");
      header("location: $home/chat/index.php?id=$id_k");
    } else {
      /*
      -----------------------------------------------------------------
      Форма ввода сообщения
      -----------------------------------------------------------------
      */
      echo '<div class="phdr"><b>'.$lng_chat['room'].':</b> ' . $kat_d['name'] . '</div><form name="form" action="index.php?act=messages&amp;mod=txt&amp;id=' . $id . '&amp;id_k=' . $id_k . '" method="post">';
      echo '<div class="gmenu"><p><h3>'.$lng_chat['select_treatment'].'</h3>';
      echo '<input type="radio" value="1" checked="checked" name="txt" />&#160;'.($set_author['cvet_n']  ? "<span style='color: ".$set_author['cvet_n']."'>" : "") .'<b>'. $set_author['name'] .'</b>'. ($set_author['cvet_n'] ? '</span>' : '').',<br />';
      echo '<input type="radio" value="2" name="txt" />&#160;'.($set_author['cvet_n']  ? "<span style='color: ".$set_author['cvet_n']."'>" : "") .'<b>'. $set_author['name'] .'</b>'. ($set_author['cvet_n'] ? '</span>' : '').', '.$lng_chat['reply_1'].',<br />';
      echo '<input type="radio" value="3" name="txt" />&#160;'.($set_author['cvet_n']  ? "<span style='color: ".$set_author['cvet_n']."'>" : "") .'<b>'. $set_author['name'] .'</b>'. ($set_author['cvet_n'] ? '</span>' : '').', '.$lng_chat['reply_2'].' (<a href="index.php?act=post&amp;id=' . $id . '&amp;id_k=' . $id_k . '">' . $vr . '</a>) '.$lng_chat['reply_3'].',<br />';
      echo '<input type="radio" value="4" name="txt" />&#160;'.($set_author['cvet_n']  ? "<span style='color: ".$set_author['cvet_n']."'>" : "") .'<b>'. $set_author['name'] .'</b>'. ($set_author['cvet_n'] ? '</span>' : '').', '.$lng_chat['reply_4'].'<br />';
      echo '<small>'.$lng_chat['text_ahead_your_text'].'</small></p>';
      echo '<p><h3>'.$lng['message'].'</h3>';
      if (!$is_mobile)                                 
        echo '</p><p>' . bbcode::auto_bb('form', 'msg').'';
      echo '<textarea rows="' . $set_user['field_h'] . '" name="msg"></textarea></p>';
      if ($set_user['translit'])
        echo '<input type="checkbox" name="msgtrans" value="1"/> '.$lng['translit'].'<br />';
      if ($kat_d['tip'] != "in" && !$s_d['id_bot'])
        echo '<input type="checkbox" name="priv" value="1"' . ($s_d['id_s'] ? ' checked="checked"' : '') . '/> <span style="color:red">'.$lng_chat['private'].'</span>';
      echo '<p><input type="submit" name="submit" value="'.$lng['save'].'"/></p></div></form>';
      echo '<div class="phdr"><a href="../pages/faq.php?act=trans">'.$lng['translit'].'</a> | <a href="../pages/faq.php?act=smileys">'.$lng['smileys'].'</a></div>';
      if ($kat_d['tip'] != "in" && !$s_d['id_bot'])
        echo '<a href="../users/pradd.php?act=write&amp;adr=' . $s_d['id_u'] . '">'.$lng_chat['write_in_private'].'</a><br />';
    }
  break;

  default :
    /*
    -----------------------------------------------------------------
    Получение сообщения
    -----------------------------------------------------------------
    */ 
    if (isset ($_POST['submit'])) {
      // Проверяем на существование сообщения
      if (empty ($_POST['msg'])) {
        echo functions::display_error($lng['error_empty_message'], '<a href="index.php?id=' . $id_k . '">'.$lng['back'].'</a>');
        require("../incfiles/end.php");
       exit;
      }
      // Принимаем и фильтруем данные
      $msg = trim($_POST['msg']);
      $msg = mb_substr($msg, 0, 500);
      if ($_POST['msgtrans'] == 1)
        $msg = functions::trans($msg);
      $brauser = strtok($agn, ' ');
      $pas = $kat_d['tip'] == 'in' || $kat_d['tip'] == 'an' ? intval($_SESSION['key']) : 0;
      $id_room = isset($_POST['msgrooms']) && $rights == 9 && $kat_d['tip'] != 'in' ? 0 : $id_k;
      // Проверяем, на повтор сообщения
      $req = mysql_query("SELECT * FROM `chat_room_".$id_k."` WHERE `id_u` = '$user_id' ORDER BY `time` DESC");
      if (mysql_num_rows($req)) {
        $res = mysql_fetch_array($req);
        if ($res['text'] == $msg) {
          echo functions::display_error($lng['error_message_exists'], '<a href="index.php?id=' . $id_k . '">'.$lng['back'].'</a>');
          require('../incfiles/end.php');
         exit;
        }
      }     
      $mass_user_post = serialize(array (
        'av' => '',
        'sex' => $datauser['sex'],
        'status' => $datauser['status'],
        'name' => $login,
        'name_delete' => '',
        'cvet' => $set_chat['cvet'],
        'cvet_n' => $set_chat['cvet_n'],
        'ip' => core::$ip,
        'soft' => $brauser,
        'rights' => $chat_us_d['rights']
      ));
      if (isset($_POST['msgrooms']) && $rights == 9) {
        $i = 0;
        $room = mysql_query("SELECT * FROM `chat_rooms`");
        while ($room_d = mysql_fetch_assoc($room)) {
          if ($room_d['tip'] != 'in' && $room_d['tip'] != 'an') {  
            mysql_query("INSERT INTO `chat_room_".$room_d['id']."` SET
              `id_u` = '".$user_id."',
              `time` = '".time()."',
              `text` = '".mysql_real_escape_string($msg)."',
              `author` = '".mysql_real_escape_string($mass_user_post)."',
              `pas` = '0'
            ");
          }
         ++$i;
        }      
      } else {
        // Заносим сообщение б.д.
        mysql_query("INSERT INTO `chat_room_".$id_k."` SET
          `id_u` = '".$user_id."',
          `time` = '".time()."',
          `text` = '".mysql_real_escape_string($msg)."',
          `author` = '".mysql_real_escape_string($mass_user_post)."',
          `pas` = '".$pas."'
        ");
      }      
      // Изменяем данные автора сообщения
      mysql_query("UPDATE `users` SET `lastpost` = '" . time() . "' WHERE `id` = '" . $user_id . "'");
      mysql_query("UPDATE `chat_users` SET `postchat` = '" . ($chat_us_d['postchat'] + 1) . "' WHERE `id_u` = '" . $user_id . "'");
		
      /*
      -----------------------------------------------------------------
      Проверка, неявляется ли сообщение ответом боту
      -----------------------------------------------------------------
      */
      if ($kat_d['bot'] && $kat_d['tip'] != 'in' && $kat_d['tip'] != 'an') {
        // Проверяем поочереди всех ботов в комнате
        $bot_mass = unserialize($kat_d['bot']);
        foreach ($bot_mass as $val) {
          $bot_id = intval($val);   
          $bot_d = mysql_fetch_assoc(mysql_query("SELECT `name`, `tip`, `mass_bot` FROM `chat_bot` WHERE `id`='".$bot_id."'")); // Получение данных
		      if ($bot_d['tip'] && $bot_d['tip'] != 4) {
            $mass_bot = unserialize($bot_d['mass_bot']);
            $n1 = mysql_query("SELECT * FROM `chat_room_".$id_k."` WHERE `tip`='3' AND `id_u`='".$bot_id."' ORDER BY TIME DESC LIMIT 1");
            // Получаем данные последнего вопроса
            $n1_d = mysql_fetch_array($n1); 
            // Проверяем, есть ли заданный вопрос на который ещё недали ответ
            $n1_c = mysql_num_rows($n1); 
            $n2_c = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_room_".$id_k."` WHERE `tip`='7' AND `id_bot`='".$n1_d['id_bot']."' AND `id_u`='".$bot_id."' AND `time`>'".$n1_d['time']."' LIMIT 1"), 0); // Кол-во
            if (!$n2_c && $n1_c && $msg) { 
              $vopros = mysql_query("SELECT * FROM `chat_vop` WHERE `id`='".$n1_d['id_bot']."' AND `otvet`='".$msg."'");
              if (mysql_num_rows($vopros)) {
                $vik = mysql_fetch_assoc($vopros);
                if ($bot_d['tip'] > 1) {
                  $n4_c = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_room_".$id_k."` WHERE `tip`='5' AND `id_bot`='".$n1_d['id_bot']."' LIMIT 1"), 0); // Кол-во
                  $n5_c = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_room_".$id_k."` WHERE `tip`='6' AND `id_bot`='".$n1_d['id_bot']."' LIMIT 1"), 0); // Кол-во
                  if ($n4_c || $n5_c){
                    if ($n4_c && $n5_c){
                      $text = $mass_bot['otv_2'];
                      $bls = $mass_bot['pods_2_n'];
                    } else {
                      $text = $mass_bot['otv_1'];
                      $bls = $mass_bot['pods_1_n'];
                    }
                  } else {
                    $text = $mass_bot['otv_0'];
                    $bls = $mass_bot['pods_0_n'];
                  }
                } else {
                  $text = $mass_bot['otv_0'];
                  $bls = $mass_bot['pods_0_n'];
                }
                $otv = $chat_us_d['otvetov'] + 1;
                $chat_balans = $chat_settings['balls'] ? $datauser['balans'] : $chat_us_d['balans'];
                $balans = $chat_balans + $bls;
                $otvtime = $mass_bot['time_on'] > time() - $n1_d['time'] - $mass_bot['time_off'] ? time() - $n1_d['time'] - $mass_bot['time_off'] : $mass_bot['time_on']; //
                $realtim = time()+1;
                $login2 = ($kat_d['tip'] != "an") ? $login : $lng_chat['anonymous'];
                $text = explode("|", $text);
                $text = $datauser['sex'] == 'm' || count($text) == 1 ? $text[0] : $text[1]; 
                $text = strtr($text, array(
                  '[login]' => $login2,
                  '[text]' => $vik['otvet'],
                  '[time]' => $otvtime,
                  '[balls]' => $bls,
                  '[balans]' => $balans,
                  '[otvetov]' => $otv
                ));
                $mass_bot_post = serialize(array (
                  'av' => $mass_bot['av'],
                  'sex' => $mass_bot['sex'],
                  'status' => $mass_bot['status'],
                  'name' => $bot_d['name'],
                  'name_delete' => '',
                  'cvet' => '',
                  'cvet_n' => '',
                  'ip' => '2130706433',
                  'soft' => 'k_2_bot',
                  'rights' => 0
                ));
                // Заносим фразу бота в б.д.
                mysql_query("INSERT INTO `chat_room_" . $id_k . "` SET
                  `id_u` = '" . $bot_id . "',
                  `id_bot` = '" . $n1_d['id_bot'] . "',
                  `time` = '" . $realtim . "',
                  `text` = '" . $text . "',
                  `author` = '".mysql_real_escape_string($mass_bot_post)."',
                  `tip` = '7',
                  `pas` = '" . $pas . "'
                ");
                // Изменяем данные автора сообщения
                if (!$chat_settings['balls']) {
                  mysql_query("UPDATE `chat_users` SET `otvetov`='" . $otv . "', `balans`='" . $balans . "' WHERE `id_u`='" . $user_id . "'");
                } else {
                  mysql_query("UPDATE `users` SET `balans` = '".$balans."' WHERE `id` = '".$user_id."'");
                  mysql_query("update `chat_users` set `otvetov`='".$otv."' where `id_u`='".$user_id."'");
                }
              } 
            }
          }
        }
      }
      header("location: $home/chat/index.php?id=$id_k");
    } else {
      /*
      -----------------------------------------------------------------
      Форма ввода сообщения
      -----------------------------------------------------------------
      */
      echo '<div class="phdr"><b>'.$lng_chat['room'].': ' . $kat_d['name'] . '</b></div>';
      echo '<div class="gmenu"><p><h3>'.$lng['message'].':</h3></p>';
      if (!$is_mobile)                                 
        echo '' . bbcode::auto_bb('form', 'msg').'';
      echo '<form name="form" action="index.php?act=messages&amp;id=' . $id_k . '" method="post"><textarea rows="' . $set_user['field_h'] . '" name="msg"></textarea><p>';
      if ($set_user['translit'])
        echo '<input type="checkbox" name="msgtrans" value="1" /> '.$lng['translit'].'<br />';
      if ($rights == 9)
        echo '<input type="checkbox" name="msgrooms" value="1" /> <span style="color:blue">'.$lng_chat['notification'].'</span>';
      echo '</p><p><input type="submit" name="submit" value="'.$lng['save'].'"/></p></form></div>';
      echo '<div class="phdr"><a href="../pages/faq.php?act=trans">'.$lng['translit'].'</a> | <a href="../pages/faq.php?act=smileys">'.$lng['smileys'].'</a></div>';
    }
   break;

}
echo '<p><a href="index.php?id=' . $id_k . '">'.$lng['back'].'</a></p>';

?>