A number of updates have been applied in announce.php BETA 7.

- Happy Hour  (Saturday, Sunday) - Will be config setting in BETA8
- Updated stats push to client (Times Completed table JOIN with NULLIF condition - uTorrent, Bittorrent, etc will see new field value in Trackers tab in client)
- Ratio-faker tool check
- Extended shoutbox notifications

BETA 8 (Management Release):

- IP check / banning
- IP Passkey check / limiting
- Announce Interval control
- Web Seeders

I dont see a lot left to add as it is practically complete and handling a ton of bandwidth and users very efficiently. As I observe mainstream announce scripts out there in the wild (like UNIT3D, etc) I will port over.
As you know (if you are in this forum category), I don't really support or maintain other editions as this is custom and way west of the rest of the codebase here on TorrentTrader.xyz, but I share for those using
this script kindly, and for those who wish to study the code and learn or use as they may.

I've spent day and night and day again on this script (mostly the summertime during lockdown) to improve at a maximum allocation of spare time and LONG nights following a couch crash most of the next day to let the brain cool off. I am very proud of this light script and its efficiency.

It just may be 1 more file update before its a final wrap and I move on to other portions of my community, such as social aspects and web-based client.


<?
// Switch-Torrents - Announce.php - BETA 7 - December/2020
require_once '../site.php';
require_once '../bencoding.php';
$db->connect();

$db->query_params('DELETE FROM peers WHERE last_announce + ' . $db->interval('1 hour') . ' < CURRENT_TIMESTAMP');

header('Content-Type: text/plain');

function fail($reason) {
   die(bencode(array('failure reason' => $reason)));
}

function ip2bytes($ip) {
   $res = '';
   $parts = explode('.', $ip);
   if (count($parts) !== 4) return null;
   for ($i = 0; $i < 4; $i++) {
       $b = $parts[$i];
       if (!is_numeric($b)) return null;
       $b = intval($b);
       if ($b < 0 || $b >= 256) return null;
       $res .= chr($b);
   }
   return $res;
}

// Check Peer ID if banned - Sep 5, 2020
function isPeerIDBanned($peer_id, $torrent_id, $passkey)
{
   global $db, $CONFIG;
   if (array_key_exists('ban_peer_ids', $CONFIG)) {
       $valid = $db->query_params('SELECT chosen_peer_id, torrent_id, passkey FROM peers WHERE torrent_id = :torrent_id AND passkey = :passkey', array('torrent_id' => $torrent_id,'passkey' => $passkey)) or fail('db error');
       foreach ($CONFIG as $key) {
           foreach ($valid as $peer) {
               if ($CONFIG['ban_peer_ids'] == $peer['chosen_peer_id']) {
                   $message = sprintf('Peer ID banned - %s', $peer['chosen_peer_id']);
                   $db->query_params('INSERT INTO announcelogs (message) VALUES (:message)', array('message' => $message)); // Log the event
                   fail(sprintf('Peer ID banned - %s', $peer['chosen_peer_id']));
               }
           }
       }
   } else {
       return;
   }
}

function isConnectable($ip, $port) {
   $fp = @fsockopen($ip, $port, $errno, $errstr, 0.1);
   if (!$fp) {
       return false;
   } else {
       fclose($fp);
       return true;
   }
}

$keys = array(
   'downloaded' => true,
   'uploaded' => true,
   'passkey' => false,
   'username' => false,
   'torrent_id' => false,
   'token' => false,
   'info_hash' => true,
   'peer_id' => true,
   'port' => true,
   'no_peer_id' => false,
   'ip' => false,
   'numwant' => false,
   'event' => false,
   'left' => true,
   'compact' => false
);

$data = array();
foreach ($keys as $key => $req) {
   if (array_key_exists($key, $_GET)) {
       $data[$key] = $_GET[$key];
   } else if ($req) {
       fail(sprintf('missing key: %s', $key));
   }
}

// Seeder or not
$seeder = ($data['left'] == 0) ? 'yes' : 'no';

// Web seeder - Oct 18, 2020 - experimental - peers.webseed
//$webseeder = ((isset($data['webseeder']) && $data['webseeder'] == 'yes' && $seeder == 'yes') ? 'yes' : 'no');

// Get client info
$client = substr($data['peer_id'], 0, 8);

$connect = isConnectable($data['ip'], $data['port']);
if ($connect) {
   $connectable = 'yes';
}else{
   $connectable = 'no';
}

$data['info_hash'] = bin2hex($data['info_hash']);
$data['peer_id'] = bin2hex($data['peer_id']);

// Token authentication - Oct 4, 2020 - Decode token hash => substitute string order => verify passkey => auth peer/user
if ($data['passkey']) {
   $passkey = $data['passkey']; // legacy
}else{
   $passkey = substr(base64_decode($data['token'], true), 11, strlen(substr(base64_decode($data['token'], true), 12)));
}

$res = $db->query_params('SELECT slots, user_id, passkey, username, class, limited FROM users WHERE passkey = :passkey', array('passkey' => $passkey));
$user_row = $res->fetch() or fail('Token authentication failed.');

// Check limited user - Oct 18, 2020 - Updated for Shoutbox notif : Nov 23, 2020
if ($user_row['limited'] == 'yes') {
   $event = "Client kicked [url=$CONFIG[base_url]/user/?id=$user_row[user_id]/ ] $user_row[username][/url] due to a limited account state";
   $db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => $user_row['username'], 'event' => $event));
   fail('Account is limited. Sign in to resolve.');
}

// Verify token hash - Oct 5, 2020
if ($data['token']) {
   if (!hash_equals($user_row['passkey'], $passkey)) {
       fail('Token is invalid');
   }
}

// Max Slots - Fixed - Seedbox-Compatible - Sep 21, 2020
// Happy Hour - No Slot Limits, No peer limits - PHP 5/7+ compatible : Saturday/Sunday - Nov 29, 2020
if (!in_array(date('l'), ['Saturday', 'Sunday'])) {
   $maxslots = $db->query_params("SELECT COUNT(DISTINCT torrent_id) AS total, last_announce FROM peers WHERE user_id = :user_id AND seeder = 'no'", array('user_id' => $user_row['user_id']));
   $current  = $maxslots->fetch();
       if ($current['total'] > $user_row['slots']) {
           $checklast   = $db->query_params('SELECT user, date, message FROM shoutbox WHERE user = :username', array('username' => $user_row['username']));
           $lastmessage = $checklast->fetch();
               if ($lastmessage['date'] < $current['last_announce']) {
                   $event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id] ] $user_row[username][/url] reached their maximum download slot $current[total]/$user_row[slots]";
                   $reason = "You have reached your max download slots of 4 (out of 3 available). You can visit Seed Bonus to upgrade to more slots.";
                   $db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => $user_row['username'], 'event' => $event));
                   $db->query_params("INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES (0, :user_id, NOW(), :reason, 0, 'Max Download Slots Reached')", array('user_id' => $user_row['user_id'], 'reason' => $reason)); // Sep 23, 2020
               }
               fail("$current[total]/$user_row[slots] download slots exceeded! Finish current transfers to reclaim slots.");
       }
} else {
   $event = "Today is Happy Hour! No slot limits, No peer limits - Full Speeds!";
   $db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => 'NerbBot', 'event' => $event));
}

if (!is_numeric($data['port'])) fail('invalid port');
$data['port'] = intval($data['port']);
if ($data['port'] < 1 || $data['port'] >= 65536) fail('Invalid port');

if (array_key_exists('left', $data)) {
   if (!is_numeric($data['left'])) fail('Invalid left');
   $data['left'] = intval($data['left']);
   if ($data['left'] < 0) fail('Invalid left');
}

if (!array_key_exists('ip', $data)) {
   $data['ip'] = getip();

   $try_keys = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP');
   foreach ($try_keys as $key) {
       if (array_key_exists($key, $_SERVER)) {
           $potential_ip = trim(explode(',', $_SERVER[$key])[0]);

           // Ignore private IP addresses
           if (strpos($potential_ip, '10.') === 0) continue;
           if (strpos($potential_ip, '192.168.') === 0) continue;
           // TODO: 172.16.0.0/12 is also private

           $data['ip'] = $potential_ip;
           break;
       }
   }
}

if (array_key_exists('numwant', $data)) {
   if (!is_numeric($data['numwant'])) fail('Invalid numwant');
   $data['numwant'] = intval($data['numwant']);
   if ($data['numwant'] < 0) $data['numwant'] = 1000;
   if ($data['numwant'] > 1000) $data['numwant'] = 1000;
} else {
   $data['numwant'] = 30;
}

$res = $db->query_params('SELECT torrent_id FROM torrents WHERE info_hash = :info_hash', array('info_hash' => $data['info_hash'])) or fail('db error');
$torrent_row = $res->fetch() or fail('no such torrent');

// Ratio-faker tool check - Oct 18, 2020
$interval = time() - $current['last_announce'];
if ($interval == 0) $interval = 1;
$downloaded = $data['downloaded'];
$uploaded   = $data['uploaded'];

// If speed is higher than 4 MB/sec, the user is apparently cheating. Frustrate user by adding their desired upload to their download
if (($uploaded / $interval) > 4194304) { // 4194304 - 4MB/Sec
   $event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id] ] $user_row[username][/url] used Ratiofaker-Tool - Event 1: " . $data['uploaded'] . " Upload @ " . ($data['uploaded'] / $interval) . "/sec Fake Rate";
   $db->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array('receiver' => $user_row['username'], 'event' => $event));
   fail('Ratiofaker-Tool detected.');

   // Add upload as download and zero out upload for event
   $downloaded += $uploaded;
   $uploaded = 0;
}

$valid = $db->query_params('SELECT * FROM peers WHERE torrent_id = :torrent_id AND passkey = :passkey', array('torrent_id' => $torrent_row['torrent_id'], 'passkey' => $data['passkey'])) or fail('db error');
$active = $valid->fetch();

$res = $db->query_params('SELECT peer_id, completed, seeder FROM peers WHERE user_id = :user_id AND torrent_id = :torrent_id AND chosen_peer_id = :chosen_peer_id', array('user_id' => $user_row['user_id'], 'torrent_id' => $torrent_row['torrent_id'], 'chosen_peer_id' => $data['peer_id'])) or fail('db error');

if (!($peer_row = $res->fetch())) {
   isPeerIDBanned($peer_row['peer_id'], $torrent_row['torrent_id'], $data['passkey']);
   $res = $db->query_params('INSERT INTO peers (started, passkey, connectable, user_id, torrent_id, chosen_peer_id, ip, port, client) VALUES (now(), :passkey, :connectable, :user_id, :torrent_id, :chosen_peer_id, :ip, :port, :client)', array('passkey' => $data['passkey'], 'connectable' => $connectable, 'user_id' => $user_row['user_id'], 'torrent_id' => $torrent_row['torrent_id'], 'chosen_peer_id' => $data['peer_id'], 'ip' => $data['ip'], 'port' => $data['port'], 'client' => $client), 'peer_id') or fail('Cant insert peer.');
   $peer_row = array('peer_id' => $res);
   $db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $uploaded, 'downloaded' => $downloaded, 'user_id' => $user_row['user_id']));
   } else {
   isPeerIDBanned($peer_row['peer_id'], $torrent_row['torrent_id'], $data['passkey']);
   $db->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array('uploaded' => $uploaded, 'downloaded' => $downloaded, 'user_id' => $user_row['user_id']));
   $db->query_params('UPDATE peers SET connectable = :connectable, to_go = :to_go, uploaded = :uploaded, downloaded = :downloaded, seeder = :seeder, client = :client, ip = :ip, port = :port, last_announce = CURRENT_TIMESTAMP WHERE peer_id = :peer_id', array('connectable' => $connectable, 'to_go' => $data['left'], 'uploaded' => $uploaded, 'downloaded' => $downloaded, 'seeder' => $seeder, 'client' => $client, 'ip' => $data['ip'], 'port' => $data['port'], 'peer_id' => $peer_row['peer_id'])) or fail('db error');
}

if (array_key_exists('left', $data)) {
   $db->query_params('UPDATE peers SET completed = :completed, seeder = :seeder WHERE peer_id = :peer_id', array('completed' => $db->encode_bool($data['left'] === 0), 'seeder' => $seeder, 'peer_id' => $peer_row['peer_id']));
}

if ($data['event'] === 'stopped') {
   $db->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array('peer_id' => $peer_row['peer_id']));
}

if ($data['event'] === 'completed') {
   $db->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array('peer_id' => $peer_row['peer_id']));
   $db->query_params('UPDATE torrents SET times_completed = times_completed + :completed WHERE torrent_id = :torrent_id', array('completed' => $db->encode_bool($data['left'] === 0), 'torrent_id' => $torrent_row['torrent_id'])); // Added Sep 9, 2020
}

//$res = $db->query_params('SELECT count(nullif(completed,false)) AS complete, count(nullif(completed,true)) AS incomplete FROM peers WHERE torrent_id = :torrent_id', array('torrent_id' => $torrent_row['torrent_id'])) or fail('db error');

// Updated to JOIN torrent table for times_completed info - Dec 2, 2020
$res = $db->query_params('SELECT count(nullif(p.completed,false)) AS complete, count(nullif(t.times_completed,false)) AS downloaded, count(nullif(p.completed,true)) AS incomplete FROM peers p LEFT JOIN torrents t ON t.torrent_id = p.torrent_id WHERE p.torrent_id = :torrent_id', array('torrent_id' => $torrent_row['torrent_id'])) or fail('db error');
$comp_res = $res->fetch() or fail('db error');

// Scrape
$output = array(
   'interval' => 30 * 60,
   'complete' => intval($comp_res['complete']),
   'incomplete' => intval($comp_res['incomplete']),
   'downloaded' => intval($comp_res['downloaded']), // Dec 2, 2020
   'peers' => array(),
);

$res = $db->query_params('SELECT chosen_peer_id, ip, port FROM peers WHERE torrent_id = :torrent_id AND peer_id != :peer_id ORDER BY ' . $db->random() . ' LIMIT :limit', array('torrent_id' => $torrent_row['torrent_id'], 'peer_id' => $peer_row['peer_id'], 'limit' => $data['numwant'])) or fail('db error');
while ($row = $res->fetch()) {
   $peer = array(
       'ip' => $row['ip'],
       'port' => intval($row['port']),
   );
   if (!array_key_exists('no_peer_id', $data)) {
       $peer['peer_id'] = hex2bin($row['chosen_peer_id']);
   }
   $output['peers'] []= $peer;
}
if (array_key_exists('compact', $data)) {
   $peer_data = '';
   foreach ($output['peers'] as $peer) {
       $bs = ip2bytes($peer['ip']);
       if (is_null($bs)) continue;
       $peer_data .= $bs;
       $peer_data .= chr($peer['port'] >> 8);
       $peer_data .= chr($peer['port'] & 0xff);
   }

   if (empty($output['peers']) || !empty($peer_data)) {
       $output['peers'] = $peer_data;
   }
}

echo bencode($output);