$scraper = new ScrapeTorrent(..., ..., ..., ..., ...);
$results = $scraper->scrapeAll(array|string, array|string);
$results = $scraper->scrape(string, string);
<?
// Switch-Torrents Torrent Scraper w/ PECL Parallel support
// Supports protocols: UDP | HTTP | HTTPS - March/2023-v1.1
// cURL | Streams
class ScrapeTorrent
{
private int $timeout;
private bool $parallel = false;
private bool $usecurl = false;
private int $maxhashes;
private string $useragent;
private ?Bencode $bencode;
private array $curlopt = [];
private bool $verifypeer;
private bool $verifyname;
public function __construct(int $timeout = 2, bool $parallel = false, bool $usecurl = false, ?Bencode $bencode = null, array $curlopts = [])
{
$this->useragent = 'Switch-Torrents Scrape/1.0';
$this->maxhashes = 74;
$this->timeout = $timeout;
$this->bencode = $bencode ?? null;
// ssl
$this->verifypeer = true;
$this->verifyname = true;
if (function_exists('curl_init') && $usecurl)
{
$this->usecurl = true;
$this->curlopt = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => $this->verifypeer,
CURLOPT_SSL_VERIFYHOST => 2
);
$this->curlopt = !empty($curlopts) ? $curlopts : $this->curlopt;
}
if (extension_loaded('parallel') && $parallel)
{
$this->parallel = true;
}
}
public function scrapeAll(array|string $urls, array|string $infohashes) : array
{
if (!is_array($urls))
{
$urls = [$urls];
}
if (!is_array($infohashes))
{
$infohashes = [$infohashes];
}
$torrents = array();
$results = array();
if ($this->parallel)
{
$pool = new \parallel\Runtime;
foreach ($urls as $url)
{
foreach ($infohashes as $infohash)
{
$task = $pool->run(function () use ($url, $infohash)
{
spl_autoload_register(function ($class)
{
include_once $class . '.php';
});
return (new \ScrapeTorrent)->scrape($url, $infohash, (new \Bencode));
});
$results[] = $task;
}
}
foreach ($results as $result)
{
$result->value();
}
}
else
{
foreach ($urls as $url)
{
foreach ($infohashes as $infohash)
{
$results[] = $this->scrape($url, $infohash, $this->bencode);
}
}
}
if ($this->parallel)
{
foreach ($results as $result)
{
if (is_array($result->value()))
{
foreach ($result->value() as $infohash => $stats)
{
$torrents[$infohash] = $stats;
}
}
}
}
else
{
foreach ($results as $result)
{
if (is_array($result))
{
foreach ($result as $infohash => $stats)
{
$torrents[$infohash] = $stats;
}
}
}
}
return $torrents;
}
public function scrape(string $url, string $infohash, ?Bencode $bencode = null) : array
{
if (!is_array($infohash))
{
$infohash = array(
$infohash
);
}
for ($i = 0;$i < count($infohash);$i++)
{
if (!preg_match('#^[a-f0-9]{40}$#i', $infohash[$i]))
{
ScrapeException::Message('Invalid infohash: ' . $infohash[$i] . '.');
}
}
if (count($infohash) > $this->maxhashes)
{
ScrapeException::Message('Too many infohashes provided.');
}
if (!preg_match('#^(udp|http|https)://([^:/]*)(?::([0-9]*))?(?:/)?#si', $url, $m))
{
ScrapeException::Message('Invalid tracker url.');
}
$torrents = array();
$tracker = $m[1] . '://' . $m[2];
$port = isset($m[3]) ? $m[3] : ($m[1] === 'https' ? 443 : 80);
$transaction_id = mt_rand(0, 65535);
if ($m[1] === 'http' || $m[1] === 'https')
{
if (!($this->bencode instanceof \Bencode) && !($bencode instanceof \Bencode))
{
ScrapeException::Message('Bencode is required for HTTP/HTTPS scraping.');
}
$port = $m[1] === 'http' ? 80 : 443;
$torrents = $this->fetch_http($url, $m[2], $port, $this->timeout, $infohash, $m[1], $this->usecurl);
}
elseif ($m[1] === 'udp')
{
$fp = fsockopen('udp://' . $m[2], $port, $errno, $errstr, $this->timeout);
if (!$fp)
{
ScrapeException::Message('Could not open ' . strtoupper($m[1]) . ' 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)
{
ScrapeException::Message('No connection response.');
}
if (strlen($ret) < 16)
{
ScrapeException::Message('Too short connection response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 0 || $retd['transid'] != $transaction_id)
{
ScrapeException::Message('Invalid connection response.');
}
$hashes = '';
$packhash = 'H*';
$current_connid = substr($ret, 8, 8);
foreach ($infohash as $hash)
{
$hashes .= pack($packhash, $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)
{
ScrapeException::Message('No scrape response.');
}
if (strlen($ret) < 8)
{
ScrapeException::Message('Too short scrape response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 2 || $retd['transid'] != $transaction_id)
{
ScrapeException::Message('Invalid scrape response.');
}
if (strlen($ret) < $readlength)
{
ScrapeException::Message('Too short scrape response.');
}
$index = 8;
$unpack = "Nseeders/Ncompleted/Nleechers";
foreach ($infohash as $hash)
{
$retd = unpack($unpack, substr($ret, $index, 12));
$retd['infohash'] = $hash;
$torrents[$hash] = $retd;
$index = $index + 12;
$torrents[$hash]['type'] = $m[1];
}
}
$empty = null;
foreach ($torrents as $torrent)
{
if (!empty($torrent))
{
$empty = $torrent;
break;
}
}
$default = array(
'complete' => 0,
'downloaded' => 0,
'incomplete' => 0,
'infohash' => $hash,
'type' => $m[1]
);
foreach ($torrents as $hash => &$torrent)
{
if (empty($torrent))
{
$torrent = ($empty ?: $default);
$torrent['infohash'] = $hash;
}
}
unset($torrent);
return $torrents;
}
private function decodeData(string $data) : array
{
if (empty($data))
{
ScrapeException::Message('Input data cannot be empty.');
}
$stream = fopen('php://memory', 'r+');
fwrite($stream, $data);
rewind($stream);
$decoder = new \Decoder(stream: $stream, bigInt: BigInt::INTERNAL);
return $decoder->decode();
}
private function fetch_http(string $url, string $host, int $port, int $timeout, array $hashes, string $prefix, bool $usecurl = false):
array
{
$storestats = array();
$ann = (strpos($url, 'scrape') !== false) ? 'scrape' : ((strpos($url, 'announce') !== false) ? 'announce' : '');
if (!$ann)
{
ScrapeException::Message('URL does not contain scrape or announce.');
}
$response = '';
foreach ($hashes as $hash)
{
$url = "$prefix://$host/$ann?info_hash=$hash";
try
{
if ($usecurl)
{
$ch = curl_init();
curl_setopt_array($ch, $this->curlopt);
curl_setopt($ch, CURLOPT_URL, $url);
$multihandle = curl_multi_init();
curl_multi_add_handle($multihandle, $ch);
$active = null;
do
{
$status = curl_multi_exec($multihandle, $active);
if ($active)
{
curl_multi_select($multihandle);
}
}
while ($status === CURLM_CALL_MULTI_PERFORM || $active);
if ($status !== CURLM_OK)
{
ScrapeException::Message('HTTP request failed.');
}
$response = curl_multi_getcontent($ch);
curl_multi_remove_handle($multihandle, $ch);
curl_multi_close($multihandle);
}
else
{
$context = stream_context_create(array(
$prefix => array(
'timeout' => $timeout,
'user_agent' => $this->useragent,
'header' => 'Content-Type: text/plain',
'ssl' => array(
'verify_peer' => $this->verifypeer,
'verify_peer_name' => $this->verifyname
)
)
));
$stream = @fopen($url, 'r', false, $context);
if ($stream)
{
$response = stream_get_contents($stream);
fclose($stream);
}
else
{
ScrapeException::Message('Could not open stream for URL.');
}
}
if (isset($response))
{
$decoded = $this->decodeData($response);
}
if (isset($decoded['files']))
{
unset($decoded['files'][0][$hash]['name']);
}
$storestats[$hash] = $decoded['files'][0][$hash] ? ? $this->decodeData($response);
$storestats[$hash]['infohash'] = $hash;
$storestats[$hash]['type'] = $prefix;
}
catch(Exception $e)
{
//ScrapeException::Message("Error fetching $prefix");
$storestats[$hash] = array();
}
}
return $storestats;
}
}
<?
class ScrapeException extends Exception
{
public static function Message(string $message)
{
throw new self($message);
}
}
$urls = array(
'udp://tracker.opentrackr.org:1337/announce',
'udp://tracker.opentrackr.org:1337/announce'
);
$infohashes = array(
'9269f2bf2c48756ac1f98fb3abdee3920893388f',
'5d33dede60ab4d24b1b720d0dee2df9505605397'
);
try
{
// Optional: cURL Options
$curlopts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 2,
CURLOPT_FOLLOWLOCATION => true,
);
// Optional: HTTP/HTTPS scraping
$bencode = new Bencode;
// Optional Parameters: Timeout | Enable Parelle | Enable cURL | Bencode | cURL Options
$scraper = new ScrapeTorrent(2, true, true, $bencode, $curlopts);
// Methods: scrapeAll(array|string, array|string) | scrape(string, string)
$results = $scraper->scrapeAll($urls, $infohashes);
// Test
print_r($results);
}
catch(\ScrapeException $e)
{
echo $e->getMessage();
}
include_once 'ScrapeTorrent.php';
<?
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
{
.........
Array ( [fe91262c62f9877f0d79c6cf87b0fb904ae80e80] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => fe91262c62f9877f0d79c6cf87b0fb904ae80e80 ) )
$timeout = 2;
$scraper = new ScrapeTorrent($timeout);
$urls = array(
'udp://tracker.opentrackr.org:1337/announce',
'udp://tracker.pomf.se:80/announce',
'udp://tracker.sylphix.com:6969/announce',
'udp://tracker.theoks.net:6969/announce',
'udp://tracker.torrent.eu.org:451/announce',
'udp://tracker1.bt.moack.co.kr:80/announce',
'udp://tracker2.dler.com:80/announce',
'udp://tracker6.lelux.fi:6969/announce'
);
foreach ($urls as $url) {
try {
$ret = $scraper->scrape($url, 'd158701550334ff31273e1f3788bdb3c1f10a3ed');
print_r($ret);
} catch (ScraperException $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
if ($e->isConnectionError()) {
echo 'Connection error: ' . $e->getCode() . PHP_EOL;
}
}
}
Array ( [d158701550334ff31273e1f3788bdb3c1f10a3ed] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => d158701550334ff31273e1f3788bdb3c1f10a3ed ) ) No connection response.Connection error: 1No connection response.Connection error: 1Array ( [d158701550334ff31273e1f3788bdb3c1f10a3ed] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => d158701550334ff31273e1f3788bdb3c1f10a3ed ) ) Array ( [d158701550334ff31273e1f3788bdb3c1f10a3ed] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => d158701550334ff31273e1f3788bdb3c1f10a3ed ) ) Array ( [d158701550334ff31273e1f3788bdb3c1f10a3ed] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => d158701550334ff31273e1f3788bdb3c1f10a3ed ) ) Array ( [d158701550334ff31273e1f3788bdb3c1f10a3ed] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => d158701550334ff31273e1f3788bdb3c1f10a3ed ) ) Could not open UDP connection: 0 - php_network_getaddresses: getaddrinfo for tracker6.lelux.fi failed: Name does not resolveConnection error: 1
class Cache implements CacheInterface
{
protected \Memcached $cache;
function __construct()
{
$this->cache = new \Memcached;
}
function store(mixed $key, mixed $data, $ttl): bool
{
try {
$result = $this->cache->set($key, $data, $ttl);
if (!$result) {
throw new Exception('Failed to store data in cache.');
}
return $result;
} catch (\MemcachedException $e) {
throw new Exception(sprintf('Failed to store data in cache. %s', $e->getMessage()), 0, $e);
}
}
function fetch(mixed $key): mixed
{
$result = $this->cache->get($key);
if ($this->cache->getResultCode() == Memcached::RES_NOTFOUND) {
return false;
}
if ($result === false) {
throw new Exception('Failed to fetch data from cache. Error: ' . $this->cache->getResultMessage());
}
return $result;
}
function delete(mixed $key): bool
{
$result = $this->cache->delete($key);
if ($result === false) {
throw new Exception('Failed to delete data from cache: ' . $this->cache->getResultMessage());
}
return $result;
}
function addServer(string $host, int $port = 11211, int $weight = 10): void
{
try {
$result = $this->cache->addServer($host, $port, $weight);
if (!$result) {
throw new Exception(sprintf('Failed to add Memcached server %s:%d.', $host, $port));
}
} catch (Throwable $e) {
throw new Exception(sprintf('Failed to add Memcached server %s:%d: %s', $host, $port, $e->getMessage()));
}
}
}
interface CacheInterface
{
public function store(string $key, mixed $data, int $ttl): bool;
public function fetch(string $key): mixed;
public function delete(string $key): bool;
public function addServer(string $host, int $port = 11211, int $weight = 10): void;
}
// Cleanup V2 - PECL Parallel support
$tasks = [
'cleancache' => [1],
'seedbonus' => [],
'comments' => [],
'checkexpiredwarns' => [],
'cleanlogs' => [3],
'autopromote' => [],
'autofreeleech' => [],
'autodemote' => [],
'pendingusers' => [],
'privseeders' => [],
'startsync' => [],
'cleanshoutbox' => [10],
'checkdead' => [],
'ratiowarn' => [],
];
$classFiles = [
'Extensions',
'Cleanup'
];
$results = [];
$runtime = new \parallel\Runtime;
$channel = new \parallel\Channel;
foreach ($tasks as $taskName => $taskParams) {
$future = $runtime->run(function () use ($taskName, $taskParams, $classFiles, $channel) {
spl_autoload_register(function ($className) use ($classFiles) {
if (!empty($classFiles) && in_array($className, $classFiles)) {
include_once "classes/$className.php";
}
});
$result = call_user_func_array([(new \Cleanup), $taskName], $taskParams);
$channel->send([$taskName, $result]);
});
}
foreach ($tasks as $taskName => $taskParams) {
[$taskName, $result] = $channel->recv();
$results[$taskName] = $result;
}
$channel->close();
foreach ($results as $taskname => $result) {
echo "Task $taskname completed.\n";
}
$config['maxFileSize']
function cleanse_filename(string $string): mixed {
if (preg_match('/[^\x20-\x7E]/', $string)) {
return array(
'error' => 'Input contains disallowed characters'
);
}
return preg_replace('/[\x00-\x1F\x7F]/', '', $string);
}
if ($check = cleanse_filename($_FILES['meta_file_']['name'])) {
if (is_array($check)) {
// bad
} elseif (is_string($check)) {
// good
}
}
$allowedMetadata = array(
'application/x-bittorrent' => 'torrent',
'application/x-switchtorrent' => 'swt'
);
$upload_dir = '/the/absolute/path/to/uploads';
if (isset($FILES['meta_file']['tmp_name']) && strlen($FILES['meta_file']['tmp_name']) > 0) {
$real_path = realpath($FILES['meta_file']['tmp_name']);
if (strpos($real_path, $upload_dir) !== 0) {
$errors[] = 'Invalid file path';
} else {
$meta_contents = file_get_contents($real_path); // memory-safe w/ filesize check
$meta_contents = preg_replace('/[^\x20-\x7E]/', '', $meta_contents);
// Bdecode and continue POST logic
}
}
<div style="height:20px;width:<?=($row['total_funds'] * 5)?>%"></div>