<?

require_once ("include/bittorrent.php");

$action = $_GET ["action"];

dbconn ( false );

parked ();
global $CURGROUP, $CURUSER;
if ($action == "add") {
	validcan ( false, 'can_addcom', true );
	if ($_SERVER ["REQUEST_METHOD"] == "POST") {
		$ltype = htmlspecialchars_uni ( $_POST ["type"] );
		if ($ltype == 'user') {
			$type = '`touid`';
			$table = 'users';
			$column = 'username';
			$page = 'userdetails';
		} else {
			$type = '`torrent`';
			$table = 'torrents';
			$column = 'name';
			$page = 'details';
		}
		validcan ( false, 'can_addcom', true );
		$torrentid = ( int ) $_POST ["tid"];
		if (! is_valid_id ( $torrentid ))
			stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
		$res = sql_query ( "SELECT $column FROM $table WHERE id = $torrentid" ) or sqlerr ( __FILE__, __LINE__ );
		$arr = mysql_fetch_array ( $res );
		if (! $arr)
			stderr ( $tracker_lang ['error'], $tracker_lang ['no_torrent_with_such_id'] );
		$name = $arr [0];
		$text = trim ( $_POST ["text"] );
		if (! $text)
			stderr ( $tracker_lang ['error'], $tracker_lang ['comment_cant_be_empty'] );
		$anti_dc = anti_dc ( $torrentid, $text, ($ltype == 'user' ? "user" : ($ltype == 'torrent' || ! $ltype ? "tor" : "")) );
		if ($anti_dc)
			sql_query ( "INSERT INTO comments (user, $type, added, text, ori_text, ip) VALUES (" . $CURUSER ["id"] ? $CURUSER ['id'] : 0 . ",$torrentid, '" . get_date_time () . "', " . sqlesc ( $text ) . "," . sqlesc ( $text ) . "," . sqlesc ( getip () ) . ")" );
		$newid = mysql_insert_id ();
		if ($anti_dc && $type == '`torrent`')
			sql_query ( "UPDATE torrents SET comments = comments + 1 WHERE id = $torrentid" );
			
		/////////////////СЛЕЖЕНИЕ ЗА КОММЕНТАМИ///////////////// 
		/*$res3 = sql_query("SELECT * FROM checkcomm WHERE checkid = $torrentid AND torrent = 1") or sqlerr(__FILE__,__LINE__);
    $subject = sqlesc("Новый комментарий");
    while ($arr3 = mysql_fetch_array($res3)) {
    	$msg = sqlesc("Для торрента [url=details.php?id=$torrentid&viewcomm=$newid#comm$newid]".$name."[/url] добавился новый комментарий.");
    	if ($CURUSER[id] != $arr3[userid])
     		sql_query("INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES (0, $arr3[userid], NOW(), $msg, 0, $subject)") or sqlerr(__FILE__,__LINE__);
    }*/
		
		$subject = sqlesc ( "Новый комментарий" );
		if ($type == '`torrent`') {
			$msg = sqlesc ( "Для торрента [url=details.php?id=$torrentid&viewcomm=$newid#comm$newid]" . $name . "[/url] добавился новый комментарий." );
			sql_query ( "INSERT INTO messages (sender, receiver, added, msg, poster, subject) SELECT 0, userid, NOW(), $msg, 0, $subject FROM checkcomm WHERE checkid = $torrentid AND torrent = 1 AND userid != $CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
		} elseif ($torrentid != $CURSUER ["id"] && $CURUSER ['checkcom']) {
			$msg = sqlesc ( "Вам добавлен новый комментарий. [url=userdetails.php?id=$torrentid&viewcomm=$newid#comm$newid]Посмотреть[/url]." );
			sql_query ( "INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUE (" . $CURUSER ["id"] . ", " . $torrentid . ", NOW(), $msg, 0, $subject)" ) or sqlerr ( __FILE__, __LINE__ );
		}
		
		/////////////////СЛЕЖЕНИЕ ЗА КОММЕНТАМИ/////////////////
		location ( "$page.php?id=$torrentid&viewcomm=$newid#comm$newid" );
		die ();
	}
	
	$torrentid = ( int ) $_GET ["tid"];
	if (! is_valid_id ( $torrentid ))
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	
	$res = sql_query ( "SELECT name FROM torrents WHERE id = $torrentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if (! $arr)
		stderr ( $tracker_lang ['error'], $tracker_lang ['no_torrent_with_such_id'] );
	
	stdhead ( "Добление комментария к \"" . $arr ["name"] . "\"" );
	
	print ( "<p><form name=\"comment\" method=\"post\" action=\"comment.php?action=add\">\n" );
	print ( "<input type=\"hidden\" name=\"tid\" value=\"$torrentid\"/>\n" );
	?>
<table class=main border=0 cellspacing=0 cellpadding=3>
	<tr>
		<td class="colhead">
<?
	print ( "" . $tracker_lang ['add_comment'] . " к \"" . htmlspecialchars_uni ( $arr ["name"] ) . "\"" );
	?>
	</td>
	</tr>
	<tr>
		<td>
<?
	textbbcode ( "comment", "text", "", "" );
	?>
	</td>
	</tr>
</table>
<?
	//print("<textarea name=\"text\" rows=\"10\" cols=\"60\"></textarea></p>\n");
	print ( "<p><input type=\"submit\" value=\"Добавить\" /></p></form>\n" );
	
	$res = sql_query ( "SELECT comments.id, text, comments.ip, comments.added, username, title, class, users.id as user, users.avatar, users.donor, users.enabled, users.warned, users.parked FROM comments LEFT JOIN users ON comments.user = users.id WHERE torrent = $torrentid ORDER BY comments.id DESC LIMIT 5" );
	
	$allrows = array ();
	while ( $row = mysql_fetch_array ( $res ) )
		$allrows [] = $row;
	
	if (count ( $allrows )) {
		print ( "<h2>Последние комментарии, в обратном порядке</h2>\n" );
		commenttable ( $allrows );
	}
	
	stdfoot ();
	die ();
} elseif ($action == "quote") {
	validcan ( false, 'can_addcom', true );
	$commentid = ( int ) $_GET ["cid"];
	$ltype = htmlspecialchars_uni ( $_GET ["type"] );
	if ($ltype == 'user') {
		$type = '`touid`';
		$table = 'users';
		$column = 'username';
		$page = 'userdetails';
	} else {
		$type = '`torrent`';
		$table = 'torrents';
		$column = 'name';
		$page = 'details';
	}
	if (! is_valid_id ( $commentid ))
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	
	$res = sql_query ( "SELECT c.*, t.$column, t.id AS tid, u.username FROM comments AS c LEFT JOIN $table AS t ON c.$type = t.id JOIN users AS u ON c.user = u.id WHERE c.id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if (! $arr)
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	
	stdhead ( "Добавления комментария к \"" . $arr [$column] . "\"" );
	
	$text = "[quote=$arr[username]]" . $arr ["text"] . "[/quote]\n";
	
	print ( "<form method=\"post\" name=\"comment\" action=\"comment.php?action=add\">\n" );
	print ( "<input type=\"hidden\" name=\"tid\" value=\"$arr[tid]\" /><input type=\"hidden\" name=\"type\" value=\"$ltype\" />\n" );
	?>

<table class=main border=0 cellspacing=0 cellpadding=3>
	<tr>
		<td class="colhead">
<?
	print ( "Добавления комментария к \"" . htmlspecialchars_uni ( $arr [$column] ) . "\"" );
	?>
	</td>
	</tr>
	<tr>
		<td>
<?
	textbbcode ( "comment", "text", htmlspecialchars_uni ( $text ), "" );
	?>
	</td>
	</tr>
</table>

<?
	
	print ( "<p><input type=\"submit\" value=\"Добавить\" /></p></form>\n" );
	
	stdfoot ();

} elseif ($action == "edit") {
	$commentid = ( int ) $_GET ["cid"];
	if (! is_valid_id ( $commentid ))
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	$ltype = htmlspecialchars_uni ( $_GET ["type"] );
	if ($ltype == 'user') {
		$type = '`touid`';
		$table = 'users';
		$column = 'username';
		$page = 'userdetails';
	} else {
		$type = '`torrent`';
		$table = 'torrents';
		$column = 'name';
		$page = 'details';
	}
	$res = sql_query ( "SELECT c.*, t.$column, t.id AS tid FROM comments AS c LEFT JOIN $table AS t ON c.$type = t.id WHERE c.id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if (! $arr)
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	if ($arr ["user"] == $CURUSER ["id"])
		validcan ( false, 'can_editcom|can_editlcom' );
	else
		validcan ( false, 'can_editlcom' );
	
	if ($_SERVER ["REQUEST_METHOD"] == "POST") {
		$text = $_POST ["text"];
		$returnto = $_POST ["returnto"];
		
		if ($text == "")
			stderr ( $tracker_lang ['error'], $tracker_lang ['comment_cant_be_empty'] );
		
		$text = sqlesc ( $text );
		
		$editedat = sqlesc ( get_date_time () );
		
		sql_query ( "UPDATE comments SET text=$text, editedat=$editedat, editedby=$CURUSER[id] WHERE id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
		
		if ($returnto)
			location ( $returnto );
		else
			location ( "$DEFAULTBASEURL/" ); // change later ----------------------
		die ();
	}
	
	stdhead ( "Редактирование комментария к \"" . $arr [$column] . "\"" );
	
	print ( "<form method=\"post\" name=\"comment\" action=\"comment.php?action=edit&amp;cid=$commentid\">\n" );
	print ( "<input type=\"hidden\" name=\"returnto\" value=\"$page.php?id={$arr["tid"]}&amp;viewcomm=$commentid#comm$commentid\" />\n" );
	print ( "<input type=\"hidden\" name=\"cid\" value=\"$commentid\" />\n" );
	?>

<table class=main border=0 cellspacing=0 cellpadding=3>
	<tr>
		<td class="colhead">
<?
	print ( "Редактирование комментария к \"" . htmlspecialchars_uni ( $arr [$column] ) . "\"" );
	?>
	</td>
	</tr>
	<tr>
		<td>
<?
	textbbcode ( "comment", "text", htmlspecialchars_uni ( $arr ["text"] ), "" );
	?>
	</td>
	</tr>
</table>

<?
	
	print ( "<p><input type=\"submit\" value=\"Отредактировать\" /></p></form>\n" );
	
	stdfoot ();
	die ();
} /////////////////СЛЕЖЕНИЕ ЗА КОММЕНТАМИ///////////////// 
elseif ($action == "check" || $action == "checkoff") {
	validcan ();
	$tid = ( int ) $_GET ["tid"];
	if (! is_valid_id ( $tid ))
		stderr ( $tracker_lang ['error'], "Неверный идентификатор $tid." );
	$docheck = mysql_fetch_array ( sql_query ( "SELECT COUNT(*) FROM checkcomm WHERE checkid = " . $tid . " AND userid = " . $CURUSER ["id"] . " AND torrent = 1" ) );
	if ($docheck [0] > 0 && $action == "check")
		stderr ( $tracker_lang ['error'], "<p>Вы уже подписаны на этот торрент.</p><a href=details.php?id=$tid#startcomments>Назад</a>" );
	if ($action == "check") {
		sql_query ( "INSERT INTO checkcomm (checkid, userid, torrent) VALUES ($tid, $CURUSER[id], 1)" ) or sqlerr ( __FILE__, __LINE__ );
		stderr ( $tracker_lang ['success'], "<p>Теперь вы следите за комментариями к этому торренту.</p><a href=details.php?id=$tid#startcomments>Назад</a>" );
	} else {
		sql_query ( "DELETE FROM checkcomm WHERE checkid = $tid AND userid = $CURUSER[id] AND torrent = 1" ) or sqlerr ( __FILE__, __LINE__ );
		stderr ( $tracker_lang ['success'], "<p>Теперь вы не следите за комментариями к этому торренту.</p><a href=details.php?id=$tid#startcomments>Назад</a>" );
	}

} /////////////////СЛЕЖЕНИЕ ЗА КОММЕНТАМИ/////////////////
elseif ($action == "delete") {
	$commentid = ( int ) $_GET ["cid"];
	$ltype = htmlspecialchars_uni ( $_GET ["type"] );
	if ($ltype == 'user') {
		$type = '`touid`';
		$table = 'users';
		$column = 'username';
		$page = 'userdetails';
	} else {
		$type = '`torrent`';
		$table = 'torrents';
		$column = 'name';
		$page = 'details';
	}
	$res = sql_query ( "SELECT c.*, t.$column, t.id AS tid FROM comments AS c LEFT JOIN $table AS t ON c.$type = t.id WHERE c.id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if (! $arr)
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	if ($arr ["user"] == $CURUSER ["id"])
		validcan ( false, 'can_delcom|can_dellcom' );
	else
		validcan ( false, 'can_dellcom' );
	if (! is_valid_id ( $commentid ))
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	
	$sure = $_GET ["sure"];
	
	if (! $sure) {
		stderr ( $tracker_lang ['delete'] . " " . $tracker_lang ['comment'], sprintf ( $tracker_lang ['you_want_to_delete_x_click_here'], $tracker_lang ['comment'], "?action=delete" . ($ltype ? "&type=$ltype" : "") . "&cid=$commentid&sure=1" ) );
	}
	
	$res = sql_query ( "SELECT $type FROM comments WHERE id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if ($arr)
		$torrentid = $arr [str_replace ( "`", "", $type )];
	
	sql_query ( "DELETE FROM comments WHERE id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	if ($torrentid && mysql_affected_rows () > 0 && $type == '`torrent`')
		sql_query ( "UPDATE torrents SET comments = comments - 1 WHERE id = $torrentid" );
	list ( $commentid ) = mysql_fetch_row ( sql_query ( "SELECT id FROM comments WHERE torrent = $torrentid ORDER BY added DESC LIMIT 1" ) );
	
	$returnto = "$page.php?id=$torrentid&amp;viewcomm=$commentid#comm$commentid";
	
	if ($returnto)
		location ( $returnto );
	else
		location ( "$DEFAULTBASEURL/" ); // change later ----------------------
	die ();
} elseif ($action == "vieworiginal") {
	validcan ( false, 'can_vieworicom', true );
	
	$commentid = ( int ) $_GET ["cid"];
	
	if (! is_valid_id ( $commentid ))
		stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	$ltype = htmlspecialchars_uni ( $_GET ["type"] );
	if ($ltype == 'user') {
		$type = '`touid`';
		$table = 'users';
		$column = 'username';
		$page = 'userdetails';
	} else {
		$type = '`torrent`';
		$table = 'torrents';
		$column = 'name';
		$page = 'details';
	}
	$res = sql_query ( "SELECT c.*, t.$column, t.id AS tid FROM comments AS c LEFT JOIN $table AS t ON c.$type = t.id WHERE c.id=$commentid" ) or sqlerr ( __FILE__, __LINE__ );
	$arr = mysql_fetch_array ( $res );
	if (! $arr)
		stderr ( $tracker_lang ['error'], "Неверный идентификатор $commentid." );
	
	stdhead ( "Просмотр оригинала" );
	print ( "<h1>Оригинальное содержание комментария №$commentid</h1><p>\n" );
	print ( "<table width=500 border=1 cellspacing=0 cellpadding=5>" );
	print ( "<tr><td class=comment>\n" );
	echo htmlspecialchars_uni ( $arr ["ori_text"] );
	print ( "</td></tr></table>\n" );
	
	$returnto = "$page.php?id={$arr["tid"]}&amp;viewcomm=$commentid#comm$commentid";
	
	//	$returnto = "details.php?id=$torrentid&amp;viewcomm=$commentid#$commentid";
	

	if ($returnto)
		print ( "<p><font size=small><a href=$returnto>Назад</a></font></p>\n" );
	
	stdfoot ();
	die ();
} else
	stderr ( $tracker_lang ['error'], "Unknown action" );

die ();
?>