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

"spiritblue, post: 69675, member: 401":

Hello

I'm looking for an old hack that allows you to select the categories to see on the torrents pages but from are account

Thank you
================================
Bonjour

Je recherche  un vieux hack qui permet de selectionner les catégories a voir sur les pages de torrents mais a partir de sont compte

Merci!


Query work. So this will be a drop down that changes torrents.categories = ID in a simple WHERE clause. The JOIN will get the actual category names.
Ajax Shoutbox V3 — 2020-12-13 01:30:53 in v3 Mods in Progress
"spiritblue, post: 69688, member: 401":

Thakns STorrents2020

why red? I want the color of the class ;)
it doesn't work it stays white


Then that involves reading the groups table and assigning colour conditions based on the class type. If still unsolved, I’ll try to do this later
"rio, post: 69674, member: 20324":

this should do it
<?php

/**

* API Request:     GET - List Games

* JSON Endpoint:  /api/public/v1/list_Games.json

* @Params:          ? $limit, $order_by, $sort_by

*/


if (array_key_exists('list_Games', $_GET)) {


   $data = $db->query_params('SELECT DISTINCT torrent_id, info_hash, name, descr AS description, cover1 AS boxart, image1 AS screen_1, image2 AS screen_2, category, size, added, comments, views, hits, times_completed AS completed, leechers, seeders, numratings AS total_ratings, external, tags, youtube, version, dlc FROM torrents ORDER BY :eek:rder_by :sort_by LIMIT :limit',

       array(

           'order_by' => strval($_GET['order_by']) ? strval($_GET['order_by']) : 'added',  // Order By - Default: added

           'sort_by' => strval($_GET['sort_by']) ? strval($_GET['sort_by']) : 'DESC',        // Sort By - Default: DESC

           'limit' => intval($_GET['limit']) ? intval($_GET['limit']) : 20)                 // Limit - Default: 20

   );

   $gameData = array();

   if ($data) {

       $listgames = $data->fetchAll();

       $status = ($data) ? 'ok' : 'error';

       $limit = 0;

       foreach ($listgames as $row => $data) {

           $limit++;

           $data = $row;

           $message = '';

           if ($data) {

               $message = 'Query was successful';

           } else {

               $message = 'Query returned error';

           }

           array_push($gameData, $listgames);

       }

   }


   echo json_encode([

       'status' => $status,

       'status_message' => $message,

       'data' =>

           [

               'game_count' => 958,

               'limit' => $limit,

               'page_number' => 1,

               'games' => json_encode($listgames, JSON_PRETTY_PRINT, JSON_INVALID_UTF8_SUBSTITUTE)


           ]

   ]);

   die();

}


/**

* API Request:     GET - Game Details

* JSON Endpoint:  /api/public/v1/Game_details.json

* @Params:         $torrent_id

*/


if (array_key_exists('Game_details', $_GET)) {

   $data = $db->query_params('SELECT torrent_id, info_hash, name, descr AS description, cover1 AS boxart, image1 AS screen_1, image2 AS screen_2, category, size, added, comments, views, hits, times_completed AS completed, leechers, seeders, numratings AS total_ratings, external, tags, youtube, version, dlc FROM torrents WHERE torrent_id = :torrent_id LIMIT 1',

       array(

           'torrent_id' => intval($_GET['torrent_id']) ? intval($_GET['torrent_id']) : 1)      // Torrent ID - Default: 1

   );

   $gameData = array();

   if ($data) {

       $listdetails = $data->fetchAll();

       $status = ($data) ? 'ok' : 'error';

       foreach ($listdetails as $row => $data) {

           $data = $row;

           $message = '';

           if ($data) {

               $message = 'Query was successful';

           } else {

               $message = 'Query returned error';

           }

           array_push($gameData, $listdetails);

       }

   }

   echo json_encode(

       [

           'status' => $status, '

           status_message' => $message,

           'data' => json_encode($listdetails, JSON_PRETTY_PRINT, JSON_INVALID_UTF8_SUBSTITUTE)

       ]);


}



Nice! Thank you
— 2020-12-12 23:07:54 in
Perfect, even less work to do. Otherwise I have no sessions clearing out of sessions table, which cant be a good thing - 9000 rows, while the other 21,000 are clearing out? Login class seems to be failing on REPLACE query, and remote sessions have no action when "signing out from other locations"
— 2020-12-12 22:28:17 in
Thank you, I didnt write any of that and the guy behind most of the functions is highly skilled so I dont dare touch any of it.

So I do have full CSRF protection out of the box in a few functions, so he has already implemented that accurately.

What I did to confirm this:

I created a offline html file with a full form including my username and password in value fields and submitted to full url / login.php with JS attack code. Completely white page, dead.

I then disable the csrf check functions on login.php and try the attack again, now it logged me in immediately (very bad). So i confirm its very protected in that regard, using the $_SESSION as array storage, which confused me as I am using database session indentifiers and not the super global $_SESSION['username'] for example, apparently that doesn't matter at all as the browser is checking for this regardless (very good thing).

So with CSRF protection confirmed & out of the way, we move on next to storing CSRF tokens => database table (is this possible or even necessary?).

I will implement bruteForce() to my login page and hammer requests using a program, and report back how that does in the database


<?
function loginTries() : int
{
   global $db;
   $query = $db->query_params('SELECT alltimes FROM bruteforces WHERE ip = :ip AND alldate = NOW()', array('ip' => getip()));
   return count($query) == 0 ? 0 : $query->fetch();
}

function bruteForce() : bool
{
   return loginTries() > 5 ? true : false;
}

function triesLogin()
{
   global $db;
   $logins = loginTries();
   if ($logins > 0) {
       $db->query_params('UPDATE bruteforces SET alltimes = :logins + 1 WHERE ip = :ip AND alldate = NOW()', array('logins' => $logins, 'ip' => getip()));
   } else {
       $db->query_params('INSERT INTO bruteforces (ip, alldate) VALUES(:ip, NOW())', array('ip' => getip()));
   }
}
— 2020-12-12 21:09:44 in
Currently these are implemented but inactive:


function random_hash() {
   $s = openssl_random_pseudo_bytes(30);
   if ($s === null) {
       die('no source of randomness');
   }
   return md5($s);
}

function check_csrf() {
   if (!array_key_exists('csrf', $_POST) || $_POST['csrf'] !== $_SESSION['csrf']) {
       die;
   }
}

function csrf_html() {
   printf('<input type="hidden", name="csrf" value="%s" />', html_escape($_SESSION['csrf']));
}

function gen_csrf($replace = false) {
   if ($replace || !array_key_exists('csrf', $_SESSION)) {
       $_SESSION['csrf'] = random_hash();
   }
}


Database sessions do not support this currently, so your class should take care of this as using token authentication correct?
Ajax Shoutbox V3 — 2020-12-12 19:46:30 in v3 Mods in Progress
"spiritblue, post: 69678, member: 401":

Hello I try to color the username for Reply_code But I can't display the grade color Here is what I did and which does not work ...

In getshout.php
$name = $row['name'];


For:
$name = class_user($row['name']);


Thank you for your help.


Where is the variable $name held? You should be able to append a string, like

$name =  ’<span style=“color:red”>’ . class_user($row[“name”]) . ‘</span>’;
— 2020-12-12 18:34:04 in
Thank you so much [USER=20288]@m-jay[/USER] and i appreciate the full written rundown, I will implement this today and monitor that table. We have had CSRF protection since the exit from TT back in August, but it’s never been supported by the user class
Thank you!
Update

As this class has evolved on our own site, including a custom sidebar item with live GB stats on voucher claims, I will only port this to the MVC PDO database class, not mysqli or mysql for stability and security. It’s time to start upgrading your PHP versions / database servers, people!

I did some time cleverly working with the JSON user column, exploding each userid and again iterating that in another loop, while grabbing the voucher ID => display data allowance per redemption, the rest was easy.

[ATTACH type="full" alt="E1981546-6CE8-42E8-9833-8B42F9DA76EE.jpeg"]5993[/ATTACH]


$claimedusers = $db->query_params('SELECT * FROM vouchers');
$pua          = $claimedusers->fetch();
$userlist     = '';
$o            = array();
foreach ($pua as $userid) {
   $uarr  = json_decode($userid, true);
   $nuarr = explode(';', $uarr['users']);
   foreach ($nuarr as $userid) {
       $o[] = $userid;
       $qry = $db->query_params('SELECT user_id, avatar_thumb AS avatar FROM users WHERE user_id = :uid', array('uid' => $userid)) or die('Unable to retrieve users.');
       while ($u = $qry->fetch()) {
           if ($userid['id'] == 1)
               $allowance = '500 MB';
           if ($userid['id'] == 2)
               $allowance = '8 GB';
           $userlist .= "<span style=\"border-top-right-radius:4px;border-bottom-right-radius:4px;margin-right:-5px;width:100px;color:#FFF;padding:5px 5px 5px 11px;text-align:center;background:#7FB335;text-shadow:0 1px 1px rgba(0,0,0,.3)\"><a href=\"/user/?id=" . $u['user_id'] . "/\"><img style=\"vertical-align:middle;border:2px solid #FFF;width:40px;height:40px;border-radius:50%;margin-right:10px\" src=\"https://www.switch-torrents.com/$u[avatar]\" /></a>+$allowance</span>";
       }
   }
}
echo $userlist;
"phoenix75, post: 69616, member: 1185":

update

[php]
CREATE TABLE `staffnavigate` (
 `id` bigint(20) NOT NULL auto_increment,
 `link` varchar(100) NOT NULL default '',
 `name` varchar(100) NOT NULL default '',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8_unicode_ci;

INSERT INTO `staffnavigate` VALUES(1, 'admincp.php?action=avatars', 'Avatar Log');
INSERT INTO `staffnavigate` VALUES(2, 'admincp.php?action=backups', 'Backups');
INSERT INTO `staffnavigate` VALUES(3, 'admincp.php?action=bannedtorrents', 'Banned Torrents');
INSERT INTO `staffnavigate` VALUES(4, 'admincp.php?action=blocks&do=view', 'Blocks');
INSERT INTO `staffnavigate` VALUES(5, 'admincp.php?action=cheats', 'Detect Possible Cheaters');
INSERT INTO `staffnavigate` VALUES(6, 'admincp.php?action=emailbans', 'Email Bans');
INSERT INTO `staffnavigate` VALUES(7, 'faq-manage.php', 'FAQ');
INSERT INTO `staffnavigate` VALUES(8, 'admincp.php?action=freetorrents', 'Free Leech Torrents');
INSERT INTO `staffnavigate` VALUES(9, 'admincp.php?action=lastcomm', 'Latest Comments');
INSERT INTO `staffnavigate` VALUES(10, 'admincp.php?action=masspm', 'Mass PM');
INSERT INTO `staffnavigate` VALUES(11, 'admincp.php?action=messagespy', 'Message Spy');
INSERT INTO `staffnavigate` VALUES(12, 'admincp.php?action=news&do=view', 'News');
INSERT INTO `staffnavigate` VALUES(13, 'admincp.php?action=peers', 'Peers List');
INSERT INTO `staffnavigate` VALUES(14, 'admincp.php?action=polls&do=view', 'Polls');
INSERT INTO `staffnavigate` VALUES(15, 'admincp.php?action=reports&do=view', 'Reports');
INSERT INTO `staffnavigate` VALUES(16, 'admincp.php?action=rules&do=view', 'Rules');
INSERT INTO `staffnavigate` VALUES(17, 'admincp.php?action=sitelog', 'Site Log');
INSERT INTO `staffnavigate` VALUES(18, 'teams-create.php', 'Teams');
INSERT INTO `staffnavigate` VALUES(19, 'admincp.php?action=categories&do=view', 'Torrent Categories');
INSERT INTO `staffnavigate` VALUES(20, 'admincp.php?action=torrentmanage', 'Torrents');
INSERT INTO `staffnavigate` VALUES(21, 'admincp.php?action=torrentlangs&do=view', 'Torrent Languages');
INSERT INTO `staffnavigate` VALUES(22, 'admincp.php?action=groups&do=view', 'User Groups');
INSERT INTO `staffnavigate` VALUES(23, 'admincp.php?action=users', 'Users');
INSERT INTO `staffnavigate` VALUES(24, 'admincp.php?action=warned', 'Warned Users');
INSERT INTO `staffnavigate` VALUES(25, 'admincp.php?action=whoswhere', 'Who\'s Where');
INSERT INTO `staffnavigate` VALUES(26, 'admincp.php?action=style', 'Theme Management');
INSERT INTO `staffnavigate` VALUES(27, 'admincp.php?action=censor', 'Word Censor');
[/php]


add in functions.php:

[php]
function staffnavigatelist() {
   $ret = array();
   $res = SQL_Query_exec("SELECT id, link, name FROM staffnavigate ORDER BY id ASC");

while ($row = mysql_fetch_array($res))
   $ret[] = $row;
       return $ret;
}
[/php]


make a new file called staffnavigate_block.php and put this inside:

[php]
<?php
if (!$site_config["MEMBERSONLY"] || $CURUSER && $CURUSER["control_panel"]=="yes") {
begin_block("" . STAFFCP . "");
?>

<center>
<form>
   <select name="staffnavigate" onChange="location = options[selectedIndex].value">
   <option value="0">Please Select</option>

<?php
   $staffnavigate = staffnavigatelist();
   $staffnavigatedropdown = "";
   foreach ($staffnavigate as $staffnavigate) {
   $staffnavigatedropdown .= "<option value=\"" . $staffnavigate["link"] . "\"";

if ($staffnavigate["id"] == $_GET["navigate"])
   $staffnavigatedropdown .= " selected=\"selected\"";
   $staffnavigatedropdown .= ">" . htmlspecialchars($staffnavigate["name"]) . "</option>\n";
}
?>

<?php echo $staffnavigatedropdown; ?>

</select>
   <input type="hidden">
</form>
</center>

<?php
end_block();
}
?>
[/php]


now find in admincp.php:

[php]
<td align="center"><a href=admincp.php?action=censor><img src="images/admin/censor.png" border=0 width=32 height=32><BR>Word Censor</a><br /></td>
[/php]


add after:

[php]
<td align="center"><a href=admincp.php?action=staffnavigatelinks><img src="images/admin/external.gif" border=0 width=32 height=32><BR>Staff<BR>Navigation Links</a><br /></td>
[/php]


now add at the end of admincp.php:

[php]
#===================================================#
#                Staff Navigation Links                #
#===================================================#
if ($action == "staffnavigatelinks") {
if ($CURUSER["class"] < "15") {
   show_error_msg("Error","Sorry you do not have the rights to view this page!", 1);
}

if ($_GET["id"] != "") {
   $id = (int) $_GET["id"];
   SQL_Query_exec("DELETE FROM staffnavigate WHERE id= $id");
}

stdhead("Staff Navigation Links");
navmenu();

begin_frame("Staff Navigation Links");
?>

<center>
<table align="center" cellpadding="0" cellspacing="0" class="table_table" width="100%" border="1">

<tr>
   <td class="table_head" align="center">ID</td>
   <td class="table_head" align="center">Link</td>
   <td class="table_head" align="center">Name</td>
   <td class="table_head" align="center">Delete</td>
</tr>

<?php
       $res=SQL_Query_exec("SELECT id,link,name FROM staffnavigate ORDER BY id ASC");
while($row=mysql_fetch_array($res)) {
extract ($row);

       $id=$row["id"];
       $link=$row["link"];
       $name=$row["name"];

       echo "<tr><td class=table_col1>$id</td><td class=table_col1>$link</td><td class=table_col1>$name</td><td class=table_col1><a href='admincp.php?action=staffnavigatelinks&id=$id'>Delete</a></td></tr>\n";
}
   echo "</table></center>\n";

end_frame();

if ($_SERVER["REQUEST_METHOD"] == "POST"){
if ($_POST["link"] == "" || $_POST["name"] == "")
   show_error_msg("Error", "missing form data.");
   $name = $_POST["name"];
   $link = $_POST["link"];
   SQL_Query_exec("INSERT INTO staffnavigate (link, name) VALUES('$link', '$name')");
}

begin_frame("Add Links");

?>
<form method="post" action=admincp.php?action=staffnavigatelinks>
<?php begin_table(TRUE); ?>
<div align=center>
<br /><font size="3"><b>Example Link: admincp.php?action=avatars</b></font><br />
<br /></div><br />
<tr><td class="tableb">Link:</td><td class="tablea"><input type="text" name="link" size="60"></td></tr>
<tr><td class="tableb">Name:</td><td class="tablea"><input type="text" name="name" size="60"></td></tr>
<tr><td class="tablea" colspan="2" style="text-align:center"><input type="submit" value="Okay" class="btn"></td></tr>
<?php end_table(); ?>
</form>

<?php
end_frame();
stdfoot();
}

#=======================================================#
#                END Staff Navigation Links                #
#=======================================================#
[/php]


You can simply build a array that holds all of the admincp.php URL parameters and iterate the entire list of param keys so you don’t have to write 27 INSERT statements, just call the query once.
Im working on a public API (version 1) in the GET stages of the documentation for application building / feeding data.

Just logging my progress as I shift a full API sandbox.

[color=rgb(65, 168, 95)]VALID (RFC 8259)[/color]

Stage 1: Retrieve data : endpoint parameters


/*
   API Request:     GET - List Games
   JSON Endpoint:  /api/public/v1/list_Games.json
   Params:          ? limit, order_by, sort_by
*/

if (array_key_exists('list_Games', $_GET)) {
   $data = $db->query_params('SELECT DISTINCT torrent_id, info_hash, name, descr AS description, cover1 AS boxart, image1 AS screen_1, image2 AS screen_2, category, size, added, comments, views, hits, times_completed AS completed, leechers, seeders, numratings AS total_ratings, external, tags, youtube, version, dlc FROM torrents ORDER BY :order_by :sort_by LIMIT :limit',
   array(
   'order_by' => strval($_GET['order_by']) ? strval($_GET['order_by']) : 'added',  // Order By - Default: added
   'sort_by' => strval($_GET['sort_by']) ? strval($_GET['sort_by']) : 'DESC',        // Sort By - Default: DESC
   'limit' => intval($_GET['limit']) ? intval($_GET['limit']) : 20)                 // Limit - Default: 20
   );
   $gameData = array();
   if ($data) {
       $listgames = $data->fetchAll();
       $status = ($data) ? 'ok' : 'error';
       $limit = 0;
       foreach ($listgames as $row => $data) {
           $limit++;
           $data = $row;
           $message = '';
           if ($data) {
               $message = 'Query was successful';
           }else{
               $message = 'Query returned error';
           }
           array_push($gameData, $listgames);
       }
   }
   echo "{\"status\":\"$status\",\"status_message\":\"$message\",\"data\":{\"game_count\":958,\"limit\":$limit,\"page_number\":1,\"games\":" . json_encode($listgames, JSON_PRETTY_PRINT, JSON_INVALID_UTF8_SUBSTITUTE) . "}}";
   die;
}

/*
   API Request:     GET - Game Details
   JSON Endpoint:  /api/public/v1/Game_details.json
   Params:          torrent_id
*/

if (array_key_exists('Game_details', $_GET)) {
   $data = $db->query_params('SELECT torrent_id, info_hash, name, descr AS description, cover1 AS boxart, image1 AS screen_1, image2 AS screen_2, category, size, added, comments, views, hits, times_completed AS completed, leechers, seeders, numratings AS total_ratings, external, tags, youtube, version, dlc FROM torrents WHERE torrent_id = :torrent_id LIMIT 1',
   array(
   'torrent_id' => intval($_GET['torrent_id']) ? intval($_GET['torrent_id']) : 1)      // Torrent ID - Default: 1
   );
   $gameData = array();
   if ($data) {
       $listdetails = $data->fetchAll();
       $status = ($data) ? 'ok' : 'error';
       foreach ($listdetails as $row => $data) {
           $data = $row;
           $message = '';
           if ($data) {
               $message = 'Query was successful';
           }else{
               $message = 'Query returned error';
           }
           array_push($gameData, $listdetails);
       }
   }
   echo "{\"status\":\"$status\",\"status_message\":\"$message\",\"data\":" . json_encode($listdetails, JSON_PRETTY_PRINT, JSON_INVALID_UTF8_SUBSTITUTE) . "}";
   die;
}
Try changing peers.seeder = ‘no’

to

peers.seeder = ‘yes’

Now you are showing all torrents you are currently seeding, with speeds etc.

If that fails, tell us or screenshot what HeidiSQL says.
Works for me, i dunno. Maybe that cache stuff is issue?
I believe I INTENDED to have this working for mysqli lol - i wont back down from that, give me this evening and I make it official
"niki, post: 69658, member: 20338":

Hello and thank you for sharing but the block doesn't show anything ???


[ATTACH type="full" alt="1607184633199.png"]5990[/ATTACH]


[ATTACH type="full"]5992[/ATTACH]

Try this


<?php
// TTv3 Active Transfers - Block
function calc_speed($b) {
   if ($b < 1024) return round($b,2) . 'B/Sec';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'KB/Sec';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'MB/Sec';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'GB/Sec';
   $b /= 1024.0;
   return round($b,2) . 'TB';
}
function calc_size($b) {
   if ($b < 1024) return round($b,2) . 'B';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'KB';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'MB';
   $b /= 1024.0;
   if ($b < 1024) return round($b,2) . 'GB';
   $b /= 1024.0;
   return round($b,2) . 'TB';
}
if (get_user_class() >= 7) {
   begin_block(T_("ACTIVE_TRANSFERS"));
   $expires = 1200;
   if (($rows = $TTCache->Get("activetransfers_block", $expires)) === false) {
       $res = SQL_Query_exec("SELECT (SUM(peers.downloaded)) / (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(peers.started)) AS speed, peers.seeder, peers.id, peers.connectable, users.id, peers.started, torrents.id AS torrentid, torrents.name, torrents.size, peers.to_go FROM peers LEFT JOIN torrents ON torrents.id = peers.id LEFT JOIN users ON peers.id = users.id WHERE peers.id = $CURUSER[id] AND peers.seeder = 'no' GROUP BY peers.started DESC LIMIT 6");
       while ($row = mysqli_fetch_assoc($res)) {
           $rows = $row;
           if (array_key_exists('torrentid', $row)) {
               print("Active Transfers: <div><a href='torrents-details.php?id=$row[torrentid]'>$row[name]</a></div><div>Speed: " . calc_speed($row['speed']) . ", Size: " . calc_size($row['size']) . "</div>");
           } else {
               echo T_("NO_ACTIVE_TRANSFERS");
           }
       }
       $TTCache->Set("activetransfers_block", $rows, $expires);
   }
   end_block();
}
?>
It appears i never converted this for TT for some reason, and not sure why I posted in this section, I must of been very tired. I'll take care of that
Announce/BETA7 — 2020-12-03 06:10:24 in Downloads & Updates
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);
Looking at your Test class, it looks like a LOT of code is missing, like data streams and routine logic, quite a lot happening in the class so I think it’s best to look at that, I know nothing about abstract extending and abstract functions, it’s possible it just needs a copy over
$foo = array();
foreach ($ret as $array => $keys)  {
  $keys[‘value’] = $array[‘othervalue’];
array_push($ret, $foo)
}

// call $ret now
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: 3
  • Members: 1
  • Guests online: 2
  • Comments: 3
  • Messages: 1,728