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
User Posts

Go to Profile

vip — 2022-06-18 02:45:46 in v3 Mods Requests
I can look at the SQL structure, and do a table/column comparison and output the results on a page. From there, we know what is necessary to update. User consents to the migration/upgrade and files are backed up, SQL is updated and files are then pushed to their respective directories. Make use of the chmod() function with prior privileges'.

The mods will never cross over this way, on any script out there - almost any social networking script will reveal this almost immediately due to the custom mods or changes off their own forums or support docs.  Forum CMS scripts are like this too. This is common. Most people look for the same mod, but compatible for the newer releases.

I know I called off V4 very early on - summer 2019, very old code base - due to the fact that people just dont know what to do with it, almost every time just pressures me to put myself in the seat of Apache/24 & PHP 5.6 and that is impossible, as I am very integrated with NGINX rewrites, mappings, caching, TCP optimizations, high grade cipher suite, etc - and code across the board is PHP 7/8 features, so right away all of this becomes a base requirement - Apache is possible but it may be slow and unpredictable.

Apache is awful for performance and disk I/O. I dont know why web hosts insist on supporting Apache for its customers. My codebase has become propitiatory / closed source due to this. Which sucks, because that puts me alone in my own seat.

But that being said, I will do what I can do here - I would like to develop a check/migration script to handle your latest SVN release, and see what can come of it. Just a matter of dumping it on my server in some directory and test away. Let me know.  I just need both SQL structures of both V3/SVN.







vip — 2022-06-16 05:51:59 in v3 Mods Requests
V3 around for about 12 years approx, you guys need to upgrade your scripts and retain your databases.

This should be considered a security concern as time goes by, and finally a PHP EOL (End of life) should have people running for the next release; at minimal PHP 7.4.

It’s not a easy migration, but it’s fairly simple if you know PHP and how cookies/sessions work and how to respond to depreciation warnings and removed functions.

That finally leaves you cleaning up that massive code and optimizing / where possible over time.

Backporting V3 with latest changes from a entirely different release will never progress and is super counter productive.

M-Jay, you need to write a DB conversion feature or simply a upgrade installer with your code base. That’s a good start. Perhaps the installer can back up and replace files and work the database with required changes.


Nice! Thank you, I missed that. Do you see any reason why the encoding would differ?
Happy Hour — 2022-06-14 19:44:17 in v3 Support
shuffle($array) shuffles array keys (the days) randomly on each call. I realize this request may require more code, but let us know and we will help.

Anytime!
This is my attempt at creating a PHP-solution for BEP 35 - torrent signing using openssl extensions.

https://www.bittorrent.org/beps/bep_0035.html

Updated: June 20, 2022

<?
// BEP_35 - Torrent Signing
function signtorrent(string $in, string $out, string $certfile, string $keyfile): bool
{
  $parsed = Bencode::decode(file_get_contents($in), bigInt: BigInt::INTERNAL);
  if (!isset($array['signatures'])) {
      $certFile      = file_get_contents($certfile);
      $keyFile       = file_get_contents($keyfile);
      $result        = openssl_x509_parse($certFile);
      $keyPassphrase = 'password';
      $privatekey    = openssl_get_privatekey($keyFile, $keyPassphrase);
      openssl_sign($parse, $signature, $privatekey);
      $info       = array();
      $fields     = $result['issuer']['C'] . $result['issuer']['ST'] . $result['issuer']['L'] . $result['issuer']['O'] . $result['issuer']['OU'] . $result['validFrom'] . $result['validTo'] . $result['subject']['O'] . $result['subject']['CN'];
      $signatures = array(
          'signatures' => array(
              'com.bittorrent' => array(
                  'certificate' => $fields . $signature, // optional, DER encoded x.509 certificate
                  'info' => $info, // optional
                  'signature' => sha1(Bencode::encode($parsed['info'])) . (!empty($info) ? Bencode::encode($info) : '') // signed data = info + sig info if present
              )
          )
      );
      if (isset($array['url-list'])) {
          unset($array['url-list']);
      }
      $array = array_merge($parsed, $signatures);
      if (file_put_contents($out, Bencode::encode($array))) {
          return true;
      }
  }
  return false;
}
vip — 2022-06-13 22:05:36 in v3 Mods Requests
I just cant.
Happy Hour — 2022-06-13 21:55:05 in v3 Support
<?
if (in_array(date('l'), array('Saturday', 'Sunday'))) {
  // do stuff on these 2 days
}


For the randomizing part, I think you do this

<?
$array = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
if (shuffle($array)) {
  // do stuff on any random day selected
}
This is actually a really good idea and I want to replicate this to a AJAX-based page that allows custom colours and backgrounds to header, sections, font etc, setting the CSS properties on the fly allows instant changes - as they click it saves both ways.

Very cool idea!
Spam ajshoutbox — 2022-06-08 23:25:20 in v3 Support
Its possible by comparing recorded date against your choosing, like '-5 minutes' for example.


if (strtotime($row['added']) < strtotime('-2 minutes')) {
  // Last post was 2 minutes ago, lets do something now
}


$row['added'] should point to the shoutbox tables last post DATETIME field.
RewriteRule help. — 2022-06-04 03:49:55 in M-BiTsy Support
This is too unclear, implying both types of web servers. I posted a solution for NGINX. Good luck.
TXT nfo to PNG. — 2022-06-03 13:25:03 in M-BiTsy Support
Yes, with GD ImageString().

It takes a string representation (in your case, file_get_contents($row[‘nfo’]) and converts to PNG/JPG/GIF which you then link on torrent details with

if (file_exists($nfofile) && $row[‘nfo’] == ‘yes’) {
  // Call GD here
}

Share your code and I’ll post your update.
Announce Class — 2022-05-31 19:20:41 in Downloads & Updates
Thank you, that makes complete sense. I know internal function calls cause overhead, and some functions are way faster than others (string manipulation will land you on this topic immediately).

I updated announce.php and added a peer field return method to the while loop, works great.

However as it’s entirely class-based now, the query right before the whole loop requires to be directly called with the database object ($db), and ignores the method $announce->peer() array completely no matter what I do.

Both arrays are the exact same, not sure why $db & fetch are required for that 1 query out of the entire file. Without it, no peers no nothing. Real head scratcher.
Announce Class — 2022-05-30 23:18:39 in Downloads & Updates
This class is a wrap. It works as is. Very proud of the 3-day rush on it, its running live and everything is confirmed - all methods are in full swing.

I dont know what the performance improvements using classes, or if it adds overhead but either way - its a breeze to maintain now!

Reusing the code, v3 compatible columns:
replace user_id with id
replace torrent_id with id
pay attention to all other queries

I can also just as well post my peers table structure.
Blank coment — 2022-05-30 22:29:06 in v3 Support
mostvotedplayer:

I think the best approach would be:
$body = trim($body);if (empty($body)) {    // Handle error here...}

Because hitting spacebar a few times would bypass strlen check.


I typically use this scenario, takes care of empty variable case: no default column value / fatal error -
$body = !empty($body) ? trim($body) : 'No body description.';
Announce Class — 2022-05-30 20:14:45 in Downloads & Updates
I have wondered about that, thats a good question..


<?
$output = array(
   'interval' => 1800,
   'min interval' => 600,
   'retry in' => 600,
   'complete' => 3,
   'incomplete' => 1,
   'downloaded' => 4,
   'peers' => array(
       array(
           'ip' => '(removed)',
           'port' => 20114,
           'peer_id' => '-lt0D60-�B�qB�O|�]'
       )
   )
);
$announce->bencodeOutput($output);

brings up this:

Quote:
d8:completei3e10:downloadedi4e10:incompletei1e8:intervali1800e12:min intervali600e5:peersld2:ip9:(removed)7:peer_id27:-lt0D60-�B�qB�O|�]4:porti20114eee8:retry ini600ee


Just makes no sense, peers are listed in Peers tab in uTorrent and transfers begin right away, but the download bar is red and all stats are  0 / 0 / 0  😐 I know I am pushing the array along correctly, as in the end $output is populated before its finally encoded. Really odd.
Announce Class — 2022-05-30 19:41:13 in Downloads & Updates
I've added this for faster debugging and having full control over the GET key/value pairs. Nullable too, looks better.


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' => 1,
       'key' => 1
   );
   if (!empty($keyname) && !empty($keyvalue)) {
       $keys[$keyname] = $keyvalue;
   }
   return $keys;
}
Announce Class — 2022-05-30 18:07:05 in Downloads & Updates
Quote:
Looking good mate, looks so much cleaner in functions  👍

Not sure you need all the keys especially as we go to v2 for example numwant, compact, no peer id these are no longer required.

Compact is a good example if client didn't have compact before it would not work but now all clients have it so it should be expected behaviour. The highest I've seen num want is 200 so again not needed you can limit this site side if you wish but it's not really neede

Have a look at this http://bittorrent.org/beps/bep_0052.html

Tracker GET requests have the following keys:
info_hash
peer_id
ip
port
uploaded
downloaded
left
event

You would still need a key but that's for personal use - not for client. What does the encryption function do ?

Debugging announce is a pain - not sure how you handler exceptions so might be worth wrapping querys in try/catch with the fail function


Thanks M-Jay! It was fun to do, and was certainly a pain to debug but I used the different methods in a test.php file and called the class from there, and looked for any fatal errors and dealt with them, and moved onto the next method, I did this for every method I implemented. From there, I used the browser output from the warnings/fatal errors and moved past those by faking $data['key'] = dummy so the client thinks im a peer (using fake values).

The decryption is my own implementation of validating the encrypted token in the announce url. ?token=<encrypted>
The reason why this appears strange, is because download.php is actually encrypting the url before pushing the .torrent file. I use tricky string manipulation to decrypted and extract the actual passkey.

the token is in this format: token{torrent_id, passkey}

download.php for example:
$token = encrypt_decrypt('encrypt', 'token{' . $row['torrent_id'] . ',' . $user_row['passkey'] . '}');


Passkey is still used for legacy, like my seedbox. I just use passkey format for seeding so announce still uses ?passkey=xx

Token is only for downloaded torrents. Both work if someone goes to the trouble to edit their torrents tracker url with their passkey, most likely not. It works the same. Probably faster to use the passkey tbh, some CPU goes into the decryption phase.  

@mostvotedplayer
That is a really neat concept! I totally agree, table seek time can be a killer on high volume r/w - always memory caching where live data is not considered at least in immediate expectation.

I provide Memcached query caching for our live peers and results in our main index, all ajax driven. I love the performance of that, but I dont like the stale data aspect. The bucket sizes are more than forgiving.

---

I made some further changes to announce/class to correct some issues and wrong variable values. Still not getting the stats through to the client though...
What the hell is this 🤣

if (!@count($_POST["users"])) show_error_msg(T_("ERROR"), "Rien de sélectionné.", 1);


Is $_POST["users"] an array or a key?

count($array) only counts arrays, not indexes.
Alternatively, you can also just use array_count_values($array) > 0.

Secondly, you dont need to silence '@' count(), its bad code practice and often
results in fatal errors due to the lack of conditional checks. Always compare with greater than 0 (> 0).

If this code is in a class, you want to use the Countable interface, and return result back.


if (isset($_POST["users"]) && count($_POST["users"]) > 0)) {
  show_error_msg(T_("ERROR"), "Rien de sélectionné.", 1);
}


It still makes no sense. 😲
Announce Class — 2022-05-29 16:57:00 in Downloads & Updates
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);
Every variable in this code in loosely defined and open to all kinds of issues.

Wrap your expected numbers with intval(), which defaults to 0 if not > 0 (prevents a fatal error), filter inputs (filter_var() is good to use), etc etc.

I would not use this code at this time. At best, implement rate limiting with a die() approach on excessive requests. That’s just the beginning lol..
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