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

if this tests well i wll add scrape controller (scraper & mega-scraper)
make sure in config you allow external and here is a upd torrent
Requested by [USER=19833]@Botanicar[/USER] new scraper to replace broken base one. Pretty basic at minute ideally it should be added to upload as well instead you must refresh page for stats, maybe should be on automatic timer so only scrapes every three days if torrent viewed etc
Been meaning to do this for a while, using https://www.torrenttrader.xyz/index.php?threads/scrape-udp-trackers.9795/ and https://github.com/johannes85/PHP-Torrent-Scraper/tree/master/src

Writing for pdo but if any one wants to try on v3 feel free to post - for v3 you would need to add the classes to backend and require them at top of functions.php the rest would just be query's
I dont use this so please share any thoughts on improvement

Need tests on pdo before i add to base but seems to work fine
unzip classes folder
add the classes to the classes folder (scraper.php, scraperexception.php, updscraper.php)
in views/torrent/read.php find

<!--buttonsstart-->


Replace everything below with

<!--buttonsstart-->
<td align="left"> <?php
/// Scrape code
   /// Scrape code
   //===| Scrape External Torrents
   if ($row["external"] == 'yes') {
       print("<td width='160' align='right' valign='top'><table><tr>");
       if ($scrape == '1') {
           print("<td class='table_col1' width='150' valign='middle'>
       <div style='margin-top:5px; margin-bottom:10px; font:bold 16px Times' align='center'><font color='#FF2000'>" . T_("EXTERNAL_TORRENT") . "</font></div>");

           $resu = DB::run("SELECT id, info_hash FROM torrents WHERE external = 'yes' AND id = $id");
           while ($rowu = $resu->fetch(PDO::FETCH_ASSOC)) {
               //parse torrent file
               $torrent_dir = $config["torrent_dir"];
               $TorrentInfo = array();
               $TorrentInfo = ParseTorrent("$torrent_dir/$rowu[id].torrent");

               $ann = $TorrentInfo[0];
               $annlist = array();

               if ($TorrentInfo[6]) {
                   foreach ($TorrentInfo[6] as $ann) {
                       $annlist[] = $ann[0];
                   }
               } else {
                   $annlist = array($ann);
               }

               $seeders = $leechers = $downloaded = null;
               foreach ($annlist as $ann) {
                   $tracker = explode("/", $ann);
                   $path = array_pop($tracker);
                   $oldpath = $path;
                   $path = str_replace("announce", "scrape", $path);
                   $tracker = implode("/", $tracker) . "/" . $path;

                   if ($oldpath == $path) {
                       continue;
                   }

                   if (preg_match('/udp:\/\//', $tracker)) {
                       $udp = true;
                       try
                       {
                           $timeout = 5;
                           $udp = new Udpscraper($timeout);
                           $stats = $udp->scrape($tracker, $rowu["info_hash"]);
                           //print_r($stats); exit();
                           foreach ($stats as $idu => $scrape) {
                               $seeders += $scrape['seeders'];
                               $leechers += $scrape['leechers'];
                               $downloaded += $scrape['completed'];
                           }
                       } catch (ScraperException $e) {
                           $e->isConnectionError();
                       }
                   } else {
                       $stats = torrent_scrape_url($tracker, $rowu["info_hash"]);
                       /*
                       $http = true;
                       try {
                           $timeout = 5;
                           $http = new HttpScraper($timeout);
                           $stats = $http->scrape($tracker, $rowu["info_hash"]);
                           //print_r($stats); exit();
                           foreach ($stats as $idu => $scrape) {
                               $seeders += $scrape['seeders'];
                               $leechers += $scrape['leechers'];
                               $downloaded += $scrape['completed'];
                           }
                       } catch (ScraperException $exc) {
                           $exc->isConnectionError();
                       }
                       */
                   }

                   if ($stats['seeds'] != -1) {
                       $seeders += $stats['seeds'];
                       $leechers += $stats['peers'];
                       $downloaded += $stats['downloaded'];

                       DB::run("
                       UPDATE `announce`
                       SET `online` = ?, `seeders` = ?, `leechers` = ?, `times_completed` = ?
                       WHERE `url` = ?
                       AND `torrent` = ?",
                       ['yes', $stats['seeds'], $stats['peers'], $stats['downloaded'], $ann, $rowu['id']]);
                   } else {
                       DB::run("
                       UPDATE `announce`
                       SET `online` = ?
                       WHERE `url` = ?
                       AND `torrent` = ?",
                       ['no', $ann, $rowu['id']]);
                   }
               }

               if ($seeders !== null) {
                   DB::run("
                   UPDATE torrents
                   SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
                   WHERE id = ?",
                       [$leechers, $seeders, $downloaded, get_date_time(), 'yes', $rowu['id']]);
               } else {
                   DB::run("
                   UPDATE torrents
                   SET last_action = ?
                   WHERE id=?", [get_date_time(), $rowu['id']]);
               }
           }
           //===| End UDP Scraper

           if ($seeders !== null) {
               print("<div style='margin-bottom:5px; margin-left:20px'><b>" . T_("LIVE_STATS") . "</b>: </div>");
               print("<div style='margin-left:20px'>" . T_("SEEDERS") . ": <font color='limegreen'>" . $seeders . "</font></div>");
               print("<div style='margin-left:20px'>" . T_("LEECHERS") . ": <font color='#FF2000'>" . $leechers . "</font></div>");
               print("<div style='margin-left:20px'>" . T_("COMPLETED") . ": <font color='#0080FF'>" . $downloaded . "</font></div>");
               print("</br>");
           } else {
               print("<div style='margin-top:10px; margin-bottom:5px' align='center'><b>" . T_("LIVE_STATS") . "</b>: </div>");
               print("<div style='font:italic 14px Times' align='center'><font color='#FF2000'>" . T_("TRACKERS_OFFLINE") . "!</font></div>");
           }
           print("</td>");
       } else {
           print("<td class='table_col1' width='150' valign='middle' align='center'>
           <div style='margin-top:5px; margin-bottom:10px; font:bold 16px Times' align='center'><font color='#FF2000'>" . T_("EXTERNAL_TORRENT") . "</font></div>
           </div>
               <form action='$config[SITEURL]/torrents/read?id=$id&amp;scrape=1' method='post'>
                   <div style='margin-top:5px; margin-bottom:10px' align='center'><input type='submit' name='submit' value=" . T_("UPDATE_STATS") . " /></div>
               </form>
           </td>");
       }
       print("</tr></table></td>");
   }
//===| End Scrape External Torrents
   ?>
           </td>
           </td>
       </tr>
       </table>
       <?php
}

//DISPLAY NFO BLOCK
if ($row["nfo"] == "yes") {
   $nfofilelocation = "$nfo_dir/$row[id].nfo";
   $filegetcontents = file_get_contents($nfofilelocation);
   // needs filtering better todo
   //    $nfo = htmlspecialchars($filegetcontents);
   $nfo = $filegetcontents;
   if ($nfo) {
       $nfo = my_nfo_translate($nfo);
       echo "<br /><br /><b>NFO:</b><br />";
       print("<div><textarea class='nfo' style='width:98%;height:100%;' rows='20' cols='20' readonly='readonly'>" . stripslashes($nfo) . "</textarea></div>");
   } else {
       print(T_("ERROR") . " reading .nfo file!");
   }
}
github updated  (y) going to try put scraper together this weekend ;)
If using another theme change user theme to default and ill add list of changes
Yes just checking everything before updating github and I'll send the updated theme back, just need to check on live server hopefully tomorrow m8
— 2020-10-11 07:15:28 in
Which file are you editing [USER=19833]@Botanicar[/USER] is it a custom one like the old ttce.css
You will know blocks code is different on bootstrap , but do you have others on old one like shoutbox.php ?
I just added new theme with better bootstrap mapping - if you send your theme progress I will take a look
I have a few TT bootstrap templates that might help

I will be using little templates like this then I include them when needed like you do the the footer/header.php etc this is disclaimer on index.php
<?php
$title = "Disclaimer";
$blockId = "b-" . sha1($title);
?>

<div class="card">
   <div class="card-header">
       <?php echo $title ?>
       <a data-toggle="collapse" href="#" class="showHide" id="<?php echo $blockId; ?>" style="float: right;"></a>
   </div>
   <div class="card-body slidingDiv<?php echo $blockId; ?>">
   <!-- content -->

       <p class="text-center">
           None of the files shown here are actually hosted on this server. The links are provided
           solely by this sites users. The administrator of this site cannot be held responsible for
           what its users post, or any other actions of its users. You may not use this site to
           distribute or download any material when you do not have the legal rights to do so. It is
           your own responsibility to adhere to these terms.
       </p>

   <!-- end content -->
   </div>
</div>
<br />
just added a new core and moved themes if you want to PM your theme [USER=60]@Propaganda[/USER] ill make the changes

here is new core for mvc, this is the skeleton and can be run with only 7 files

obvs the db class and you can use this for anything not just TT you just need to add home controller, view & model at minute the old TT is spaghetti code but with good classes can be really slimmed down ive been saving classes for some time now so just need to implement them.

index.php
<?php
require_once "core/TTcore.php";
TTcore::run();


TTcore.php
<?php
class TTcore
{

   public static function run()
   {
       self::init();
       self::autoload();
       self::dispatch();
   }

   private static function init()
   {
       // Define path constants
       define("DS", DIRECTORY_SEPARATOR);
       define("ROOT", __DIR__ . DS);
       // Core
       require "core/Database.php"; // Extened PDO connection
       require "core/Router.php"; // Set Paths
       require "core/Controller.php"; // Load Models/Views
       // Include all helpers & connection
       require_once "helpers/a_start_function.php";
       session_start();
   }

   private static function autoload()
   {
       // Autoload Classes (Controllers & Models already loaded)
       spl_autoload_register ( function ($class) {
           $sources = array("classes/$class.php"); // just one for now but it is a array
               foreach ($sources as $source) {
                   if (file_exists($source)) {
                       require_once $source;
                   }
               }
           });

   }

   private static function dispatch()
   {
       $router = new Router;
   }

}


controller.php (puts models and views into controllers)
<?php
/*
* Base Controller
* Loads the models and views
*/
class Controller
{
   // Load model
   public function model($model)
   {
       // Require model file
       require_once 'models/' . $model . '.php';

       // Instatiate model
       return new $model();
   }

   // Load View (we add data with array $data[] )
   public function view($file, $data = [], $inc = false)
   {
       global $config, $THEME, $LANGUAGE;
       // Check for view file
       if (file_exists('views/' . $file . '.php')) {
           if ($inc) {
               require "themes/" . ($_SESSION['stylesheet'] ?: $config['default_theme']) . "/header.php";
               require "themes/" . ($_SESSION['stylesheet'] ?: $config['default_theme']) . "/topnavbar.php";
               require_once "views/" . $file . ".php";
               require "themes/" . ($_SESSION['stylesheet'] ?: $config['default_theme']) . "/footer.php";
           } else {
               require_once "views/" . $file . ".php";
           }
       } else {
           // View does not exist
           die('View does not exist');
       }
   }
}


router.php (links everything together)
<?php
/*
* App Router Class
* Creates URL & loads core controller
* URL FORMAT - /controller/method/params
*/
class Router
{
   protected $currentController = 'Home';
   protected $currentMethod = 'index';
   protected $params = [];

   public function __construct()
   {
       //print_r($this->getUrl());

       $url = $this->getUrl();

       // Look in controllers for first value
       if (file_exists('controllers/' . ucwords($url[0]) . '.php')) {
           // If exists, set as controller
           $this->currentController = ucwords($url[0]);
           // Unset 0 Index
           unset($url[0]);
       }

       // Require the controller
       require_once 'controllers/' . $this->currentController . '.php';

       // Instantiate controller class
       $this->currentController = new $this->currentController;

       // Check for second part of url
       if (isset($url[1])) {
           // Check to see if method exists in controller
           if (method_exists($this->currentController, $url[1])) {
               $this->currentMethod = $url[1];
               // Unset 1 index
               unset($url[1]);
           }
       }

       // Get params
       $this->params = $url ? array_values($url) : [];

       // Call a callback with array of params
       call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
   }

   public function getUrl()
   {
       if (isset($_GET['url'])) {
           $url = rtrim($_GET['url'], '/');
           $url = filter_var($url, FILTER_SANITIZE_URL);
           $url = explode('/', $url);
           return $url;
       }
   }
}
It's not complex at all I find it much simpler, plus small size
The speed is average compared to v3 just need to find time to work on it it's a long task.
Only thing not working is scraper got idea for that though
/db.php  should be /config.php, for clarity is the serve folder public_html and classes / advert outside of the public or transfer all (upload folder) into public_html folder (where the index.php normally is)
"Propaganda, post: 69371, member: 60":

- login page has footer. Frontpage and other pages are missing footer. Maybe this is because of the Poll Block...which is now empty.
- The VIP Option should only be visible for VIP/Mods/Super Mods/Admin. Normal uploader should not have the option.
- poll vote


dont have these issues at minute but ill do fresh install later today and check again, rest is fixed
- For Members and Power Users, which by default should not be able to upload, the menu item to upload torrents should lead them to the Uploader application mod. https://www.torrenttrader.xyz/index.php?threads/uploader-app.3531/      At this moment it will throw an error page.
[color=rgb(250, 197, 28)]is this set  [/color][color=rgb(250, 197, 28)]$config["UPLOADERSONLY"] ? (still need to work on applications)[/color]

looks like the iplog table is missing a key, good idea [USER=20382]@STorrents2020[/USER] just need to insert original ip i thought signup but there is no id that is added as auto inc after the query might see if i can get that login query working ideally this should be last 5 ips or in config (iphistorylimit for large sites) if not the dbconn or userlogin should be possible or using username instead
going to throw this on a server later on, thanks for this and your hard work
thread cleaned and slimmed, github updated https://github.com/M-jay84/Torrent-Trader-MVC-PDO-OOP
Post cleaned, and slimmed any post with bugs/observations which are now fixed have been removed so can be tracked better  (y)
Updating github today ;)

To keep first post these have been fixed
-  Text field for new topic is small
- The "Browse Torrents" block, the link for "Show all of" is not correct.
- When mobile screen, logo should change to alternative smaller image.
- Selecting multiple message, and next select "Make Selected as Read" does not work
- When you have actually read a message, the system does not auto update the status of the message to "Read"
- Voting results in blank page
Shoutbox:
- Full Date vs time vs width
First post updated, seems to work fine i have added pdo class for v3 backend, sure i can get this slimmer

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

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

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

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

function err($msg)
{
   return benc_resp_raw("d" . benc_str("failure reason") . benc_str($msg) . "e");
}

function benc_str($s)
{
   return strlen($s) . ":$s";
}

function benc_int($i)
{
   return "i" . $i . "e";
}

function benc_resp_raw($x)
{
   header("Content-Type: text/plain");
   header("Pragma: no-cache");

   if (extension_loaded('zlib') && !ini_get('zlib.output_compression') && $_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
       header("Content-Encoding: gzip");
       echo gzencode($x, 9, FORCE_GZIP);
   } else {
       print($x);
   }

   exit();
}

function gmtime()
{
   return strtotime(get_date_time());
}

function get_date_time($timestamp = 0)
{
   if ($timestamp) {
       return date("Y-m-d H:i:s", $timestamp);
   } else {
       return gmdate("Y-m-d H:i:s");
   }

}

function portblacklisted($port)
{
   // direct connect
   if ($port >= 411 && $port <= 413) {
       return true;
   }

   // kazaa
   if ($port == 1214) {
       return true;
   }

   // gnutella
   if ($port >= 6346 && $port <= 6347) {
       return true;
   }

   // emule
   if ($port == 4662) {
       return true;
   }

   // winmx
   if ($port == 6699) {
       return true;
   }

   return false;
}

//////////////////////// NOW WE DO THE ANNOUNCE CODE ////////////////////////

// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
if (preg_match("/^Mozilla|^Opera|^Links|^Lynx/i", $agent)) {
   die("No");
}

//GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
   $GLOBALS[$x] = $_GET[$x];
}

foreach (array("port", "downloaded", "uploaded", "left") as $x) {
   $GLOBALS[$x] = 0 + $_GET[$x];
}

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

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

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

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

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

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

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

}

$ip = $_SERVER["REMOTE_ADDR"];

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

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

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

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

$dbh = new Database();

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

//End Agent Bans

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

$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey, g.can_download"; //user details to get

$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get

$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

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

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

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

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

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

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

$torrentid = $torrent["id"];

//Now get data from peers table
$peerlimit = 50;
$numpeers = $torrent["numpeers"];
if ($numpeers > $peerlimit) {
   $limit = "ORDER BY RAND() LIMIT $peerlimit";
} else {
   $limit = "";
}
$res = $dbh->run("
      SELECT $peerfields
      FROM peers
      WHERE torrent = $torrentid $limit")
      or err("Error Selecting Peers");

//DO SOME BENC STUFF TO THE PEERS CONNECTION
$resp = "d8:completei$torrent[seeders]e10:downloadedi$torrent[times_completed]e10:incompletei$torrent[leechers]e";
$resp .= benc_str("interval") . "i" . $config['announce_interval'] . "e" . benc_str("min interval") . "i300e" . benc_str("peers");
unset($self);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
   if ($row["peer_id"] === $peer_id) {
       $self = $row;
       continue;
   }

   $peers .= "d" . benc_str("ip") . benc_str($row["ip"]);
   if (!$no_peer_id) {
       $peers .= benc_str("peer id") . benc_str($row["peer_id"]);
   }

   $peers .= benc_str("port") . "i" . $row["port"] . "ee";
}
$resp .= "l{$peers}e";
$resp .= "ee";

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

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

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

   }

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

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

   }

   $res = $dbh->run("SELECT $peerfields FROM peers WHERE torrent = ? AND peer_id = ?", [$torrentid, $peer_id]);
   $row = $res->fetch(PDO::FETCH_ASSOC);
   if ($row) {
       $self = $row;
   }
}
// END $SELF FILL

if (!isset($self)) { //IF PEER IS NOT IN PEERS TABLE DO THE WAIT TIME CHECK
   if ($MEMBERSONLY_WAIT && $MEMBERSONLY) {
       //wait time check
       if ($left > 0 && in_array($user["class"], explode(",", $config["WAIT_CLASS"]))) { //check only leechers and lowest user class
           $gigs = $user["uploaded"] / (1024 * 1024 * 1024);
           $elapsed = floor((gmtime() - $torrent["ts"]) / 3600);
           $ratio = (($user["downloaded"] > 0) ? ($user["uploaded"] / $user["downloaded"]) : 1);
           if ($ratio == 0 && $gigs == 0) {
               $wait = $config["WAITA"];
           } elseif ($ratio < $config["RATIOA"] || $gigs < $config["GIGSA"]) {
               $wait = $config["WAITA"];
           } elseif ($ratio < $config["RATIOB"] || $gigs < $config["GIGSB"]) {
               $wait = $config["WAITB"];
           } elseif ($ratio < $config["RATIOC"] || $gigs < $config["GIGSC"]) {
               $wait = $config["WAITC"];
           } elseif ($ratio < $config["RATIOD"] || $gigs < $config["GIGSD"]) {
               $wait = $config["WAITD"];
           } else {
               $wait = 0;
           }

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

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

   @fclose($sockres);

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

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

$updateset = array();

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

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


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

   }
}

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

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

   // snatch
   $dbh->run("UPDATE LOW_PRIORITY `snatched` SET `completed` = '1' WHERE `tid` = '$torrentid' AND `uid` = '$userid' AND `utime` = '" . gmtime() . "'");
} //END COMPLETED

if (isset($self)) { // NO EVENT? THEN WE MUST BE A NEW PEER OR ARE NOW SEEDING A COMPLETED TORRENT

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

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

} else {

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

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

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

   }
}

//////////////////    END TRACKER EVENT UPDATES ///////////////////

// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
   if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
   {
       $updateset[] = "visible = 'yes'";
   }

   $updateset[] = "last_action = '" . get_date_time() . "'";
}

// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset)) {
   $dbh->run("UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or err("Tracker error: Unable to update torrent");
}

// NOW BENC THE DATA AND SEND TO CLIENT???
benc_resp_raw($resp);
Two things I've learnt that might be useful
Close connection under header()
header("Connection: Close");


Close page after output
exit();
It is marked in progress so shouldn't be tried if you have 10,000 torrents but I assume it would be like a server going down for a hour and restarting with current announce
There is less querys then the v2 but at the minute are quite broad for testing purposes its the events where any improvement can be made the rest is solid off top of my head we need to update completed, torrent and snatched tables most of which is covered in the section from the old announce just need to simplify it
The announce.php is over 20 years old and i have put off updating the torrent side of for ages but needed doing so here is some thing im playing with
[color=rgb(247, 218, 100)]UPDATED 19/09/20[/color]

Add Database.php to backend folder (pdo connection)

Replace announce.php ( i use snatched mod)

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

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

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

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

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

function gmtime()
{
   return strtotime(get_date_time());
}

function get_date_time($timestamp = 0)
{
   if ($timestamp) {
       return date("Y-m-d H:i:s", $timestamp);
   } else {
       return gmdate("Y-m-d H:i:s");
   }

}

function portblacklisted($port)
{
   // direct connect
   if ($port >= 411 && $port <= 413) {
       return true;
   }
   // kazaa
   if ($port == 1214) {
       return true;
   }
   // gnutella
   if ($port >= 6346 && $port <= 6347) {
       return true;
   }
   // emule
   if ($port == 4662) {
       return true;
   }
   // winmx
   if ($port == 6699) {
       return true;
   }
   return false;
}

// NOW WE DO THE ANNOUNCE CODE

// BLOCK ACCESS WITH WEB BROWSERS
$agent = $_SERVER["HTTP_USER_AGENT"];
if (preg_match("/^Mozilla|^Opera|^Links|^Lynx/i", $agent)) {
   die("No Browser Access");
}

// GET DETAILS OF PEERS ANNOUNCE
foreach (array("passkey", "info_hash", "peer_id", "ip", "event") as $x) {
   $GLOBALS[$x] = $_GET[$x];
}

foreach (array("port", "downloaded", "uploaded", "left") as $x) {
   $GLOBALS[$x] = 0 + $_GET[$x];
}

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

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

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

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

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

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

}

$ip = $_SERVER["REMOTE_ADDR"];

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

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

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

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

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

$dbh = new Database();

$userfields = "u.id, u.class, u.uploaded, u.downloaded, u.ip, u.passkey, g.can_download"; //user details to get

$peerfields = "seeder, UNIX_TIMESTAMP(last_action) AS ez, peer_id, ip, port, uploaded, downloaded, userid, passkey"; //peers details to get

$torrentfields = "id, info_hash, banned, freeleech, seeders + leechers AS numpeers, UNIX_TIMESTAMP(added) AS ts, seeders, leechers, times_completed"; //torrent details to get

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SEEDED, LETS MAKE IT VISIBLE THEN
if ($seeder == "yes") {
   if ($torrent["banned"] != "yes") // DONT MAKE BANNED ONES VISIBLE
   {
       $updateset[] = "visible = 'yes'";
   }
   $updateset[] = "last_action = '" . get_date_time() . "'";
}

// NOW WE UPDATE THE TORRENT AS PER ABOVE
if (count($updateset)) {
   $dbh->run("UPDATE torrents SET " . join(",", $updateset) . " WHERE id=$torrentid") or die(track("Tracker error: Unable to update torrent"));
}

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

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

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

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

// Final output to client
die(track($reply, $seeders, $leechers, $completed));
Database Error — 2020-09-02 21:56:03 in v3 Support
try replace that big query with

$filecounts = (int) $filecount;
$ret = SQL_Query_exec("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action, allocine) VALUES (".sqlesc($fname).", '".$CURUSER['id']."', ".sqlesc($name).", ".sqlesc($descr).", '".$inames[0]."', '".$inames[1]."', '".$catid."', '" . get_date_time() . "', '".$infohash."', '".$torrentsize."', '".$filecount."', ".sqlesc($fname).", '".$announce."', '".$external."', '".$nfo."', '".$langid."','$anon', '".get_date_time()."', ".sqlesc($_POST['allocine']).")");
double ip — 2020-09-02 19:09:10 in v3 Mods Requests
Look for header ( something index.php ) this is where the redirect to index is
is most likely bottom of file and replace for autolink
double ip — 2020-09-02 17:18:45 in v3 Mods Requests
It depends on settings if email confirmation for example account-ce or no checks account signup
You could edit a few files so any condition redirect to torrents you just need auto link
I use auto link for everything lol

autolink("torrents.php, "you are now   logged in");
I seem to have one outstanding bug which a user is getting the error Not contacted yet, the user in question is using utorrent which some versions are not the best and cause problems

The best way to test is to play with his passkey but every time i add a second passkey ( so two trackers 2 passkeys) i get the error Not contacted yet (on one), if i delete one tracker it works and vice versa its when there is two. In xampp i can use two at same time

Gone through my old gits  and even decided to try v3 the same in xampp i can test with two trackers but on live server it causes error

Can anyone check if they have the same would like to make sure its working 100% and not abnormal behavior
make a test account on your site looking for live & xampp tests
upload torrent with your account and also download with test account
or just use test account to download one of your existing torrents and share results please

pretty certain its user error but always good to check on off chance its code or server
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: 10

  • Online

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