<?
define('_IN_JOHNCMS', 1);
/*
 by Str@nnik
 http://johncms.com/users/profile.php?user=21326
 ICQ: 609745227
*/
$headmod ="mchat";
$textl = 'Чат';
$rootpath = '../';
require_once ("../incfiles/core.php");
require_once ("../incfiles/head.php");

// Выгоняем гостей
if (!$user_id) {
	echo '<div class="rmenu">Вход гостям в Чат запрещен! Авторизуйтесь или зарегистрируйте учетную запись!</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[] = 'Вы забанены!';
		    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.'');
		        header('location: ?');
			} else {
				echo functions::display_error($error, '<a href="index.php">Назад</a>');
			}	
	}
	break;
	//Удаляем сообщение
	case 'del':
    if ($us['user_id'] == $user_id || $rights >= 9) {
	    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">Вы действительно желаете удалить сообщение?<br />
            <input type="submit" name="submit" value="Удалить" /><br /><a href="?">Назад</a></form></div>';			
	}
}	
	break;
	// Чистим мини-чат
	case 'clean':
	if ($rights >= 9) {
		if (isset($_POST['submit'])) {
			mysql_query('truncate `m_chat`');
		    header('location: ?');
		} else {
			echo '<div class="rmenu"><form action="?act=clean" method="post">Вы действительно желаете очистить чат?<br />
            <input type="submit" name="submit" value="Очистить" /><br /><a href="?">Назад</a></form></div>';	
		}
	}
	break;
    // Редактируем сообщение
	case 'edit':
		if ($us['user_id'] == $user_id || $rights >= 9) {
		$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[] = 'Пустое сообщение!';
            if ($ban['1'] || $ban['13'])
            $error[] = 'Вы забанены!';
		    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">Назад</a>');
			}
		} else {
			echo '<div class="phdr"><b>Редактируем пост</b></div>';
			echo '<div class="gmenu"><form action="?act=edit&amp;id=' . $id . '" name="edit" method="post">';
	        echo 'Сообщение (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="Сохранить" /></form></div>';
			echo '<div class="menu"><a href="?">Назад</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'].'\'y</b></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[] = 'Пустое сообщение!';
        if (isset($ban['1']) || isset($ban['13'])  || isset($ban['12']))
            $error[] = 'Вы забанены!';
		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.'">Назад</a>');
		}
	} else {
		echo '<div class="gmenu"><form action="?act=otv&amp;id='.$user_otv['id'].'" name="form" method="post">' .
		    'Сообщение (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" /> Приватно<br />' .
		    '<input type="submit" name="submit" value="Ответить" /></form></div>';
		echo '<div class="menu"><a href="?">Назад</a></div>';
	}
	break;
	//Цитируем юзера
	case 'cyt':
	$user_post = mysql_fetch_assoc(mysql_query('select * from `m_chat` where `id` = '.$id.''));
	$user_cyt = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$user_post['user_id'].''));
	echo '<div class="phdr"><b>Цитируем '.$user_cyt['name'].'\'а</b></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[] = 'Пустое сообщение!';
        if (isset($ban['1']) || isset($ban['13'])  || isset($ban['12']))
            $error[] = 'Вы забанены!';
		if (!$error) {
			if ($private) {
				mysql_query('INSERT INTO `m_chat` SET
					`user_id` = "' . $user_id . '",
					`message` = "' . mysql_real_escape_string($message) . '",
					`cid` = "' . $user_post['id'] . '",
					`private` = ' . $user_cyt['id'] . ',
					`time` = "' . time() . '";');
			} else {
				mysql_query('INSERT INTO `m_chat` SET
					`user_id` = "' . $user_id . '",
					`message` = "' . mysql_real_escape_string($message) . '",
					`cid` = "' . $user_post['id'] . '",
					`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=cyt&amp;id='.$id.'">Назад</a>');
		}
	} else {
		echo '<div class="gmenu"><form action="?act=cyt&amp;id='.$user_post['id'].'" name="form" method="post">' .
		    'Сообщение (max 500):<br />';
		echo bbcode::auto_bb('form', 'message');
		echo '<div class="quote"><b>' . $user_cyt['name'] . '</b>&nbsp;(' . functions::display_date($user_post['time']) . ')<br />' . $user_post['message'] . '</div>';
		echo '<textarea rows="' . $set_user['field_h'] . '" name="message"></textarea><br />' .
		    '<input type="checkbox" name="private" /> Приватно<br />' .
		    '<input type="submit" name="submit" value="Цитировать" /></form></div>';
		echo '<div class="menu"><a href="?">Назад</a></div>';
	}
	break;
	// По умолчанию (главная мини-чата)
	default:
	echo '<div class="phdr"><b>Мини-чат</b></div>';
		echo '<div class="gmenu"><form action="?act=add" name="add" method="post">';
	    echo 'Сообщение (max 500):<br />';
	    echo bbcode::auto_bb('add', 'message');
	    echo '<textarea rows="' . $set_user['field_h'] . '" name="message"></textarea><br />';
	    echo '<input type="submit" name="submit" value="Сказать" /></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;
		while ($res = mysql_fetch_assoc($req)) {
			echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
			$user = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = ' . $res['user_id'] . ';'));
			
                if (file_exists((ROOTPATH . 'files/users/avatar/' . $user['id'] . '.png')))
                    echo '<img src="' . $home . '/files/users/avatar/' . $user['id'] . '.png" width="32" height="32" alt="" />&#160;';
                else
                    echo '<img src="' . $home . '/images/empty.png" width="32" height="32" alt="" />&#160;';
				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'] ? '<b>' . $user['name'] . '</b>&#160;' : '<a href="' . $home . '/users/profile.php?user=' . $user['id'] . '"><b>' . $user['name'] . '</b></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 $rank[$Rights];
				echo (time() > $user['lastdate'] + 300 ? '<span class="red"> [Off]</span>' : '<span class="green"> [ON]</span>');
			    echo '&#160;<span class="gray">(' . functions::display_date($res['time']) . ')</span>&#160;';	
				echo ($res['private']) ? '[#'.$res['id'].']<br />' : '<a href="view_mess.php?id='.$res['id'].'">[#'.$res['id'].']</a><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>';
					}	
				}	
			    $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>Приватно</b></small></span>';
						if ($user_id && $user_id != $res['user_id'])
			                echo '<div class="sub">[<a href="index.php?act=otv&amp;id='.$res['user_id'].'">Отв</a>]&#160;[<a href="index.php?act=cyt&amp;id='.$res['id'].'">Цит</a>]</div>';
					} else {
						echo '<span class="red"><b>Приватное сообщение видит только адресат!</b></span>';
					}
				} else {
					echo $post;
					if ($user_id && $user_id != $res['user_id'])
			            echo '<div class="sub">[<a href="index.php?act=otv&amp;id='.$res['user_id'].'">Отв</a>]&#160;[<a href="index.php?act=cyt&amp;id='.$res['id'].'">Цит</a>]</div>';
				}	
				if ($res['user_id'] == $user_id || $rights >= 7){
					echo '<div class="sub"><a href="?act=del&amp;id=' . $res['id'] . '">Удалить</a> | <a href="?act=edit&amp;id=' . $res['id'] . '">Изменить</a></div>';
				}					
			echo '</div>';
			$i++;
		}
	} else {
		echo '<div class="menu">Пусто</div>';
	}
	echo '<div class="phdr">Всего: ' . $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" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
        }
		
	if ($rights >= 7) {
		echo '<div class="rmenu"><a href="?act=clean">Очистка чата</a></div>';
	}
	$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="who_is.php">Кто здесь?</a>&nbsp;('.$who.')' .
	        '<br /><a href="call_friend.php">Позвать друга</a></div></div>';
	break;
}

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