<?
define('_IN_JOHNCMS', 1);

$headmod ="mchat";
$textl = ''.$lng['mchat'].'';
$rootpath = '../';
require_once ("../incfiles/core.php");
require_once ("../incfiles/head.php");

// Выгоняем гостей
if (!$user_id) {
	echo '<div class="rmenu">'.$lng['access_guest_forbidden'].'!</div>';
	require_once ("../incfiles/end.php");
	exit;
}

if ($id)
$us = mysql_fetch_assoc(mysql_query('select * from `m_chat` where `id` = ' . $id . ';'));

switch ($act) {
	// Добавляем сообщение
	case 'add':
	if (isset($_POST['submit'])) {
		$message = isset($_POST['message']) ? functions::checkin(mb_substr(trim($_POST['message']), 0, 500)) : '';
		    if (empty($message))
            $error[] = 'Пустое сообщение!';
            if (isset($ban['1']) || isset($ban['13'])  || isset($ban['12']))
            $error[] = 'Siz banlangansiz!';
		    if (!$error) {
				mysql_query('INSERT INTO `m_chat` SET
		        `user_id` = "' . $user_id . '",
		        `message` = "' . mysql_real_escape_string($message) . '",
		        `time` = "' . time() . '";');
				mysql_query('update `users` set `postchat` = `postchat`+1 where `id` = '.$user_id.'');
				/** fix by ДоХтор **/
				if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == 'http://'. $_SERVER['SERVER_NAME'] .'/')
					header('location: '. $_SERVER['HTTP_REFERER']);
				else
					header('location: ?');
				/** ** End fix ** **/
			} else {
				echo functions::display_error($error, '<a href="index.php">'.$lng['back'].'</a>');
			}	
	}
	break;
	//Удаляем сообщение
	case 'del':
    if ($us['user_id'] == $user_id || $rights >= 7) {
	    if (isset($_POST['submit'])) {
		    mysql_query('delete from `m_chat` where `id` = ' . $id . ';');
		    header('location: ?');
	    } else {
		    echo '<div class="rmenu"><form action="?act=del&amp;id=' . $id . '" method="post">Siz rostdan ham ushbu xabarni o\'chirmoqchimisiz?<br />
            <input type="submit" name="submit" value="'.$lng['delete'].'" /><br /><a href="?">'.$lng['back'].'</a></form></div>';
		}
	}

	// Mass delete
	case 'mass_delete':
		if (isset($_GET['yes'])) {
			foreach ($_SESSION['posts_id'] as $posts_id) {
				mysql_query("delete from `m_chat` where `id` = " . $posts_id . "");
			}
			unset($_SESSION['posts_id']);
			header('location: ?');
		} else {
			if (empty($_POST['delete'])) {
				echo '<div class="rmenu">Siz birorta ham xabarni belgilamadingiz! <a href="?">'.$lng['back'].'</a></div>';
			} else {
				for ($i = 0; $i < count($_POST['delete']); $i++) {
					$_SESSION['posts_id'][] =  $_POST['delete'][$i];
				}
				echo '<div class="rmenu">Siz rostdan ham barcha belgilangan xabarlarni o\'chirmoqchimisiz?<br />
            		<a href="?act=mass_delete&amp;yes">'.$lng['delete'].'</a> | <a href="?">'.$lng['back'].'</a></div>';
			}
		}
		break;

	// Чистим мини-чат
	case 'clean':
	if ($rights >= 7) {
		if (isset($_POST['submit'])) {
			mysql_query('truncate `m_chat`');
		    header('location: ?');
		} else {
			echo '<div class="rmenu"><form action="?act=clean" method="post">Siz rostdan ham mini-chatni tozalamoqchimisiz?<br />
            <input type="submit" name="submit" value="Tozalash" /><br /><a href="?">'.$lng['back'].'</a></form></div>';
		}
	}
	break;

    // Редактируем сообщение
	case 'edit':
		if ($us['user_id'] == $user_id || $rights >= 7) {
		$post = mysql_fetch_assoc(mysql_query('select * from `m_chat` where `id` = ' . $id . ';'));
		if (isset($_POST['submit'])) {
			$message = isset($_POST['message']) ? functions::checkin(mb_substr(trim($_POST['message']), 0, 500)) : '';
            if (empty($message))
            $error[] = 'Bo\'sh xabar!';
            if ($ban['1'] || $ban['13'])
            $error[] = 'Siz banlangansiz!';
		    if (!$error) {
				mysql_query('update `m_chat` set `message` = "' . mysql_real_escape_string($message) . '" where `id` = ' . $id . ';');
		        header('location: ?');
			} else {
				echo functions::display_error($error, '<a href="index.php">'.$lng['back'].'</a>');
			}
		} else {
			echo '<div class="phdr"><b>Xabarni tahrirlash</b></div>';
			echo '<div class="gmenu"><form action="?act=edit&amp;id=' . $id . '" name="edit" method="post">';
	        echo 'Xabar (max 500):<br />';
	        echo bbcode::auto_bb('edit', 'message');
	        echo '<textarea rows="' . $set_user['field_h'] . '" name="message">' . $post['message'] . '</textarea><br />' .
	            '<input type="submit" name="submit" value="Saqlash" /></form></div>';
			echo '<div class="menu"><a href="?">'.$lng['back'].'</a></div>';
		}
	}
	break;
	// Отвечаем юзеру
	case 'otv':
	$user_otv = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$id.''));
	echo '<div class="phdr"><b>'.$user_otv['name'].'</b>ga javob yozish</div>';
	if (isset($_POST['submit'])) {
		$private = isset($_POST['private']);
		$message = isset($_POST['message']) ? functions::checkin(mb_substr(trim($_POST['message']), 0, 500)) : '';
		if (empty($message))
            $error[] = 'Bo\'sh xabar!';
        if (isset($ban['1']) || isset($ban['13'])  || isset($ban['12']))
            $error[] = 'Siz banlangansiz!';
		if (!$error) {
			if ($private) {
				mysql_query('INSERT INTO `m_chat` SET
					`user_id` = "' . $user_id . '",
					`message` = "' . mysql_real_escape_string($message) . '",
					`private` = '.$id.',
					`time` = "' . time() . '";');	
			} else {
				mysql_query('INSERT INTO `m_chat` SET
					`user_id` = "' . $user_id . '",
					`message` = "' . mysql_real_escape_string($message) . '",
					`time` = "' . time() . '";');
			}
			mysql_query('update `users` set `postchat` = `postchat`+1 where `id` = '.$user_id.'');
			header('location: ?');
		} else {
			echo functions::display_error($error, '<a href="?act=otv&amp;id='.$id.'">'.$lng['back'].'</a>');
		}
	} else {
		echo '<div class="gmenu"><form action="?act=otv&amp;id='.$user_otv['id'].'" name="form" method="post">' .
		    'Xabar (max 500):<br />';
		echo bbcode::auto_bb('form', 'message');
		echo '<textarea rows="' . $set_user['field_h'] . '" name="message">[b]'.$user_otv['name'].',[/b] </textarea><br />' .
	        '<input type="checkbox" name="private" /> Yashirin<br />' .
		    '<input type="submit" name="submit" value="Javob yozish" /></form></div>';
		echo '<div class="menu"><a href="?">'.$lng['back'].'</a></div>';
	}
	break;

	// Кто в чате
	case 'who_is':
		echo '<div class="phdr"><a href="index.php">'.$lng['mchat'].'</a>&nbsp;|&nbsp;'.$lng['who_is_mchat'].'</div>';
		$total = mysql_result(mysql_query('select count(*) from `users` where `place` = "mchat" and `lastdate`+300 > '.time().''), 0);
		if ($total) {
			$req = mysql_query('select * from `users` where `place` = "mchat" and `lastdate`+300 > ' . time() . '');
			$i = 0;
			while ($res = mysql_fetch_assoc($req)) {
				echo $i % 2 ? '<div class="list1">' : '<div class="list2">' . functions::display_user($res, '') . '</div>';
			}
			echo '<div class="phdr">'.$lng['total'].': '.$total.'</div>';
		} else {
			echo '<div class="menu">'.$lng['empty_list'].'</div>';
		}
		echo '<div class="menu"><a href="index.php">'.$lng['back'].'</a></div>';
		break;

	case 'view_mess':
		$view_mess = mysql_fetch_assoc(mysql_query('select * from `m_chat` where `id` = '.$id.';'));
		$view_user = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$view_mess['user_id'].';'));
		echo '<div class="phdr"><a href="index.php">'.$lng['mchat'].'</a>&nbsp;|&nbsp; <b>'.$view_user['name'].'ning xabari</b></div><div class="menu">';
		if (file_exists((ROOTPATH . 'files/users/avatar/' . $view_user['id'] . '.png')))
			echo '<img src="' . $home . '/files/users/avatar/' . $view_user['id'] . '.png" width="32" height="32" alt="" />&#160;';
		else
			echo '<img src="' . $home . '/images/empty.png" width="32" height="32" alt="" />&#160;';
		if ($view_user['sex'])
			echo functions::image(($view_user['sex'] == 'm' ? 'm' : 'w') . ($view_user['datereg'] > time() - 86400 ? '_new' : '') . '.png', array('class' => 'icon-inline'));
		else
			echo functions::image('del.png');
		echo !$user_id || $user_id == $view_user['id'] ? ''.(strlen($cnick) == 1 ? '<b>' . $view_user['name'] . '</b>&#160;' : '<font color="'.$cnick.'"><b>' . $view_user['name'] . '</b></font>&#160;').'' : ''.(strlen($cnick) == 1 ? '<a href="' .$system_set['homeurl'] . '/users/profile.php?user=' . $view_user['id'] . '"><b>' . $view_user['name'] . '</b></a>&#160;' : '<a href="' . $system_set['homeurl'] . '/users/profile.php?user=' . $view_user['id'] . '"><font color="'.$cnick.'"><b>' . $view_user['name'] . '</b></font></a>&#160;').'';
		$rank = array(
			0 => '',
			1 => '(GMod)',
			2 => '(CMod)',
			3 => '(FMod)',
			4 => '(DMod)',
			5 => '(LMod)',
			6 => '(Smd)',
			7 => '(Adm)',
			9 => '(SV!)'
		);
		$Rights = isset($view_user['rights']) ? $view_user['rights'] : 0;
		echo $rank[$Rights];
		echo (time() > $view_user['lastdate'] + 300 ? ' <img src="/mages/off.png">' : ' <img src="/mages/on.png">');
		echo '&#160;<span class="gray">(' . functions::display_date($view_mess['time']) . ')</span><br />';
		if ($view_mess['cid']) {
			$view = mysql_fetch_assoc(mysql_query('select * from `m_chat` join `users` on `m_chat`.`user_id` = `users`.`id` and `m_chat`.`id` = '.$view_mess['cid'].';'));
			$view_post = functions::checkout($view['message'], 1, 1);
			if ($set_user['smileys'])
				$view_post = functions::smileys($view_post, $user['rights'] >= 1 ? 1 : 0);
			echo '<div class="quote"><b>' . $view['name'] . '</b>&nbsp;(' . functions::display_date($view['time']) . ')<br />' . $view_post . '</div>';
		}
		$post = functions::checkout($view_mess['message'], 1, 1);
		if ($set_user['smileys'])
			$post = functions::smileys($post, $user['rights'] >= 1 ? 1 : 0);
		echo $post;
		if ($user_id && $user_id != $view_mess['user_id']) {
			echo '<a href="index.php?act=otv&amp;id='.$view_mess['user_id'].'">'.$lng['otv'].'</a>';
		}
		if ($view_mess['user_id'] == $user_id || $rights >= 7) {
			echo '<div style="margin-left: 38px;"><a href="index.php?act=del&amp;id=' . $view_mess['id'] . '">'.$lng['delete'].'</a> | <a href="index.php?act=edit&amp;id=' . $view_mess['id'] . '">'.$lng['edit'].'</a></div>';
		}
		echo '</div>';
		break;

	// По умолчанию (главная мини-чата)
	default:


		if (isset($_SESSION['posts_id']))
			unset($_SESSION['posts_id']);
	echo '<div class="phdr"><b>'.$lng['mchat'].'</b></div>';
		echo '<div class="gmenu">' .
			'<form action="?act=add" name="add" method="post">' .
			''.$lng['mess_max'].':<br />';
	    echo bbcode::auto_bb('add', 'message');
	    echo '<textarea rows="' . $set_user['field_h'] . '" name="message"></textarea><br />' .
			'<input type="submit" name="submit" value="'.$lng['say'].'" /> <input type="button" onclick="document.location.reload()" value="'.$lng['refresh'].'"></form></div>';
	
	$total = mysql_result(mysql_query('select count(*) from `m_chat`'), 0);
	if ($total) {
		$req = mysql_query('select * from `m_chat` order by `time` desc limit ' . $start . ', ' . $kmess . ';');
		$i = 0;
		if ($rights >= 7)
			echo '<form action="?act=mass_delete" method="post">';
		while ($res = mysql_fetch_assoc($req)) {
			echo $i % 2 ? '<div class="menu">' : '<div class="menu">';
				$user = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = ' . $res['user_id'] . ';'));
				    $nom = $user['name'];
	$javob = substr($nom, 0, 1);
	$massiv = array(
		'=' => 'X',
		'_' => 'X',
		'1' => '1',
		'2' => '2',
		'3' => '3',
		'4' => '4',
		'5' => '5',
		'6' => '6',
		'7' => '7',
		'8' => '8',
		'9' => '9',
		'0' => '0',
		'$' => 'S',
		'!' => 'X',
		'@' => 'A',
		'a' => 'A',
		'b' => 'B',
		'c' => 'C',
		'd' => 'D',
		'e' => 'E',
		'f' => 'F',
		'g' => 'G',
		'h' => 'H',
		'i' => 'I',
		'j' => 'J',
		'k' => 'K',
		'l' => 'L',
		'm' => 'M',
		'n' => 'N',
		'o' => 'O',
		'p' => 'P',
		'q' => 'Q',
		'r' => 'R',
		's' => 'S',
		't' => 'T',
		'u' => 'U',
		'v' => 'V',
		'x' => 'X',
		'y' => 'Y',
		'z' => 'X',
		'w' => 'W'
	);
$nick = strtr($javob, $massiv);
// klub
$club = mysql_fetch_array 
(mysql_query("SELECT `id`, `name` FROM `fman_clubs` WHERE `user_id` = " . $user ['id'] . ";"));
//end klub
// запросы для Магазина Сайта
	$clr = mysql_fetch_assoc(mysql_query("SELECT `cnick`,`cstat` FROM `users` WHERE `id`='".$user['id']."'"));
        $cnick = $clr['cnick'];
        $cstat = $clr['cstat'];

				if (file_exists((ROOTPATH . 'files/users/avatar/' . $user['id'] . '.png')))
					echo '<div style="float: left; width: 38px;"><img src="' . $home . '/files/users/avatar/' . $user['id'] . '.png" width="32" height="32" alt="" />&#160;';
				else
					echo '<div style="float: left; width: 38px;"><div class="cover_pro '.$nick.'" style="width: 32px; height: 32px; line-height: 32px; font-size: 15px; color: #fff;"><b><center>'.$nick.'</center></b></div>&#160;';
				echo'</div>';
				echo'<div style="margin-left:38px;">';
				
				if ($user['sex'])
					echo functions::image(($user['sex'] == 'm' ? 'm' : 'w') . ($user['datereg'] > time() - 86400 ? '_new' : '') . '.png', array('class' => 'icon-inline'));
				else
					echo functions::image('del.png');
				echo !$user_id || $user_id == $user['id'] ? ''.(strlen($cnick) == 1 ? '<b>' . $user['name'] . '</b>&#160;' : '<font color="'.$cnick.'"><b>' . $user['name'] . '</b></font>&#160;').'' : ''.(strlen($cnick) == 1 ? '<a href="' .$system_set['homeurl'] . '/users/profile.php?user=' . $user['id'] . '"><b>' . $user['name'] . '</b></a>&#160;' : '<a href="' . $system_set['homeurl'] . '/users/profile.php?user=' . $user['id'] . '"><font color="'.$cnick.'"><b>' . $user['name'] . '</b></font></a>&#160;').'';
				$rank = array(
					0 => '',
					1 => '(GMod)',
					2 => '(CMod)',
					3 => '(FMod)',
					4 => '(DMod)',
					5 => '(LMod)',
					6 => '(Smd)',
					7 => '(Adm)',
					9 => '(SV!)'
				);
				$Rights = isset($user['rights']) ? $user['rights'] : 0;
				echo '<small style="font-weight: bold;">'.$rank[$Rights].'</small>';
				echo (time() > $user['lastdate'] + 300 ? ' <img src="/images/off.png">' : ' <img src="/images/on.png">');
	if ($club)
		echo'&#160;<a href="'.$home.'/man/club.php?id=' . $club['id'] . '"><img src="'.$home.'/man/emblems/'.$club['id'].'.jpg" style="width:16px; height: 16px;" class="icon-inline"></a>';			
				echo '&#160;<small style=" color:#586776; font-size: x-small; float: right;">' . functions::display_date($res['time']) . '</small><br>';
				if ($res['cid']) {
					if ($res['private']) {
						if ($user_id == $res['private'] || $user_id == $res['user_id']) {
							$view = mysql_fetch_assoc(mysql_query('select * from `m_chat` join `users` on `m_chat`.`user_id` = `users`.`id` and `m_chat`.`id` = '.$res['cid'].';'));
							$view_post = functions::checkout($view['message'], 1, 1);
							if ($set_user['smileys'])
								$view_post = functions::smileys($view_post, $user['rights'] >= 1 ? 1 : 0);
							echo '<div class="quote"><b>' . $view['name'] . '</b>&nbsp;(' . functions::display_date($view['time']) . ')<br />' . $view_post . '</div>';
						}
					} else {
						$view = mysql_fetch_assoc(mysql_query('select * from `m_chat` join `users` on `m_chat`.`user_id` = `users`.`id` and `m_chat`.`id` = '.$res['cid'].';'));
						$view_post = functions::checkout($view['message'], 1, 1);
						if ($set_user['smileys'])
							$view_post = functions::smileys($view_post, $user['rights'] >= 1 ? 1 : 0);
						echo '<div class="quote"><b>' . $view['name'] . '</b>&nbsp;(' . functions::display_date($view['time']) . ')<br />' . $view_post . '</div>';
					}
				}
				echo'</div>';
				$post = functions::checkout($res['message'], 1, 1);
				if ($set_user['smileys'])
					$post = functions::smileys($post, $user['rights'] >= 1 ? 1 : 0);
				if ($res['private']) {
					if ($user_id == $res['private'] || $user_id == $res['user_id']) {
						echo $post;
						echo '<br /><span class="red"><small><b>'.$lng['private'].'</b></small></span>';
						if ($user_id && $user_id != $res['user_id'])
							echo '<span style="font-size: x-small; float: right;"><a href="index.php?act=otv&amp;id='.$res['user_id'].'">'.$lng['otv'].'</a>&#160;</span>';
					} else {
						echo '<span class="red"><b>'.$lng['you_may_not_read_private_mess'].'!</b></span>';
					}
				} else {
					echo $post;
					if ($user_id && $user_id != $res['user_id'])
						echo '<span style="font-size: x-small; float: right;"><a href="index.php?act=otv&amp;id='.$res['user_id'].'">'.$lng['otv'].'</a></span>';
				}
				if ($res['user_id'] == $user_id || $rights >= 7){
					echo '<div style="margin-left: 38px; font-size: x-small;">' . (($rights >= 7) ? '<input type="checkbox" style="vertical-align:-2px;" value="' . $res['id'] . '" name="delete[]">&nbsp;' : '') . '<a href="?act=del&amp;id=' . $res['id'] . '">'.$lng['delete'].'</a> <span style="font-size: 10px; vertical-align: 1px;">|</span> <a href="?act=edit&amp;id=' . $res['id'] . '">'.$lng['edit'].'</a></div>';
				}
			
			echo '</div>';
			$i++;
		}
		echo ($rights >= 7) ? '<div class="list2"><input type="submit" class="write" name="mass_delete" value="'.$lng['delete_selected'].'"></div></form>' : '';
	} else {
		echo '<div class="menu">'.$lng['empty_list'].'</div>';
	}
	echo '<div class="phdr">'.$lng['all'].': ' . $total . '</div>';
	if ($total > $kmess) {
         echo '<div class="topmenu">' . functions::display_pagination('index.php?', $start, $total, $kmess) . '</div>' .
            '<p><form action="index.php" method="get"><input type="text" name="page" size="2"/>' .
            '<input type="submit" class="write" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
        }

	$who = mysql_result(mysql_query('select count(*) from `users` where `place` = "mchat" and `lastdate`+300 > '.time().''), 0);
	echo '<div class="gmenu"><div class="quote"><a href="?act=who_is">'.$lng['who_is_mchat'].'</a>&nbsp;('.$who.')</div></div>';
    if ($rights >= 7)
		echo '<div class="rmenu"><a href="?act=clean">'.$lng['clear_mess'].'</a></div>';
	break;
}

	
require_once ("../incfiles/end.php");