I've converted the latest announce codebase to a new class, autoloaded of course.
I decided to use my favorite approach, and implement a interface that holds all of the public methods available, and construct the database class (I'll be extending this later).
This is a working version, but has a flow at the very end that does not provide the right stats (peer count, downloaded, completed).
If I decide to update to PHP 8.1 and risk my configuration carefully set, I'll use the new Enumeration feature.
Changes (30/5/2022):
- Fixed iteration memory leak, resulting in correct encoded output
- Fixed peers not being picked up by client
- Corrected some incorrectctly referenced variables
- Fixed decryption handling, and adding a check for passkey/token
- Fixed/Added verifyToken() method to validate user row passkey with token
- Remove checkIP() method *will be implemented better next update
STAnnounce.php
<?
// Switch-Torrents.com Announce
interface Handler
{
public function notifyHappyHourDays();
public function notifyBonusDays();
public function notifyFreeSlotDays();
public function notifyFreeleech();
public function notifyFreeUserDays();
public function happyhour_multiplier(int $torrent_id, int $user_id);
public function multiplier(?int $multiplier, string $username, ?int $uploaded);
public function freeleech(mixed $row);
public function checkNumWait(int $numwait, array $data = []);
public function getTorrentRow(string $info_hash);
public function insertNewPeer(string $key, string $passkey, string $ip, int $port, int $user_id, int $torrent_id, $peer_id, ?string $client);
public function returnKeys(?string $keyname, mixed $keyvalue);
public function fail(?string $reason);
public function clearPeers(string $string = '');
public function lastShoutDate(string $message);
public function userDetails(string $passkey);
public function torrentDetails(string $info_hash);
public function decryptToken(string $token);
public function insertShout(string $event, string $username);
public function peerData(int $user_id, int $torrent_id, string $peer_id);
public function insertPeer(string $key, string $passkey, int $user_id, int $torrent_id, string $chosen_peer_id, string $ip, int $port, string $client);
public function updateLastExchange(int $to_go, int $user_id);
public function updatePeerKey(string $key, string $peer_id);
public function updateLeft(int $completed, string $seeder, string $peer_id);
public function peerProgress(int $torrent_id);
public function peer(int $torrent_id, string $peer_id, int $numwant);
public function updateUserAgent(string $user_agent, string $key);
public function maxSlots(int $user_id);
public function notifyUser(int $user_id);
public function updatePeer(string $passkey, string $ip, int $port, int $left, int $uploaded, int $downloaded, string $seeder, string $client, string $peer_id, string $key);
public function updateLeecher(int $uploaded, int $downloaded, int $user_id);
public function updateSeeder(int $uploaded, int $user_id);
public function deletePeer(int $peer_id);
public function updateCompleted(int $left, int $torrent_id, int $peer_id);
public function bencodeOutput(array $output);
public function checkLeft(int $left, array $data = []);
public function checkPort(int $port);
public function kickPeerNoData(int $user_id, string $username, string $gender);
public function verifyToken(string $passkey, string $token);
public function getPeerArray(int $complete, int $incomplete, int $downloaded);
public function getCompactPeers(array $output, array $data = []);
public function grantDataBonus(array $torrent_row, int $downloaded = 0, int $uploaded = 0);
public function grandHappyHourBonus(int $torrent_id, int $user_id, int $uploaded, string $username);
public function useDataBonus(string $seeder, int $last_exchange, int $downloaded, int $uploaded, string $username, int $user_id);
public function encode_bool($s);
public function writeLog(string $string = '');
}
class STAnnounce implements Handler
{
public function __construct($db = 'database', $username = 'username', $password = 'password', $host = 'localhost', $port = 3306, $options = [])
{
$dsn = "mysql:host=$host;dbname=$db;port=$port;charset=utf8mb4";
try {
$this->pdo = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e) {
$this->log_exception($e->getMessage(), $e->getLine());
}
}
public function setNumber($number) {
$this->CONFIG = $number;
}
private function log_exception($msg, $line)
{
$query = "INSERT INTO sql_logging(exception, added) VALUES(?, NOW())";
$stt = $this->pdo->prepare($query);
$stt->bindValue(1, $msg . $line);
$stt->execute();
}
public 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');
}
public function preprocess($query, $get_id)
{
return $query;
}
public function write_log(?string $text): void
{
$this->query_params('INSERT INTO log (added, txt) VALUES(NOW(), :log)', array(
'log' => $text
));
}
public function sql_timestamp_to_unix_timestamp(string $s): string
{
return mktime(substr($s, 11, 2), substr($s, 14, 2), substr($s, 17, 2), substr($s, 5, 2), substr($s, 8, 2), substr($s, 0, 4));
}
public function gmtime(): string
{
return $this->sql_timestamp_to_unix_timestamp($this->get_date_time());
}
public function interval($s)
{
return sprintf("INTERVAL '%s'", $s);
}
protected function get_last_id($stmt, $get_id) {
return $this->conn->lastInsertId($get_id);
}
public function query_params(string $query, array $params = null, $get_id = null) {
if (is_null($params)) {
$params = array();
}
try {
$query = $this->preprocess($query, $get_id);
$stmt = $this->pdo->prepare($query);
foreach ($params as $key => $param) {
if ($key == "data") {
$stmt->bindValue(':' . $key, $param, PDO::PARAM_LOB);
} else if ($key == "limit") {
$stmt->bindValue(':' . $key, (int) trim($param), PDO::PARAM_INT);
} else {
$stmt->bindValue(':' . $key, $param);
}
}
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if (is_null($get_id)) {
return $stmt;
} else {
return $this->get_last_id($stmt, $get_id);
}
}
catch (PDOException $e) {
$this->log_exception($e->getMessage(), $e->getLine());
}
}
public function notifyHappyHourDays(): void {
$event = "Today is Happy Hour! No slots, Data frozen, 2X UP/DL Multiplier!";
$lastmsg = $this->lastshoutdate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
}
public function notifyBonusDays(): void {
$event = "Today is Bonus Data Day! Bonus data is Doubled X2!";
$lastmsg = $this->lastshoutdate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
}
public function notifyFreeSlotDays(): void {
$event = "Today is Free Slots Day! All slot limits Turned Off!";
$lastmsg = $this->lastshoutdate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
}
public function notifyFreeleech(): void {
$event = "Today is Freeleech Day! UP/DL Boosts Stackable!";
$lastmsg = $this->lastshoutdate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
}
public function notifyFreeUserDays(): void {
$event = "Today is Free User Day! All limited accounts are Unlocked Today!";
$lastmsg = $this->lastshoutdate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
}
public function multiplier(?int $multiplier, string $username, ?int $uploaded): void {
if ($multiplier > 0) {
$uploaded = $uploaded * $multiplier;
$downloaded = 0;
$event = "Happy Hour Upload Multiplier: X" . $multiplier . "";
$this->insertShout($event, $username);
}
}
public function freeleech(mixed $row): int {
if (!empty($row)) {
if ($row == 1) {
$downloaded = 0;
} else if ($row == 'silver') {
$downloaded = round($downloaded / 2);
} else if ($row == 'upboost') {
$uploaded = round($uploaded * 5);
} else if ($row == 'dlboost') {
$downloaded = round($downloaded * 5);
}
return $downloaded;
}
}
public function happyhour_multiplier(int $torrent_id, int $user_id): mixed {
if (in_array(date('l'), array('Saturday', 'Sunday'))) {
$res_happy = $this->query_params('SELECT id, userid, torrentid, multiplier FROM happyhour WHERE userid = :user_id', array(
'user_id' => $user_id
));
$happy = array();
if ($res_happy) {
$rowhappy = $res_happy->fetch();
$happy[$rowhappy['torrentid']] = $rowhappy['multiplier'];
}
$this->query_params('INSERT INTO happyhour (userid, torrentid, multiplier) VALUES(:user_id, :torrent_id, :multiplier)', array(
'user_id' => $user_id,
'torrent_id' => $torrent_id,
'multiplier' => (float) $happy
));
$event = 'It is Happy Hour! No data limits!';
$lastmsg = $this->lastShoutDate($event); // bool
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$this->insertShout($event, 'NerbBot');
}
if (!empty($happy) && isset($happy[$torrent_id])) {
return $happy[$torrent_id];
}
}
return false;
}
public function checkNumWait(int $numwait, array $data = []): int {
if (array_key_exists('numwant', $data)) {
if (!is_numeric($numwait))
$this->fail('Invalid numwant');
if ($numwait < 0)
return 1000;
if ($numwait > 1000)
return 1000;
} else {
return 30;
}
}
public function getTorrentRow(string $info_hash): mixed {
$res = $this->query_params('SELECT webseed, size, seeders, leechers, torrent_id, freeleech, name, cover1 FROM torrents WHERE info_hash = :info_hash', array(
'info_hash' => $info_hash
));
if ($t = $res->fetch())
return $t;
return false;
}
public function insertNewPeer(?string $key, string $passkey, string $ip, int $port, int $user_id, int $torrent_id, $peer_id, ?string $client) {
$res = $this->query_params('INSERT INTO peers (clientkey, started, passkey, connectable, user_id, torrent_id, chosen_peer_id, ip, port, client) VALUES (:clientkey, NOW(), :passkey, :connectable, :user_id, :torrent_id, :chosen_peer_id, :ip, :port, :client)', array(
'clientkey' => $key,
'passkey' => $passkey,
'connectable' => fsockopen($ip, $port) ? 'yes' : 'no',
'user_id' => $user_id,
'torrent_id' => $torrent_id,
'chosen_peer_id' => $peer_id,
'ip' => $ip,
'port' => $port,
'client' => $client
), 'peer_id');
return $res;
}
public function returnKeys(?string $keyname, mixed $keyvalue): array {
$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' => 0,
'ip' => false,
'numwant' => false,
'event' => false,
'left' => true,
'compact' => 0,
'key' => 1
);
if (!empty($keyname) && !empty($keyvalue)) {
$keys[$keyname] = $keyvalue;
}
return $keys;
}
public function fail(?string $reason) {
echo Bencode::encode(array(
'failure reason' => $reason
));
}
public function clearPeers(string $interval = ''): bool {
$checklast = !empty($interval)
? $this->interval($interval)
: '';
$clear = $this->query_params('DELETE FROM peers WHERE last_announce + ' . $checklast . ' < CURRENT_TIMESTAMP');
if ($clear)
return true;
return false;
}
public function lastShoutDate(string $message): mixed {
$lastshout = $this->query_params('SELECT message, date FROM shoutbox_finalmsg WHERE message = :message ORDER BY date DESC LIMIT 1', array(
'message' => trim($message)
));
if ($lastdate = $lastshout->fetch()) {
return $lastdate['date'];
}
return false;
}
public function userDetails(string $passkey): mixed {
$checkpasskey = $this->query_params('SELECT last_exchange, gender, slots, user_id, passkey, username, class, limited, uploaded, downloaded FROM users WHERE passkey = :passkey', array(
'passkey' => $passkey
));
if ($c = $checkpasskey->fetch())
return $c;
return false;
}
public function encrypt_decrypt(string $action, string $string): string {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'ee3c1f386a8a322c63a6175242a4e1ff';
$secret_iv = 'D309D488';
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
public function torrentDetails(string $info_hash): mixed
{
$details = $this->query_params('SELECT webseed, size, seeders, leechers, torrent_id, freeleech, name, cover1 FROM torrents WHERE info_hash = :info_hash', array(
'info_hash' => trim($info_hash)
));
if ($t = $details->fetch())
return $t;
return false;
}
public function decryptToken(string $token): string {
return substr($this->encrypt_decrypt('decrypt', $token), 11, strlen(substr($this->encrypt_decrypt('decrypt', $token), 12)));
}
public function insertShout(string $event, string $username): bool {
$insert = $this->query_params('INSERT INTO shoutbox_finalmsg (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
'receiver' => $username,
'event' => $event
));
if ($insert)
return true;
return false;
}
public function peerData(int $user_id, int $torrent_id, string $peer_id): mixed {
$peer = $this->query_params('SELECT clientkey, peer_id, completed, seeder, last_announce FROM peers WHERE user_id = :user_id AND torrent_id = :torrent_id AND chosen_peer_id = :chosen_peer_id', array(
'user_id' => $user_id,
'torrent_id' => $torrent_id,
'chosen_peer_id' => $peer_id
));
if ($p = $peer->fetch())
return $p;
return false;
}
public function insertPeer(string $key, string $passkey, int $user_id, int $torrent_id, string $chosen_peer_id, string $ip, int $port, string $client): mixed {
$res = $this->query_params('INSERT INTO peers (clientkey, started, passkey, connectable, user_id, torrent_id, chosen_peer_id, ip, port, client) VALUES (:clientkey, NOW(), :passkey, :connectable, :user_id, :torrent_id, :chosen_peer_id, :ip, :port, :client)', array(
'clientkey' => $key,
'passkey' => $passkey,
'connectable' => fsockopen($ip, $port) ? 'yes' : 'no',
'user_id' => $user_id,
'torrent_id' => $torrent_id,
'chosen_peer_id' => $chosen_peer_id,
'ip' => $ip,
'port' => $port,
'client' => $client
), 'peer_id');
if ($res)
return array(
'peer_id' => $res
);
return false;
}
public function updateLastExchange(int $to_go, int $user_id): bool
{
$deduct = $this->query_params('UPDATE users SET last_exchange = last_exchange - :deduct_data WHERE user_id = :user_id', array(
'deduct_data' => $to_go,
'user_id' => $user_id
));
if ($deduct)
return true;
return false;
}
public function updatePeerKey(string $key, string $peer_id): bool
{
$update = $this->query_params('UPDATE peers SET clientkey = :clientkey WHERE peer_id = :peer_id', array(
'clientkey' => $key,
'peer_id' => $peer_id
));
if ($update)
return true;
return false;
}
public function updateLeft(int $completed, string $seeder, string $peer_id): bool
{
$updateleft = $this->query_params('UPDATE peers SET completed = :completed, seeder = :seeder WHERE peer_id = :peer_id', array(
'completed' => boolval($completed),
'seeder' => $seeder,
'peer_id' => $peer_id
));
if ($updateleft)
return true;
return false;
}
public function peerProgress(int $torrent_id): mixed
{
$progress = $this->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_id
));
if ($p = $progress->fetch())
return $p;
return false;
}
public function peer(int $torrent_id, string $peer_id, int $numwant): mixed
{
$peer = $this->query_params('SELECT chosen_peer_id, ip, port FROM peers WHERE torrent_id = :torrent_id AND peer_id != :peer_id ORDER BY RAND() LIMIT :limit', array(
'torrent_id' => $torrent_id,
'peer_id' => $peer_id,
'limit' => $numwant
));
if ($p = $peer->fetch())
return $p;
return false;
}
public function updateUserAgent(string $user_agent, string $key): bool
{
$update = $this->query_params('UPDATE peers SET http_client = :client WHERE clientkey = :clientkey', array(
'client' => $user_agent,
'clientkey' => $key
));
if ($update)
return true;
return false;
}
public function maxSlots(int $user_id): mixed
{
$maxslots = $this->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_id
));
if ($m = $maxslots->fetch())
return $m;
return false;
}
public function notifyUser(int $user_id): bool
{
$notify = $this->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_id,
'reason' => 'You have reached your max download slots of 4 (out of 3 available). You can visit Seed Bonus to upgrade to more slots.'
));
if ($notify)
return true;
return false;
}
public function updatePeer(string $passkey, string $ip, int $port, int $left, int $uploaded, int $downloaded, string $seeder, string $client, string $peer_id, string $key): bool
{
$update = $this->query_params('UPDATE peers SET passkey = :passkey, clientkey = :clientkey, 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(
'passkey' => $passkey,
'connectable' => fsockopen($ip, $port) ? 'yes' : 'no',
'to_go' => $left,
'uploaded' => $uploaded,
'downloaded' => $downloaded,
'seeder' => $seeder,
'client' => $client,
'ip' => $ip,
'port' => $port,
'peer_id' => $peer_id,
'clientkey' => $key
));
if ($update)
return true;
return false;
}
public function updateLeecher(int $uploaded, int $downloaded, int $user_id): bool {
$update = $this->query_params('UPDATE users SET uploaded = uploaded + :uploaded, downloaded = downloaded + :downloaded WHERE user_id = :user_id', array(
'uploaded' => $uploaded,
'downloaded' => $downloaded,
'user_id' => $user_id
));
if ($update)
return true;
return false;
}
public function updateSeeder(int $uploaded, int $user_id): bool {
$update = $this->query_params('UPDATE users SET uploaded = uploaded + :uploaded WHERE user_id = :user_id', array(
'uploaded' => $uploaded,
'user_id' => $user_id
));
if ($update)
return true;
return false;
}
public function deletePeer(int $peer_id): bool {
$delete = $this->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array(
'peer_id' => $peer_id
));
if ($delete)
return true;
return false;
}
public function updateCompleted(int $left, int $torrent_id, int $peer_id): bool {
$clear = $this->query_params('DELETE FROM peers WHERE peer_id = :peer_id', array(
'peer_id' => $peer_id
));
if ($clear) {
$update = $this->query_params('UPDATE torrents SET times_completed = times_completed + :completed WHERE torrent_id = :torrent_id', array(
'completed' => $left,
'torrent_id' => $torrent_id
));
if ($update)
return true;
}
return false;
}
public function checkLeft(int $left, array $data = []): mixed {
if (array_key_exists('left', $data)) {
if ($left < 0) {
$this->fail('Invalid left');
}
}
}
public function checkPort(int $port): mixed {
if ($port < 1 || $port >= 65536) {
$this->fail('Invalid port');
}
}
public function bencodeOutput(array $output): void {
echo Bencode::encode($output);
}
public function kickPeerNoData(int $user_id, string $username, string $gender): void {
$kick = $this->query_params("DELETE FROM peers WHERE user_id = :user_id AND seeder = 'no'", array(
'user_id' => $user_id
));
if ($kick) {
$seeding = $this->query_params("SELECT COUNT(torrent_id) as total FROM peers WHERE user_id = :user_id AND seeder = 'yes'", array(
'user_id' => $user_id
));
$seeding = (($s = $seeding->fetch()) && intval($s['total']) > 0) ? '[/b], but is seeding ' . intval($s['total']) . ($s['total'] == 1 ? ' torrent' : ' torrents') . ' to earn seedbonus points & free data.' : '![/b]';
$event = '[url=/user/?id=' . $user_id . '] ' . $username . '[/url] used all of ' . (($gender == 'Male') ? 'his' : 'her') . ' upload data' . $seeding;
$this->query_params('INSERT INTO shoutbox_finalmsg (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
'receiver' => $username,
'event' => $event
));
$this->fail('No data left! Upgrade w/ More Data.');
}
}
public function encode_bool($s) {
return $s ? 1 : 0;
}
public function getPeerArray(int $complete, int $incomplete, int $downloaded): array {
return array(
'interval' => 30 * 60,
'min interval' => 10 * 60,
'retry in' => 10 * 60,
'complete' => intval($complete),
'incomplete' => intval($incomplete),
'downloaded' => intval($downloaded),
'peers' => array()
);
}
public function getCompactPeers(array $output, array $data = []): mixed {
if (array_key_exists('compact', $data)) {
$peer_data = '';
foreach ($output as $peer) {
$bs = inet_pton($peer['ip']);
if ($bs === false)
continue;
$peer_data .= $bs;
$peer_data .= chr($peer['port'] >> 8);
$peer_data .= chr($peer['port'] & 0xff);
}
if (empty($output) || !empty($peer_data)) {
return $peer_data;
}
}
return false;
}
public function grantDataBonus(array $torrent_row, int $downloaded = 0, int $uploaded = 0): int {
if ($torrent_row['freeleech'] == 1) {
$downloaded = 0;
} else if ($torrent_row['freeleech'] == 'silver') {
$downloaded = round($downloaded / 2);
} else if ($torrent_row['freeleech'] == 'upboost') {
$uploaded = round($uploaded * 5);
} else if ($torrent_row['freeleech'] == 'dlboost') {
$downloaded = round($downloaded * 5);
}
return ($uploaded > 0) ? $uploaded : $downloaded;
}
public function grandHappyHourBonus(int $torrent_id, int $user_id, int $uploaded, string $username): int {
if ($m = $this->happyhour_multiplier($torrent_id, $user_id)) {
if ($m > 0) {
$event = "[b]Happy Hour Upload Multiplier: X" . $m . "";
$this->insertShout($event, $username);
return $uploaded * $m;
}
return $uploaded;
}
}
public function useDataBonus(string $seeder, int $last_exchange, int $downloaded, int $uploaded, string $username, int $user_id): bool {
if ($seeder == 'no') {
$exchange = is_null($last_exchange) ? round($downloaded * 2) : ($last_exchange + $uploaded);
$grantbonus = $this->query_params('UPDATE users SET last_exchange = :data_bonus WHERE user_id = :user_id', array(
'data_bonus' => $exchange,
'user_id' => $user_id
));
if ($grantbonus && intval($exchange) > 0) {
$event = '[url=/user/?id=' . $user_id . ' ] ' . $username . '[/url] earned a data bonus of ' . format_size($exchange);
$this->insertShout($event, $username);
}
if ($grantbonus)
return true;
}
return false;
}
public function writeLog(string $string = ''): bool {
$write = $this->query_params("INSERT INTO log (added, txt) VALUES (NOW(), :log)", array(
'log' => trim($string)
));
if ($write)
return true;
return false;
}
public function verifyToken(string $passkey, string $token): bool {
if (hash_equals($passkey, $this->decryptToken($token))) {
return true;
}
return false;
}
}
[b]Announce.php
<?
require_once '../site.php';
$announce = new STAnnounce;
$announce->clearPeers('1 hour');
header('Content-Type: text/plain');
$freeleech_days = array(
'Friday',
'Saturday'
);
$happyhour_days = array(
'Saturday',
'Sunday'
);
$slotfree_days = array(
'Friday',
'Thursday'
);
$freeuser_days = array(
'Wednesday',
'Saturday'
);
$bonus_days = array(
'Monday',
'Tuesday'
);
$keys = $announce->returnKeys('compact', 1);
$data = array();
foreach ($keys as $key => $req) {
if (array_key_exists($key, $_GET)) {
$data[$key] = $_GET[$key];
} else if ($req) {
$announce->fail(sprintf('%s', $key));
}
}
$seeder = ($data['left'] == 0) ? 'yes' : 'no';
$client = substr($data['peer_id'], 0, 8);
$data['info_hash'] = bin2hex($data['info_hash']);
$data['peer_id'] = bin2hex($data['peer_id']);
$passkey = isset($data['token']) ? $announce->decryptToken($data['token']) : trim($data['passkey']);
$res = $announce->userDetails($passkey) or $announce->fail('Failed getting user details.');
$user_row = $res;
if (array_key_exists('token', $data)) {
$announce->verifyToken($user_row['passkey'], $data['token']) or $announce->fail('Token not verified');
}
if (in_array(date('l'), $happyhour_days)) {
$event = "Today is Happy Hour! No slots, Data frozen, 2X UP/DL Multiplier!";
if (strtotime($announce->lastShoutDate($event)) < strtotime('-2 minutes')) {
$announce->insertShout($event, 'NerbBot');
}
}
if (in_array(date('l'), $freeuser_days)) {
$event = "Today is Free User Day! All limited accounts are Unlocked Today!";
if (strtotime($announce->lastShoutDate($event)) < strtotime('-2 minutes')) {
$announce->insertShout($event, 'NerbBot');
}
}
if (in_array(date('l'), $freeleech_days)) {
$event = "Today is Freeleech Day! UP/DL Boosts Stackable!";
if (strtotime($announce->lastShoutDate($event)) < strtotime('-2 minutes')) {
$announce->insertShout($event, 'NerbBot');
}
}
if (in_array(date('l'), $slotfree_days)) {
$event = "Today is Free Slots Day! All slot limits Turned Off!";
if (strtotime($announce->lastShoutDate($event)) < strtotime('-2 minutes')) {
$announce->insertShout($event, 'NerbBot');
}
}
if (in_array(date('l'), $bonus_days)) {
$event = "Today is Bonus Data Day! Bonus data is Doubled X2!";
if (strtotime($announce->lastShoutDate($event)) < strtotime('-2 minutes')) {
$announce->insertShout($event, 'NerbBot');
}
}
$torrent_row = $announce->torrentDetails($data['info_hash']);
$res = $announce->peerData($user_row['user_id'], $torrent_row['torrent_id'], $data['peer_id']);
if (!in_array(date('l'), $bonus_days)) {
if ($seeder === 'no') {
$current = $announce->maxSlots($user_row['user_id']);
if ($current['total'] > $user_row['slots']) {
$event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id] ] $user_row[username][/url] requested download slot $current[total] (with only $user_row[slots] unlocked)";
$lastmsg = $announce->lastShoutDate($event);
if (strtotime($lastmsg) < strtotime('-2 minutes')) {
$announce->insertShout($event, $user_row['username']);
}
$announce->fail("$current[total]/$user_row[slots] Slots used up!");
}
}
}
if (!in_array(date('l'), $happyhour_days)) {
if (!is_null($user_row['last_exchange']) && intval($user_row['last_exchange']) > 0 && ($seeder === 'no')) {
$announce->updateLastExchange(intval($res['to_go']), $user_row['user_id']);
$event = "[url=$CONFIG[base_url]/user/?id=$user_row[user_id]/ ] $user_row[username][/url] used " . format_size($user_row['last_exchange']) . " of bonus data";
$announce->insertShout($event, $user_row['username']);
} else {
if (max(($user_row['uploaded'] - $user_row['downloaded']), 0) === 0 && ($seeder === 'no')) {
$announce->kickPeerNoData($user_row['user_id'], $user_row['username'], $user_row['gender']);
}
}
}
if (!($peer_row = $res)) {
$res = $announce->insertPeer($data['key'], $user_row['passkey'], $user_row['user_id'], $torrent_row['torrent_id'], $data['peer_id'], getip(), $data['port'], $client) or $announce->fail('Failed to insert peer.');
$peer_row = array(
'peer_id' => $res
);
} else {
$uploaded = max(0, $data['uploaded'] - $peer_row['uploaded']);
$downloaded = max(0, $data['downloaded'] - $peer_row['downloaded']);
if (in_array(date('l'), $happyhour_days)) {
$uploaded = $announce->grandHappyHourBonus($torrent_row['torrent_id'], $user_row['user_id'], $uploaded, $user_row['username']);
}
if (in_array(date('l'), $freeleech_days)) {
$announce->grantDataBonus($torrent_row, $downloaded, $uploaded);
}
if ($peer_row['seeder'] == 'no') {
$announce->updateLeecher($uploaded, $downloaded, $user_row['user_id']);
}
if ($peer_row['seeder'] == 'yes' && $data['left'] === 0) {
$announce->updateSeeder($uploaded, $user_row['user_id']);
}
$announce->updatePeer($user_row['passkey'], getip(), $data['port'], $data['left'], $uploaded, $downloaded, $seeder, $client, $peer_row['peer_id'], $data['key']) or $announce->fail('Failed to update peer.');
}
if ($data['key'] !== $peer_row['clientkey']) {
$announce->updatePeerKey($data['key'], $peer_row['peer_id']);
}
if (array_key_exists('left', $data)) {
$announce->updateLeft($announce->encode_bool($data['left'] === 0), $seeder, $peer_row['peer_id']);
}
if ($data['event'] === 'stopped') {
$announce->deletePeer($peer_row['peer_id']);
}
if ($data['event'] === 'completed') {
$announce->updateCompleted($announce->encode_bool($data['left'] === 0), $torrent_row['torrent_id'], $peer_row['peer_id']);
}
$comp_res = $announce->peerProgress($torrent_row['torrent_id']) or $announce->fail('Failed to get peer progress.');
$output = $announce->getPeerArray($comp_res['complete'], $comp_res['incomplete'], $comp_res['downloaded']);
$res1 = $announce->peer($torrent_row['torrent_id'], $peer_row['peer_id'], $data['numwant']);
foreach ($res1 as $value => $key) {
$peer = array(
$value => $key
);
if (!array_key_exists('no_peer_id', $data)) {
$peer['peer_id'] = hex2bin($key);
}
$output['peers'][] = $peer;
}
if (is_string($announce->getCompactPeers($output, $data))) {
$output['peers'] = $announce->getCompactPeers($output, $data);
}
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$announce->updateUserAgent($_SERVER['HTTP_USER_AGENT'], $data['key']);
}
$announce->bencodeOutput($output);