Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
New Announce (v3) In Progress
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / Torrent Trader / v3 Support

2020-09-12 06:24:19
The announce.php is over 20 years old and i have put off updating the torrent side of for ages but needed doing so here is some thing im playing with
[color=rgb(247, 218, 100)]UPDATED 19/09/20[/color]

Add Database.php to backend folder (pdo connection)

Replace announce.php ( i use snatched mod)

<?php
require 'backend/config.php';
require 'backend/Database.php';

// Use the correct content-type
header("Content-type: Text/Plain");
header("Connection: Close");

// Add settings
define("__TTURL", $site_config['SITEURL']);
define("__MEMBERSONLY", $site_config["MEMBERSONLY"]);
define("__MEMBERSONLY_WAIT", $site_config["MEMBERSONLY_WAIT"]);
define('__INTERVAL', 1800); // Peer announce interval (Seconds)
define('__TIMEOUT', 60); // Time out if peer is this late to re-announce (Seconds)
define('__INTERVAL_MIN', 600); // Minimum announce interval (Seconds), Most clients honor this, but not all
define('__MAX_PPR', 25); // Never encode more than this number of peers in a single request

// Bencoding function, returns a bencoded dictionary (You may go ahead and enter custom keys in the dictionary)
function track($list, $c=0, $i=0, $completed=0) {
   global $site_config;
   if (is_string($list)) { // Did we get a string? Return an error to the client
       return 'd14:failure reason'.strlen($list).':'.$list.'e';
   }
   $p = ''; // Peer directory
   foreach($list as $d) { // Runs for each client
       
       $pid = '';
       if (!isset($no_peer_id)) { // Send out peer_ids in the reply
           $real_id = $d[2];
           $pid = '7:peer id'.strlen($real_id).':'.$real_id;
       }
       
       $p .= 'd2:ip'.strlen($d[0]).':'.$d[0].$pid.'4:porti'.$d[1].'ee';
   }

   // Add some other paramters in the dictionary and merge with peer list
      $r = 'd8:completei'.$c.'e10:downloadedi'.$completed.'e10:incompletei'.$i.'e8:intervali'.$site_config['announce_interval'].'e12:min intervali'.$site_config['announce_interval'].'e5:peersl'.$p.'eee';
   return $r;
}

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)) {
   die("No Browser Access");
}

// GET DETAILS OF PEERS ANNOUNCE
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)) {
       die(track("Missing key: $x"));
   }
}

if (strlen($peer_id) != 20) {
   die(track("Invalid peer_id"));
}

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

if (strlen($GLOBALS['info_hash']) == 20) {
   $GLOBALS['info_hash'] = bin2hex($GLOBALS['info_hash']);
} else if (strlen($GLOBALS['info_hash']) != 40) {
   die(track("Invalid info hash value."));
}

$GLOBALS['info_hash'] = strtolower($GLOBALS['info_hash']);

if (__MEMBERSONLY) {
   if (strlen($passkey) != 32) {
       die(track("Invalid passkey (" . strlen($passkey) . " - $passkey)"));
   }

}

$ip = $_SERVER["REMOTE_ADDR"];

foreach (array("num want", "numwant", "num_want") as $k) {
   if (isset($_GET[$k])) {
       $rsize = (int) $_GET[$k];
       break;
   }
}

//PORT CHECK
if (!$port || $port > 0xffff) {
   die(track("invalid port"));
}

//TRACKER EVENT CHECK
if (!isset($event)) {
   $event = "";
}

$seeder = ($left == 0) ? "yes" : "no";

if (portblacklisted($port)) {
   die(track("Port $port is blacklisted."));
}

$dbh = new Database();

$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

$userid = 0;
if (__MEMBERSONLY) {
   //check passkey is valid, and get users details
   $res = $dbh->run("
          SELECT $userfields
          FROM users u
          INNER JOIN groups g
          ON u.class = g.group_id
          WHERE u.passkey=? AND u.enabled = ? AND u.status = ? LIMIT 1", [$passkey, 'yes', 'confirmed'])
           or die(track("Cannot Get User Details"));
   $user = $res->fetch(PDO::FETCH_ASSOC);
   if (!$user) {
       die(track("Cannot locate a user with that passkey!"));
   }

   if ($user["can_download"] == "no") {
       die(track("You do not have permission to download."));
   }

   $userid = $user["id"]; //etc
}

//check torrent is valid and get torrent fields
$res = $dbh->run("
      SELECT $torrentfields
      FROM torrents
      WHERE info_hash=?
      ", [$info_hash]) or die(track("Cannot Get Torrent Details"));
$torrent = $res->fetch(PDO::FETCH_ASSOC);

if (!$torrent) {
   die(track("Torrent not found on this tracker - hash = " . $info_hash));
}

if ($torrent["banned"] == 'yes') {
   die(track("Torrent has been banned - hash = " . $info_hash));
}

$torrentid = $torrent["id"];
$numpeers = $torrent["numpeers"];
$updateset = array();

// Check if peer has been announced before
$res = $dbh->run("
      SELECT $peerfields
      FROM peers
      WHERE torrent = $torrentid LIMIT 1")
      or die(track("Error Selecting Peers"));

unset($current_peer);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
   if ($row["peer_id"] === $peer_id) {
       $current_peer = $row;
       continue;
   }
}

// So it's new lets do some checks
if (!isset($current_peer)) {
   // Check connected
   $sockres = @fsockopen($ip, $port, $errno, $errstr, 5);
   if (!$sockres) {
       $connectable = "no";
   } else {
       $connectable = "yes";
   }
   @fclose($sockres);
   
   if (__MEMBERSONLY) {
       // Check slots
       $countslot = $dbh->run("
                    SELECT DISTINCT torrent
                    FROM peers WHERE userid =? AND seeder=?", [$userid, 'no']);
       $slot = $countslot->rowCount();
       $maxslot = $dbh->run("
                  SELECT `maxslots`
                  FROM `groups`
                  WHERE `group_id` = $user[class]")->fetchColumn();
       if ($slot >= $maxslot) {
           die(track("Maximum Slot exceeded! You may only download $maxslot torrent at a time."));
       }
       //check passkey isnt leaked
       $sql = $dbh->run("
                SELECT COUNT(*)
                FROM peers
                WHERE torrent=? AND passkey=?
                ", [$torrentid, $passkey]);
       $valid = $sql->rowCount();
       if ($valid >= 1 && $seeder == 'no') {
           die(track("Connection limit exceeded! You may only leech from one location at a time."));
       }

       if ($valid >= 3 && $seeder == 'yes') {
           die(track("Connection limit exceeded!"));
       }

   }
   // Snatch
   if ((__MEMBERSONLY) && (($seeder == 'no' && $torrent['freeleech'] == 0))) {
       $dbh->run("INSERT INTO `snatched` (`uid`, `tid`, `stime`, `utime`) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE `utime` = ?", [$userid, $torrentid, gmtime(), gmtime(), gmtime()]);
   }
   // Insert announced peer
   $ret = $dbh->run("
      INSERT INTO peers
      (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client)
      VALUES
      (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
      [$connectable, $torrentid, $peer_id, $ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), get_date_time(), $seeder, $userid, $agent]);

   if ($ret) {
       if ($seeder == "yes") {
          $updateset[] = "seeders = seeders + 1";
       } else {
          $updateset[] = "leechers = leechers + 1";
       }
   }

} else { // it is a old peer
   // snatch
   $elapsed = ($current_peer['seeder'] == 'yes') ? $site_config['announce_interval'] - floor(($current_peer['ez'] - time()) / 60) : 0; //
   $upthis = max(0, $uploaded - $current_peer["uploaded"]);
   $downthis = max(0, $downloaded - $current_peer["downloaded"]);

   if (($upthis > 0 || $downthis > 0 || $elapsed > 0) && $userid) { // LIVE STATS!)
       if ($torrent["freeleech"] == 1) {
           $dbh->run("UPDATE users SET uploaded = uploaded + $upthis
                      WHERE id=$userid") or die(track("Tracker error: Unable to update stats"));
       } else {
           $dbh->run("UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis
                      WHERE id=$userid") or die(track("Tracker error: Unable to update stats"));
           // snatch
           $dbh->run("UPDATE LOW_PRIORITY `snatched`
                      SET `uload` = `uload` + '$upthis', `dload` = `dload` + '$downthis', `utime` = '" . gmtime() . "', `ltime` = `ltime` + '$elapsed'
                      WHERE `tid` = '$torrentid'
                      AND `uid` = '$userid'");
       }
   }

   $peerupd = $dbh->run("
              UPDATE peers
              SET ip = ?, passkey = ?, port = ?, uploaded = ?, downloaded = ?, to_go = ?, last_action = ?, client = ?, seeder = ? WHERE torrent = ? AND peer_id = ?",
              [$ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), $agent, $seeder, $torrentid, $peer_id]
   );

   if ($peerupd && $current_peer["seeder"] != $seeder) {
       if ($seeder == "yes") {
           $updateset[] = "seeders = seeders + 1";
           $updateset[] = "leechers = leechers - 1";
       } else {
           $updateset[] = "seeders = seeders - 1";
           $updateset[] = "leechers = leechers + 1";
       }
   }

   if ($event === 'stopped') {
       // DELETE PEER AND REMOVE SEEDER OR LEECHER
       if (isset($current_peer)) {
           $q = $dbh->run(
               'DELETE FROM peers WHERE torrent = ? AND passkey = ?',
               [$torrentid, $passkey]
           );
           if ($q->rowCount()) {
               if ($seeder == "yes") {
                   $updateset[] = "seeders = seeders - 1";
               } else {
                   $updateset[] = "leechers = leechers - 1";
               }
           }
       }
   }
} //END

// UPDATE "COMPLETED" EVENT
if ($event == "completed") {
   $updateset[] = "times_completed = times_completed + 1";

   if (__MEMBERSONLY) {
       $dbh->run("INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
   }
   // snatch
   $dbh->run("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
} //END COMPLETED

// 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)) {
   $dbh->run("UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or die(track("Tracker error: Unable to update torrent"));
}

//Now get data from peers table
$peerlimit = 50;
// $numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
   $limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
   $limit = "";
}

// Select ip, port, peer_id to send back to client
$res = $dbh->run("
      SELECT ip, port, peer_id
      FROM peers
      WHERE torrent = $torrentid $limit") ;
 
$reply = array(); //To be encoded and sent to the client
while ($r=$res->fetch(PDO::FETCH_ASSOC)) { //Runs for every client with the same infohash
   $reply[] = array($r['ip'], $r['port'], $r['peer_id']);
}

try {
$select_peers = $dbh->run("
      SELECT seeders, leechers, times_completed
      FROM torrents
      WHERE info_hash=? LIMIT 1
      ", [$info_hash]);
$seeders = 0;
$leechers = 0;
$completed = 0;
if ($r = $select_peers->fetch(PDO::FETCH_ASSOC))
{
   $seeders = $r['seeders'];
   $leechers = $r['leechers'];
   $completed = $r['times_completed'];
}

} catch (PDOException $e) {
   die(track('Unable to select:'.$e->getMessage()));
}

// Final output to client
die(track($reply, $seeders, $leechers, $completed));
Database.zip
Download
Unknown User
2020-09-12 10:37:08
What will happen if 10.000 bittorrent users are using at any point of time /announce.php without stopping?

There are too many queries, serious rate limiting and network bytes shuffling will be required.

Don't even attempt doing this on big sites and cloudflare. If you do use http method  cloudflare will be contacting you to pay for overusage of the websockets.
2020-09-12 20:07:54
It is marked in progress so shouldn't be tried if you have 10,000 torrents but I assume it would be like a server going down for a hour and restarting with current announce
There is less querys then the v2 but at the minute are quite broad for testing purposes its the events where any improvement can be made the rest is solid off top of my head we need to update completed, torrent and snatched tables most of which is covered in the section from the old announce just need to simplify it
2020-09-13 03:43:49
Anyways, see the PM about token hashes. It’s a very real problem with passkey leaking. I wonder how many if not all are effected?

my announce

$token = md5('token{' . $data['torrent_id'] . ',' . $user_row['passkey'] . '}');
if (!hash_equals($token, $data['token'])) fail('access denied');
2020-09-18 23:32:26
First post updated, seems to work fine i have added pdo class for v3 backend, sure i can get this slimmer

here is the old announce in pdo ([color=rgb(247, 218, 100)]dont use for comparison to first post only[/color]) first post for v3
<?php
require 'config/config.php';
require 'core/Database.php';

define("TTURL", $config['SITEURL']);
// Register custom exception handler
include "helpers/exception_helper.php";
set_exception_handler("handleUncaughtException");

$MEMBERSONLY = $config["MEMBERSONLY"];
$MEMBERSONLY_WAIT = $config["MEMBERSONLY_WAIT"];

function is_valid_id($id)
{
   return is_numeric($id) && ($id > 0) && (floor($id) == $id);
}

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 (extension_loaded('zlib') && !ini_get('zlib.output_compression') && $_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)) {
   die("No");
}

//GET DETAILS OF PEERS ANNOUNCE
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];
}

if (strpos($passkey, "?")) {
   $tmp = substr($passkey, strpos($passkey, "?"));
   $passkey = substr($passkey, 0, strpos($passkey, "?"));
   $tmpname = substr($tmp, 1, strpos($tmp, "=") - 1);
   $tmpvalue = substr($tmp, strpos($tmp, "=") + 1);
   $GLOBALS[$tmpname] = $tmpvalue;
}

foreach (array("passkey", "info_hash", "peer_id", "port", "downloaded", "uploaded", "left") as $x) {
   if (!isset($$x)) {
       err("Missing key: $x");
   }
}

if (strlen($peer_id) != 20) {
   err("Invalid peer_id");
}

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

if (strlen($GLOBALS['info_hash']) == 20) {
   $GLOBALS['info_hash'] = bin2hex($GLOBALS['info_hash']);
} else if (strlen($GLOBALS['info_hash']) != 40) {
   err("Invalid info hash value.");
}

$GLOBALS['info_hash'] = strtolower($GLOBALS['info_hash']);

if ($MEMBERSONLY) {
   if (strlen($passkey) != 32) {
       err("Invalid passkey (" . strlen($passkey) . " - $passkey)");
   }

}

$ip = $_SERVER["REMOTE_ADDR"];

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";

$dbh = new Database();

//Agent Ban Moved To DB
$agentarray = $dbh->run("
             SELECT agent_name
             FROM agents
             ")->fetchAll(PDO::FETCH_COLUMN);
$useragent = substr($peer_id, 0, 8);
foreach ($agentarray as $bannedclient) {
   if (@strpos($useragent, $bannedclient) !== false) {
       err("Client is banned");
   }
}

//End Agent Bans

if (portblacklisted($port)) {
   err("Port $port is blacklisted.");
}

$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

$userid = 0;
if ($MEMBERSONLY) {
   //check passkey is valid, and get users details
   $res = $dbh->run("
          SELECT $userfields
          FROM users u
          INNER JOIN groups g
          ON u.class = g.group_id
          WHERE u.passkey=? AND u.enabled = ? AND u.status = ? LIMIT 1", [$passkey, 'yes', 'confirmed'])
           or err("Cannot Get User Details");
   $user = $res->fetch(PDO::FETCH_ASSOC);
   if (!$user) {
       err("Cannot locate a user with that passkey!");
   }

   if ($user["can_download"] == "no") {
       err("You do not have permission to download.");
   }

   $userid = $user["id"]; //etc
}

//check torrent is valid and get torrent fields
$res = $dbh->run("
      SELECT $torrentfields
      FROM torrents
      WHERE info_hash=?
      ", [$info_hash]) or err("Cannot Get Torrent Details");
$torrent = $res->fetch(PDO::FETCH_ASSOC);

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 = $dbh->run("
      SELECT $peerfields
      FROM peers
      WHERE torrent = $torrentid $limit")
      or err("Error Selecting Peers");

//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" . $config['announce_interval'] . "e" . benc_str("min interval") . "i300e" . benc_str("peers");
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
   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";

$selfwhere = "torrent = $torrentid AND peer_id = $peer_id";

// FILL $SELF WITH DETAILS FROM PEERS TABLE (CONNECTING PEERS DETAILS)
if (!isset($self)) {

   if ($MEMBERSONLY) { // todo slots mod
       $countslot = $dbh->run("
                    SELECT DISTINCT torrent
                    FROM peers WHERE userid =? AND seeder=?", [$userid, 'no']);
       $slot = $countslot->rowCount();
       $maxslot = $dbh->run("
                  SELECT `maxslots`
                  FROM `groups`
                  WHERE `group_id` = $user[class]")->fetchColumn();
       if ($slot >= $maxslot) {
           err("Maximum Slot exceeded! You may only download $maxslot torrent at a time.");
       }

   }

   //check passkey isnt leaked
   if ($MEMBERSONLY) {
       $sql = $dbh->run("
                SELECT COUNT(*)
                FROM peers
                WHERE torrent=? AND passkey=?
                ", [$torrentid, $passkey]);
       $valid = $sql->rowCount();
       if ($valid >= 1 && $seeder == 'no') {
           err("Connection limit exceeded! You may only leech from one location at a time.");
       }

       if ($valid >= 3 && $seeder == 'yes') {
           err("Connection limit exceeded!");
       }

   }

   $res = $dbh->run("SELECT $peerfields FROM peers WHERE torrent = ? AND peer_id = ?", [$torrentid, $peer_id]);
   $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
   if ($MEMBERSONLY_WAIT && $MEMBERSONLY) {
       //wait time check
       if ($left > 0 && in_array($user["class"], explode(",", $config["WAIT_CLASS"]))) { //check only leechers and lowest user class
           $gigs = $user["uploaded"] / (1024 * 1024 * 1024);
           $elapsed = floor((gmtime() - $torrent["ts"]) / 3600);
           $ratio = (($user["downloaded"] > 0) ? ($user["uploaded"] / $user["downloaded"]) : 1);
           if ($ratio == 0 && $gigs == 0) {
               $wait = $config["WAITA"];
           } elseif ($ratio < $config["RATIOA"] || $gigs < $config["GIGSA"]) {
               $wait = $config["WAITA"];
           } elseif ($ratio < $config["RATIOB"] || $gigs < $config["GIGSB"]) {
               $wait = $config["WAITB"];
           } elseif ($ratio < $config["RATIOC"] || $gigs < $config["GIGSC"]) {
               $wait = $config["WAITC"];
           } elseif ($ratio < $config["RATIOD"] || $gigs < $config["GIGSD"]) {
               $wait = $config["WAITD"];
           } else {
               $wait = 0;
           }

           if ($elapsed < $wait) {
               err("Wait Time (" . ($wait - $elapsed) . " hours) - Visit " . $config["SITEURL"] . " for more info");
           }

       }
   }
   $sockres = @fsockopen($ip, $port, $errno, $errstr, 5);
   if (!$sockres) {
       $connectable = "no";
   } else {
       $connectable = "yes";
   }

   @fclose($sockres);

} else {
   // snatch
   $elapsed = ($self['seeder'] == 'yes') ? $config['announce_interval'] - floor(($self['ez'] - time()) / 60) : 0; //
   $upthis = max(0, $uploaded - $self["uploaded"]);
   $downthis = max(0, $downloaded - $self["downloaded"]);

   if (($upthis > 0 || $downthis > 0 || $elapsed > 0) && is_valid_id($userid)) { // LIVE STATS!)
       if ($torrent["freeleech"] == 1) {
           $dbh->run("UPDATE users SET uploaded = uploaded + $upthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
       } else {
           $dbh->run("UPDATE users SET uploaded = uploaded + $upthis, downloaded = downloaded + $downthis WHERE id=$userid") or err("Tracker error: Unable to update stats");
           // snatch
           $dbh->run("UPDATE LOW_PRIORITY `snatched` SET `uload` = `uload` + '$upthis', `dload` = `dload` + '$downthis', `utime` = '" . gmtime() . "', `ltime` = `ltime` + '$elapsed' WHERE `tid` = '$torrentid' AND `uid` = '$userid'");
       }
   }
} //END WAIT AND STATS UPDATE

$updateset = array();

////////////////// NOW WE DO THE TRACKER EVENT UPDATES ///////////////////

if ($event == "stopped") { // UPDATE "STOPPED" EVENT
   // SNATCHED
   $res_se = $dbh->run("SELECT uid, utime, tid FROM snatched WHERE tid = ? AND uid = ?", [$torrentid, $userid]);
   while ($row_se = $res_se->fetch(PDO::FETCH_ASSOC)) {
   $dbh->run("UPDATE snatched SET utime  =? WHERE completed =? AND tid =? AND uid =?", [$dt, 'yes', $row_se['tid'], $row_se['uid']]);
   }


   $sql = $dbh->run("DELETE FROM peers WHERE torrent = ? AND peer_id = ?", [$torrentid, $peer_id]);
   if($sql) {
if ($self["seeder"] == "yes") {
           $updateset[] = "seeders = seeders - 1";
       } else {
           $updateset[] = "leechers = leechers - 1";
       }
       

   }
}

if ($event == "completed") { // UPDATE "COMPLETED" EVENT
   $updateset[] = "times_completed = times_completed + 1";

   if ($MEMBERSONLY) {
       $dbh->run("INSERT INTO completed (userid, torrentid, date) VALUES ($userid, $torrentid, '" . get_date_time() . "')");
   }

   // snatch
   $dbh->run("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

   $peerupd = $dbh->run("
           UPDATE peers
           SET ip = ?, passkey = ?, port = ?, uploaded = ?, downloaded = ?, to_go = ?, last_action = ?, client = ?, seeder = ? WHERE torrent = ? AND peer_id = ?",
           [$ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), $agent, $seeder, $torrentid, $peer_id]);

   if ($peerupd && $self["seeder"] != $seeder) {
       if ($seeder == "yes") {
           $updateset[] = "seeders = seeders + 1";
           $updateset[] = "leechers = leechers - 1";
       } else {
           $updateset[] = "seeders = seeders - 1";
           $updateset[] = "leechers = leechers + 1";
       }
   }

} else {

   $ret = $dbh->run("
          INSERT INTO peers
          (connectable, torrent, peer_id, ip, passkey, port, uploaded, downloaded, to_go, started, last_action, seeder, userid, client)
          VALUES
          (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [$connectable, $torrentid, $peer_id, $ip, $passkey, $port, $uploaded, $downloaded, $left, get_date_time(), get_date_time(), $seeder, $userid, $agent]);

   // snatch
   if (($MEMBERSONLY) && (($seeder == 'no' && $torrent['freeleech'] == 0))) {
       $dbh->run("INSERT INTO `snatched` (`uid`, `tid`, `stime`, `utime`) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE `utime` = ?", [$userid, $torrentid, gmtime(), gmtime(), gmtime()]);
   }

   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)) {
   $dbh->run("UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}

// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 1
  • Members: 0
  • Guests online: 1
  • Comments: 3
  • Messages: 1,728