<?

require_once ("include/bittorrent.php");

gzip ();

function getagent($httpagent, $peer_id = "") {
	if (preg_match ( "/^Azureus ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]\_B([0-9][0-9|*])(.+)$)/", $httpagent, $matches ))
		return "Azureus/$matches[1]";
	elseif (preg_match ( "/^Azureus ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]\_CVS)/", $httpagent, $matches ))
		return "Azureus/$matches[1]";
	elseif (preg_match ( "/^Java\/([0-9]+\.[0-9]+\.[0-9]+)/", $httpagent, $matches ))
		return "Azureus/<2.0.7.0";
	elseif (preg_match ( "/^Azureus ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $httpagent, $matches ))
		return "Azureus/$matches[1]";
	elseif (preg_match ( "/BitTorrent\/S-([0-9]+\.[0-9]+(\.[0-9]+)*)/", $httpagent, $matches ))
		return "Shadow's/$matches[1]";
	elseif (preg_match ( "/BitTorrent\/U-([0-9]+\.[0-9]+\.[0-9]+)/", $httpagent, $matches ))
		return "UPnP/$matches[1]";
	elseif (preg_match ( "/^BitTor(rent|nado)\\/T-(.+)$/", $httpagent, $matches ))
		return "BitTornado/$matches[2]";
	elseif (preg_match ( "/^BitTornado\\/T-(.+)$/", $httpagent, $matches ))
		return "BitTornado/$matches[1]";
	elseif (preg_match ( "/^BitTorrent\/ABC-([0-9]+\.[0-9]+(\.[0-9]+)*)/", $httpagent, $matches ))
		return "ABC/$matches[1]";
	elseif (preg_match ( "/^ABC ([0-9]+\.[0-9]+(\.[0-9]+)*)\/ABC-([0-9]+\.[0-9]+(\.[0-9]+)*)/", $httpagent, $matches ))
		return "ABC/$matches[1]";
	elseif (preg_match ( "/^Python-urllib\/.+?, BitTorrent\/([0-9]+\.[0-9]+(\.[0-9]+)*)/", $httpagent, $matches ))
		return "BitTorrent/$matches[1]";
	elseif (preg_match ( "/^BitTorrent\/brst(.+)/", $httpagent, $matches ))
		return "Burst";
	elseif (preg_match ( "/^RAZA (.+)$/", $httpagent, $matches ))
		return "Shareaza/$matches[1]";
	elseif (preg_match ( "/Rufus\/([0-9]+\.[0-9]+\.[0-9]+)/", $httpagent, $matches ))
		return "Rufus/$matches[1]";
	elseif (preg_match ( "/^Python-urllib\\/([0-9]+\\.[0-9]+(\\.[0-9]+)*)/", $httpagent, $matches ))
		return "G3 Torrent";
	elseif (preg_match ( "/MLDonkey\/([0-9]+).([0-9]+).([0-9]+)*/", $httpagent, $matches ))
		return "MLDonkey/$matches[1].$matches[2].$matches[3]";
	elseif (preg_match ( "/ed2k_plugin v([0-9]+\\.[0-9]+).*/", $httpagent, $matches ))
		return "eDonkey/$matches[1]";
	elseif (preg_match ( "/uTorrent\/([0-9]+)([0-9]+)([0-9]+)([0-9A-Z]+)/", $httpagent, $matches ))
		return "µTorrent/$matches[1].$matches[2].$matches[3].$matches[4]";
	elseif (preg_match ( "/CT([0-9]+)([0-9]+)([0-9]+)([0-9]+)/", $peer_id, $matches ))
		return "cTorrent/$matches[1].$matches[2].$matches[3].$matches[4]";
	elseif (preg_match ( "/Transmission\/([0-9]+).([0-9]+)/", $httpagent, $matches ))
		return "Transmission/$matches[1].$matches[2]";
	elseif (preg_match ( "/KT([0-9]+)([0-9]+)([0-9]+)([0-9]+)/", $peer_id, $matches ))
		return "KTorrent/$matches[1].$matches[2].$matches[3].$matches[4]";
	elseif (preg_match ( "/rtorrent\/([0-9]+\\.[0-9]+(\\.[0-9]+)*)/", $httpagent, $matches ))
		return "rTorrent/$matches[1]";
	elseif (preg_match ( "/^ABC\/Tribler_ABC-([0-9]+\.[0-9]+(\.[0-9]+)*)/", $httpagent, $matches ))
		return "Tribler/$matches[1]";
	elseif (preg_match ( "/^BitsOnWheels( |\/)([0-9]+\\.[0-9]+).*/", $httpagent, $matches ))
		return "BitsOnWheels/$matches[2]";
	elseif (preg_match ( "/BitTorrentPlus\/(.+)$/", $httpagent, $matches ))
		return "BitTorrent Plus!/$matches[1]";
	elseif (ereg ( "^Deadman Walking", $httpagent ))
		return "Deadman Walking";
	elseif (preg_match ( "/^eXeem( |\/)([0-9]+\\.[0-9]+).*/", $httpagent, $matches ))
		return "eXeem$matches[1]$matches[2]";
	elseif (preg_match ( "/^libtorrent\/(.+)$/", $httpagent, $matches ))
		return "libtorrent/$matches[1]";
	elseif (substr ( $peer_id, 0, 12 ) == "d0c")
		return "Mainline";
	elseif (substr ( $peer_id, 0, 1 ) == "M")
		return "Mainline/Decoded";
	elseif (substr ( $peer_id, 0, 3 ) == "-BB")
		return "BitBuddy";
	elseif (substr ( $peer_id, 0, 8 ) == "-AR1001-")
		return "Arctic Torrent/1.2.3";
	elseif (substr ( $peer_id, 0, 6 ) == "exbc\08")
		return "BitComet/0.56";
	elseif (substr ( $peer_id, 0, 6 ) == "exbc\09")
		return "BitComet/0.57";
	elseif (substr ( $peer_id, 0, 6 ) == "exbc\0:")
		return "BitComet/0.58";
	elseif (substr ( $peer_id, 0, 4 ) == "-BC0")
		return "BitComet/0." . substr ( $peer_id, 5, 2 );
	elseif (substr ( $peer_id, 0, 7 ) == "exbc\0L")
		return "BitLord/1.0";
	elseif (substr ( $peer_id, 0, 7 ) == "exbcL")
		return "BitLord/1.1";
	elseif (substr ( $peer_id, 0, 3 ) == "346")
		return "TorrenTopia";
	elseif (substr ( $peer_id, 0, 8 ) == "-MP130n-")
		return "MooPolice";
	elseif (substr ( $peer_id, 0, 8 ) == "-SZ2210-")
		return "Shareaza/2.2.1.0";
	elseif (ereg ( "^0P3R4H", $httpagent ))
		return "Opera BT Client";
	elseif (substr ( $peer_id, 0, 6 ) == "A310--")
		return "ABC/3.1";
	elseif (ereg ( "^XBT Client", $httpagent ))
		return "XBT Client";
	elseif (ereg ( "^BitTorrent\/BitSpirit$", $httpagent ))
		return "BitSpirit";
	elseif (ereg ( "^DansClient", $httpagent ))
		return "XanTorrent";
	else
		return "Unknown";
}

function dltable($name, $arr, $torrent) {
	
	global $tracker_lang, $CURGROUP;
	$s = "<b>" . count ( $arr ) . " $name</b>\n";
	if (! count ( $arr ))
		return $s;
	$s .= "\n";
	$s .= "<table width=100% class=main border=1 cellspacing=0 cellpadding=5>\n";
	$s .= "<tr><td class=colhead>" . $tracker_lang ['user'] . "</td>" . "<td class=colhead align=center>" . $tracker_lang ['port_open'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['uploaded'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['ul_speed'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['downloaded'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['dl_speed'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['ratio'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['completed'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['connected'] . "</td>" . "<td class=colhead align=right>" . $tracker_lang ['idle'] . "</td>" . "<td class=colhead align=left>" . $tracker_lang ['client'] . "</td></tr>\n";
	$now = time ();
	foreach ( $arr as $e ) {
		// user/ip/port
		// check if anyone has this ip
		$s .= "<tr>\n";
		if ($e ["username"])
			$s .= "<td>" . ($CURGROUP ['can_viewprof'] ? "<a href=\"userdetails.php?id=$e[userid]\"><b>" . get_user_group_color ( $e ["group"], $e ["username"] ) . "</b></a>" : "<b>" . get_user_group_color ( $e ["group"], $e ["username"] )) . "</b>" . ($CURGROUP ['can_viewip'] ? "&nbsp;[<span title=\"{$e["ip"]}\" style=\"cursor: pointer\">IP</span>]" : "") . "</td>\n";
		else
			$s .= "<td>" . ($CURGROUP ['can_viewip'] ? $e ["ip"] : preg_replace ( '/\.\d+$/', ".xxx", $e ["ip"] )) . "</td>\n";
		$secs = max ( 10, ($e ["la"]) - $e ["pa"] );
		$revived = $e ["revived"] == "yes";
		$s .= "<td align=\"center\">" . ($e [connectable] == "yes" ? "<span style=\"color: green; cursor: help;\" title=\"Порт открыт. Этот пир может подключатся к любому пиру.\">" . $tracker_lang ['yes'] . "</span>" : "<span style=\"color: red; cursor: help;\" title=\"Порт закрыт. Рекомендовано проверить настройки Firwewall'а.\">" . $tracker_lang ['no'] . "</span>") . "</td>\n";
		$s .= "<td align=\"right\"><nobr>" . mksize ( $e ["uploaded"] ) . "</nobr></td>\n";
		$s .= "<td align=\"right\"><nobr>" . mksize ( $e ["uploadoffset"] / $secs ) . "/s</nobr></td>\n";
		$s .= "<td align=\"right\"><nobr>" . mksize ( $e ["downloaded"] ) . "</nobr></td>\n";
		//if ($e["seeder"] == "no")
		$s .= "<td align=\"right\"><nobr>" . mksize ( $e ["downloadoffset"] / $secs ) . "/s</nobr></td>\n";
		/*else
                        $s .= "<td align=\"right\"><nobr>" . mksize($e["downloadoffset"] / max(1, $e["finishedat"] - $e["st"])) . "/s</nobr></td>\n";*/
		if ($e ["downloaded"]) {
			$ratio = floor ( ($e ["uploaded"] / $e ["downloaded"]) * 1000 ) / 1000;
			$s .= "<td align=\"right\"><font color=" . get_ratio_color ( $ratio ) . ">" . number_format ( $ratio, 3 ) . "</font></td>\n";
		} else if ($e ["uploaded"])
			$s .= "<td align=\"right\">Inf.</td>\n";
		else
			$s .= "<td align=\"right\">---</td>\n";
		$s .= "<td align=\"right\">" . sprintf ( "%.2f%%", 100 * (1 - ($e ["to_go"] / $torrent ["size"])) ) . "</td>\n";
		$s .= "<td align=\"right\">" . mkprettytime ( $now - $e ["st"] ) . "</td>\n";
		$s .= "<td align=\"right\">" . mkprettytime ( $now - $e ["la"] ) . "</td>\n";
		$s .= "<td align=\"left\">" . htmlspecialchars_uni ( getagent ( $e ["agent"], $e ["peer_id"] ) ) . "</td>\n";
		$s .= "</tr>\n";
	}
	$s .= "</table>\n";
	return $s;
}

dbconn ( false );

validcan ( false, 'can_details', true );

$id = ( int ) $_GET ["id"];

if (! isset ( $id ) || ! $id)
	die ();
$res = sql_query ( "SELECT torrents.poster, torrents.screenshot1, torrents.screenshot2, torrents.screenshot3, torrents.screenshot4, torrents.reliz, torrents.dops, torrents.trailer, torrents.moderated, torrents.moderatedby, torrents.moderatorname, torrents.seeders, torrents.hide, torrents.report, torrents.banned, torrents.leechers, torrents.info_hash, torrents.filename, UNIX_TIMESTAMP() - UNIX_TIMESTAMP(torrents.last_action) AS lastseed, torrents.numratings, torrents.name, torrents.free, IF(torrents.numratings < $minvotes, NULL, ROUND(torrents.ratingsum / torrents.numratings, 1)) AS rating, torrents.owner, torrents.save_as, torrents.descr, torrents.visible, torrents.size, torrents.added, torrents.views, torrents.hits, torrents.times_completed, torrents.id, torrents.type, torrents.numfiles, categories.name AS cat_name, incat.name AS incat_name, users.username, users.group, thanks.userid AS tuid FROM torrents LEFT JOIN categories ON torrents.category = categories.id LEFT JOIN thanks ON torrents.id = thanks.torrentid AND thanks.userid = '$CURUSER[id]' LEFT JOIN incat ON torrents.incat = incat.id LEFT JOIN users ON torrents.owner = users.id WHERE torrents.id = $id" ) or sqlerr ( __FILE__, __LINE__ );
$row = mysql_fetch_array ( $res );
global $pic_base_url, $torrent_dir, $CURGROUP, $CURUSER, $use_nodown, $use_hide;
if ($row ["hide"] == 'yes' && $CURGROUP ['can_viewhidden'])
	stderr ( "Ошибка", "Нет торрента с таким ID" );
	
/// MOD SHOP ///


if ($CURUSER)
	$myres = sql_query ( "SELECT pb.inrbin, p.price FROM products AS p LEFT JOIN prodbuy AS pb ON pb.pid = p.id AND pb.uid = " . $CURUSER [id] . " WHERE p.vid = '$id' AND p.type='torrent' LIMIT 1" ) or sqlerr ( __FILE__, __LINE__ );
else {
	$myres = sql_query ( "SELECT price FROM products WHERE vid = '$id' AND type='torrent' LIMIT 1" ) or sqlerr ( __FILE__, __LINE__ );
	$myresar ['inrbin'] = 1;
}
$myresar = mysql_fetch_array ( $myres );
if ($myresar ['inrbin'] && $myresar ['price'] && ! $CURGROUP ['can_dtforsell']) {
	global $tracker_lang;
	stdhead ( $tracker_lang ['error'] . "!" );
	$groups = array ();
	foreach ( $ALLGROUPS as $crgrp )
		if ($crgrp ['price'])
			$groups [] = $tracker_lang [$crgrp ['name']];
	$groupsna = implode ( ' или ', $groups );
	stdmsg ( $tracker_lang ['error'], "Этот торрент доступен только, тем кто его купил или для " . $groups [0] . " и ВЫШЕ. Он стоит $money евро. Покупка осуществляеться через систему webmoney не только в евро, но и в рублях и долларах. Вы можете <a href=takebuy.php?id=$id>купить</a>" . ($CURGROUP ['can_rbin'] ? " или <a href=takerbin.php?id=$id>добавить в корзину</a> этот продукт" : "") . ". Также вы можете сделать пожертвование и получить статусы: " . $groupsna . " <a href=donate.php>здесь</a>.", 'error' );
	stdfoot ();
	exit ();
}
/// MOD SHOP ///
$owned = 0;
if ($CURUSER ["id"] == $row ["owner"])
	$owned = 1;
	//}


if (! $row || ($row ["banned"] == "yes" && ! $CURGROUP ['can_viewbanned']))
	stderr ( $tracker_lang ['error'], $tracker_lang ['no_torrent_with_such_id'] );
else {
	if ($_GET ["hit"]) {
		sql_query ( "UPDATE torrents SET views = views + 1 WHERE id = $id" );
		if ($_GET ["tocomm"])
			location ( "$DEFAULTBASEURL/details.php?id=$id&page=0#startcomments" );
		elseif ($_GET ["filelist"])
			location ( "$DEFAULTBASEURL/details.php?id=$id&filelist=1#filelist" );
		elseif ($_GET ["toseeders"])
			location ( "$DEFAULTBASEURL/details.php?id=$id&dllist=1#seeders" );
		elseif ($_GET ["todlers"])
			location ( "$DEFAULTBASEURL/details.php?id=$id&dllist=1#leechers" );
		else
			location ( "$DEFAULTBASEURL/details.php?id=$id" );
		exit ();
	}
	
	if (! isset ( $_GET ["page"] )) {
		stdhead ( $tracker_lang ['torrent_details'] . " \"" . $row ["name"] . "\"" );
		
		$spacer = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		
		$prive = "";
		$s = $row ["name"];
		
		begin_frame ( $row ["name"] );
		print ( "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\">\n" );
		$nodown = 0;
		if ($use_nodown) {
			$downloadered = sql_query ( "SELECT users.id, snatched.startdat, snatched.last_action, snatched.completedat, snatched.seeder, snatched.userid, snatched.uploaded AS sn_up, snatched.downloaded AS sn_dn FROM snatched INNER JOIN users ON snatched.userid = users.id WHERE snatched.finished='yes' AND snatched.torrent =" . sqlesc ( $id ) . " AND users.id = '$CURUSER[id]' LIMIT 1" ) or sqlerr ( __FILE__, __LINE__ );
			$rowdownlrd = mysql_fetch_array ( $downloadered );
			if ($CURUSER ["downloaded"] > 0)
				$ratia = $CURUSER ["uploaded"] / $CURUSER ["downloaded"];
			else
				$ratia = 1;
			if ($rowdownlrd ["id"] != $CURUSER ["id"] && $ratia < 0.5 && ! $CURGROUP ['can_freeratio']) {
				print ( "<tr height=25><td colSpan=2 bgColor=#77ff77 align=left valign=center style='padding-top: 1px; padding-bottom: 0px'><div align=center><b>Ваш ратио ниже 0,5, вы не можете качать торрент. НО вы можете купить VIP или Супер VIP <a href=\"donated.php\">Здесь</a> и скачать этот торрент.</font></b></div></td></tr>\n" );
				$nodown = 1;
			}
		}
		if (! $row ["tuid"] && $CURUSER ["id"] != $row ["owner"] && ! $CURGROUP ['can_admin']) {
			print ( "<tr height=25><td colSpan=2 bgColor=#77ff77 align=left valign=center style='padding-top: 1px; padding-bottom: 0px'><div align=center><b>Вы должны сказать спасибо, чтобы скачать этот торрент!</font></b></div></td></tr>\n" );
			$nodown = 1;
		}
		if (isset ( $_GET ["returnto"] )) {
			$addthis = "&amp;returnto=" . urlencode ( $_GET ["returnto"] );
			$url .= $addthis;
			$keepget .= $addthis;
		}
		$s = "<b>" . $row ["name"] . "</b>";
		if ($CURUSER ["id"] != $row ["owner"] || $CURGROUP ['can_editltor'])
			$s .= " $spacer<a href=\"edit.php?id=$row[id]\"><img border=\"0\" src=\"" . $pic_base_url . "pen.gif\" alt=\"" . $tracker_lang ['edit'] . "\" title=\"" . $tracker_lang ['edit'] . "\" /></a>";
		
		$s .= " $spacer<a href=\"bookmark.php?torrent=$row[id]\"><img border=\"0\" src=\"" . $pic_base_url . "bookmark.gif\" alt=\"" . $tracker_lang ['bookmark_this'] . "\" title=\"" . $tracker_lang ['bookmark_this'] . "\" /></a>";
		
		if ($CURGROUP ['can_ontop'])
			$s .= " $spacer<a href=\"ontop.php?id=$row[id]\"><img border=\"0\" src=\"" . $pic_base_url . "accept.png\" alt=\"На главную\" title=\"На главную\" /></a>";
			/// MOD SHOP ///
		

		if ($CURGROUP ['can_shop'])
			$s .= " $spacer<a href=\"shop.php?addid=$row[id]\"><img border=\"0\" src=\"" . $pic_base_url . "product_add.png\" alt=\"" . $tracker_lang ['shop_add'] . "\" title=\"" . $tracker_lang ['shop_add'] . "\" /></a>";
			
		/// MOD SHOP ///
		/// MOD TRAILERS ///
		if (! empty ( $row ["filename"] ) && ! $nodown && $CURUSER ["parked"] == "no")
			$s .= " $spacer<a href=\"download.php?id=$id&amp;name=" . rawurlencode ( $row ["filename"] ) . "\"><img border=\"0\" src=\"" . $pic_base_url . "download.gif\" alt=\"Скачать\" title=\"Скачать\"/></a>";
			/// MOD TRAILERS ///
		tr ( "Скачать", $s, 1 );
		
		function hex_esc($matches) {
			return sprintf ( "%02x", ord ( $matches [0] ) );
		}
		
		if ($CURGROUP ['can_editltor']) {
			
			if ($row ["moderated"] == "no") 

			{
				if ($CURUSER ["id"] == $row ["owner"])
					$check = "<b>это твой торрент</b>";
				
				else
					
					//$check = "<a href=check.php?id=$id><b>Нет</b></a>";
					$check = "<b>Нет</b>";
			} 

			else
				$check = $CURGROUP ['can_viewprof'] ? "<a href=\"userdetails.php?id=$row[moderatedby]\"><b>$row[moderatorname]</b></a>" : "<b>$row[moderatorname]</b>";
			
			tr ( "Проверен", $check, 1 );
		}
		/// MOD TRAILERS ///
		if (! empty ( $row ["filename"] ))
			tr ( $tracker_lang ['info_hash'], $row ["info_hash"] );
		
		if ($row ["trailer"] == "yes")
			print ( "<tr height=25><td colSpan=2 align=left valign=center style='padding-top: 1px; padding-bottom: 0px'><div align=center><img src=\"" . $pic_base_url . "Trailer.gif\"></div></td></tr>\n" );
			
		/// MOD TRAILERS ///
		if ($row [free] > 0)
			print ( "<tr height=25><td colSpan=2 bgColor=#77ff77 align=left valign=center style='padding-top: 1px; padding-bottom: 0px'><div align=center><b>Download не учитывается на <font color=red>" . $row ['free'] . "%</font></b></div></td></tr>\n" );
		print ( "<tr><td></td><td>" );
		if (! empty ( $row ["poster"] ))
			print ( ($CURGROUP ['can_downloadtor'] ? "<a href=\"download.php?id=$id&amp;name=" . rawurlencode ( $row ["filename"] ) . "\">" : "") . "<img src='" . ($img_on_server ? "$torrent_dir/images/" : '') . "" . $row ["poster"] . "' width='250'><br>" . ($CURGROUP ['can_downloadtor'] ? "</a>" : "") );
		if (! empty ( $row ["descr"] ))
			print ( "<br>" . format_comment ( $row ['descr'], true, $ALLGROUPS [$row ['group']] ['can_usepsmile'] ) . "<br>" );
		if (! empty ( $row ["dops"] ))
			print ( "" . format_comment ( $row ['dops'], true, $ALLGROUPS [$row ['group']] ['can_usepsmile'] ) . "<br><br>" );
		else
			print ( "<br>" );
			/*if (! empty ( $row ["screenshot1"] ) and ! $img_on_server)
			print ( format_comment ( $row ["screenshot1"] ) );*/
		if (! empty ( $row ["screenshot1"] ) and ! $img_on_server) {
			$screenshots = explode ( "\n", $row ["screenshot1"] );
			$scrs = array ();
			function checkcpaces($string) {
				if (! $string)
					return true;
				$space = 0;
				for($i = 0; $i < strlen ( $string ); $i ++) {
					if ($string [$i] == ' ') {
						$space ++;
					}
				}
				if ($space == strlen ( $string ))
					return true;
				return false;
			}
			foreach ( $screenshots as $screenshot )
				if (checkcpaces ( $screenshot ))
					$scrs [] = "<a href='viewallimage.php?pic=" . htmlspecialchars_uni ( $screenshot ) . "'><img border='0' width=150 src='" . htmlspecialchars_uni ( $screenshot ) . "' /></a>";
			if ($scrs)
				tr ( "Скриншоты", implode ( "&nbsp&nbsp", $scrs ), 1 );
		} else {
			if (! empty ( $row ["screenshot1"] ) or ! empty ( $row ["screenshot2"] ) or ! empty ( $row ["screenshot3"] ) or ! empty ( $row ["screenshot4"] )) {
				if (! empty ( $row ["screenshot1"] ))
					$scr1 = "<a href='viewimage.php?pic=" . htmlspecialchars_uni ( $row [screenshot1] ) . "'><img border='0' width=150 src='$torrent_dir/images/" . htmlspecialchars_uni ( $row [screenshot1] ) . "' /></a>";
				if ($row ["screenshot2"] != "")
					$scr2 = "<a href='viewimage.php?pic=" . htmlspecialchars_uni ( $row [screenshot2] ) . "'><img border='0' width=150 src='$torrent_dir/images/" . htmlspecialchars_uni ( $row [screenshot2] ) . "' /></a>";
				if ($row ["screenshot3"] != "")
					$scr3 = "<a href='viewimage.php?pic=" . htmlspecialchars_uni ( $row [screenshot3] ) . "'><img border='0' width=150 src='$torrent_dir/images/" . htmlspecialchars_uni ( $row [screenshot3] ) . "' /></a>";
				if ($row ["screenshot4"] != "")
					$scr4 = "<a href='viewimage.php?pic=" . htmlspecialchars_uni ( $row [screenshot4] ) . "'><img border='0' width=150 src='$torrent_dir/images/" . htmlspecialchars_uni ( $row [screenshot4] ) . "' /></a>";
				tr ( "Скриншоты", $scr1 . "&nbsp&nbsp" . $scr2 . "&nbsp&nbsp" . $scr3 . "&nbsp&nbsp" . $scr4, 1 );
			} else
				print ( "" );
		}
		print ( "</td></tr>" );
		if (! empty ( $row ["reliz"] ))
			print ( "<tr><td valign=middle align=right><b>Релиз от</b></td><td>" . format_comment ( $row ['reliz'], true, $ALLGROUPS [$row ['group']] ['can_usepsmile'] ) . "</td><tr>" );
		if ($row ["visible"] == "no" && ! empty ( $row ["filename"] ))
			tr ( $tracker_lang ['visible'], "<b>" . $tracker_lang ['no'] . "</b> (" . $tracker_lang ['dead'] . ")", 1 );
		if ($CURGROUP ['can_viewbanned'])
			tr ( $tracker_lang ['banned'], ($row ["banned"] == 'no' ? $tracker_lang ['no'] : $tracker_lang ['yes']) );
		
		if (isset ( $row ["cat_name"] ))
			tr ( $tracker_lang ['type'], $row ["cat_name"] );
		else
			tr ( $tracker_lang ['type'], "(" . $tracker_lang ['no_choose'] . ")" );
			/// MOD INCAT ///
		if (isset ( $row ["incat_name"] ))
			tr ( "Подкатегория", $row ["incat_name"] );
			/// MOD INCAT ///
		tr ( $tracker_lang ['seeder'], $tracker_lang ['seeder_last_seen'] . " " . mkprettytime ( $row ["lastseed"] ) . " " . $tracker_lang ['ago'] );
		/// MOD TRAILERS ///
		if (! empty ( $row ["filename"] ))
			tr ( $tracker_lang ['size'], mksize ( $row ["size"] ) . " (" . number_format ( $row ["size"] ) . " " . $tracker_lang ['bytes'] . ")" );
			/// MOD TRAILERS ///
		?>
<script type="text/javascript">
function ratings(){

var ajax = new engine_ajax();
var varsString = "";
ajax.requestFile = "takerate.php";
ajax.method = 'POST';
ajax.setVar('id', <?=$id?>);
ajax.element = 'ajax_rating';
ajax.sendAJAX(varsString);
setTimeout('ratings()', 10000);
}
ratings();
function send_rating(rating){

var ajax = new engine_ajax();
var varsString = "";
ajax.requestFile = "takerate.php";
ajax.method = 'POST';
ajax.setVar('id', <?=$id?>);
ajax.setVar('rating', rating);
ajax.sendAJAX(varsString);
}
</script>
<?
		tr ( $tracker_lang ['rating'], "<div id='ajax_rating'>" . $tracker_lang ['loading'] . "</div>", 1 );
		tr ( $tracker_lang ['added'], $row ["added"] );
		tr ( $tracker_lang ['views'], $row ["views"] );
		/// MOD TRAILERS ///
		if (! empty ( $row ["filename"] )) {
			tr ( $tracker_lang ['hits'], $row ["hits"] );
			tr ( $tracker_lang ['snatched'], $row ["times_completed"] . " " . $tracker_lang ['times'] );
			$keepget = "";
			$uprow = (isset ( $row ["username"] ) ? ($CURGROUP ['can_viewprof'] ? "<a href=userdetails.php?id=" . $row ["owner"] . ">" . htmlspecialchars_uni ( $row ["username"] ) . "</a>" : htmlspecialchars_uni ( $row ["username"] )) : "<i>Аноним</i>");
			/*
                if ($owned)
                        $uprow .= " $spacer<$editlink><b>[".$tracker_lang['edit']."]</b></a>";
*/
			if (! $use_hide)
				tr ( $tracker_lang ['uploaded'], $uprow . ($CURGROUP ['can_symp'] ? '&nbsp;<a href="simpaty.php?action=add&amp;good&amp;targetid=' . $row ["owner"] . '&amp;type=torrent' . $id . '&amp;returnto=' . urlencode ( $_SERVER ["REQUEST_URI"] ) . '" title="' . $tracker_lang ['respect'] . '"><img src="' . $pic_base_url . 'thum_good.gif" border="0" alt="' . $tracker_lang ['respect'] . '" title="' . $tracker_lang ['respect'] . '" /></a>&nbsp;&nbsp;<a href="simpaty.php?action=add&amp;bad&amp;targetid=' . $row ["owner"] . '&amp;type=torrent' . $id . '&amp;returnto=' . urlencode ( $_SERVER ["REQUEST_URI"] ) . '" title="' . $tracker_lang ['antirespect'] . '"><img src="' . $pic_base_url . 'thum_bad.gif" border="0" alt="' . $tracker_lang ['antirespect'] . '" title="' . $tracker_lang ['antirespect'] . '" /></a>' : ""), 1 );
			
			if ($row ["type"] == "multi") {
				if (! $_GET ["filelist"])
					tr ( $tracker_lang ['files'] . "<br /><a href=\"details.php?id=$id&amp;filelist=1$keepget#filelist\" class=\"sublink\">[" . $tracker_lang ['open_list'] . "]</a>", $row ["numfiles"] . " " . $tracker_lang ['files_l'], 1 );
				else {
					tr ( $tracker_lang ['files'], $row ["numfiles"] . " " . $tracker_lang ['files_l'], 1 );
					
					$s = "<table class=main border=\"1\" cellspacing=0 cellpadding=\"5\">\n";
					
					$subres = sql_query ( "SELECT * FROM files WHERE torrent = $id ORDER BY id" );
					$s .= "<tr><td class=colhead>" . $tracker_lang ['path'] . "</td><td class=colhead align=right>" . $tracker_lang ['size'] . "</td></tr>\n";
					while ( $subrow = mysql_fetch_array ( $subres ) ) {
						$s .= "<tr><td>" . $subrow ["filename"] . "</td><td align=\"right\">" . mksize ( $subrow ["size"] ) . "</td></tr>\n";
					}
					
					$s .= "</table>\n";
					tr ( "<a name=\"filelist\">" . $tracker_lang ['file_list'] . "</a><br /><a href=\"details.php?id=$id$keepget\" class=\"sublink\">[" . $tracker_lang ['close_list'] . "]</a>", $s, 1 );
				}
			}
			
			if (! $_GET ["dllist"]) {
				/*
                        $subres = sql_query("SELECT seeder, COUNT(*) FROM peers WHERE torrent = $id GROUP BY seeder");
                        $resarr = array(yes => 0, no => 0);
                        $sum = 0;
                        while ($subrow = mysql_fetch_array($subres)) {
                                $resarr[$subrow[0]] = $subrow[1];
                                $sum += $subrow[1];
                        }
                        tr("Peers<br /><a href=\"details.php?id=$id&amp;dllist=1$keepget#seeders\" class=\"sublink\">[See full list]</a>", $resarr["yes"] . " seeder(s), " . $resarr["no"] . " leecher(s) = $sum peer(s) total", 1);
                        */
				tr ( $tracker_lang ['downloading'] . "<br />" . (! $use_hide ? "<a href=\"details.php?id=$id&amp;dllist=1$keepget#seeders\" class=\"sublink\">[" . $tracker_lang ['open_list'] . "]</a>" : ""), $row ["seeders"] . " " . $tracker_lang ['seeders_l'] . ", " . $row ["leechers"] . " " . $tracker_lang ['leechers_l'] . " = " . ($row ["seeders"] + $row ["leechers"]) . " " . $tracker_lang ['peers_l'], 1 );
			} else {
				$downloaders = array ();
				$seeders = array ();
				$subres = sql_query ( "SELECT seeder, finishedat, downloadoffset, uploadoffset, peers.ip, port, peers.uploaded, peers.downloaded, to_go, UNIX_TIMESTAMP(started) AS st, connectable, agent, peer_id, UNIX_TIMESTAMP(last_action) AS la, UNIX_TIMESTAMP(prev_action) AS pa, userid, users.username, users.`group` FROM peers INNER JOIN users ON peers.userid = users.id WHERE torrent = $id" ) or sqlerr ( __FILE__, __LINE__ );
				while ( $subrow = mysql_fetch_array ( $subres ) ) {
					if ($subrow ["seeder"] == "yes")
						$seeders [] = $subrow;
					else
						$downloaders [] = $subrow;
				}
				
				function leech_sort($a, $b) {
					if (isset ( $_GET ["usort"] ))
						return seed_sort ( $a, $b );
					$x = $a ["to_go"];
					$y = $b ["to_go"];
					if ($x == $y)
						return 0;
					if ($x < $y)
						return - 1;
					return 1;
				}
				function seed_sort($a, $b) {
					$x = $a ["uploaded"];
					$y = $b ["uploaded"];
					if ($x == $y)
						return 0;
					if ($x < $y)
						return 1;
					return - 1;
				}
				
				usort ( $seeders, "seed_sort" );
				usort ( $downloaders, "leech_sort" );
				
				if (! $use_hide) {
					tr ( "<b>" . $tracker_lang ['details_seeding'] . "</b><br /><a href=\"details.php?id=$id$keepget\" class=\"sublink\">[" . $tracker_lang ['close_list'] . "]</a>", dltable ( $tracker_lang ['details_seeding'], $seeders, $row ), 1 );
					tr ( "<b>" . $tracker_lang ['details_leeching'] . "</b><br /><a href=\"details.php?id=$id$keepget\" class=\"sublink\">[" . $tracker_lang ['close_list'] . "]</a>", dltable ( $tracker_lang ['details_leeching'], $downloaders, $row ), 1 );
				}
			}
			if ($row ["times_completed"] > 0) {
				$res = mysql_query ( "SELECT users.id, users.username, users.title, users.uploaded, users.downloaded, users.donor, users.enabled, users.warned, users.last_access, users.`group`, snatched.startdat, snatched.last_action, snatched.completedat, snatched.seeder, snatched.userid, snatched.uploaded AS sn_up, snatched.downloaded AS sn_dn FROM snatched INNER JOIN users ON snatched.userid = users.id WHERE snatched.finished='yes' AND snatched.torrent =" . sqlesc ( $id ) . " ORDER BY users.`group` DESC $limit" ) or sqlerr ( __FILE__, __LINE__ );
				$snatched_full = "<table width=100% class=main border=1 cellspacing=0 cellpadding=5>\n";
				$snatched_full .= "<tr><td class=colhead>Юзер</td><td class=colhead>Раздал</td><td class=colhead>Скачал</td><td class=colhead>Рейтинг</td><td class=colhead align=center>Начал / Закончил</td><td class=colhead align=center>Действие</td><td class=colhead align=center>Сидирует</td>" . ($CURGROUP ['can_pm'] ? "<td class=colhead align=center>ЛС</td>" : "") . "</tr>";
				
				while ( $arr = mysql_fetch_assoc ( $res ) ) {
					//start Global
					if ($arr ["downloaded"] > 0) {
						$ratio = number_format ( $arr ["uploaded"] / $arr ["downloaded"], 2 );
						//  $ratio = "<font color=" . get_ratio_color($ratio) . ">$ratio</font>";
					} else if ($arr ["uploaded"] > 0)
						$ratio = "Inf.";
					else
						$ratio = "---";
					$uploaded = mksize ( $arr ["uploaded"] );
					$downloaded = mksize ( $arr ["downloaded"] );
					//start torrent
					if ($arr ["sn_dn"] > 0) {
						$ratio2 = number_format ( $arr ["sn_up"] / $arr ["sn_dn"], 2 );
						$ratio2 = "<font color=" . get_ratio_color ( $ratio2 ) . ">$ratio2</font>";
					} else if ($arr ["sn_up"] > 0)
						$ratio2 = "Inf.";
					else
						$ratio2 = "---";
					$uploaded2 = mksize ( $arr ["sn_up"] );
					$downloaded2 = mksize ( $arr ["sn_dn"] );
					$snatched_small [] = $CURGROUP ['can_viewprof'] ? "<a href=userdetails.php?id=$arr[userid]>" . get_user_group_color ( $arr ["group"], $arr ["username"] ) . "</a>" : get_user_group_color ( $arr ["group"], $arr ["username"] );
				}
				$snatched_full .= "</table>\n";
				if ($row ["seeders"] == 0 || ($row ["leechers"] / $row ["seeders"] >= 2))
					$reseed_button = "<form action=\"takereseed.php\"><input type=\"hidden\" name=\"torrent\" value=\"$id\" /><input type=\"submit\" value=\"Позвать скачавших\" /></form>";
				if (! $_GET ["snatched"] == 1 and ! $use_hide)
					tr ( "Скачавшие", @implode ( ", ", $snatched_small ) . $reseed_button, 1 );
			}
		}
		/// MOD TRAILERS ///
		$torrentid = ( int ) $_GET ["id"];
		if (! is_valid_id ( $torrentid ))
			bark ( "Bad Torrent ID." );
		if ($row ["report"] == "no" and $CURUSER ["id"] != $row ["owner"])
			tr ( "Пожаловаться", "<form method=\"post\" action=\"report.php?id=" . $row ['id'] . "\">Причина:&nbsp;<input name=motive cols=40 >&nbsp;<input type=\"submit\" value=\"Отправить\" /><input type=\"hidden\" name=\"torrentid\" value=\"$torrentid\"></form>", 1 );
		$touserid = $row ["owner"];
		$thanks_sql = mysql_query ( "SELECT * FROM thanks t INNER JOIN users u on t.userid = u.id where t.torrentid=$torrentid" ) or sqlerr ( __FILE__, __LINE__ );
		if (! $use_hide) {
			while ( $rows_t = mysql_fetch_object ( $thanks_sql ) ) {
				$thanksby .= $CURGROUP ['can_viewprof'] ? "<a href='userdetails.php?id=$rows_t->id'>" . get_user_group_color ( $rows_t->group, $rows_t->username ) . "</a>, " : get_user_group_color ( $rows_t->group, $rows_t->username );
			}
			if (isset ( $thanksby ))
				$thanksby = substr ( $thanksby, 0, strlen ( $thanksby ) - 2 );
			else
				$thanksby = "Еще никто не поблагодарил.";
		} else {
			$thanks_sql = mysql_query ( "SELECT COUNT(*) FROM thanks WHERE torrentid=$torrentid" ) or sqlerr ( __FILE__, __LINE__ );
			$rows_t = mysql_fetch_array ( $thanks_sql );
			if ($rows_t [0] == 0) {
				$thanksby = "Еще никто не благодарил";
			} else {
				$thanksby = "<font color=\"darkgreen\"><b>" . $rows_t [0] . "&nbsp;раз</b>(а)</font>";
			}
		}
		
		$t_userid = $CURUSER ["id"];
		if ($t_userid) {
			$tsql = mysql_query ( "SELECT NULL FROM thanks where torrentid=$torrentid and userid=$t_userid" );
			$tsrow = mysql_fetch_object ( $tsql );
		}
		$owntorrentquery = mysql_query ( "SELECT NULL FROM torrents WHERE id = '$torrentid' and owner = '$t_userid'" ) or sqlerr ( __FILE__, __LINE__ );
		$owntorrentrow = mysql_fetch_object ( $owntorrentquery );
		
		if ($tsrow || $owntorrentrow || !$t_userid) {
			$disabled = " disabled";
		}
		$thanksby .= " <form action=\"thanks.php\" method=\"post\" id=\"thanksForm\">
        <input type=\"submit\" name=\"submit\" value=\"Спасибо!\"$disabled>
        <input type=\"hidden\" name=\"torrentid\" value=\"$torrentid\">
        <!--<input type=\"hidden\" name=\"touserid\" value=\"$touserid\">-->
        </form>";
		
		tr ( "Поблагодарили", $thanksby, 1 );
		print ( "</table></p>\n" );
		end_frame ();
	
	} else {
		stdhead ( $tracker_lang ['comments_for'] . " \"" . $row ["name"] . "\"" );
		print ( "<h1>" . $tracker_lang ['comments_for'] . " <a href=details.php?id=$id>" . $row ["name"] . "</a></h1>\n" );
	}
	
	print ( "<p><a name=\"startcomments\"></a></p>\n" );
	
	$subres = mysql_query ( "SELECT COUNT(*) FROM comments WHERE torrent = $id" );
	$subrow = mysql_fetch_array ( $subres );
	$count = $subrow [0];
	
	$limited = 10;
	if (! $count) {
		
		?>

<script language="javascript" type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
function send_comment(){

text = escape(document.comment.text.value);
tid = <?=$id?>;
var ajax = new engine_ajax();
ajax.onShow ('');
var varsString = "";
ajax.requestFile = "takecomment.php";
ajax.setVar("tid", tid);
ajax.setVar("text", text);
ajax.method = 'POST';
ajax.element = 'ajax_c';
ajax.sendAJAX(varsString);
}
</script>
<div id="loading-layer"
	style="display: none; font-family: Verdana; font-size: 11px; width: 200px; height: 50px; background: #FFF; padding: 10px; text-align: center; border: 1px solid #000">
<div style="font-weight: bold" id="loading-layer-text">Загрузка.
Подождите пожалуйста...</div>
<br />
<img src="<?=$pic_base_url?>loading.gif" border="0" /></div>
<div id="ajax_c">
<?
		begin_frame ( "Список комментариев" );
		print ( "<table style=\"margin-top: 2px;\" cellpadding=\"5\" width=\"100%\">" );
		print ( "<tr><td align=\"center\" class=\"noborder\">" );
		print ( "Комментариев нет. " . ($CURGROUP ['can_addcom'] ? "<a href=#comments>Желаете добавить?</a>" : "") );
		print ( "</td></tr></table><br>" );
		end_frame ();
		if ($CURGROUP ['can_addcom']) {
			begin_frame ( "Добавить комментарий" );
			print ( "<table style=\"margin-top: 2px;\" cellpadding=\"5\" width=\"100%\">" );
			print ( "<tr><td align=\"center\" class=\"noborder\">" );
			print ( "<form name=comment method=\"post\" action=\"takecomment.php\">" );
			print ( "<div>" );
			textbbcode ( "comment", "text", "", 0 );
			print ( "</div>" );
			print ( "</td></tr><tr><td  align=\"center\" colspan=\"2\" class=\"noborder\">" );
			print ( "<input type=\"hidden\" name=\"tid\" value=\"$id\"/>" );
			print ( "<input type=\"submit\" onClick=\"send_comment(); return false;\" class=btn value=\"Разместить комментарий\" />" );
			print ( "</td></tr></form></table></div>" );
			end_frame ();
		}
	} else {
		
		?>

<script language="javascript" type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
function send_comment(){

text = escape(document.comment.text.value);
tid = <?=$id?>;

var ajax = new engine_ajax();
ajax.onShow ('');
var varsString = "";
ajax.requestFile = "takecomment.php";
ajax.setVar("tid", tid);
ajax.setVar("text", text);
ajax.method = 'POST';
ajax.element = 'ajax_c';
ajax.sendAJAX(varsString);
}
</script>
<div id="loading-layer"
	style="display: none; font-family: Verdana; font-size: 11px; width: 200px; height: 50px; background: #FFF; padding: 10px; text-align: center; border: 1px solid #000">
<div style="font-weight: bold" id="loading-layer-text">Загрузка.
Подождите пожалуйста...</div>
<br />
<img src="<?=$pic_base_url?>loading.gif" border="0" /></div>
<div id="ajax_c">
<?
		if ($CURGROUP ['can_comment']) {
			list ( $pagertop, $pagerbottom, $limit ) = pager ( $limited, $count, "details.php?id=$id&", array (lastpagedefault => 1 ) );
			$subres = sql_query ( "SELECT c.id, c.ip, c.text, c.user, c.added, c.editedby, c.editedat, u.avatar, u.warned, u.username, u.title, u.`group`, u.donor, u.downloaded, u.uploaded, u.gender, u.last_access, e.username AS editedbyname FROM comments AS c LEFT JOIN users AS u ON c.user = u.id LEFT JOIN users AS e ON c.editedby = e.id WHERE torrent = $id ORDER BY c.id $limit" ) or sqlerr ( __FILE__, __LINE__ );
			$allrows = array ();
			while ( $subrow = mysql_fetch_array ( $subres ) )
				$allrows [] = $subrow;
			begin_frame ( "Список комментариев" );
			print ( "<table class=main cellspacing=\"0\" cellPadding=\"5\" width=\"100%\" >" );
			
			print ( "<tr><td class=\"noborder\">" );
			print ( $pagertop );
			print ( "</td></tr>" );
			print ( "<tr><td class=\"noborder\">" );
			commenttable ( $allrows );
			print ( "</td></tr>" );
			print ( "<tr><td class=\"noborder\">" );
			print ( $pagerbottom );
			print ( "</td></tr>" );
			print ( "</table>" );
			end_frame ();
		}
		if ($CURGROUP ['can_addcom']) {
			begin_frame ( "Добавить комментарий" );
			print ( "<table style=\"margin-top: 2px;\" cellpadding=\"5\" width=\"100%\">" );
			print ( "<tr><td width=\"100%\" align=\"center\" class=\"noborder\">" );
			print ( "<form name=comment method=\"post\" action=\"takecomment.php\">" );
			print ( "<center><table border=\"0\"><tr><td class=\"noborder\">" );
			print ( "<div align=\"center\">" . textbbcode ( "comment", "text", "", 0 ) . "</div>" );
			print ( "</td></tr></table></center>" );
			print ( "</td></tr><tr><td  align=\"center\" colspan=\"2\" class=\"noborder\">" );
			print ( "<input type=\"hidden\" name=\"tid\" value=\"$id\"/>" );
			print ( "<input type=\"submit\" onClick=\"send_comment(); return false;\" class=btn value=\"Разместить комментарий\" />" );
			print ( "</td></tr></form></table></div>" );
		}
		end_frame ();
	
	}

}

stdfoot ();

?>