<!--buttonsstart-->
<!--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&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!");
}
} <?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 /> <?php
require_once "core/TTcore.php";
TTcore::run();<?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;
}
}<?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');
}
}
}<?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;
}
}
} "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
<?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); header("Connection: Close");exit();
<?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));