<? 
require_once("include/bittorrent.php");

dbconn();
loggedinorreturn();
parked();

function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 
   
    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 
   
    $bytes /= pow(1024, $pow); 
   
    return round($bytes, $precision) . '' . $units[$pow]; 
}

function announce_list($announce_urls) {
  for ($i = 0; $i < count($announce_urls); $i++) {
  	
 	if (!empty($announce_urls[$i])) {
    $list[$i][$i] = bdec(benc_str(trim($announce_urls[$i])));
    $list[$i]= bdec(benc_list($list[$i]));
    }
  }
  return bdec(benc_list($list));
}

if (@ini_get('output_handler') == 'ob_gzhandler' AND @ob_get_length() !== false){	
	@ob_end_clean();
	header('Content-Encoding:');
}

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

if (!is_numeric($id))
	stderr($tracker_lang['error'],$tracker_lang['invalid_id']);
	
global $announce_urls;

$res = sql_query("SELECT multi_time, multitracker, name, size, f_trackers FROM torrents WHERE id = ".sqlesc($id)) or sqlerr(__FILE__, __LINE__);
$row = mysql_fetch_assoc($res);

if (!$row)
stderr($tracker_lang['error'], "В базе нет названия торрента к такому id");

// создаем массив проверенных аннонсов
$arrayrow = explode("\n",$row["f_trackers"]);

/// создаем массив "битых" аннонсов по :0:0:0 данным
for($i = 0, $c = count($arrayrow); $i < $c; $i++) {

if (!preg_match("|(:0:0:0)|U", $arrayrow[$i], $li)){
unset($arrayrow[$i]);
} else
$arrayrow[$i] = trim(str_replace(":0:0:0","",$arrayrow[$i]));
}

/// перебираем оригинал аннонсов для удаления "битых"
for($iu = 0, $cu = count($announce_urls); $iu < $cu; $iu++) {

foreach ($arrayrow as $b=>$c) {

if (stristr($announce_urls[$iu],$c)){
unset($announce_urls[$iu]);
}
}

}

$size=formatBytes($row["size"]);
$fname = $row['name']."^(".$size.")";

$ru = array("а","б","в","г","д","е","ё","ж","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ч","ш","щ","ъ","ы","ь","э","ю","я","А","Б","В","Г","Д","Е","Ё","Ж","З","И","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ч","Ш","Щ","Ъ","Ы","Ь","Э","Ю","Я"," ");
$en = array("a","b","v","g","d","e","e","zg","z","i","i","k","l","m","n","o","p","r","s","t","y","f","h","c","ch","sh","zh","","u","","e","iu","ia","A","B","V","G","D","E","E","Zg","Z","I","K","L","M","N","O","P","R","S","T","Y","F","H","C","Ch","Sh","Zh","", "U","","E","IU","Ia","_");

$fname = str_replace($ru, $en, $fname); 

$rui = array(",",".",";","'","\"","/",":","&","~");

$fname = str_replace($rui, "_", $fname); 

$name = $fname."[$SITENAME].torrent";  

$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"]));
}


//////////////////////// временное правило
$dt_multi = get_date_time(gmtime() - 43200); // пол дня - увеличьте время или уберите вовсе проверку.
if ($row["multitracker"]=="yes" && $row["multi_time"]<$dt_multi){

$sql = sql_query("SELECT info_hash FROM torrents WHERE id=$id"); 
while($torrent = mysql_fetch_array($sql)) {
    $tracker_cache = array(); 
    $f_leechers = 0; 
    $f_seeders = 0; 
    $announce_list=$announce_urls;
    foreach($announce_list as $announce) 
    {
        $response = get_remote_peers($announce, $torrent['info_hash'],true); 
        if($response['state']=='ok'){
          $tracker_cache[] = $response['tracker'].':'.($response['leechers'] ? $response['leechers'] : 0).':'.($response['seeders'] ? $response['seeders'] : 0).':'.($response['downloaded'] ? $response['downloaded'] : 0); 
            if ($f_leechers < $response['leechers'])
            $f_leechers = $response['leechers'];
            
            if ($f_seeders < $response['seeders'])
            $f_seeders = $response['seeders']; 
        }
        else 
            $tracker_cache[] = $response['tracker'].':false'; 
    }
    $tracker_cache = implode("\n",$tracker_cache); 
     
    sql_query("UPDATE LOW_PRIORITY torrents SET f_leechers = ".sqlesc($f_leechers).', f_seeders = '.sqlesc($f_seeders).', f_trackers = '.sqlesc($tracker_cache).' WHERE id = '.$id) or sqlerr(__FILE__,__LINE__);
}
}
//////////////////////// временное правило








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


//$dict['value']['announce']['value'] = $announce_urls[0]."?passkey=$CURUSER[passkey]";//"$DEFAULTBASEURL/announce.php?passkey=$CURUSER[passkey]";

if ($row["multitracker"]=="yes"){
$announce_urls[0]=$announce_urls[0]."?passkey=$CURUSER[passkey]";
$dict['value']['announce-list'] = announce_list($announce_urls);
} else {

$dict['value']['comment']=bdec(benc_str("Торрент создан для '$SITENAME'")); // change torrent comment
$dict['value']['comment']=bdec(benc_str("$DEFAULTBASEURL/details.php?id=$id")); // change torrent comment to URL
unset($dict['value']['announce-list']); // remove multi-tracker capability
$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 ("Accept-Ranges: bytes");
header ("Connection: close");
header ("Content-Transfer-Encoding: binary");
header ("Content-Disposition: attachment; filename=\"".$name."\"");
header ("Content-Type: application/x-bittorrent");
ob_implicit_flush(true);

print(benc($dict));

?>