<?php
require "include/bittorrent.php";
dbconn ();
validcan ( false, "can_ban" );
global $CURGROUP, $CURUSER, $ALLGROUPS;
$id = ( int ) $_GET ['id'];
if (! $id)
	$id = ( int ) $_POST ['id'];
$log = $_GET ['viewlog'];
if (! $id && ! $log)
	die ();
if (! $log) {
	$sql = sql_query ( "SELECT username, ip, email, `group` FROM users WHERE id = " . $id . " LIMIT 1" ) or sqlerr ( __FILE__, __LINE__ );
	if (! mysql_num_rows ( $sql ))
		die ();
	$res = mysql_fetch_array ( $sql );
	$sum1 = summgroup ( $ALLGROUPS [$res ['group']] );
	$sum2 = summgroup ( $CURGROUP );
	if ($sum2 <= $sum1)
		die ();
	if (! $ALLGROUPS [$res ['group']] ['can_bebanned'])
		die ();
	preg_match ( "#(.*?)\@(.*?)\.(.*?)\\z#si", $res ['email'], $matches );
	$email_mask = "*@" . $matches [2] . "." . $matches [3];
}
if (! $_POST ["id"] && ! $log) {
	stdhead ( "Блокировка пользователя" );
	begin_frame ( "Блокировка " . get_user_group_color ( $res ['group'], $res ['username'] ) );
	?><form action='banuser.php' method='post'><input type='hidden'
	name='id' value='<?=$id?>'>
<table width='100%' align='center'>
	<tr valign='top'>
		<td align='center'>
		<center><strong>Стандартные опции блокировки</strong></center>
		<table width='100%' align='center'>
			<tr>
				<td>Имя пользователя</td>
				<td><?=get_user_group_color ( $res ['group'], $res ['username'] )?></td>
			</tr>
			<tr>
				<td>Группа пользователя</td>
				<td><?=get_user_group_color ( $res ['group'], get_user_group_name ( $res ['group'] ) )?></td>
			</tr>
			<tr>
				<td>Заблокировать IP-адрес? <input type='checkbox' name='ban_ip'
					checked></td>
				<td><?=$res ['ip']?></td>
			</tr>
			<tr>
				<td>Заблокировать E-Mail? <input type='checkbox' name='ban_email'
					checked></td>
				<td><?=$res ['email']?></td>
			</tr>
			<tr>
				<td>Заблокировать доменное имя E-Mail? <input type='checkbox'
					name='ban_email_mask'></td>
				<td><?=$email_mask?></td>
			</tr>
			<tr>
				<td>Дата разбана</td>
				<td><?=take_full_datetime ( date ( "Y" ), date ( "m" ), date ( "d" ) )?><br />
				<center><input type='checkbox' name='never'> Никогда</center>
				</td>
			</tr>
		</table>
		<br />
		<center><strong>Дополнительные опции</strong></center>
		<table width='100%' align='center'>
			<tr>
				<td>Удалить все торренты\трейлеры пользователя<br />
				<font size='1'>*Эта опция также удаляет все комментарии, находящиеся
				в торренте</font></td>
				<td><input type='checkbox' name='del_torrents'>&nbsp;<input
					type='checkbox' name='del_trailers'></td>
			</tr>
			<tr>
				<td>Удалить все комментарии пользователя</td>
				<td><input type='checkbox' name='del_comments'></td>
			</tr>
			<tr>
				<td>Удалить все новости пользователя</td>
				<td><input type='checkbox' name='del_news'></td>
			</tr>
			<tr>
				<td>Удалить все запросы\предложения пользователя<br />
				<font size='1'>*Эта опция также удаляет все комментарии, находящиеся
				в запросах\предложениях</font></td>
				<td><input type='checkbox' name='del_offers'>&nbsp;<input
					type='checkbox' name='del_requests'></td>
			</tr>
			<tr>
				<td>Удалить все улыбки пользователя</td>
				<td><input type='checkbox' name='del_lols'></td>
			</tr>
			<tr>
				<td>Удалить все благодарности\респекты пользователя</td>
				<td><input type='checkbox' name='del_thanks'>&nbsp;<input
					type='checkbox' name='del_respects'></td>
			</tr>
			<tr>
				<td>Удалить все приглашения пользователя</td>
				<td><input type='checkbox' name='del_invites'></td>
			</tr>
		</table>
		</td>
		<td>
		<center><strong>Причина блокировки</strong></center>
		<table width='100%' align='center'>
			<tr>
				<td>Введите причину<br />
				<font size='1'><i>*( Эта секция обязательна к заполнению )</i></font></td>
				<td><textarea name='comment' rows='6' cols='40'></textarea></td>
			</tr>
		</table>
		<br />
		<center><input type='submit' value='Заблокировать'>&nbsp;<a
			href='banuser.php?viewlog=1'><input type='button'
			value='Логи моих блокировок'></a></center>
		</td>
	</tr>
</table>
</form><?
} elseif ($_GET ['viewlog']) {
	stdhead ( "Блокировка пользователя" );
	begin_frame ( "Блокировка " . get_user_group_color ( $res ['group'], $res ['username'] ) );
	$res = sql_query ( "SELECT b.*, u.username AS banned FROM bans AS b LEFT JOIN users AS u ON b.uid=u.id WHERE b.addedby = $CURUSER[id] ORDER BY b.added DESC" ) or sqlerr ( __FILE__, __LINE__ );
	if (! mysql_num_rows ( $res )) {
		print ( "<center><strong>Вы ещё никого не заблокировали " . format_comment ( ":)" ) . "</strong></center>\n" );
	} else {
		while ( $arr = mysql_fetch_assoc ( $res ) ) {
			$new_arr [] = $arr;
			if ($arr ['first'] || $arr ['last'])
				$be ['ip'] = 1;
			if ($arr ['email'])
				$be ['email'] = 1;
			if ($arr ['uid'])
				$be ['user'] = 1;
		}
		print ( "<center>" );
		if ($CURGROUP ['can_banip'] && $be ['ip']) {
			print ( "<center><strong>Забаненые IP</strong></center>\n" );
			begin_table ();
			print ( "<tr><td class=\"colhead\">Добавлен</td><td class=\"colhead\" align=\"left\">Первый IP</td><td class=\"colhead\" align=\"left\">Последний IP</td>" . "<td class=\"colhead\" align=\"left\">Комментарий</td><td class=\"colhead\">Снять бан</td></tr>\n" );
			foreach ( $new_arr as $arr ) {
				if ($arr ["first"] || $arr ["last"]) {
					$arr ["first"] = long2ip ( $arr ["first"] );
					$arr ["last"] = long2ip ( $arr ["last"] );
					print ( "<tr><td class=\"row1\">$arr[added]</td><td class=\"row1\" align=\"left\">$arr[first]</td><td  class=\"row1\" align=\"left\">$arr[last]</td></td><td  class=\"row1\" align=\"left\">" . $arr ["comment"] . "</td><td  class=\"row1\"><a href=\"bans.php?remove=$arr[id]&location=1\">Снять бан</a></td></tr>\n" );
				}
			}
			end_table ();
		}
		if ($CURGROUP ['can_ban'] && $be ['user']) {
			print ( "<center><strong>Забаненые пользователи</strong></center>\n" );
			begin_table ();
			print ( "<tr><td class=\"colhead\">Добавлен</td><td class=\"colhead\" align=\"left\">Пользователь</td><td class=\"colhead\" align=\"left\">До</td>" . "<td class=\"colhead\" align=\"left\">Комментарий</td><td class=\"colhead\">Снять бан</td></tr>\n" );
			foreach ( $new_arr as $arr ) {
				if ($arr ["uid"])
					print ( "<tr><td class=\"row1\">$arr[added]</td><td class=\"row1\" align=\"left\">" . ($CURGROUP ['can_viewprof'] ? "<a href=\"userdetails.php?id=$arr[uid]\">$arr[banned]</a>" : $arr [banned]) . "</td><td  class=\"row1\" align=\"left\">" . ($arr [totime] != "0000-00-00 00:00:00" ? $arr [totime] : "Никогда") . "</td><td  class=\"row1\" align=\"left\">" . $arr ["comment"] . "</td><td  class=\"row1\"><a href=\"bans.php?remove=$arr[id]&location=1\">Снять бан</a></td></tr>\n" );
			}
			end_table ();
		}
		if ($CURGROUP ['can_admin'] && $be ['email']) {
			print ( "<center><strong>Забаненые E-Mail`ы</strong></center>\n" );
			begin_table ();
			print ( "<tr><td class=\"colhead\">Добавлен</td><td class=\"colhead\" align=\"left\">E-Mail</td>" . "<td class=\"colhead\" align=\"left\">Комментарий</td><td class=\"colhead\">Снять бан</td></tr>\n" );
			foreach ( $new_arr as $arr ) {
				if ($arr ["email"])
					print ( "<tr><td class=\"row1\">$arr[added]</td><td class=\"row1\" align=\"left\">$arr[email]</td><td  class=\"row1\" align=\"left\">" . $arr ["comment"] . "</td><td  class=\"row1\"><a href=\"bans.php?remove=$arr[id]&location=1\">Снять бан</a></td></tr>\n" );
			}
			end_table ();
		}
		print ( "</center>" );
	}
} else {
	if (! $_POST ['comment'])
		stderr ( 'Ошибка', 'Вы не указали причину блокировки' );
	$y = intval ( $_POST ["tyear"] );
	$m = intval ( $_POST ["tmonth"] );
	$d = intval ( $_POST ["tday"] );
	$h = intval ( $_POST ["thour"] );
	$mn = intval ( $_POST ["tminut"] );
	$s = intval ( $_POST ["tsecond"] );
	$never = $_POST ['never'];
	if ((! $y || ! $m || ! $d || $h < 0 || $mn < 0 || $s < 0) && ! $never)
		stderr ( $tracker_lang ['error'], 'Не указана дата разбана' );
	$totime = $y . "-" . $m . "-" . $d . " " . $h . ":" . $mn . ":" . $s;
	if ($never)
		$totime = "0000-00-00 00:00:00";
	$comment = sqlesc ( htmlspecialchars_uni ( $_POST ['comment'] ) );
	$this_time = sqlesc ( get_date_time () );
	sql_query ( 'INSERT INTO bans (uid, totime, comment, added, addedby) VALUE(' . $id . ', ' . sqlesc ( $totime ) . ', ' . $comment . ', ' . $this_time . ', ' . $CURUSER ['id'] . ')' ) or sqlerr ( __FILE__, __LINE__ );
	sql_query ( "UPDATE users SET enabled='no' WHERE id=" . $id ) or sqlerr ( __FILE__, __LINE__ );
	write_log ( "Пользователь ID $id был забанен пользователем $CURUSER[username] по $totime.", "", "bans" );
	if ($_POST ['ban_ip']) {
		sql_query ( 'INSERT INTO bans (`first`, `last`, comment, added, addedby) VALUE(' . sqlesc ( ip2long ( $res ['ip'] ) ) . ', ' . sqlesc ( ip2long ( $res ['ip'] ) ) . ', ' . $comment . ', ' . $this_time . ', ' . $CURUSER ['id'] . ')' ) or sqlerr ( __FILE__, __LINE__ );
	}
	if ($_POST ['ban_email']) {
		sql_query ( 'INSERT INTO bans (email, comment, added, addedby) VALUE(' . sqlesc ( $res ['email'] ) . ', ' . $comment . ', ' . $this_time . ', ' . $CURUSER ['id'] . ')' ) or sqlerr ( __FILE__, __LINE__ );
		write_log ( "E-Mail $row[email] был забанен пользователем $CURUSER[username]." );
	}
	if ($_POST ['ban_email_mask']) {
		sql_query ( 'INSERT INTO bans (email, comment, added, addedby) VALUE(' . sqlesc ( $email_mask ) . ', ' . $comment . ', ' . $this_time . ', ' . $CURUSER ['id'] . ')' ) or sqlerr ( __FILE__, __LINE__ );
		write_log ( "E-Mail $email_mask был забанен пользователем $CURUSER[username]." );
	}
	if ($_POST ['del_torrents'] || $_POST ['del_trailers']) {
		if ($_POST ['del_torrents'] && ! $_POST ['del_trailers'])
			$type = "trailer='no' AND";
		if (! $_POST ['del_torrents'] && $_POST ['del_trailers'])
			$type = "trailer='yes' AND";
		if ($_POST ['del_torrents'] && $_POST ['del_trailers'])
			$type = "";
		$tids = array ();
		$rest = sql_query ( "SELECT id FROM torrents WHERE $type owner=" . $id );
		while ( $rowt = mysql_fetch_array ( $rest ) ) {
			$tids [] = $rowt ['id'];
		}
		if ($tids) {
			sql_query ( "DELETE FROM torrents WHERE trailer='no' AND id IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM snatched WHERE torrent IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM ratings WHERE torrent IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM checkcomm WHERE checkid IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ") AND torrent = 1" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM bookmarks WHERE torrentid IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM files WHERE torrent IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
			sql_query ( "DELETE FROM comments WHERE torrent IN (" . implode ( ", ", array_map ( "sqlesc", $tids ) ) . ")" ) or sqlerr ( __FILE__, __LINE__ );
		}
	}
	if ($_POST ["del_comments"])
		sql_query ( "DELETE FROM comments WHERE user = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_news"])
		sql_query ( "DELETE FROM news WHERE userid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_offers"])
		sql_query ( "DELETE FROM offers WHERE userid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_requests"])
		sql_query ( "DELETE FROM requests WHERE userid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_lols"])
		sql_query ( "DELETE FROM lol WHERE uid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_invites"])
		sql_query ( "DELETE FROM invites WHERE inviter = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_respects"])
		sql_query ( "DELETE FROM simpaty WHERE fromuserid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	if ($_POST ["del_thanks"])
		sql_query ( "DELETE FROM thanks WHERE userid = $id" ) or sqlerr ( __FILE__, __LINE__ );
	location ( "banuser.php?viewlog=1" );
}
end_frame ();
stdfoot ();
?>