<?
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.'');
				/** 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">Назад</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">Вы действительно желаете удалить сообщение?<br />
            <input type="submit" name="submit" value="Удалить" /><br /><a href="?">Назад</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">Вы не отметили ни одного сообщения! <a href="?">Назад</a></div>';
			} else {
				for ($i = 0; $i < count($_POST['delete']); $i++) {
					$_SESSION['posts_id'][] =  $_POST['delete'][$i];
				}
				echo '<div class="rmenu">Вы действительно желаете удалить помеченные сообщения?<br />
            		<a href="?act=mass_delete&amp;yes">Да</a> | <a href="?">Назад</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">Вы действительно желаете очистить чат?<br />
            <input type="submit" name="submit" value="Очистить" /><br /><a href="?">Назад</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[] = 'Пустое сообщение!';
            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;

	// Кто в чате
	case 'who_is':
		echo '<div class="phdr"><a href="index.php">Мини-чат</a>&nbsp;|&nbsp;Кто в мини-чате</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">Всего: '.$total.'</div>';
		} else {
			echo '<div class="menu">Никого</div>';
		}
		echo '<div class="menu"><a href="index.php">Назад</a></div>';
		break;

	// Call friend
	case 'call_friend':
		echo '<div class="phdr"><a href="index.php">Мини-чат</a>&nbsp;|&nbsp;Позвать друга</div>';
		$total = mysql_result(mysql_query('select count(*) from `cms_contact` where `user_id` = '.$user_id.' and `friends` = 1'), 0);
		if ($total) {
			if (isset($_GET['send'])) {
				$user = mysql_fetch_assoc(mysql_query('select * from `users` where `id` = '.$user_id.''));
				$text = 'Ваш друг [url=' . core::$system_set['homeurl'] . '/users/profile.php?user=' . $user_id . ']'.$user['name'].'[/url] пригласил Вас в [url=' . core::$system_set['homeurl'] . '/mchat]мини-чат[/url]!';
				mysql_query("INSERT INTO `cms_mail` SET
					`user_id` = '$user_id',
					`from_id` = '$id',
					`text` = '$text',
					`time` = '" . time() . "',
					`sys` = '1',
					`them` = 'Мини-чат'");
				echo '<div class="gmenu">Вы успешно пригласили своего друга в мини-чат!</div>';
			}
			$req = mysql_query('select * from `cms_contact` join `users` on `cms_contact`.`from_id` = `users`.`id` and `user_id` = '.$user_id.'');
			$i = 0;
			while ($res = mysql_fetch_assoc($req)) {
				echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
				echo '<a href="?act=call_friend&amp;id=' . $res['id'] . '&amp;send"><b>' . $res['name'] . '</b></a>';
				echo '</div>';
				$i++;
			}
			echo '<div class="phdr">Всего: '.$total.'</div>';
		} else {
			echo '<div class="menu">У вас нету ещё друзей</div>';
		}
		echo '<div class="menu"><a href="index.php">Назад</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">Мини-чат</a>&nbsp;|&nbsp;Сообщение <b>'.$view_user['name'].'\'a</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'] ? '<b>' . $view_user['name'] . '</b>&#160;' : '<a href="' . $home . '/users/profile.php?user=' . $view_user['id'] . '"><b>' . $view_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($view_user['rights']) ? $view_user['rights'] : 0;
		echo $rank[$Rights];
		echo (time() > $view_user['lastdate'] + 300 ? '<span class="red"> [Off]</span>' : '<span class="green"> [ON]</span>');
		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 '<div class="sub">[<a href="index.php?act=otv&amp;id='.$view_mess['user_id'].'">Отв</a>]&#160;[<a href="index.php?act=cyt&amp;id='.$view_mess['id'].'">Цит</a>]</div>';
		}
		if ($view_mess['user_id'] == $user_id || $rights >= 7) {
			echo '<div class="sub"><a href="index.php?act=del&amp;id=' . $view_mess['id'] . '">Удалить</a> | <a href="index.php?act=edit&amp;id=' . $view_mess['id'] . '">Изменить</a></div>';
		}
		echo '</div>';
		break;

	// По умолчанию (главная мини-чата)
	default:
		if (isset($_SESSION['posts_id']))
			unset($_SESSION['posts_id']);
		if ($user_id) {
			if (mysql_result(mysql_query("select count(*) from `users` where `place` = 'mchat' and `id` = $user_id and `lastdate` + 300 > " . time() . ""), 0)) {
				if (mysql_result(mysql_query("select count(`id`) from `m_chat` where `time` + 300 > " . time() . " and (`user_id` = $user_id or `guest_id` = $user_id)"), 0) == 0) {
					$u_guest = mysql_fetch_assoc(mysql_query("select `name` from `users` where `id` = $user_id"));
					$message = 'Пользователь [url=' . core::$system_set['homeurl'] . '/users/profile.php?user=' . $user_id . ']' . $u_guest['name'] . '[/url] зашел в мини-чат!';
					mysql_query("insert into `m_chat` set
						`user_id` = 0,
						`message` = '$message',
						`time` = '" . time() . "',
						`guest_id` = " . $user_id . "");
				}
			}
		}
	echo '<div class="phdr"><b>Мини-чат</b></div>';
		echo '<div class="gmenu">' .
			'<form action="?act=add" name="add" method="post">' .
			'Сообщение (max 500):<br />';
	    echo bbcode::auto_bb('add', 'message');
	    echo '<textarea rows="' . $set_user['field_h'] . '" name="message"></textarea><br />' .
			'<input type="submit" name="submit" value="Сказать" /> <input type="button" onclick="document.location.reload()" 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;
		if ($rights >= 7)
			echo '<form action="?act=mass_delete" method="post">';
		while ($res = mysql_fetch_assoc($req)) {
			echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
			if ($res['user_id'] == 0) {
				$view = mysql_fetch_assoc(mysql_query("select `message`, `time` from `m_chat` where `id` = " . $res['id'] . ""));
				$message = functions::checkout($view['message'], 1, 1);
				if ($set_user['smileys'])
					$message = functions::smileys($message, $user['rights'] >= 1 ? 1 : 0);
				echo '<b>Система</b>&nbsp;<span class="gray">(' . functions::display_date($res['time']) . ')</span><br>' . $message;
			} else {
				$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="?act=view_mess&amp;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">' . (($rights >= 7) ? '<input type="checkbox" value="' . $res['id'] . '" name="delete[]">&nbsp;' : '') . '<a href="?act=del&amp;id=' . $res['id'] . '">Удалить</a> | <a href="?act=edit&amp;id=' . $res['id'] . '">Изменить</a></div>';
				}
			}
			echo '</div>';
			$i++;
		}
		echo ($rights >= 7) ? '<div class="rmenu"><input type="submit" name="mass_delete" value="Удалить отмеченные"></div></form>' : '';
	} 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>';
        }

	$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">Кто здесь?</a>&nbsp;('.$who.')' .
	        '<br /><a href="?act=call_friend">Позвать друга</a></div></div>';
    if ($rights >= 7)
		echo '<div class="rmenu"><a href="?act=clean">Очистка чата</a></div>';
	break;
}

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