$res = SQL_Query_exec("SELECT COUNT(DISTINCT torrent) FROM peers WHERE `seeder` = 'yes'");
var_dump($res);
<?php
#================================#
# TorrentTrader 2.08 #
# http://www.torrenttrader.org #
#--------------------------------#
# Modified by M-Jay #
#================================#
// HIDE ERRORS
error_reporting(0);
// GET SETTINGS
require_once("backend/mysql.php");
require_once("backend/config.php");
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . $mysql_host . ';dbname=' . $mysql_db . ';charset=utf8';
try {
$pdo = new PDO($dsn, $mysql_user, $mysql_pass, $opt);
} catch (\Exception $e) {
err('The Database Details Are Incorrect');
}
// SQL FUNKTION TO DISPLAY ERRORS
function pdo($pdo, $sql, $args = NULL)
{
try {
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
} catch (\Exception $e) {
err($e);
}
}
// WRITE RESPONSE TO FILE
function mydebug($msg)
{
if (is_writeable('test.txt')) {
$fh = fopen('test.txt', 'a+');
fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
fclose($fh);
}
}
// MEMBERS SETTINGS
$MEMBERSONLY = $site_config["MEMBERSONLY"];
$MEMBERSONLY_WAIT = $site_config["MEMBERSONLY_WAIT"];
//START FUNCTIONS
function sqlesc($x)
{
if (!is_numeric($x)) {
$x = "'" . $x . "'";
}
return $x;
}
function unesc($x)
{
stripslashes($x);
return $x;
}
function err($msg)
{
return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}
function benc_str($s)
{
return strlen($s) . ":$s";
}
function benc_int($i)
{
return "i" . $i . "e";
}
function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
print($x);
}
exit();
}
function gmtime()
{
return strtotime(get_date_time());
}
function get_date_time($timestamp = 0)
{
if ($timestamp) {
return date("Y-m-d H:i:s", $timestamp);
} else {
return gmdate("Y-m-d H:i:s");
}
}
function portblacklisted($port)
{
if ($port >= 411 && $port <= 413) {
// direct connect
return true;
} elseif ($port == 1214) {
// kazaa
return true;
} elseif ($port >= 6346 && $port <= 6347) {
// gnutella
return true;
} elseif ($port == 4662) {
// emule
return true;
} elseif ($port == 6699) {
// winmx
return true;
}
return false;
}
//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////
// BLOCK ACCESS WITH WEB BROWSERS - TEST ADDED
$agent = $_SERVER["HTTP_USER_AGENT"];
if (preg_match("/^Mozilla|^Opera|^Chrome|^Links|^Lynx/i", $agent))
die("Bad decision pal. None of this works this way");
//GET DETAILS OF PEERS ANNOUNCE M-JAY
//foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
// if (isset($_GET["$x"])) {
// $GLOBALS[$x] = "" . $_GET[$x];
// }
// }
//GET DETAILS OF PEERS ANNOUNCE OLD
foreach (array("passkey","info_hash","peer_id","ip","event") as $x) {
$GLOBALS[$x] = $_GET[$x];
}
foreach (array("port", "downloaded", "uploaded", "left") as $x) {
$GLOBALS[$x] = 0 + $_GET[$x];
}
foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
if (!isset($x)) {
err("Missing key: $x");
}
}
$no_peer_id = (int) $_GET["no_peer_id"];
foreach (array("info_hash") as $x) {
if (strlen($GLOBALS[$x]) != 20) {
err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
}
}
unset($x);
if ($MEMBERSONLY) {
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}
$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
/*
foreach (array("num want", "numwant", "num_want") as $k) {
if (isset($_GET[$k])) {
$rsize = (int) $_GET[$k];
break;
}
}
*/
if (!$port || $port > 0xffff) {
err("invalid port");
}
if (!isset($event)) {
$event = "";
}
$seeder = ($left == 0) ? "yes" : "no";
// CLIENT BAN - TEST ADDED
$agentarray = array_map("trim", explode(",", $site_config["BANNED_AGENTS"]));
$useragent = substr($peer_id, 0, 8);
foreach($agentarray as $bannedclient)
if (@strpos($useragent, $bannedclient) !== false) {
mysqli_close($GLOBALS["DBconnector"]); // will throw error use $pdo = null;
err("Client is banned");
}
// END CLIENT BAN
if (portblacklisted($port)) {
mysqli_close($GLOBALS["DBconnector"]); // will throw error use $pdo = null;
err("Port $port is blacklisted.");
}
// WANTED DATA FROM DB
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey, g.can_download"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get
// CHECK USER
$userid = 0;
if ($MEMBERSONLY) {
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user) {
err("Cannot locate a user with that passkey!");
} elseif ($user["can_download"] == "no") {
err("You do not have permission to download.");
}
$userid = $user["id"]; //etc
}
// CHECK TORRENT
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent) {
err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];
// LIMIT NUMBER OF PEERS
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
$limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
$limit = "";
}
// CHECK PEER NEW OR OLD
$sql = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
$res = $sql->fetch(PDO::FETCH_ASSOC);
if ($res) {
// Already Peer So Update User & Peer Table
$elapsed = ($res['seeder'] == 'yes') ? $site_config['announce_interval'] - floor(($res['ez'] - time()) / 60) : 0;
$upthis = max(0, $uploaded - $res["uploaded"]);
$downthis = max(0, $downloaded - $res["downloaded"]);
//==== ADD TO DEBUG
mydebug("upthis - $upthis - uploaded - $uploaded - peer - $res[uploaded] - torrentid - $torrent[id] - freeleech - $torrent[freeleech] - seeder - $seeder - user -$user[id] - event - $event");
mydebug("downthis - $downthis - downloaded - $downloaded - peer - $res[downloaded] - torrentid - $torrent[id] - freeleech - $torrent[freeleech] - seeder - $seeder - user -$user[id] - event - $event");
//=== END DEBUG
if (($upthis > 0 || $downthis > 0 || $elapsed > 0) && is_int($userid)) {
if ($user["class"] >= "4" || $torrent["freeleech"] == 1) {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
pdo($pdo, "UPDATE `snatched` SET `uload` = `uload` + '$upthis', `utime` = '".gmtime()."', `ltime` = `ltime` + '$elapsed' WHERE `tid` = '$torrentid' AND `uid` = '$userid'");
} else {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
pdo($pdo, "UPDATE `snatched` SET `uload` = `uload` + '$upthis', `dload` = `dload` + '$downthis', `utime` = '".gmtime()."', `ltime` = `ltime` + '$elapsed' WHERE `tid` = '$torrentid' AND `uid` = '$userid'");
}
}
pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
} else {
// todo check new peer
//check passkey isnt leaked,
//wait time check
// NEW PEER SO ADD
pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('yes', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");
// i dont like this
if ( ( $MEMBERSONLY ) && ( $seeder == 'no' ) ) {
pdo($pdo, "INSERT DELAYED INTO `snatched` (`uid`, `tid`, `stime`, `utime`) VALUES ('$userid', '$torrentid', '".gmtime()."', '".gmtime()."') ON DUPLICATE KEY UPDATE `utime` = '" . gmtime() . "'");
} else {
pdo($pdo, "INSERT DELAYED INTO `snatched` (`uid`, `tid`, `stime`, `utime`, `dload`, `completed`) VALUES ('$userid', '$torrentid', '".gmtime()."', '".gmtime()."', '".$downloaded."', '1') ON DUPLICATE KEY UPDATE `utime` = '" . gmtime() . "'");
}
// maybe try
/*
if ( ( $MEMBERSONLY ) {
$seedercompleted = ($left == 0) ? 1 : 0;
pdo($pdo, "INSERT DELAYED INTO `snatched` (`uid`, `tid`, `stime`, `utime`, `completed`) VALUES ('$userid', '$torrentid', '".gmtime()."', '".gmtime()."', '".$seedercompleted."') ON DUPLICATE KEY UPDATE `utime` = '" . gmtime() . "'");
}
*/
}
// NOW DO EVENTS
if ($event == "stopped") {
pdo($pdo, "DELETE FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
}
if ($event == "completed") {
$updateset[] = "times_completed = times_completed + 1";
if ($MEMBERSONLY) {
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
pdo($pdo, "UPDATE `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
}
// LETS GET ALL PEERS
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit");
// Sort Response
$seeders = 0;
$leechers = 0;
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row['seeder'] == 'no') {
$leechers++;
} else {
$seeders++;
}
$peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$peerlist['seeders'] = $seeders;
$peerlist['leechers'] = $leechers;
$resp = "d8:intervali$site_config[announce_interval]e12:min intervali30e8:completei$peerlist[seeders]e10:incompletei$peerlist[leechers]e5:peersl$peerlist[list]ee";
// NOW UPDATE TORRENT
$updateset = array();
$updateset[] = "seeders = $peerlist[seeders]";
$updateset[] = "leechers = $peerlist[leechers]";
if ($seeder == "yes") {
if ($torrent["banned"] != "yes")
$updateset[] = "visible = 'yes'";
$updateset[] = "last_action = '" . get_date_time() . "'";
}
if (count($updateset)) {
pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}
// SEND BENCODED DATA TO DEBUG FILE PLACE TEST.TXT IN ROOT
//mydebug($resp);
// SEND DATA TO CLIENT
benc_resp_raw($resp);


mydebug("upthis - $upthis - uploaded - $uploaded - peer - $res[uploaded] - torrentid - $torrent[id] - freeleech - $torrent[freeleech] - seeder - $seeder - user -$user[id] - event - $event");
mydebug("downthis - $downthis - downloaded - $downloaded - peer - $res[downloaded] - torrentid - $torrent[id] - freeleech - $torrent[freeleech] - seeder - $seeder - user -$user[id] - event - $event");[Log] 12.10.2022 22:34:01 upthis - 0 - uploaded - 60946200 - peer - 60946200
[Log] 12.10.2022 22:34:01 downthis - 0 - downloaded - 1075980998 - peer - 1075980998[Log] 12.10.2022 22:33:56 upthis - 0 - uploaded - 0 - peer - 0 $upthis = max(0, $uploaded - $res["uploaded"]);
$downthis = max(0, $downloaded - $res["downloaded"]); mydebug("upthis - $upthis - uploaded - $uploaded - peer - $res[uploaded]");
mydebug("downthis - $downthis - downloaded - $downloaded - peer - $res[downloaded]"); <?php
// Hide Errors
error_reporting(0);
// Get Settings
require_once("backend/mysql.php");
require_once("backend/config.php");
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . $mysql_host . ';dbname=' . $mysql_db . ';charset=utf8';
try {
$pdo = new PDO($dsn, $mysql_user, $mysql_pass, $opt);
} catch (\Exception $e) {
err('The Database Details Are Incorrect');
}
// SQL Function To Display Errors
function pdo($pdo, $sql, $args = NULL)
{
try {
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
} catch (\Exception $e) {
err($e);
}
}
// Write Response To File
function mydebug($msg)
{
if (is_writeable('test.txt')) {
$fh = fopen('test.txt', 'a+');
fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
fclose($fh);
}
}
// Member Settings
$MEMBERSONLY = $site_config["MEMBERSONLY"];
$MEMBERSONLY_WAIT = $site_config["MEMBERSONLY_WAIT"];
// Default Functions
function sqlesc($x)
{
if (!is_numeric($x)) {
$x = "'" . $x . "'";
}
return $x;
}
function unesc($x)
{
stripslashes($x);
return $x;
}
function err($msg)
{
return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}
function benc_str($s)
{
return strlen($s) . ":$s";
}
function benc_int($i)
{
return "i" . $i . "e";
}
function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
print($x);
}
exit();
}
function gmtime()
{
return strtotime(get_date_time());
}
function get_date_time($timestamp = 0)
{
if ($timestamp) {
return date("Y-m-d H:i:s", $timestamp);
} else {
return gmdate("Y-m-d H:i:s");
}
}
function portblacklisted($port)
{
if ($port >= 411 && $port <= 413) {
// direct connect
return true;
} elseif ($port == 1214) {
// kazaa
return true;
} elseif ($port >= 6346 && $port <= 6347) {
// gnutella
return true;
} elseif ($port == 4662) {
// emule
return true;
} elseif ($port == 6699) {
// winmx
return true;
}
return false;
}
// NOW WE DO THE ANNOUNCE CODE
// todo block browser access here
// Agent
$agent = $_SERVER["HTTP_USER_AGENT"];
// Get Client Details
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
if (isset($_GET["$x"])) {
$GLOBALS[$x] = "" . $_GET[$x];
}
}
foreach (array("port", "downloaded", "uploaded", "left") as $x) {
$GLOBALS[$x] = 0 + $_GET[$x];
}
foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
if (!isset($x)) {
err("Missing key: $x");
}
}
$no_peer_id = (int) $_GET["no_peer_id"];
foreach (array("info_hash") as $x) {
if (strlen($GLOBALS[$x]) != 20) {
err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
}
}
unset($x);
if ($MEMBERSONLY) {
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}
$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
foreach (array("num want", "numwant", "num_want") as $k) {
if (isset($_GET[$k])) {
$rsize = (int) $_GET[$k];
break;
}
}
if (!$port || $port > 0xffff) {
err("invalid port");
}
if (!isset($event)) {
$event = "";
}
$seeder = ($left == 0) ? "yes" : "no";
// todo client ban here
// Wanted Data From DB
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey, g.can_download"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get
// Check User
$userid = 0;
if ($MEMBERSONLY) {
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user) {
err("Cannot locate a user with that passkey!");
} elseif ($user["can_download"] == "no") {
err("You do not have permission to download.");
}
$userid = $user["id"]; //etc
}
// Check Torrent
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent) {
err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];
// Limit Number Of Peers
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
$limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
$limit = "";
}
// Check Peer New Or Old
$sql = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "") or err("Error Selecting Peers");
$res = $sql->fetch(PDO::FETCH_ASSOC);
if ($res) {
// Already Peer So Update User & Peer Table
$upthis = max(0, $uploaded - $res["uploaded"]);
$downthis = max(0, $downloaded - $res["downloaded"]);
if (($upthis > 0 || $downthis > 0)) {
if ($torrent["freeleech"] == 1) {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
// todo pdo($pdo, "UPDATE `snatched` SET `uload` = `uload` + '$upthis', `utime` = '".gmtime()."', `ltime` = `ltime` + '$elapsed' WHERE `tid` = '$torrentid' AND `uid` = '$userid'");
} else {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
// todo pdo($pdo, "UPDATE `snatched` SET `uload` = `uload` + '$upthis', `dload` = `dload` + '$downthis', `utime` = '".gmtime()."', `ltime` = `ltime` + '$elapsed' WHERE `tid` = '$torrentid' AND `uid` = '$userid'");
}
}
pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
} else {
// todo check new peer //check passkey isnt leaked, //wait time check
// New Peer So Add
pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('yes', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");
/* // todo
if ( ( $MEMBERSONLY ) && ( $seeder == 'no' ) ) {
pdo($pdo, "INSERT DELAYED INTO `snatched` (`uid`, `tid`, `stime`, `utime`) VALUES ('$userid', '$torrentid', '".gmtime()."', '".gmtime()."') ON DUPLICATE KEY UPDATE `utime` = '" . gmtime() . "'");
} else {
pdo($pdo, "INSERT DELAYED INTO `snatched` (`uid`, `tid`, `stime`, `utime`, `dload`, `completed`) VALUES ('$userid', '$torrentid', '".gmtime()."', '".gmtime()."', '".$tsize."', '1') ON DUPLICATE KEY UPDATE `utime` = '" . gmtime() . "'");
}
*/
}
// Now We Did Current Peer Lets Get All Peers
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid");
// Sort Response
$seeders = 0;
$leechers = 0;
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row['seeder'] == 'no') {
$leechers++;
} else {
$seeders++;
}
$peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$peerlist['seeders'] = $seeders;
$peerlist['leechers'] = $leechers;
$resp = "d8:intervali60e12:min intervali30e8:completei$peerlist[seeders]e10:incompletei$peerlist[leechers]e5:peersl$peerlist[list]ee";
// Now Do Events
if ($event == "stopped") {
pdo($pdo, "DELETE FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
}
if ($event == "completed") {
$updateset[] = "times_completed = times_completed + 1";
if ($MEMBERSONLY) {
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
// todo pdo($pdo, "UPDATE `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
}
// Now Update Torrent
$updateset = array();
$updateset[] = "seeders = $peerlist[seeders]";
$updateset[] = "leechers = $peerlist[leechers]";
if ($seeder == "yes") {
if ($torrent["banned"] != "yes")
$updateset[] = "visible = 'yes'";
$updateset[] = "last_action = '" . get_date_time() . "'";
}
if (count($updateset)) {
pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}
// Send Bencoded Data To File For Debug - place test.txt in root
mydebug($resp);
// Finally Send Data To Client
benc_resp_raw($resp);
<?php
// Hide Errors
error_reporting(0);
// Get Settings
require_once("backend/mysql.php");
// Set Database Settings
define("DB_HOST", $mysql_host);
define("DB_USER", $mysql_user);
define("DB_PASS", $mysql_pass);
define("DB_NAME", $mysql_db);
define('DB_CHAR', 'utf8');
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
err('The Database Details Are Incorrect');
}
// SQL Function To Display Errors
function pdo($pdo, $sql, $args = NULL)
{
try {
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
} catch (\Exception $e) {
err($e);
}
}
// Write Response To File
function mydebug($msg)
{
if (is_writeable('test.txt')) {
$fh = fopen('test.txt', 'a+');
fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
fclose($fh);
}
}
// Member Settings
$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
// Default Functions
function sqlesc($x)
{
if (!is_numeric($x)) {
$x = "'" . $x . "'";
}
return $x;
}
function unesc($x)
{
stripslashes($x);
return $x;
}
function err($msg)
{
return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}
function benc_str($s)
{
return strlen($s) . ":$s";
}
function benc_int($i)
{
return "i" . $i . "e";
}
function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
print($x);
}
exit();
}
function gmtime()
{
return strtotime(get_date_time());
}
function get_date_time($timestamp = 0)
{
if ($timestamp) {
return date("Y-m-d H:i:s", $timestamp);
} else {
return gmdate("Y-m-d H:i:s");
}
}
function portblacklisted($port)
{
if ($port >= 411 && $port <= 413) {
// direct connect
return true;
} elseif ($port == 1214) {
// kazaa
return true;
} elseif ($port >= 6346 && $port <= 6347) {
// gnutella
return true;
} elseif ($port == 4662) {
// emule
return true;
} elseif ($port == 6699) {
// winmx
return true;
}
return false;
}
// NOW WE DO THE ANNOUNCE CODE
// Agent
$agent = $_SERVER["HTTP_USER_AGENT"];
// Get Client Details
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
if (isset($_GET["$x"])) {
$GLOBALS[$x] = "" . $_GET[$x];
}
}
foreach (array("port", "downloaded", "uploaded", "left") as $x) {
$GLOBALS[$x] = 0 + $_GET[$x];
}
foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
if (!isset($x)) {
err("Missing key: $x");
}
}
$no_peer_id = (int) $_GET["no_peer_id"];
foreach (array("info_hash") as $x) {
if (strlen($GLOBALS[$x]) != 20) {
err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
}
}
unset($x);
if ($MEMBERSONLY) {
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}
$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
foreach (array("num want", "numwant", "num_want") as $k) {
if (isset($_GET[$k])) {
$rsize = (int) $_GET[$k];
break;
}
}
if (!$port || $port > 0xffff) {
err("invalid port");
}
if (!isset($event)) {
$event = "";
}
$seeder = ($left == 0) ? "yes" : "no";
// Wanted Data From DB
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get
// Check User
$userid = 0;
if ($MEMBERSONLY) {
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user) {
err("Cannot locate a user with that passkey!");
}
$userid = $user["id"]; //etc
}
// Check Torrent
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent) {
err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];
// Limit Number Of Peers
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
$limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
$limit = "";
}
// Check Peer New Or Old
$sql = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "") or err("Error Selecting Peers");
$res = $sql->fetch(PDO::FETCH_ASSOC);
if ($res) {
// Already Peer So Update User & Peer Table
$upthis = max(0, $uploaded - $res["uploaded"]);
$downthis = max(0, $downloaded - $res["downloaded"]);
if (($upthis > 0 || $downthis > 0)) {
if ($torrent["freeleech"] == 1) {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
} else {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}
}
pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
} else {
// New Peer So Add
pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");
}
// Now Do Events
if ($event == "stopped") {
pdo($pdo, "DELETE FROM peers WHERE torrent = $torrentid AND peer_id = " . sqlesc($peer_id) . "");
}
if ($event == "completed") {
$updateset[] = "times_completed = times_completed + 1";
if ($MEMBERSONLY) {
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
}
}
// Now We Did Current Peer Lets Get All Peers
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid");
// Sort Response
$seeders = 0;
$leechers = 0;
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row['seeder'] == 'no') {
$leechers++;
} else {
$seeders++;
}
$peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$peerlist['seeders'] = $seeders;
$peerlist['leechers'] = $leechers;
$resp = "d8:intervali600e12:min intervali300e8:completei$peerlist[seeders]e10:incompletei$peerlist[leechers]e5:peersl$peerlist[list]ee";
// Now Update Torrent
$updateset = array();
$updateset[] = "seeders = $peerlist[seeders]";
$updateset[] = "leechers = $peerlist[leechers]";
if ($seeder == "yes") {
if ($torrent["banned"] != "yes")
$updateset[] = "visible = 'yes'";
$updateset[] = "last_action = '" . get_date_time() . "'";
}
if (count($updateset)) {
pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}
// Send Bencoded Data To File For Debug
mydebug($resp);
// Finally Send Data To Client
benc_resp_raw($resp); <?php
// stat here
error_reporting(0);
require_once("backend/mysql.php");
// Set Database Settings
define("DB_HOST", $mysql_host);
define("DB_USER", $mysql_user);
define("DB_PASS", $mysql_pass);
define("DB_NAME", $mysql_db);
define('DB_CHAR', 'utf8');
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
err('The Database Details Are Incorrect');
}
// Register custom exception handler
// include "../app/helpers/exception_helper.php";
// set_exception_handler("handleUncaughtException");
function pdo($pdo, $sql, $args = NULL)
{
try {
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
} catch (\Exception $e) {
err($e);
}
}
$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
function sqlesc($x)
{
if (!is_numeric($x)) {
$x = "'" . $x . "'";
}
return $x;
}
function unesc($x)
{
stripslashes($x);
return $x;
}
function err($msg)
{
return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}
function benc_str($s)
{
return strlen($s) . ":$s";
}
function benc_int($i)
{
return "i" . $i . "e";
}
function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else
print($x);
exit();
}
function gmtime()
{
return strtotime(get_date_time());
}
function get_date_time($timestamp = 0)
{
if ($timestamp)
return date("Y-m-d H:i:s", $timestamp);
else
return gmdate("Y-m-d H:i:s");
}
function portblacklisted($port)
{
// direct connect
if ($port >= 411 && $port <= 413) return true;
// kazaa
if ($port == 1214) return true;
// gnutella
if ($port >= 6346 && $port <= 6347) return true;
// emule
if ($port == 4662) return true;
// winmx
if ($port == 6699) return true;
return false;
}
//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////
// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
if (isset($_GET["$x"])) {
$GLOBALS[$x] = "" . $_GET[$x];
}
}
foreach (array("port", "downloaded", "uploaded", "left") as $x) {
$GLOBALS[$x] = 0 + $_GET[$x];
}
foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
if (!isset($x)) {
err("Missing key: $x");
}
}
$no_peer_id = (int) $_GET["no_peer_id"];
//foreach (array("info_hash", "peer_id") as $x) {
foreach (array("info_hash") as $x) {
if (strlen($GLOBALS[$x]) != 20) {
err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
}
}
unset($x);
if ($MEMBERSONLY) {
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}
$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
//$peer_id = bin2hex($peer_id); todo
foreach (array("num want", "numwant", "num_want") as $k) {
if (isset($_GET[$k])) {
$rsize = (int) $_GET[$k];
break;
}
}
//PORT CHECK
if (!$port || $port > 0xffff) {
err("invalid port");
}
//TRACKER EVENT CHECK
if (!isset($event)) {
$event = "";
}
$seeder = ($left == 0) ? "yes" : "no";
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get
$userid = 0;
if ($MEMBERSONLY) {
//check passkey is valid, and get users details
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user) {
err("Cannot locate a user with that passkey!");
}
$userid = $user["id"]; //etc
}
//check torrent is valid and get torrent fields
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=" . sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent) {
err("Torrent not found on this tracker - hash = " . $info_hash);
} elseif ($torrent["banned"] == 'yes') {
err("Torrent has been banned - hash = " . $info_hash);
}
$torrentid = $torrent["id"];
//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
$limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
$limit = "";
}
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit") or err("Error Selecting Peers");
//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}
$peers .= "d2:ip" . strlen($row['ip']) . ":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";
$selfwhere = "torrent = $torrentid AND peer_id = " . sqlesc($peer_id);
// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)) {
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE $selfwhere");
$row = $res->fetch(PDO::FETCH_ASSOC);
if ($row) {
$self = $row;
}
}
// END $SELF FILL
if (!isset($self)) { //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK
} else {
$upthis = max(0, $uploaded - $self["uploaded"]);
$downthis = max(0, $downloaded - $self["downloaded"]);
if (($upthis > 0 || $downthis > 0)) { // LIVE STATS!)
if ($torrent["freeleech"] == 1) {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
} else {
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}
}
} //END WAIT AND STATS UPDATE
$updateset = array();
////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////
if ($event == "stopped") { // UPDATE "STOPPED" EVENT
$RUN = pdo($pdo, "DELETE FROM peers WHERE $selfwhere");
if ($RUN) {
if ($self["seeder"] == "yes")
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
else
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
}
}
if ($event == "completed") { // UPDATE "COMPLETED" EVENT
$updateset[] = "times_completed = times_completed + 1";
if ($MEMBERSONLY) {
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
//uncomment below if using snatched table
//SQL_Query_exec("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
} //END COMPLETED
if (isset($self)) { // NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT
pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '" . get_date_time() . "', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE $selfwhere");
if ($self["seeder"] != $seeder) {
if ($seeder == "yes") {
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
} else {
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
}
}
} else {
$ret = pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '" . get_date_time() . "', '" . get_date_time() . "', '$seeder', '$userid', " . sqlesc($agent) . ")");
if ($ret) {
if ($seeder == "yes")
$updateset[] = "seeders = seeders + 1";
else
$updateset[] = "leechers = leechers + 1";
}
}
////////////////// END TRACKER EVENT UPDATES ///////////////////
// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
$updateset[] = "visible = 'yes'";
$updateset[] = "last_action = '" . get_date_time() . "'";
}
// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset)) {
pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}
function mydebug($msg)
{
if (is_writeable('test.txt')) {
$fh = fopen('test.txt', 'a+');
fputs($fh, "[Log] " . date("d.m.Y H:i:s") . " $msg\n");
fclose($fh);
}
}
mydebug($resp);
// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp); //DO SOME BENC STUFF TO THE PEERS CONNECTION
$resp = "d8:completei$torrent[seeders]e10:downloadedi$torrent[times_completed]e10:incompletei$torrent[leechers]e";
$resp .= benc_str("interval") . "i" . $site_config['announce_interval'] . "e" . benc_str("min interval") . "i300e" . benc_str("peers");
unset($self);
while ($row = mysqli_fetch_assoc($res)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}
$peers .= "d" . benc_str("ip") . benc_str($row["ip"]);
if (!$no_peer_id)
$peers .= benc_str("peer id") . benc_str($row["peer_id"]);
$peers .= benc_str("port") . "i" . $row["port"] . "ee";
}
$resp .= "l{$peers}e";
$resp .= "ee";//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = mysqli_fetch_assoc($res)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}
$peers .= "d2:ip".strlen($row['ip']).":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";<?php
// Please Note: Languages should not be implemented here...
error_reporting(0);
// Set Database Settings
define("DB_HOST", "localhost");
define("DB_USER", "torrent1");
define("DB_PASS", "password");
define("DB_NAME", "dbname");
define('DB_CHAR', 'utf8');
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
//die(response('The Database Details Are Incorrect'));
}
// Register custom exception handler
// include "../app/helpers/exception_helper.php";
// set_exception_handler("handleUncaughtException");
function pdo($pdo, $sql, $args = NULL)
{
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
$MEMBERSONLY = true;
$MEMBERSONLY_WAIT = false;
function sqlesc($x)
{
if (!is_numeric($x)) {
$x = "'" . $x . "'";
}
return $x;
}
function unesc($x) {
stripslashes($x);
return $x;
}
function err($msg) {
return benc_resp_raw("d".benc_str("failure reason").benc_str($msg)."e");
}
function benc_str($s) {
return strlen($s) . ":$s";
}
function benc_int($i) {
return "i" . $i . "e";
}
function benc_resp_raw($x) {
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else
print($x);
exit();
}
function gmtime() {
return strtotime(get_date_time());
}
function get_date_time($timestamp = 0) {
if ($timestamp)
return date("Y-m-d H:i:s", $timestamp);
else
return gmdate("Y-m-d H:i:s");
}
function portblacklisted($port) {
// direct connect
if ($port >= 411 && $port <= 413) return true;
// kazaa
if ($port == 1214) return true;
// gnutella
if ($port >= 6346 && $port <= 6347) return true;
// emule
if ($port == 4662) return true;
// winmx
if ($port == 6699) return true;
return false;
}
//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////
// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
if (
preg_match('%^Mozilla/|^Opera/|^Links |^Lynx/%i', $agent) ||
isset($_SERVER['HTTP_COOKIE']) ||
isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ||
isset($_SERVER['HTTP_ACCEPT_CHARSET'])
)
err("torrent not registered with this tracker CODE 1");
//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey","info_hash","peer_id","ip","event") as $x) {
if(isset($_GET["$x"])) {
$GLOBALS[$x] = "" . $_GET[$x];
}
}
foreach (array("port","downloaded","uploaded","left") as $x)
$GLOBALS[$x] = 0 + $_GET[$x];
foreach (array("passkey","info_hash","peer_id","port","downloaded","uploaded","left") as $x)
if (!isset($x))
err("Missing key: $x");
$no_peer_id = (int) $_GET["no_peer_id"];
//foreach (array("info_hash", "peer_id") as $x) {
foreach (array("info_hash") as $x) {
if (strlen($GLOBALS[$x]) != 20){
err("Invalid $x (" . strlen($GLOBALS[$x]) . " - " . urlencode($GLOBALS[$x]) . ")");
}
}
unset($x);
if ($MEMBERSONLY){
if (strlen($passkey) != 32)
err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
}
$ip = $_SERVER["REMOTE_ADDR"];
$info_hash = bin2hex($info_hash);
//$peer_id = bin2hex($peer_id); todo
foreach(array("num want", "numwant", "num_want") as $k)
{
if (isset($_GET[$k]))
{
$rsize = (int) $_GET[$k];
break;
}
}
//PORT CHECK
if (!$port || $port > 0xffff)
err("invalid port");
//TRACKER EVENT CHECK
if (!isset($event))
$event = "";
$seeder = ($left == 0) ? "yes" : "no";
$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey"; //user details to get
$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get
$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get
$userid = 0;
if ($MEMBERSONLY){
//check passkey is valid, and get users details
$res = pdo($pdo, "SELECT $userfields FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? AND u.enabled = 'yes' AND u.status = 'confirmed' LIMIT 1", [$passkey]) or err("Cannot Get User Details");
$user = $res->fetch();
if (!$user)
err("Cannot locate a user with that passkey!");
$userid = $user["id"]; //etc
}
//check torrent is valid and get torrent fields
$res = pdo($pdo, "SELECT $torrentfields FROM torrents WHERE info_hash=".sqlesc($info_hash)) or err("Cannot Get Torrent Details");
$torrent = $res->fetch();
if (!$torrent)
err("Torrent not found on this tracker - hash = " . $info_hash);
if ($torrent["banned"]=='yes')
err("Torrent has been banned - hash = " . $info_hash);
$torrentid = $torrent["id"];
//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit){
$limit = "ORDER BY RAND() LIMIT $peerlimit";
}else{
$limit = "";
}
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE torrent = $torrentid $limit") or err("Error Selecting Peers")->fetch(PDO::FETCH_ASSOC);
//DO SOME BENC STUFF TO THE PEERS CONNECTION
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
if ($row["peer_id"] === $peer_id) {
$self = $row;
continue;
}
$peers .= "d2:ip".strlen($row['ip']).":$row[ip]4:porti$row[port]ee";
}
$peerlist['list'] = $peers;
$resp = "d8:intervali60e12:min intervali30e8:completei$torrent[seeders]e10:incompletei$torrent[leechers]e5:peersl$peerlist[list]ee";
$selfwhere = "torrent = $torrentid AND peer_id = ".sqlesc($peer_id);
// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)){
$res = pdo($pdo, "SELECT $peerfields FROM peers WHERE $selfwhere");
$row = $res->fetch(PDO::FETCH_ASSOC);
if ($row){
$self = $row;
}
}
// END $SELF FILL
if (!isset($self)){ //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK
}else{
$upthis = max(0, $uploaded - $self["uploaded"]);
$downthis = max(0, $downloaded - $self["downloaded"]);
if (($upthis > 0 || $downthis > 0)){ // LIVE STATS!)
if ($torrent["freeleech"] == 1){
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}else{
pdo($pdo, "UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
}
}
}//END WAIT AND STATS UPDATE
$updateset = array();
////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////
if ($event == "stopped") { // UPDATE "STOPPED" EVENT
$RUN = pdo($pdo, "DELETE FROM peers WHERE $selfwhere");
if ($RUN){
if ($self["seeder"] == "yes")
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
else
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
}
}
if ($event == "completed") { // UPDATE "COMPLETED" EVENT
$updateset[] = "times_completed = times_completed + 1";
if ( $MEMBERSONLY )
{
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '".get_date_time()."')");
//uncomment below if using snatched table
//SQL_Query_exec("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
}
}//END COMPLETED
if (isset($self)){// NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT
pdo($pdo, "UPDATE peers SET ip = " . sqlesc($ip) . ", passkey = " . sqlesc($passkey) . ", port = $port, uploaded = $uploaded, downloaded = $downloaded, to_go = $left, last_action = '".get_date_time()."', client = " . sqlesc($agent) . ", seeder = '$seeder' WHERE $selfwhere");
if ($self["seeder"] != $seeder){
if ($seeder == "yes"){
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
} else {
$updateset[] = "seeders = (CASE WHEN (seeders < 1) THEN 0 ELSE (seeders - 1) END)";
$updateset[] = "leechers = (CASE WHEN (leechers < 1) THEN 0 ELSE (leechers - 1) END)";
}
}
} else {
$ret = pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client) VALUES ('$connectable', $torrentid, " . sqlesc($peer_id) . ", " . sqlesc($ip) . ", " . sqlesc($passkey) . ", $port, $uploaded, $downloaded, $left, '".get_date_time()."', '".get_date_time()."', '$seeder', '$userid', " . sqlesc($agent) . ")");
if ($ret){
if ($seeder == "yes")
$updateset[] = "seeders = seeders + 1";
else
$updateset[] = "leechers = leechers + 1";
}
}
////////////////// END TRACKER EVENT UPDATES ///////////////////
// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
$updateset[] = "visible = 'yes'";
$updateset[] = "last_action = '".get_date_time()."'";
}
// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset))
pdo($pdo, "UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
function mydebug($msg) {
if(is_writeable('test.txt')) {
$fh = fopen('test.txt','a+');
fputs($fh,"[Log] ".date("d.m.Y H:i:s")." $msg\n");
fclose($fh);
}
}
mydebug($resp);
// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);function getimage($row, $_data)
{
if ( $row["imdb"] != '' && $_data["poster"] !='') {
$img = $_data["poster"];
} elseif ($row["tmdb"] != ''&& $_data["poster"] !='') {
$img = $_data["poster"];
} elseif ($row["image1"] != '') {
$img = $row["image1"];
} elseif ($row["image2"] != '') {
$img = $row["image2"];
} else {
$img = "assets/images/misc/default_avatar.webp";
}
return $img;
}
<?php
// DB Details
define("DB_HOST", "localhost");
define("DB_USER", "dbusername");
define("DB_PASS", "dbpassword");
define("DB_NAME", "dbname");
define('DB_CHAR', 'utf8mb4');
// Debug, true - log exception OR false - simple error to client
define('DEBUG', true);
// Debug - Allow Browsers (NEVER USE ON LIVE SITE, FOR TESTING ONLY)
define('PRINT_DEBUG', false);
// 1st Fuction PDO Prepared Statement & DEBUG
function pdo($pdo, $sql, $args = NULL, $message = 'Strange Error')
{
try {
if (!$args) {
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
} catch (\Exception $e) {
if (DEBUG) {
throw $e;
} else {
die(response($message));
}
}
}
// 2nd Fuction Response To Client
function response($peer_array, $seeders = 0, $leechers = 0)
{
if (is_string($peer_array)) {
return 'd14:failure reason' . strlen($peer_array) . ':' . $peer_array . 'e';
}
$peer_list = '';
foreach ($peer_array as $peer) {
$pid = '';
if (!isset($_GET['no_peer_id'])) {
$real_id = hex2bin($peer[2]);
$pid = '7:peer id' . strlen($real_id) . ':' . $real_id;
}
$peer_list .= 'd2:ip' . strlen($peer[0]) . ':' . $peer[0] . $pid . '4:porti' . $peer[1] . 'ee';
}
$response = 'd8:intervali60e12:min intervali30e8:completei' . $seeders . 'e10:incompletei' . $leechers . 'e5:peersl' . $peer_list . 'ee';
return $response;
}
// Set Database Connection
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHAR;
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
} catch (\Exception $e) {
die(response('The Database Details Are Incorrect'));
}
// Register custom exception handler
if (DEBUG) {
include "exception_helper.php";
set_exception_handler("handleUncaughtException");
}
// Block Browsers
$agent = $_SERVER["HTTP_USER_AGENT"] ?? 'n/a';
if (!PRINT_DEBUG && preg_match("/^Mozilla|^Opera|^Links|^Lynx/i", $agent)) {
die('What Are you doing ???');
}
// Block Unwanted Clients
//$stmt = pdo($pdo, "SELECT code FROM clients", null, 'Error in agent select')->fetchAll();
//$users_agent = substr($_GET['peer_id'], 0, 8);
//foreach ($stmt as $bannedclient) {
// if (@strpos($users_agent, $bannedclient['code']) !== false) {
// die(response('Client is banned'));
// }
//}
// Needed Fields
foreach (['info_hash', 'peer_id', 'port', 'uploaded', 'downloaded', 'left'] as $key) {
$client[$key] = $_GET[$key];
if (!isset($client[$key])) {
die(response("missing key $key"));
}
}
// Check info_hash & peer_id correct
foreach (["info_hash", "peer_id"] as $key) {
if (strlen($client[$key]) != 20) {
die(response("short peer_id or hash"));
}
}
// Check Correct Values
foreach (['uploaded', 'downloaded', 'left'] as $key) {
if (!is_numeric($client[$key]) || $client[$key] < 0) {
die(response("wierd number"));
}
}
foreach (['event'] as $key) {
$client[$key] = $_GET[$key];
}
// Check Event
if (!in_array(strtolower($client['event']), ['started', 'completed', 'stopped', ''])) {
die(response("no event"));
}
// Check Port
if (!ctype_digit($client['port']) || $client['port'] < 1 || $client['port'] > 65535) {
die(response('Invalid client port'));
}
// Check IP
$client['ip'] = $_SERVER["REMOTE_ADDR"] ?? $_GET['ip'];
// bin2hex info_hash
$client['info_hash'] = bin2hex($client['info_hash']);
// bin2hex peer_id
$client['peer_id'] = bin2hex($client['peer_id']);
// Check 20 Byte Hex String
if (strlen($client['info_hash']) != 40) {
die(response("Invalid info hash hex value."));
} elseif (strlen($client['peer_id']) != 40) {
die(response("Invalid peer id hex value."));
}
$client['passkey'] = $_GET['passkey'];
if (empty($client['passkey'])) {
die(response("no passkey"));
} elseif (strlen($client['passkey']) != 32) {
die(response("Invalid passkey (" . strlen($client['passkey']) . " - $client[passkey])"));
}
$client['seeder'] = ($client['left'] == 0) ? "yes" : "no";
// Get User
$user = array();
$stmt = pdo($pdo, "SELECT u.id, u.class, u.uploaded, u.downloaded, u.enabled, u.status, u.ip, u.passkey FROM users u INNER JOIN `groups` g ON u.class = g.group_id WHERE u.passkey=? LIMIT 1", [$client['passkey']], 'Error getting user')->fetch(PDO::FETCH_ASSOC);
foreach ($stmt as $key => $value) {
$user[$key] = $value;
}
//$role = $user['group_role_id'];
//$permission = pdo($pdo, "SELECT permission_id, can_download FROM `permissions` WHERE `permission_id`=?", [$role], 'Error getting user permission')->fetch(PDO::FETCH_ASSOC);
//foreach ($permission as $key => $value) {
// $user[$key] = $value;
//}
// Check User
if (!$user) {
die(response("Cannot locate a user with that passkey!"));
//} elseif ($user["can_download"] == "no") {
// die(response("You do not have permission to download."));
} elseif (!$user["passkey"] == $client['passkey']) {
die(response("Can NOT find user passkey."));
} elseif (!$user["enabled"] == 'yes') {
die(response("not enabled."));
} elseif (!$user["status"] == 'confirmed') {
die(response("status not confirmed."));
}
// Get Torrent
$torrent = pdo($pdo, "SELECT id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed FROM torrents WHERE info_hash=?", [$client['info_hash']], 'error getting torrent')->fetch(PDO::FETCH_ASSOC);
// Check Torrent
if (!$torrent) {
die(response("Torrent not found on this hash = $client[info_hash]"));
} elseif ($torrent["banned"] == 'yes') {
die(response("Torrent has been banned - hash = $client[info_hash]"));
}
// Get Peer
$peer = pdo($pdo, "SELECT seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey FROM peers WHERE torrent = ? AND peer_id = ? AND passkey = ?", [$torrent['id'], $client['peer_id'], $client['passkey']], 'Error getting user peer')->fetch(PDO::FETCH_ASSOC);
if (!$peer) {
// New Peer
//$countslot = pdo($pdo, "SELECT DISTINCT torrent FROM peers WHERE userid =? AND seeder=?", [$user['id'], 'no'], 'Error getting user slots')->rowCount();
//if ($slot >= $user['maxslots']) {
// die(response("Maximum Slot exceeded! You may only download $slot torrent at a time."));
//}
pdo($pdo, "INSERT INTO peers (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client)VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ['yes', $torrent['id'], $client['peer_id'], $client['ip'], $client['passkey'], $client['port'], $client['uploaded'], $client['downloaded'], $client['left'], gmdate("Y-m-d H:i:s"), gmdate("Y-m-d H:i:s"), $client['seeder'], $user['id'], $agent], 'Error getting inserting peer');
//pdo($pdo, "INSERT INTO `snatched` (`uid`, `tid`, `start_time`, `upload_time`, `completed`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `upload_time` = ?", [$user['id'], $torrent['id'], strtotime(gmdate("Y-m-d H:i:s")), strtotime(gmdate("Y-m-d H:i:s")), $client['seeder'], gmdate("Y-m-d H:i:s")], 'Error getting inserting snatched');
} else {
// Update Peer
$elapsed = ($peer['seeder'] == 'yes') ? 600 - floor(($peer['ez'] - time()) / 60) : 0;
$upthis = max(0, $client['uploaded'] - $peer["uploaded"]);
$downthis = max(0, $client['downloaded'] - $peer["downloaded"]); // $downthis = $user['class'] == _VIP ? 0 : max(0, $client['downloaded'] - $peer["downloaded"]);
if ($upthis > 0 || $downthis > 0 || $elapsed > 0) {
if ($torrent["freeleech"] == 1) {
pdo($pdo, "UPDATE users SET uploaded = uploaded + ? WHERE id=?", [$upthis, $userid], 'Error getting updating user');
//pdo($pdo, "UPDATE LOW_PRIORITY `snatched` SET `upload` = `upload` + '$upthis', `upload_time` = '" . strtotime(gmdate("Y-m-d H:i:s")) . "', `last_time` = `last_time` + '$elapsed', completed = ? WHERE `tid` = ? AND `uid` = ?", [$client['seeder'], $torrent['id'], $user['id']], 'Error getting updating snatched');
} else {
pdo($pdo, "UPDATE users SET uploaded = uploaded + ?, downloaded = downloaded + ? WHERE id=?", [$upthis, $downthis, $user['id']], 'Error getting updating snatched');
//pdo($pdo, "UPDATE LOW_PRIORITY `snatched` SET `upload` = `upload` + '$upthis', `download` = `download` + '$downthis', `upload_time` = '" . strtotime(gmdate("Y-m-d H:i:s")) . "', `last_time` = `last_time` + '$elapsed', completed = ? WHERE `tid` = ? AND `uid` = ?", [$client['seeder'], $torrent['id'], $user['id']], 'Error getting updating snatched');
}
}
pdo($pdo, "UPDATE peers SET ip = ?, passkey = ?, port = ?, uploaded = ?, downloaded = ?, to_go = ?, last_action = ?, client = ?, seeder = ? WHERE torrent = ? AND peer_id = ?", [$client['ip'], $client['passkey'], $client['port'], $client['uploaded'], $client['downloaded'], $client['left'], gmdate("Y-m-d H:i:s"), $agent, $client['seeder'], $torrent['id'], $client['peer_id']], 'Error getting updating peer');
}
// Event Completed
if ($client['event'] == "completed") {
pdo($pdo, "INSERT INTO completed (userid, torrentid, date) VALUES (?,?,?) ON DUPLICATE KEY UPDATE date = ?", [$user['id'], $torrent['id'], gmdate("Y-m-d H:i:s"), gmdate("Y-m-d H:i:s")], 'Error getting inserting completed');
//pdo($pdo, "UPDATE `snatched` SET `completed` = ? WHERE `tid` = ? AND `uid` = ?", [1, $torrent['id'], $user['id']], 'Error snatched complete');
$torrent['times_completed']++;
}
// Event Stopped Delete & Return Empty Response
if ($client['event'] == "stopped") {
pdo($pdo, "DELETE FROM peers WHERE torrent = ? AND peer_id = ?", [$torrent['id'], $client['peer_id']], 'Error getting updating peer');
//die(response(array(), 0, 0));
}
// Get Peers For Response
$all_peers = pdo($pdo, "SELECT peer_id, ip, port, seeder FROM peers WHERE torrent = ?", [$torrent['id']], 'Error getting all peers')->fetchAll();
$response_array = array();
$seeders = 0;
$leechers = 0;
foreach ($all_peers as $peer) {
if ($peer['seeder'] == 'no') {
$leechers++;
} else {
$seeders++;
}
$response_array[] = array($peer['ip'], $peer['port'], $peer['peer_id']);
}
// Update Torrent
if ($torrent["banned"] != "yes") {
pdo($pdo, "UPDATE torrents SET last_action = ?, leechers = ?, seeders = ?, times_completed = ?, visible = ? WHERE id=?", [gmdate("Y-m-d H:i:s"), $leechers, $seeders, $torrent['times_completed'], 'yes', $torrent['id']], 'Error getting all peers');
}
// Show Response
die(response($response_array, $seeders, $leechers));<?php
//start add 19.01.2020 DrTech76, Exception handler verbose output
/**
* Prepares verbose output of the debug backtrace, for inclusion in trace and debug outputs and logging
* Parameters:
* @param backtrace - the output of a call to debug_backtrace() function
* @param depth - How many levels back to read the traces for
* Returns:
* @return string
**/
function get_verbose_backtrace($backtrace = null, $depth = 0)
{
$skipFirst = false;
$output = array();
if (!(isset($depth) and is_numeric($depth))) { //no limit
$depth = 0;
} else {
$depth = intval($depth);
}
if (!(isset($backtrace) and is_array($backtrace))) {
if (function_exists("ReflectionFunction")) {
$dbtRef = new ReflectionFunction("debug_backtrace");
if ($dbtRef->getNumberOfParameters() == 2) {
$backtrace = debug_backtrace(true, $depth);
} else {
$backtrace = debug_backtrace();
}
} else {
$backtrace = debug_backtrace();
}
$skipFirst = true; //the first item will be this function so skip accordingly
}
foreach ($backtrace as $currDepth => $trace) {
if ($skipFirst === true and $currDepth === 0) {
continue;
}
if (!(isset($trace["file"]) or isset($trace["function"]))) {
continue;
}
$isObject = (isset($trace["class"]));
$function = $trace["function"];
//$output[]="Function: ReflectionMethod exists ".var_export(function_exists("ReflectionMethod"),true);
//$output[]="Function: ReflectionFunction exists ".var_export(function_exists("ReflectionFunction"),true);
if ($isObject === true) {
if (function_exists("ReflectionMethod")) {
$funcParamsRef = new ReflectionMethod($trace["class"], $trace["function"]);
}
$function = $trace['class'] . $trace['type'] . $function;
} else {
if (function_exists("ReflectionFunction")) {
$funcParamsRef = new ReflectionFunction($trace["function"]);
}
}
$currTrace = "\n[" . $currDepth . "] File: " . ((isset($trace["file"])) ? $trace["file"] : "Undefined") . " Line: " . ((isset($trace["line"])) ? $trace["line"] : "Undefined");
$currTrace .= "\nFunction: " . $function;
if (isset($trace["args"])) {
$currTrace .= "\nCall parameters";
if (isset($funcParamsRef)) {
$funcParams = $funcParamsRef->getParameters();
foreach ($funcParams as $fpIndex => $funcParam) {
$currTrace .= "\nParam: " . $funcParam["name"] . " Passed value: " . ((isset($trace["args"][$fpIndex])) ? var_export($trace["args"][$fpIndex], true) : "[Not passed]: " . (($funcParam->isDefaultValueAvailable() === true) ? "[Using the Default value]" . var_export($funcParam->getDefaultValue(), true) : "[No Default value is available]"));
}
} else {
foreach ($trace["args"] as $fpIndex => $funcParam) {
$currTrace .= "\nParam[" . $fpIndex . "]: Passed value: " . var_export($trace["args"][$fpIndex], true);
}
}
}
$output[] = $currTrace;
}
if (count($output) > 0) {
$output = array_merge(array("Call Stack"), $output);
}
return join("\n", $output);
}
// Debug Complex Exception Log & Redirect
function handleUncaughtException($e)
{
// Construct the error string
$error = "\nUncaught Exception: " . ($message = date("Y-m-d H:i:s - "));
$error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";
// Add verbose trace and debug output
$error .= "\n" . get_verbose_backtrace($e->getTrace());
// Log details of error in a file
error_log($error, 3, "exception_log.txt");
//autolink(URLROOT, Lang::T("OOPS_ERR"));
}