<?
// AJAX Torrent Scrape - Update Stats - BETA - May 19, 2020
// Public torrents only / UDP, HTTPS, HTTP
// Takes POST by torrent ID via AJAX call, scrapes announce in torrent table
// with much better class and logic, and updates seeders/leechers in database by ID
require_once 'backend/functions.php';
$torrentid = isset($_GET['id'])?intval($_GET['id']):0; // Get torrent ID ?id=
$limit = 1;
$dsn = 'mysql:dbname=database;host=localhost;charset=utf8';
$user = 'username';
$password = 'password';
$torrentid = $_GET['id'];
try {
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$stmt = $conn->prepare("SELECT id, announce, info_hash FROM torrents WHERE external = 'yes' AND id = :torrentid LIMIT 1");
$stmt->bindValue(':torrentid', $torrentid, PDO::PARAM_INT);
$stmt->execute();
class ScraperException extends Exception
{
private $connectionerror;
public function __construct($message, $code = 0, $connectionerror = false)
{
$this->connectionerror = $connectionerror;
parent::__construct($message, $code);
}
public function isConnectionError()
{
return ($this->connectionerror);
}
}
abstract class tscraper
{
protected $timeout;
public function __construct($timeout = 2)
{
$this->timeout = $timeout;
}
}
class udptscraper extends tscraper
{
public function scrape($url, $infohash)
{
if (!is_array($infohash)) {
$infohash = array(
$infohash
);
}
foreach ($infohash as $hash) {
if (!preg_match('#^[a-f0-9]{40}$#i', $hash)) {
throw new ScraperException('Invalid infohash: ' . $hash . '.');
}
}
if (count($infohash) > 74) {
throw new ScraperException('Too many infohashes provided.');
}
if (!preg_match('%udp://([^:/]*)(?::([0-9]*))?(?:/)?%si', $url, $m)) {
throw new ScraperException('Invalid tracker url.');
}
$tracker = 'udp://' . $m[1];
$port = isset($m[2]) ? $m[2] : 80;
$transaction_id = mt_rand(0, 65535);
$fp = fsockopen($tracker, $port, $errno, $errstr);
if (!$fp) {
throw new ScraperException('Could not open UDP connection: ' . $errno . ' - ' . $errstr, 0, true);
}
stream_set_timeout($fp, $this->timeout);
$current_connid = "\x00\x00\x04\x17\x27\x10\x19\x80";
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp, $packet);
$ret = fread($fp, 16);
if (strlen($ret) < 1) {
throw new ScraperException('No connection response.', 0, true);
}
if (strlen($ret) < 16) {
throw new ScraperException('Too short connection response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 0 || $retd['transid'] != $transaction_id) {
throw new ScraperException('Invalid connection response.');
}
$current_connid = substr($ret, 8, 8);
$hashes = '';
foreach ($infohash as $hash) {
$hashes .= pack('H*', $hash);
}
$packet = $current_connid . pack("N", 2) . pack("N", $transaction_id) . $hashes;
fwrite($fp, $packet);
$readlength = 8 + (12 * count($infohash));
$ret = fread($fp, $readlength);
if (strlen($ret) < 1) {
throw new ScraperException('No scrape response.', 0, true);
}
if (strlen($ret) < 8) {
throw new ScraperException('Too short scrape response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 2 || $retd['transid'] != $transaction_id) {
throw new ScraperException('Invalid scrape response.');
}
if (strlen($ret) < $readlength) {
throw new ScraperException('Too short scrape response.');
}
$torrents = array();
$index = 8;
foreach ($infohash as $hash) {
$retd = unpack("Nseeders/Ncompleted/Nleechers", substr($ret, $index, 12));
$retd['infohash'] = $hash;
$torrents[$hash] = $retd;
$index = $index + 12;
}
return ($torrents);
}
}
try {
$timeout = 2;
$scraper = new udptscraper($timeout);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ret = $scraper->scrape($row['announce'], $row['info_hash']);
}
foreach ($ret as $key => $value) {
$stmt = $conn->prepare("UPDATE torrents SET leechers='" . $value['leechers'] . "', seeders='" . $value['seeders'] . "', times_completed='" . $value['completed'] . "', last_action='" . get_date_time() . "', visible='yes' WHERE id = :torrentid");
$stmt->bindValue(':torrentid', $torrentid, PDO::PARAM_INT);
$stmt->execute();
}
}
catch (ScraperException $e) {
echo ('Error: ' . $e->getMessage() . "<br />\n");
echo ('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
?>
<?
// AJAX Torrent Scrape - Get Stats - BETA - May 19, 2020
// Include database
$dsn = 'mysql:dbname=database;host=localhost;charset=utf8';
$user = 'username';
$password = 'password';
$torrentid = isset($_GET['id'])?intval($_GET['id']):0; // Get torrent ID ?id=
try {
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$limit = 1;
$stmt = $conn->prepare("SELECT id, seeders, leechers FROM torrents WHERE id = :torrentid LIMIT :datalimit");
$stmt->bindParam(":datalimit", $limit, PDO::PARAM_INT);
$stmt->bindParam(":torrentid", $torrentid, PDO::PARAM_INT);
$stmt->execute();
$userData = array();
if ($stmt->rowCount() > 0) {
$usersactive = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($usersactive as $row => $data) {
$data['seeders'] = $row['seeders'];
$data['leechers'] = $row['leechers'];
array_push($userData, $usersactive);
}
}
echo json_encode($usersactive, JSON_UNESCAPED_SLASHES);
?>
<? if (stripos($_SERVER['PHP_SELF'],'torrents-details.php') && $CURUSER) { ?>
<script>
// Get peer data
function fetchPeerData() {
$(document).ready(function () {
$.ajax({
url: "get-torrent-stats.php?id=<?=$id; ?>",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
html_to_append +=
'<div style="float:right"><span id="peers-updated"></span><span style="text-align:right;font-size:25px;color:#2E8B57">' +
item.seeders +
'</span><span style="text-align:right;font-size:25px;color:#C0C0C0;padding-left:10px;padding-right:5px">/</span><span style="text-align:right;font-size:18.75pt;color:#DC143C">' +
item.leechers +
'</span></div>';
});
$("#updated-stats").html(html_to_append);
$("#animate").toggleClass('flip');
$("#peers-updated").html("Peers updated").delay(1000).fadeIn().delay(2000).fadeOut();
}
});
});
// Update peer data
$(document).ready(function() {
$.ajax({
url: "trader-scrape.php?id=<?=$id; ?>",
method: "POST",
success: function (data) {
$("#peers-updated").html("Peers updated").delay(1000).fadeIn().delay(2000).fadeOut();
}
});
});
}
fetchPeerData();
setInterval(function () {
fetchPeerData()
}, 15000); // Update peer data every 15 sec on viewing torrent
<?
}
?>
</script>
<div id="updated-stats"></div> var_dump($filecount);"m-jay, post: 68578, member: 20288":
Nice mod m8, some would advise to escape but at a glance I dont think its necessary.
You should be able to trust the bots input it's just collecting data from cleanup
$site_config['autoclean_interval'] = '300'; // 300 = 5 minutes (seconds)
$res = SQL_Query_exec("SELECT torrent, seeder, COUNT(*) AS c FROM peers GROUP BY torrent, seeder");
// Send to Shoutbox - Total seeders today
$getcount = mysql_fetch_assoc($res);
$seeders = $getcount["c"];
$event = "There are $seeders Private Seeders Today!";
SQL_Query_exec("INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, 'NerbBot', '$event', NOW(), 0)");
$res = SQL_Query_exec("SELECT torrent, COUNT(torrent) as c FROM comments WHERE torrent > 0 GROUP BY torrent");
// Send to Shoutbox - Total comments posted
$getcount = SQL_Query_exec("SELECT COUNT(torrent) as c FROM comments");
$restotal = mysql_fetch_assoc($getcount);
$commcount = $restotal["c"];
$event = "Currently there are $commcount comments posted";
SQL_Query_exec("INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, 'NerbBot', '$event', NOW(), 0)");
SQL_Query_exec("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime) AND seeders = '0' AND leechers = '0' AND external !='yes'");
// Send to Shoutbox Bot - May 15, 2020
$thedate = time_ago($site_config["max_dead_torrent_time"]);
$logged = str_replace('ago', '', $thedate);
$event = "Torrent dead for $logged Sending to graveyard.";
SQL_Query_exec("INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, 'NerbBot', '$event', NOW(), 0)");
SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES ('0', '".$arr["id"]."', '".$timenow."', '".$reason."', '0', 'Warning: Poor Ratio')");
// Send to Shoutbox - Low ratio warning
$warneduser = $arr["username"];
$event = "Auto Leech warning has been added for $warneduser";
SQL_Query_exec("INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, 'NerbBot', '$event', NOW(), 0)");
"shadows, post: 68555, member: 20311":
After successful ajax request, include window.location.href = '/torrents-edit.php?id=<?= mysqli_insert_id() ?>';
Set redirect in json to be true.
success: function(data) {
if (data.redirect == true) {
// data.redirect contains the string URL to redirect to
window.location.href = '/torrents-edit.php?id=<?= mysqli_insert_id() ?>';
}
.newtd {
background: linear-gradient(to bottom, #072F5F, #3895D3), -webkit-linear-gradient(top, #072F5F, #3895D3) rgba(255, 255, 255, 1) repeat-x
}
"shadows, post: 68551, member: 20311":
Looks fancy and way better organized than the default torrent upload, but this requires serious sanitization and security checks.
Here's some suggestions:
1. Use $_SERVER['REQUEST_METHOD'] === 'POST' to verify that request is indeed a post.
2. Use require instead of require_once.
3. if (is_array($_FILES['torrent'])) should be moved as a separate if/else security measure.
$error = '';
// If/else checkings
if (!is_array($_FILES['torrent']))
{
$error = 'The file contains no array';
}
elseif (empty($_FILES['torrent']))
{
$error = 'You did not select a torrent file';
}
//Proceed with uploading if no errors are met.
if ($error === '')
{
$insert = $db->query("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action)
VALUES ('" . $torr_saveas . "', " . sqlesc($userid) . ", '" . $torr_name . "', 'Torrent POST description', 'image1', 'image2', 1, '" . get_date_time() . "', '" . $torr_hash . "', '" . $torr_size . "', 3, '" . $torr_name . "', '" . $torr_announce . "', '" . $torr_private . "', 'no', 1, 'no', '" . get_date_time() . "')");
die;
}
else
{
die($error);
}
<form id="form-torupload" action="/ajax/ajax_torrent_upload.php" method="post" enctype="multipart/form-data">
<input type="file" accept=".torrent" name="torrent" />
<input type="hidden" name="userid" value="<?php echo $CURUSER["id"]; ?>" required />
</form>
<!-- Status -->
<div id="err"></div>
<!-- Feedback -->
<div id="preview-torrent"></div>
<?php
/*
AJAX Torrent Uploading - Using Parsing class - Torrent()->object()
Replaces old torrents-upload.php and related classes: BDecode(), BEncode()
Triggered by AJAX call. Accepts .torrent, parses data and builds array, inserts to DB.
https://www.phpclasses.org/package/4896-PHP-Create-and-parse-Torrent-files.html
*/
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['torrent'])) {
$uploadedFile = $_FILES['torrent']['tmp_name'];
$dirPath = "../uploads/";
$ext = pathinfo($_FILES['torrent']['name'], PATHINFO_EXTENSION);
move_uploaded_file($uploadedFile, '../uploads/' . $_FILES["torrent"]['name']);
$dbHost = 'localhost';
$dbUsername = 'username';
$dbPassword = 'password';
$dbName = 'database';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
$userid = isset($_POST['userid']) ? intval($_POST['userid']) : 0;
$name = $_FILES["torrent"]['name'];
require('../backend/functions.php');
require('parse.class.php');
$torrent = new Torrent("../uploads/$name");
$torr_hash = $torrent->hash_info();
$torr_announce = $torrent->announce('http://tracker2.itzmx.com:6961/announce'); // Alternative tracker
$torr_size = $torrent->size();
$torr_saveas = $torrent->name();
$torr_private = $torrent->is_private() ? 'yes' : 'no';
// Prep for form fields - input type = text, name = "torrentname"
if (!empty($_POST['torrentname'])) {
$torr_name = $_POST['torrentname'];
} else {
$torr_name = str_replace('.torrent', '', $torrent->name());
}
$error = '';
// Check upload
if (!is_array($_FILES['torrent'])) {
$error = 'The file contains no array';
} elseif (empty($_FILES['torrent'])) {
$error = 'You did not select a torrent file';
}
// Proceed if no error
if ($error === '') {
$insert = $db->query("INSERT INTO torrents (filename, owner, name, descr, image1, image2, category, added, info_hash, size, numfiles, save_as, announce, external, nfo, torrentlang, anon, last_action)
VALUES ('" . $torr_saveas . "', " . sqlesc($userid) . ", '" . $torr_name . "', 'Torrent Description.', ''image1', 'image2', 1, '" . get_date_time() . "', '" . $torr_hash . "', '" . $torr_size . "', 3, '" . $torr_name . "', '" . $torr_announce . "', '" . $torr_private . "', 'no', 1, 'no', '" . get_date_time() . "')");
$edit_id = mysqli_insert_id($db);
mysqli_close($db);
header("Location: " . $site_config["SITEURL"] . "/torrents-edit.php?id=" . $edit_id);
die;
} else {
die($error);
}
} else {
echo 'Invalid request.';
}
?>
$(document).ready(function (e) {
$("#form-torupload").on('change', (function (e) {
e.preventDefault();
$.ajax({
url: "/ajax/ajax_torrent_upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$("#preview-torrent").html("Uploading torrent...").delay(4000).fadeOut().delay(4000).fadeIn();
$("#preview-torrent").fadeIn();
$("#err").fadeOut();
},
success: function (data) {
if (data.redirect == true) {
// Redirect to torrent editor
window.location.href = '/torrents-edit.php?id=<?= mysqli_insert_id(); ?>';
}
if (data == 'invalid') {
// Invalid format
$("#err").html("Invalid torrent!").fadeIn();
} else {
$("#preview-torrent").fadeOut();
$("#updated-torrent").html("Torrent has been uploaded. Refresh to see all changes.").delay(1000).fadeIn().delay(2000).fadeOut();
}
},
error: function (e) {
$("#err").html(e).fadeIn();
}
});
}));
});
function where($where)
{
$where = substr($where, 1);
$files['torrents-upload.php/'] = 'Uploading Torrent';
$files['torrents-details.php/'] = 'Viewing Torrent ID ' . $_GET["id"];
$files['account.php/'] = 'Viewing Account';
$files['torrents-search.php/'] = 'Searching Torrents: ' . $_GET["search"];
$files['forums.php/'] = 'Browsing Forums';
$files['mailbox.php/'] = 'Viewing Messages';
$files['comments.php'] = 'Viewing Comments';
$files['bookmarks.php'] = 'Viewing Bookmarks';
$files['download.php/'] = 'Downloaded Torrent ' . $_GET["name"];
$files['faq.php/'] = 'Reading FAQ';
$files['friends.php/'] = 'Viewing Friends';
$files['admincp.php'] = 'Managing Admin Panel';
$files['torrents.php/'] = 'Browsing Torrents';
$files['tags/'] = 'Browsing Tags: ' . $_GET["search"];
$result = null;
foreach ($files as $file => $descr) {
if (0 === strpos($where, $file)) {
$result = urldecode($descr);
break;
}
}
if ($result === null) {
$result = sprintf('Browsing Homepage %s', $where);
}
return $result;
SQL_Query_exec("UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid);
}
function loggedinonly() {
global $CURUSER;
if (!$CURUSER) {
header("Refresh: 0; url=" . $site_config["SITEURL"] . "/account-login.php?returnto=" . urlencode($_SERVER["REQUEST_URI"]));
exit();
}
}