<?php

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

define('_IN_JOHNCMS', 1);

require('../incfiles/core.php');
$lng_chat = core::load_lng('chat');

// Задаем настройки системы
$req = mysql_query("SELECT * FROM `chat_settings`");
$chat_settings = array();
while ($res = mysql_fetch_row($req)) $chat_settings[$res[0]] = $res[1];
mysql_free_result($req);

/*
-----------------------------------------------------------------
Ограничиваем доступ к Чату
-----------------------------------------------------------------
*/
$error = '';
if (!$chat_settings['access'] && $rights < 7)
  $error = $lng_chat['chat_close'];
elseif ($chat_settings['access'] == 1 && !$user_id)
  $error = $lng['access_guest_forbidden'];
if ($error) {
  require('../incfiles/head.php');
  echo functions::display_error($error);
  require('../incfiles/end.php');
 exit;
}

/*
-----------------------------------------------------------------
Функция статистики онлайн в чате
-----------------------------------------------------------------
*/
function wch($id = 0) {
  if ($id)
    return mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > '" . (time() - 300) . "' AND `place` = 'chat," . $id . "'"), 0);
  else
    return mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > '" . (time() - 300) . "' AND `place` LIKE 'chat%'"), 0);
}

$id_k = isset($_REQUEST['id_k']) ? abs(intval($_REQUEST['id_k'])) : false;

/*
-----------------------------------------------------------------
Получаем пользовательские данные
-----------------------------------------------------------------
*/
$chat_us_d = array();
if ($user_id)
  $chat_us = mysql_query("SELECT `ban_naz_time`, `ban_time`, `ban_text`, `postchat`, `otvetov`, `rights`, `balans`, `set_chat` FROM `chat_users` WHERE `id_u` = '" . $user_id . "' LIMIT 1");
if (mysql_num_rows($chat_us)) {
  $chat_us_d = mysql_fetch_assoc($chat_us);
} else {
  if ($user_id)  
    mysql_query("INSERT INTO `chat_users` SET `id_u` = '" . $user_id . "', `ban_time` = '0', `postchat` = '0', `otvetov` = '0', `rights` = '0', `balans` = '0'");
  $chat_us_d = array (
    'set_chat' => '',
    'ban_time' => 0,
    'ban_text' => '',
    'postchat' => 0,
    'otvetov' => 0,
    'rights' => 0,
    'balans' => 0
  ); 
}

/*
-----------------------------------------------------------------
Настройки чата
-----------------------------------------------------------------
*/
$set_chat = array();
if (mysql_num_rows($chat_us))
  $set_chat = unserialize($chat_us_d['set_chat']);
// Настроки по-умолчанию
if (!isset($set_chat) || empty($set_chat))
  $set_chat = array (
    'refresh' => 20,
    'chmes' => 10,
    'carea' => 0,
    'avatar' => 1,
    'cvet' => '',
    'cvet_n' => '',
    'cvet_ns' => ''
  );
$headmod = !empty ($id) ? 'chat,' . $id : 'chat';

/*
-----------------------------------------------------------------
Переключаем режимы работы
-----------------------------------------------------------------
*/
$array = array (
  'password',
  'faq',
  'messages',
  'delete',
  'close',
  'dell',
  'filter',
  'massdel',
  'who',
  'moders',
  'post',
  'my_set',
  'ban',
  'top'
);
if ($act && ($key = array_search($act, $array)) !== false && file_exists('includes/' . $array[$key] . '.php')) {   
  $zag = array(
    'faq' => $lng_chat['rules'],
    'messages' => $lng_chat['say'],
    'delete' => $lng_chat['remove_post'], 
    'dell' => $lng_chat['cleaning_room'],
    'filter' => $lng_chat['filter_messages'],
    'massdel' => $lng_chat['mass_removal'],
    'who' => $lng_chat['stats_chat'], 
    'moders' => $lng_chat['chat_moderators'],
    'post' => $lng_chat['separate_post'],
    'my_set' => $lng_chat['settings'],
    'ban' => $lng_chat['ban_panel'],
    'top' => $lng_chat['top_chat']
  );
  if ($zag[$act]) 
    $textl = $zag[$act];
  $stat = array(
    'faq' => 'chatfaq',
    'who' => 'chatwho',
    'moders' => 'chatmoders',
    'my_set' => 'chatset',
    'top' => 'chattop'
  );
  if ($stat[$act] && !$id)
    $headmod = $stat[$act]; 
  require('../incfiles/head.php');
  // Выводим сообщение о Бане
  if ($chat_us_d['ban_time'] > time() && $act != 'ban')
    echo '<div class="alarm">' . $lng['ban'] . '&#160;<a href="index.php?act=ban">' . $lng['in_detail'] . '</a></div>';
  require('includes/' . $array[$key] . '.php');
  require('../incfiles/end.php');
} else {
  
  /*
  -----------------------------------------------------------------
  Определяем тип запроса (комната, или прихожая)
  -----------------------------------------------------------------
  */
  if ($id) {
    // Отображаем комнату Чата
    $komnata = mysql_query("SELECT `name`, `tip`, `bot`, `nev` FROM `chat_rooms` WHERE `id` = '" . $id . "' LIMIT 1");
    $k_d = mysql_fetch_assoc($komnata);
    // Переадресация при несущ. комнаты
    if (!mysql_num_rows($komnata)) {
      header("location: index.php");
     exit;
    }
    $textl = $k_d['name'];

    /*
    -----------------------------------------------------------------
    Очищаем комнату от старых сообщений (если опция включена)
    -----------------------------------------------------------------
    */
    if ($chat_settings['time'] < time() - $chat_settings['auto_delete'] && $chat_settings['auto_delete']) {
      $room = mysql_query("SELECT * FROM `chat_rooms`");
      while ($room_d = mysql_fetch_assoc($room)) {
        if ($chat_settings['leave_post'])
          $count_posts = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_room_" . $room_d['id'] . "`"), 0);
        mysql_query("DELETE FROM `chat_room_" . $room_d['id'] . "` WHERE `time` < '" . (time() - $chat_settings['auto_delete']) . "'" . ($chat_settings['leave_post'] ? "ORDER BY `time` ASC LIMIT " . ($count_posts - $chat_settings['leave_post']) : "") . "");
        mysql_query("OPTIMIZE TABLE `chat_room_" . $room_d['id'] . "`");
      }
      mysql_query("UPDATE `chat_settings` SET  `val` = '" . time() . "' WHERE `key` = 'time' LIMIT 1");
    }
    
    /*
    -----------------------------------------------------------------
    Подключаем файл с ботами если это необходимо
    -----------------------------------------------------------------
    */ 
    if ($k_d['bot'] && $user_id && $k_d['tip'] != 'in' && $k_d['tip'] != 'an')
      require('incfiles/bot.php');

    /*
    -----------------------------------------------------------------
    Определяем тип комнаты (интим, инкогнито, беспредел, простая)
    -----------------------------------------------------------------
    */
    switch ($k_d['tip']) {
      case 'in':
        if (!$user_id) {
          header("Location: index.php");
         exit;
        }
        // Интим
        if (empty ($_SESSION['key'])) {
          require('../incfiles/head.php');
          echo '<div class="phdr"><a href="index.php"><b>' . $lng_chat['chat'] . '</b></a> &gt;&gt; ' . $k_d['name'] . '</div>';
          echo '<div class="gmenu">';
          echo '<center><img src="img/in.gif" alt="" />&#160;</center>';
          echo '<form action="index.php?act=password&amp;id=' . $id . '" method="post">' . $lng_chat['password'] . '<br /><input type="text" name="parol" size="10" maxlength="10"/><p><input type="submit" name="submit" value="' . $lng['continue'] . '"/></p></form></div>';
          echo '<div class="phdr"><a href="index.php"><b>' . $lng["back"] . '</b></a></div>';
          require('../incfiles/end.php');
         exit;
        }
     break;

      case 'an':
        // Инкогнито
        if (empty ($_SESSION['key']) && $chat_settings['faq']) {
          require('../incfiles/head.php');
          echo '<div class="phdr"><a href="index.php"><b>' . $lng_chat['chat'] . '</b></a> &gt;&gt; ' . $k_d['name'] . '</div>';
          echo '<div class="menu">';
          echo '<center><img src="img/an.gif" alt="" />&#160;</center>';
          echo $lng_chat['incognito_rules'].'<br />';
          echo '<p><a href ="index.php?act=password&amp;mod=rand&amp;id=' . $id . '"><b>' . $lng['continue'] . '</b></a></p></div>';
          echo '<div class="phdr"><a href="index.php"><b>' . $lng["back"] . '</b></a></div>';
          require('../incfiles/end.php');
         exit;
        } elseif (empty($_SESSION['key'])) {
          header("Location: $home/chat/index.php?act=password&mod=rand&id=$id");
         exit;
        }
       break;
       
      case 'sr':
        // Беспредел
        if (empty ($_SESSION['key']) && $chat_settings['faq']) {
          require('../incfiles/head.php');
          echo '<div class="phdr"><a href="index.php"><b>' . $lng_chat['chat'] . '</b></a> &gt;&gt; ' . $k_d['name'] . '</div>';
          echo '<div class="menu">';
          echo '<center><img src="img/sr.gif" alt="" />&#160;</center>';
          echo '<span class="red"><b>' . $lng_chat['warning'] . '</b></span><br />' . $lng_chat['lawlessness_rules'] . '<br />';
          echo '<p><a href ="index.php?act=password&amp;mod=rand&amp;id=' . $id . '"><b>' . $lng['continue'] . '</b></a></p></div>';
          echo '<div class="phdr"><a href="index.php"><b>' . $lng["back"] . '</b></a></div>';
          require('../incfiles/end.php');
         exit;
        }
       break;

      default:
        echo '';
    }

    /*
    -----------------------------------------------------------------
    Оповещаем о новом посетителе в комнате (если опция включена)
    -----------------------------------------------------------------
    */
    if ($k_d['nev'] && $user_id) {   
      if ($_SESSION['nev'] != $id) {
        $_SESSION['nev'] = $id;
        $pas = $k_d['tip'] == 'in' || $k_d['tip'] == 'an' ? intval($_SESSION['key']) : 0;
        $login_u = $k_d['tip'] == 'an' ? 'Аноним [i](№: ' . $pas . ')[/i]' : $login;      
        $new_text = explode("|", $k_d['nev']);
        $new_text = $datauser['sex'] == 'm' || count($new_text) == 1 ? $new_text[0] : $new_text[1]; 
        $new_text = strtr($new_text, array(
          '[login]' => $login_u,
          ':login:' => $login_u
        ));
        $mass_bot_post = serialize(array (
          'av' => '',
          'sex' => 'm',
          'status' => '',
          'name' => $lng_chat['ticker'],
          'name_delete' => '',
          'cvet' => '',
          'cvet_n' => '',
          'ip' => '2130706433',
          'soft' => 'k_2_bot',
          'rights' => 0
        ));
        // Заносим данные в б.д.
        mysql_query("INSERT INTO `chat_room_" . $id . "` SET
          `id_bot` = '1',
          `time` = '" . time() . "',
          `text` = '" . $new_text . "',
          `author` = '" . mysql_real_escape_string($mass_bot_post) . "',
          `tip` = '2',
          `pas` = '" . $pas . "'
        ");
      }
    }
    
    /*
    -----------------------------------------------------------------
    Отображаем комнату
    -----------------------------------------------------------------
    */
    $refr = rand(0, 999);
    require('incfiles/head.php');
    if ($chat_us_d['ban_time'] > time())
      echo '<div class="alarm">' . $lng['ban'] . '&#160;<a href="index.php?act=ban">' . $lng['in_detail'] . '</a></div>';    
    if ($set_chat['carea'] && $user_id) {
      echo '<div class="phdr"><a href="index.php?id=' . $id . '&amp;refr=' . $refr . '"><b>' . $lng_chat['refresh'] . '</b></a></div>';
      echo '<div class="gmenu">';
      // Поле "Написать"
      echo '<form name="form2" action="index.php?act=messages&amp;id=' . $id . '" method="post">';
      if (!$is_mobile)
        echo bbcode::auto_bb('form2', 'msg');
      echo '<textarea rows="' . $set_user['field_h'] . '" name="msg"></textarea><br />';
      if ($set_user['translit'])
        echo '<input type="checkbox" name="msgtrans" value="1" /> ' . $lng['translit'] . '<br />';
      if ($rights == 9 && $k_d['tip'] != 'in')
        echo '<input type="checkbox" name="msgrooms" value="1" /> <span style="color:blue">' . $lng_chat['notification'] . '</span><br />';
      echo '<input type="submit" name="submit" value="' . $lng_chat['say'] . '"/><br /></form>';
      echo '</div>';
    } elseif ($user_id) {
      echo '<div class="news"><a href="index.php?act=messages&amp;id=' . $id . '"><b><font color="red">' . $lng_chat['say'] . '</font></b></a> | ';
      echo '<a href="index.php?id=' . $id . '&amp;refr=' . $refr . '"><b>' . $lng_chat['refresh'] . '</b></a></div>';
    } else {
      echo '<div class="phdr"><a href="index.php?id=' . $id . '&amp;refr=' . $refr . '"><b>Обновить</b></a></div>';
    }
    $sql = $rights > 6 ? "" : " `tip` != '1'";
    $sql .= ($k_d['tip'] != 'in') ? "" : " " . ($sql ? 'AND ' : '') . "`pas` = '" . intval($_SESSION['key']) . "'";
    if ($k_d['tip'] != 'an')
      $filter = isset ($_SESSION['chat_id']) && $_SESSION['chat_k'] == $id ? 1 : 0;
    else
      $filter = '';
    if ($filter) {
      // Подготавливаем запрос на фильтрацию юзеров
      $sw = 0;
      $sql .= ' ' . ($sql ? "AND " : "") . '(';
      $fsort_users = unserialize($_SESSION['chat_id']);
      foreach ($fsort_users as $val) {
        if ($sw)
          $sql .= ' OR ';
        $sortid = intval($val);
        $sql .= "`id_u` = '$sortid'";
        $sw = 1;
      }
      $sql .= ')';
      echo '<div class="rmenu">' . $lng_chat['filtering'] . '</div>';
    }
    if ($rights != 9 && $user_id)
      $sql .= " " . ($sql ? 'AND ' : '') . "(`id_s` = '0' OR `id_u` = '" . $user_id . "' OR `id_s` = '" . $user_id . "')";
    elseif (!$user_id)
      $sql .= " " . ($sql ? 'AND ' : '') . "`id_s` = '0'";
    // Счётчик постов в комнате
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_room_" . $id . "`" . ($sql ? ' WHERE' : '') . $sql . ""), 0);
    if ($total) {
      // Запрос в базу для вывода постов
      $soob = mysql_query("SELECT `id`, `id_u`, `id_s`, `time`, `text`, `author`, `tip`, `pas` FROM `chat_room_" . $id . "`" . ($sql ? ' WHERE' : '') . $sql . " ORDER BY `time` DESC LIMIT $start, $kmess");
      $i = 0;
      echo '<form action="index.php?act=massdel&amp;id=' . $id . '" method="post">';
      while ($message = mysql_fetch_assoc($soob)) {        
        // Метка о том, что пост удалён
        if ($rights >= 7 && $message['tip'] == 1)
          echo '<div class="rmenu">';
        else
          echo is_integer($i / 2) ? '<div class="list1">' : '<div class="list2">';
        $vrp = (core::$system_set['timeshift'] + core::$user_set['timeshift']) * 3600;
        if (date("d.m.Y", $message['time'] + $vrp) == date("d.m.Y"))
          $vr = date("H:i", $message['time'] + $vrp);  // Время "сегодняшнего" поста
        else
          $vr = date("d.m.Y/H:i", $message['time'] + $vrp);  // Время "старых" постов
        $text = $message['text'];
        $text = functions::checkout($text, 1, 1);
        // Подсветка ника в тексте                  
        if ($set_chat['cvet_ns'])
          $text = preg_replace('|' . $login . '|si', '<span style="color:' . $set_chat['cvet_ns'] . '">' . $login . '</span>', $text); 
        
        /*
        -----------------------------------------------------------------
        Выбор отображения данных автора поста (пользователь, аноним или бот)
        -----------------------------------------------------------------
        */ 
        $set_author = array();
        $set_author = unserialize($message['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
        ));
        if ($message['tip'] < 2) {
          if ($message['id_u'] != $user_id || !$user_id) {
            $us_d = mysql_fetch_assoc(mysql_query("SELECT `datereg`, `lastdate`, `rights` FROM `users` WHERE `id` = '" . $message['id_u'] . "'"));
          } else {
            $us_d = $datauser;
          }
          $rights_p = $us_d['rights'] ? $us_d['rights'] : $set_author['rights'];
          if ($set_user['smileys'])
            $text = functions::smileys($text, $rights_p ? 1 : 0);
          $sex = '../theme/' . $set_user['skin'] . '/images/' . ($set_author['sex'] == 'm' ? 'm' : 'w') . ($us_d['datereg'] > time() - 86400 ? '_new' : '') . '.png';
          if ($user_id && $user_id != $message['id_u'])
            $nik =  '<a href="../users/profile.php?user=' . $message['id_u'] . '">' . ($set_author['cvet_n']  ? '<span style="color: ' . $set_author['cvet_n'] . '">' : '') . '<b>' . $set_author['name'] . '</b>' . ($set_author['cvet_n'] ? '</span>' : '') . '</a> ';
          else
            $nik =  ($set_author['cvet_n']  ? '<span style="color: ' . $set_author['cvet_n'] . '">' : '') . '<b>' . $set_author['name'] . '</b>' . ($set_author['cvet_n'] ? '</span>' : '');
          if ($k_d['tip'] == 'an')
            $nik .= ' <b><small>(№: <span class="green">' . $message['pas'] . '</span>)</small></b>';
          $user_stat = array(6 => ' (Smd)', 7 => ' (Adm)', 9 => ' (SV!)');
          $nik .= $user_stat[$us_d['rights']];              
          if ($set_author['rights'] == 1)
            $nik .= ' (Cmod)';
          $onl = $us_d['lastdate'];
          if ($k_d['tip'] != 'an' && $user_id && $user_id != $message['id_u'])
            $otv_cit = '<a href="index.php?act=messages&amp;mod=txt&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['reply_btn'] . '</a>&#160;<a href="index.php?act=messages&amp;mod=citata&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['cytate_btn'] . '</a> ';
          else
            $otv_cit = '';
          if (!empty ($set_author['status']))
            $stat = '<div class="status">&#160;' . $set_author['status'] . '</div>';
		/*<img src="../theme/' . $set_user['skin'] . '/images/label.png" alt="" align="middle"/>*/
          else
            $stat = ''; 
          if ($set_author['cvet'] && $k_d['tip'] != 'an')
            $text = '<span style="color: ' . $set_author['cvet'] . '">' . $text . '</span>';
          $avatar = '../files/users/avatar/' . $message['id_u'] . '.png';
          if ($k_d['tip'] == 'an' && !$chat_us_d['rights'] && $rights < 6) {
            // Пост Анонима
            $avatar = '../images/empty.png';             
            //  Отображение номера Анонима
            if (intval($_SESSION['key']) == $message['pas'])
              $nik = '<b>' . $lng_chat['anonymous'] . ' №: <span class="red">' . $message['pas'] . '</span></b>';
            else
              $nik = '<b>' . $lng_chat['anonymous'] . ' №: ' . $message['pas'] . '</b>';
            $otv_cit = '';
            $stat = '';
          }
        } else {
          // Пост Бота
          $rights_p = 0;
          if ($set_user['smileys'])
            $text = functions::smileys($text, 0);
          $avatar = 'img/' . $set_author['av'] . '.png';
          $sex = '../theme/' . $set_user['skin'] . '/images/' . ($set_author['sex'] == 'zh' ? 'w' : 'm') .  '.png'; 
          if ($message['id_u'] && $user_id)
            $nik =  '<a href="profile.php?user=' . $message['id_u'] . '"><b>' . $set_author['name'] . '</b></a> ';
          else
            $nik =  '<b>' . $set_author['name'] . '</b> ';
          $onl = time();         
          if ($k_d['tip'] != 'an' && $message['id_u'] && $user_id)
            $otv_cit = '<a href="index.php?act=messages&amp;mod=txt&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['reply_btn'] . '</a>&#160;<a href="index.php?act=messages&amp;mod=citata&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['cytate_btn'] . '</a> ';
          else
            $otv_cit = '';
          if (!empty ($set_author['status']))
            $stat = '<div class="status">&#160;' . $set_author['status'] . '</div>';
		/*$stat = '<div class="status"><img src="../theme/' . $set_user['skin'] . '/images/label.png" alt="" align="middle"/>' . $set_author['status'] . '</div>*/
          else
            $stat = '';
        }
		
        
        /*
        -----------------------------------------------------------------
        Вывод данных автора поста
        -----------------------------------------------------------------
        */
        // Аватар
        if ($set_user['avatar'] && $set_chat['avatar']) {
          echo '<table cellpadding="0" cellspacing="0"><tr><td>';
          if (file_exists($avatar))
            echo '<img class="kon-img" src="' . $avatar . '" width="32" height="32" alt="" />&#160;';
          else
            echo '<img src="../images/empty.png" width="32" height="32" alt="" />&#160;';
          echo '</td><td>';
        }
        // Метка пола
        echo '<img src="' . $sex . '" width="16" height="16" align="middle" />&#160;';
        // Ник и должность
        echo $nik;
        // Метка Онлайн / Офлайн
        echo (time() > $onl + 300 ? '<span class="red"> [Off]</span> ' : '<span class="green"> [ON]</span> ');
        echo $otv_cit;
        echo '<span class="gray">(' . $vr . ')</span><br />';
        echo $stat;
        // Метка о приватности сообщения
        if ($message['id_s'] && $user_id) {
          if ($user_id == $message['id_s'])
            echo '<small><span class="red">' . $lng_chat['privately'] . '</span></small><br />'; 
          elseif ($user_id == $message['id_u'])
            echo '<small><span class="green">' . $lng_chat['privately'] . '</span></small><br />';
          elseif ($rights == 9) {
            $dn = mysql_fetch_assoc(mysql_query("SELECT `name` FROM `users` WHERE `id` = '" . $message['id_s'] . "' LIMIT 1"));
            echo '<small><span class="red">' . $lng_chat['privately'] . ' =&gt;&gt; <a href="../users/profile.php?user=' . $message['id_s'] . '">' . $dn['name'] . '</a></span></small><br />'; 
          }
        }
        // Аватар
        if ($set_user['avatar'] && $set_chat['avatar'])
          echo '</td></tr></table>';
        
        /*
        -----------------------------------------------------------------
        Вывод текста поста
        -----------------------------------------------------------------
        */
        echo $text . '<br />';
        // Ссылки скрыть/восстановить, удалить сообщение:
        if ($chat_us_d['rights'] && $rights >= $rights_p || $rights >= 6 && $rights > $rights_p || $rights == 9) {
          echo '<div class="sub">';
          if ($message['tip'] < 2)
            echo '<input type="checkbox" name="delch[]" value="' . $message['id'] . '"/>&#160;';
          if ($rights == 9) {
            echo '<a href="index.php?act=delete&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng['delete'] . '</a>';
            if ($message['tip'] == 1 && !$message['id_s'])
              echo ' | <a href="index.php?act=close&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['restore'] . '</a>';
            elseif (!$message['tip'] && !$message['id_s'])
              echo ' | <a href="index.php?act=close&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '&amp;mod=closed">' . $lng_chat['hide'] . '</a>';
          }
          if ($chat_us_d['rights'] == 1 && !$message['tip'] && $rights < 6 || $rights == 6)
            echo '<a href="index.php?act=close&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '&amp;mod=closed">' . $lng['delete'] . '</a>';
          if ($rights == 7 && !$message['id_s']){
            if ($message['tip'] == 1) 
              echo '<a href="index.php?act=close&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '">' . $lng_chat['restore'] . '</a>';
            elseif (!$message['tip']) 
              echo '<a href="index.php?act=close&amp;id=' . $message['id'] . '&amp;id_k=' . $id . '&amp;mod=closed">' . $lng['delete'] . '</a>';
          }
          if ($message['tip'] < 2 && ($rights > $rights_p || $chat_us_d['rights'] > $rights_p) && $k_d['tip'] != 'sr')
            echo ' | <a href="index.php?act=ban&amp;mod=ban&amp;id=' . $id . '&amp;user=' . $message['id_u'] . '">' . $lng['ban_do'] . '</a>';
          // Метка о том, что пост удалён
          if ($message['tip'] == 1 && $rights > 6 && $set_author['name_delete'])
            echo '<br /><span class="red">' . $lng_chat['post_delete'] . ': <b>' . $set_author['name_delete'] . '</b></span>';
          elseif ($set_author['name_delete'] && $rights > 6)
            echo '<br /><span class="green">' . $lng_chat['post_off_delete'] . ': <b>' . $set_author['name_delete'] . '</b></span>';
          echo '<br /><span class="gray">' . long2ip($set_author['ip']) . ' - ' . $set_author['soft'] . '</span>';
          echo '</div>';
        }
        echo '</div>';
       ++$i;
      }
      if ($chat_us_d['rights'] == 1 || $rights >= 6)
        echo '<div class="rmenu"><input type="submit" value="' . $lng['delete'] . '"/></div>';
      echo '</form>';
    } else {
      echo '<div class="menu">' . $lng_chat['no_message'] . '</div>';
    }
    echo '<div class="phdr"><a href="index.php?act=messages&amp;id=' . $id . '"><b>' . $lng_chat['say'] . '</b></a> | ';
    echo '<a href="index.php?id=' . $id . '&amp;refr=' . $refr . '"><b>' . $lng_chat['refresh'] . '</b></a></div>';
    // Постраничная навигация
    if ($total > $kmess) {
      echo '<div class="topmenu">' . functions::display_pagination('?id=' . $id . '&amp;', $start, $total, $kmess) . '</div>';
      echo '<p><form action="index.php?id=' . $id . '" method="post">';
      echo '<input type="text" name="page" size="2"/>';
      echo '<input type="submit" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
    }
    echo '<p>';
    if ($k_d['tip'] == 'in')
      echo '<a href="index.php?act=password&amp;mod=new&amp;id=' . $id . '"><b>' . $lng_chat['change_password'] . '</b></a>';
    elseif ($k_d['tip'] == 'an')
      echo '<a href="index.php?act=password&amp;mod=rand&amp;id=' . $id . '"><b>' . $lng_chat['change_number'] . '</b></a>';
    else {
      if ($filter)
        echo '<a href="index.php?act=filter&amp;id=' . $id . '&amp;do=unset"><b>' . $lng_chat['off_filter'] . '</b></a>';
      else
        echo '<a href="index.php?act=filter&amp;id=' . $id . '"><b>' . $lng_chat['on_filter'] . '</b></a>';
    }
    echo '</p>';
    // Ссылка на очистку комнаты (только Супервизор)
    if ($rights == 9)
      echo '<p><div class="func"><a href="index.php?act=dell&amp;id=' . $id . '"><b>' . $lng_chat['cleaning'] . '</b></a></div></p>';
    require('incfiles/end.php'); 
  } else { 
    
    /*
    -----------------------------------------------------------------
    Отображаем прихожую Чата
    -----------------------------------------------------------------
    */ 
    $textl = $lng_chat['hallway'];
    require('../incfiles/head.php');
    // Выводим сообщение о Бане
    if ($chat_us_d['ban_time'] > time())
      echo '<div class="alarm">' . $lng['ban'] . '&#160;<a href="index.php?act=ban">' . $lng['in_detail'] . '</a></div>';
    // Выводим сообщение Админу при закрытом чате
    if (!$chat_settings['access'])
      echo '<div class="alarm">' . $lng_chat['chat_close'] . '</div>';
    echo '<div class="phdr"><b>' . $lng_chat['chat'] . '</b></div>';
    $_SESSION['key'] = '';
    $_SESSION['nev'] = '';
    $sql = ($user_id) ? "" : " WHERE `tip` != 'in'";
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms`" . $sql . ""), 0);
    $req = mysql_query("SELECT `id`, `name`, `op` FROM `chat_rooms`" . $sql . " LIMIT $start, $kmess");
    // Вывод списка комнат
    while ($mass = mysql_fetch_assoc($req)) {
      echo is_integer($i / 2) ? '<div class="list1">' : '<div class="list2">';
      echo '<a href="index.php?id=' . $mass['id'] . '">' . $mass['name'] . '</a> <small>(' . ( wch($mass['id']) ? '<a href="index.php?act=who&amp;id=' . $mass['id'] . '">' . wch($mass['id']) . '</a>' : '<span class="gray">' . wch($mass['id']) . '</span>') . ')</small>';
      // Вывод описания комнаты
      if (!empty($mass['op']))
        echo '<div class="sub"><span class="gray">' . functions::checkout($mass['op'], 1, 0) . '</span></div>';
      echo '</div>';
     ++$i;
    }
    echo '<div class="phdr"><a href="index.php?act=who"><b>' . $lng_chat['who_s_chatting'] . '</b></a> <b>(' . wch() . ')</b></div>';
    // Навигация внизу страницы
    if ($total > $kmess) {
      echo '<div class="topmenu">' . functions::display_pagination('index.php?', $start, $total, $kmess) . '</div>';
      echo '<p><form action="index.php" method="post">';
      echo '<input type="text" name="page" size="2"/>';
      echo '<input type="submit" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
    }
    // Ссылка на админку чата
    if ($rights == 9)
      echo '<p><div class="func"><a href="menu.php">' . $lng['admin_panel'] . '</a></div></p>';
    if ($user_id)
      echo '<p><a href="index.php?act=my_set">' . $lng['settings'] . '</a><br />';
    else
      echo '<p>';
    echo '<a href="index.php?act=moders">' . $lng['moders'] . '</a><br />';
    if ($user_id)
      echo '<a href="index.php?act=top">' . $lng_chat['top_10'] . '</a> | ';
    echo '<a href="index.php?act=faq">FAQ</a></p>';
    require('../incfiles/end.php');    
  }
}

?>