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

IMDb Mod [TTv3] — 2023-03-12 18:38:56 in v3 Mods Completed
Anything with T_ is a language key. It just displays text. Everything after that is typically code or a variable.
This enables you to scrape multiple UDP/HTTP(S) announce urls against info hashes. It accepts array or single strings. It enables custom cURL options, a optional Bencode object, and optional parameters to enable/disable cURL (defaults to streams) and enable/disable PECL parallel tasks.

I built this over the weekend mostly from scratch with the exception of the UDP connection logic, which was ported and updated. Since the original "Scrapeer", "tscraper" classes are falling behind and becoming non-functional.. I decided it was time for a PHP 8x rewrite.

Requires: PHP 8.1+, sockets, PECL Parallel extension (optional)

---

Parameters: Timeout | Enable Parelle | Enable cURL | Bencode | cURL Options
$scraper = new ScrapeTorrent(..., ..., ..., ..., ...);


Methods:

$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;
       }
   }


Exception class

<?
class ScrapeException extends Exception
{
   public static function Message(string $message)
   {
       throw new self($message);
   }
}


Usage:


$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();
}


Autoloading
If you are not autoloading your classes, you need to include the class.

include_once 'ScrapeTorrent.php';
UDP Scrape not work... — 2023-03-11 16:26:39 in v3 Support

<?
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
{
.........


Im reworking this today. Hang in there.


Array ( [fe91262c62f9877f0d79c6cf87b0fb904ae80e80] => Array ( [seeders] => 0 [completed] => 0 [leechers] => 0 [infohash] => fe91262c62f9877f0d79c6cf87b0fb904ae80e80 ) )


UPDATE


$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


--

The class works fine. It can use improvements (like a multi-announce array I showed), other than that, im going to add parallel support for each url request, so its faster (only if enabled, code will check). It doesnt have to be a fixed array, it can be read from $site_config, or a database table (preferred).
Seed losing... — 2023-03-11 16:21:28 in v3 Support
This implies the nature of Bittorrent in the way that it is just how it works. Your are expediting a remote timeout or disconnect.

Alternatively, its your operating system and we can not help with that as this is a code forum.
Check if curl is installed and enabled.

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;
}
download direct — 2023-03-07 21:31:38 in v3 Mods Requests
You need a field on upload form that filters and writes to this field in database. I’ve had this for YouTube url for years. It’s effective
Updated Cleanup to utilize PECL parallel processing. Uses CPU cores effectively across all threads / workers.

https://www.php.net/manual/en/intro.parallel.php


// 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";
}


NOTE: You can't autoload classes prior to the block scope of the run() method.

Because Cleanup extends Extensions, I have to explicitly define both for autoloading to avoid the unnecessary overhead of autoloading every single class file. Whether that only matters upon instance is of question, but I feel better with this way.
Just to note, this doesn't actually limit anyone in a IP scope (VPN) - They just switch countries and their back in with new account. The best way to actually deal with this, is to use a Anti-VPN API. I did it on TTv3 long ago, and it worked perfectly.

But thats as far as you will get I believe.
No that is just an array key pointing to a mysql instance object. That’s already true if module enabled. The connection string defines the rest.

For example,

Always always.. start all things you call for $_REQUEST, $_POST, $_GET with an initialized state check - isset

Just start writing isset($_GET[‘whatever’]) and depending on what you expect..

ALWAYS: isset($_GET[‘key’])
INT: && intval($_GET[‘key’]) > 0
STRING: && strlen($_GET[‘key’]) > 0

Use this same approach when dealing with anything in a closed scope

If (cond) { … } (we check isset here)

Better to pre-define your variables before scope

$var = ‘’;
If (true) {
  $var = ‘hello’
}

Otherwise you have to:

// no warnings, no exceptions
If (isset($var)) {
  // do
}


PHP has a consistent set of is_*<T>()

T = Type
(&var) = wrapper

is_string, is_int, is_object, is_null, etc. it’s a excellent set of conditionals that I always maintain as routine on anything I do. It’s never failed.
You need to use isset in your code. You must check these global variables, or arrays first before working with it.

You will surely see many warnings.
 $config['maxFileSize']


Can’t you just read the ini setting? That’s probably a safer bet across hosts.
What is the reason behind including audio files? Be sure you use a proper tags for these media types or they may not render.

Can’t post example without stripping tags but it’s at Google  

Do you guys just want my image processing function? It handles absolutely everything, loops all form fields containing a image* name, and gives you a variety of options to convert to if you wish (via radio checkbox or drop-down).

I noticed the array, and that indicates the use for this much more easily. Let me know
This may be a helpful wrapper


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
     }
}


Now I have to wonder how far down the pipe this problem exists. For example,


$allowedMetadata = array(
     'application/x-bittorrent' => 'torrent',
     'application/x-switchtorrent' => 'swt'
);


I better consult MSDN too.
That is gold. And fully noted. I will keep that in my notes and consult the expression.

And the realpath() string parameter should be an absolute filesystem path for best case from what I understand, perhaps a local constant.

Code updated.
I will review that change for my own codebase as it raises a good indication of a potential security hole, I would like to look more into this for myself.

I use a crafty system, but as I see it.. it does not prevent directory traversal attacks. Thanks!


$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
   }
}
donate_block.php — 2023-02-20 17:18:56 in v3 Support
What you need to do use something like


<div style="height:20px;width:<?=($row['total_funds'] * 5)?>%"></div>


To get the growing progressbar effect. The calculation needs to depend on the expected output.
Your calling a local function 13 times, up top of a database transaction. I cant see PHP caching the first instance because their all different variables.. that must be slow.
I’ve never seen that attribute before, interesting!

I know for file, you can use accept=“image/*”
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

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