<?

require_once ("include/bittorrent.php");

dbconn ();
validcan ( false, 'can_downloadtor' );
parked ();
global $CURUSER, $CURGROUP;
if (@ini_get ( 'output_handler' ) == 'ob_gzhandler' and @ob_get_length () !== false) { // if output_handler = ob_gzhandler, turn it off and remove the header sent by PHP
	@ob_end_clean ();
	header ( 'Content-Encoding:' );
}

/*if (!preg_match(':^/(\d{1,10})/(.+)\.torrent$:', $_SERVER["PATH_INFO"], $matches))
	httperr();*/
$id = ( int ) $_GET ["id"];
if (! is_numeric ( $id ))
	stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );

$name = $_GET ["name"];
if (! isset ( $name ))
	stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
	
/*$id = 0 + $matches[1];
if (!$id)
	httperr();*/
$res = sql_query ( "SELECT name FROM torrents WHERE id = " . sqlesc ( $id ) ) or sqlerr ( __FILE__, __LINE__ );
$row = mysql_fetch_assoc ( $res );
if (! $row)
	stderr ( $tracker_lang ['error'], $tracker_lang ['invalid_id'] );
global $use_nodown;
if ($use_nodown) {
	$downloadered = sql_query ( "SELECT users.id 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']) {
		$nodown = 1;
	}
}
if ($nodown)
	die ();
$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__ );
$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 ();
}
if ($CURUSER ['warned']=='yes')
	stderr ( $tracker_lang ['error'], 'У вас ещё не истёк срок предупреждения, поэтому вам запрещено скачивать торренты!' );
$fn = "$torrent_dir/$id.torrent";

if (! $row || ! is_file ( $fn ) || ! is_readable ( $fn ))
	stderr ( $tracker_lang ['error'], $tracker_lang ['unable_to_read_torrent'] );

sql_query ( "UPDATE torrents SET hits = hits + 1 WHERE id = " . sqlesc ( $id ) );

require_once "include/benc.php";

if (strlen ( $CURUSER ['passkey'] ) != 32) {
	$CURUSER ['passkey'] = md5 ( $CURUSER ['username'] . get_date_time () . $CURUSER ['passhash'] );
	sql_query ( "UPDATE users SET passkey=" . sqlesc ( $CURUSER [passkey] ) . " WHERE id=" . sqlesc ( $CURUSER [id] ) );
}

$dict = bdec_file ( $fn, (1024 * 1024) );

$dict ['value'] ['announce'] ['value'] = $announce_urls [0] . "?passkey=$CURUSER[passkey]"; //"$DEFAULTBASEURL/announce.php?passkey=$CURUSER[passkey]";
$dict ['value'] ['announce'] ['string'] = strlen ( $dict ['value'] ['announce'] ['value'] ) . ":" . $dict ['value'] ['announce'] ['value'];
$dict ['value'] ['announce'] ['strlen'] = strlen ( $dict ['value'] ['announce'] ['string'] );

header ( "Expires: Tue, 1 Jan 1980 00:00:00 GMT" );
header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
header ( "Cache-Control: no-store, no-cache, must-revalidate" );
header ( "Cache-Control: post-check=0, pre-check=0", false );
header ( "Pragma: no-cache" );
header ( "X-Powered-by: CyBERhype Tracker - http://bt-tracker.co.cc" );
header ( "Accept-Ranges: bytes" );
header ( "Connection: close" );
header ( "Content-Transfer-Encoding: binary" );
header ( "Content-Disposition: attachment; filename=\"" . urlencode ( $name ) . "\"" );
header ( "Content-Type: application/x-bittorrent" );
ob_implicit_flush ( true );

print ( benc ( $dict ) );

?>