require_once(BACKEND."/Scraper.php");
require_once(BACKEND."/Torrent.php");
<?php
declare(strict_types=1);
/**
* Scrapeer, a tiny PHP library that lets you scrape
* HTTP(S) and UDP trackers for torrent information.
*
* This file is extensively based on Johannes Zinnau's
* work, which can be found at https://goo.gl/7hyjde
*
* Licensed under a Creative Commons
* Attribution-ShareAlike 3.0 Unported License
* http://creativecommons.org/licenses/by-sa/3.0
*/
/**
* The one and only class you'll ever need.
*/
class Scraper
{
/**
* Current version of Scrapeer.
*
* @var string
*/
const VERSION = '0.6.0';
/**
* Array of errors.
*
* @var array
*/
private $errors = [];
/**
* Array of infohashes to scrape.
*
* @var array
*/
private $infohashes = [];
/**
* Timeout for a single tracker.
*
* @var int
*/
private $timeout;
/**
* Initiates the scraper.
*
* @param array|string $hashes list (>1) or string of infohash(es)
* @param array|string $trackers list (>1) or string of tracker(s)
* @param null|int $max_trackers Optional. Maximum number of trackers to be scraped, Default all.
* @param int $timeout Optional. Maximum time for each tracker scrape in seconds, Default 2.
* @param bool $announce Optional. Use announce instead of scrape, Default false.
*
* @throws Exception|RangeException in case of invalid amount of info-hashes
*
* @return array list of results
*/
public function scrape($hashes, $trackers, $max_trackers = null, $timeout = 2, $announce = false)
{
$final_result = [];
if (empty($trackers)) {
$this->errors[] = 'No tracker specified, aborting.';
return $final_result;
}
if (!is_array($trackers)) {
$trackers = [$trackers];
}
if (is_int($timeout)) {
$this->timeout = $timeout;
} else {
$this->timeout = 2;
$this->errors[] = 'Timeout must be an integer. Using default value.';
}
try {
$this->infohashes = $this->normalize_infohashes($hashes);
} catch (RangeException $e) {
$this->errors[] = $e->getMessage();
return $final_result;
}
$max_iterations = is_int($max_trackers) ? $max_trackers : count($trackers);
foreach ($trackers as $index => $tracker) {
if (!empty($this->infohashes) && $index < $max_iterations) {
$tracker = is_array($tracker) ? $tracker[0] : $tracker;
$info = parse_url($tracker);
$protocol = $info['scheme'];
$host = $info['host'];
if (empty($protocol) || empty($host)) {
$this->errors[] = 'Skipping invalid tracker (' . $tracker . ').';
continue;
}
$port = $info['port'] ?? null;
$path = $info['path'] ?? null;
$passkey = $this->get_passkey($path);
$result = $this->try_scrape($protocol, $host, $port, $passkey, $announce);
$final_result = array_merge($final_result, $result);
continue;
}
break;
}
return $final_result;
}
/**
* Checks if there are any errors.
*
* @return bool true or false, depending if errors are present or not
*/
public function has_errors()
{
return !empty($this->errors);
}
/**
* Returns all the errors that were logged.
*
* @return array all the logged errors
*/
public function get_errors()
{
return $this->errors;
}
/**
* Normalizes the given hashes.
*
* @param array $infohashes list of infohash(es)
*
* @throws RangeException if amount of valid infohashes > 64 or < 1
*
* @return array normalized infohash(es)
*/
private function normalize_infohashes($infohashes)
{
if (!is_array($infohashes)) {
$infohashes = [$infohashes];
}
foreach ($infohashes as $index => $infohash) {
if (!preg_match('/^[a-f0-9]{40}$/i', $infohash)) {
$this->errors[] = 'Invalid infohash skipped (' . $infohash . ').';
unset($infohashes[$index]);
}
}
$total_infohashes = count($infohashes);
if ($total_infohashes > 64 || $total_infohashes < 1) {
throw new RangeException('Invalid amount of valid infohashes (' . $total_infohashes . ').');
}
return array_values($infohashes);
}
/**
* Returns the passkey found in the scrape request.
*
* @param string $path path from the scrape request
*
* @return string passkey or empty string
*/
private function get_passkey($path)
{
if (!empty($path) && preg_match('/[a-z0-9]{32}/i', $path, $matches)) {
return '/' . $matches[0];
}
return '';
}
/**
* Tries to scrape with a single tracker.
*
* @param string $protocol protocol of the tracker
* @param string $host domain or address of the tracker
* @param int $port Optional. Port number of the tracker.
* @param string $passkey Optional. Passkey provided in the scrape request.
* @param bool $announce Optional. Use announce instead of scrape, Default false.
*
* @throws Exception in case of unsupported protocol
*
* @return array list of results
*/
private function try_scrape($protocol, $host, $port, $passkey, $announce)
{
$infohashes = $this->infohashes;
$this->infohashes = [];
$results = [];
try {
switch ($protocol) {
case 'udp':
$port = $port ?? 80;
$results = $this->scrape_udp($infohashes, $host, $port, $announce);
break;
case 'http':
$port = $port ?? 80;
$results = $this->scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce);
break;
case 'https':
$port = $port ?? 443;
$results = $this->scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce);
break;
default:
throw new Exception('Unsupported protocol (' . $protocol . '://' . $host . ').');
}
} catch (Exception $e) {
$this->infohashes = $infohashes;
$this->errors[] = $e->getMessage();
}
return $results;
}
/**
* Initiates the HTTP(S) scraping.
*
* @param array|string $infohashes list (>1) or string of infohash(es)
* @param string $protocol protocol to use for the scraping
* @param string $host domain or IP address of the tracker
* @param int $port Optional. Port number of the tracker, Default 80 (HTTP) or 443 (HTTPS).
* @param string $passkey Optional. Passkey provided in the scrape request.
* @param bool $announce Optional. Use announce instead of scrape, Default false.
*
* @throws Exception
*
* @return array list of results
*/
private function scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce)
{
if (true === $announce) {
$response = $this->http_announce($infohashes, $protocol, $host, $port, $passkey);
} else {
$query = $this->http_query($infohashes, $protocol, $host, $port, $passkey);
$response = $this->http_request($query, $host, $port);
}
return $this->http_data($response, $infohashes, $host);
}
/**
* Builds the HTTP(S) query.
*
* @param array|string $infohashes list (>1) or string of infohash(es)
* @param string $protocol protocol to use for the scraping
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
* @param string $passkey Optional. Passkey provided in the scrape request.
*
* @return string request query
*/
private function http_query($infohashes, $protocol, $host, $port, $passkey)
{
$tracker_url = $protocol . '://' . $host . ':' . $port . $passkey;
$scrape_query = '';
foreach ($infohashes as $index => $infohash) {
if ($index > 0) {
$scrape_query .= '&info_hash=' . urlencode(pack('H*', $infohash));
} else {
$scrape_query .= '/scrape?info_hash=' . urlencode(pack('H*', $infohash));
}
}
return $tracker_url . $scrape_query;
}
/**
* Executes the query and returns the result.
*
* @param string $query the query that will be executed
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
*
* @throws Exception if the response isn't valid
* @throws Exception if the connection can't be established
*
* @return string request response
*/
private function http_request($query, $host, $port)
{
$context = stream_context_create([
'http' => [
'timeout' => $this->timeout,
],
]);
if (false === ($response = @file_get_contents($query, false, $context))) {
throw new Exception('Invalid scrape connection (' . $host . ':' . $port . ').');
}
if (substr($response, 0, 12) !== 'd5:filesd20:') {
throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
}
return $response;
}
/**
* Builds the query, sends the announce request and returns the data.
*
* @param array|string $infohashes list (>1) or string of infohash(es)
* @param string $protocol protocol to use for the scraping
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
* @param string $passkey Optional. Passkey provided in the scrape request.
*
* @throws Exception if the connection can't be established
*
* @return string request response
*/
private function http_announce($infohashes, $protocol, $host, $port, $passkey)
{
$tracker_url = $protocol . '://' . $host . ':' . $port . $passkey;
$context = stream_context_create([
'http' => [
'timeout' => $this->timeout,
],
]);
$response_data = '';
foreach ($infohashes as $infohash) {
$query = $tracker_url . '/announce?info_hash=' . urlencode(pack('H*', $infohash));
if (false === ($response = @file_get_contents($query, false, $context))) {
throw new Exception('Invalid announce connection (' . $host . ':' . $port . ').');
}
if (substr($response, 0, 12) !== 'd8:completei'
|| substr($response, 0, 46) === 'd8:completei0e10:downloadedi0e10:incompletei1e') {
continue;
}
$ben_hash = '20:' . pack('H*', $infohash) . 'd';
$response_data .= $ben_hash . $response;
}
return $response_data;
}
/**
* Parses the response and returns the data.
*
* @param string $response the response that will be parsed
* @param array $infohashes list of infohash(es)
* @param string $host domain or IP address of the tracker
*
* @return array parsed data
*/
private function http_data($response, $infohashes, $host)
{
$torrents_data = [];
foreach ($infohashes as $infohash) {
$ben_hash = '20:' . pack('H*', $infohash) . 'd';
$start_pos = strpos($response, $ben_hash);
if (false !== $start_pos) {
$start = $start_pos + 24;
$head = substr($response, $start);
$end = strpos($head, 'ee') + 1;
$data = substr($response, $start, $end);
$seeders = '8:completei';
$torrent_info['seeders'] = $this->get_information($data, $seeders, 'e');
$completed = '10:downloadedi';
$torrent_info['completed'] = $this->get_information($data, $completed, 'e');
$leechers = '10:incompletei';
$torrent_info['leechers'] = $this->get_information($data, $leechers, 'e');
$torrents_data[$infohash] = $torrent_info;
} else {
$this->collect_infohash($infohash);
$this->errors[] = 'Invalid infohash (' . $infohash . ') for tracker: ' . $host . '.';
}
}
return $torrents_data;
}
/**
* Parses a string and returns the data between $start and $end.
*
* @param string $data the data that will be parsed
* @param string $start beginning part of the data
* @param string $end ending part of the data
*
* @return int parsed information or 0
*/
private function get_information($data, $start, $end)
{
$start_pos = strpos($data, $start);
if (false !== $start_pos) {
$start = $start_pos + strlen($start);
$head = substr($data, $start);
$end = strpos($head, $end);
$information = substr($data, $start, $end);
return (int) $information;
}
return 0;
}
/**
* Initiates the UDP scraping.
*
* @param array|string $infohashes list (>1) or string of infohash(es)
* @param string $host domain or IP address of the tracker
* @param int $port Optional. Port number of the tracker, Default 80.
* @param bool $announce Optional. Use announce instead of scrape, Default false.
*
* @throws Exception
*
* @return array list of results
*/
private function scrape_udp($infohashes, $host, $port, $announce)
{
list($socket, $transaction_id, $connection_id) = $this->prepare_udp($host, $port);
if (true === $announce) {
$response = $this->udp_announce($socket, $infohashes, $connection_id);
$keys = 'Nleechers/Nseeders';
$start = 12;
$end = 16;
$offset = 20;
} else {
$response = $this->udp_scrape($socket, $infohashes, $connection_id, $transaction_id, $host, $port);
$keys = 'Nseeders/Ncompleted/Nleechers';
$start = 8;
$end = $offset = 12;
}
return $this->udp_scrape_data($response, $infohashes, $host, $keys, $start, $end, $offset);
}
/**
* Prepares the UDP connection.
*
* @param string $host domain or IP address of the tracker
* @param int $port Optional. Port number of the tracker, Default 80.
*
* @throws Exception
*
* @return array created socket, transaction ID and connection ID
*/
private function prepare_udp($host, $port)
{
$socket = $this->udp_create_connection($host, $port);
$transaction_id = $this->udp_connection_request($socket);
$connection_id = $this->udp_connection_response($socket, $transaction_id, $host, $port);
return [$socket, $transaction_id, $connection_id];
}
/**
* Creates the UDP socket and establishes the connection.
*
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80
*
* @throws Exception if the socket couldn't be created or connected to
*
* @return resource $socket created and connected socket
*/
private function udp_create_connection($host, $port)
{
if (false === ($socket = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))) {
throw new Exception("Couldn't create socket.");
}
$timeout = $this->timeout;
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $timeout, 'usec' => 0]);
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => $timeout, 'usec' => 0]);
if (false === @socket_connect($socket, $host, $port)) {
throw new Exception("Couldn't connect to socket.");
}
return $socket;
}
/**
* Writes to the connected socket and returns the transaction ID.
*
* @param resource $socket the socket resource
*
* @throws Exception if the socket couldn't be written to
*
* @return int the transaction ID
*/
private function udp_connection_request($socket)
{
$connection_id = "\x00\x00\x04\x17\x27\x10\x19\x80";
$action = pack('N', 0);
$transaction_id = mt_rand(0, 2147483647);
$buffer = $connection_id . $action . pack('N', $transaction_id);
if (false === @socket_write($socket, $buffer, strlen($buffer))) {
socket_close($socket);
throw new Exception("Couldn't write to socket.");
}
return $transaction_id;
}
/**
* Reads the connection response and returns the connection ID.
*
* @param resource $socket the socket resource
* @param int $transaction_id the transaction ID
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80
*
* @throws Exception if anything fails with the scraping
*
* @return string the connection ID
*/
private function udp_connection_response($socket, $transaction_id, $host, $port)
{
if (false === ($response = @socket_read($socket, 16))) {
socket_close($socket);
throw new Exception('Invalid scrape connection! (' . $host . ':' . $port . ').');
}
if (strlen($response) < 16) {
socket_close($socket);
throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
}
$result = unpack('Naction/Ntransaction_id', $response);
if (0 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
socket_close($socket);
throw new Exception('Invalid scrape result (' . $host . ':' . $port . ').');
}
return substr($response, 8, 8);
}
/**
* Reads the socket response and returns the torrent data.
*
* @param resource $socket the socket resource
* @param array $hashes list (>1) or string of infohash(es)
* @param string $connection_id the connection ID
* @param int $transaction_id the transaction ID
* @param string $host domain or IP address of the tracker
* @param int $port port number of the tracker, Default 80
*
* @throws Exception if anything fails while reading the response
*
* @return string response data
*/
private function udp_scrape($socket, $hashes, $connection_id, $transaction_id, $host, $port)
{
$this->udp_scrape_request($socket, $hashes, $connection_id, $transaction_id);
$read_length = 8 + (12 * count($hashes));
if (false === ($response = @socket_read($socket, $read_length))) {
socket_close($socket);
throw new Exception('Invalid scrape connection (' . $host . ':' . $port . ').');
}
socket_close($socket);
if (strlen($response) < $read_length) {
throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
}
$result = unpack('Naction/Ntransaction_id', $response);
if (2 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
throw new Exception('Invalid scrape result (' . $host . ':' . $port . ').');
}
return $response;
}
/**
* Writes to the connected socket.
*
* @param resource $socket the socket resource
* @param array $hashes list (>1) or string of infohash(es)
* @param string $connection_id the connection ID
* @param int $transaction_id the transaction ID
*
* @throws Exception if the socket couldn't be written to
*/
private function udp_scrape_request($socket, $hashes, $connection_id, $transaction_id)
{
$action = pack('N', 2);
$infohashes = '';
foreach ($hashes as $infohash) {
$infohashes .= pack('H*', $infohash);
}
$buffer = $connection_id . $action . pack('N', $transaction_id) . $infohashes;
if (false === @socket_write($socket, $buffer, strlen($buffer))) {
socket_close($socket);
throw new Exception("Couldn't write to socket.");
}
}
/**
* Writes the announce to the connected socket.
*
* @param resource $socket the socket resource
* @param array $hashes list (>1) or string of infohash(es)
* @param string $connection_id the connection ID
*
* @throws Exception if the socket couldn't be written to
*
* @return string torrent(s) data
*/
private function udp_announce($socket, $hashes, $connection_id)
{
$action = pack('N', 1);
$downloaded = $left = $uploaded = "\x30\x30\x30\x30\x30\x30\x30\x30";
$peer_id = $this->random_peer_id();
$event = pack('N', 3);
$ip_addr = pack('N', 0);
$key = pack('N', mt_rand(0, 2147483647));
$num_want = -1;
$ann_port = pack('N', mt_rand(0, 255));
$response_data = '';
foreach ($hashes as $infohash) {
$transaction_id = mt_rand(0, 2147483647);
$buffer = $connection_id . $action . pack('N', $transaction_id) . pack('H*', $infohash) .
$peer_id . $downloaded . $left . $uploaded . $event . $ip_addr . $key . $num_want . $ann_port;
if (false === @socket_write($socket, $buffer, strlen($buffer))) {
socket_close($socket);
throw new Exception("Couldn't write announce to socket.");
}
$response = $this->udp_verify_announce($socket, $transaction_id);
if (false === $response) {
continue;
}
$response_data .= $response;
}
socket_close($socket);
return $response_data;
}
/**
* Generates a random peer ID.
*
* @return string generated peer ID
*/
private function random_peer_id()
{
$identifier = '-SP0054-';
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
return $identifier . substr(str_shuffle($chars), 0, 12);
}
/**
* Verifies the correctness of the announce response.
*
* @param resource $socket the socket resource
* @param int $transaction_id the transaction ID
*
* @return string response data
*/
private function udp_verify_announce($socket, $transaction_id)
{
if (false === ($response = @socket_read($socket, 20))) {
return false;
}
if (strlen($response) < 20) {
return false;
}
$result = unpack('Naction/Ntransaction_id', $response);
if (1 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
return false;
}
return $response;
}
/**
* Reads the socket response and returns the torrent data.
*
* @param string $response data from the request response
* @param array $hashes list (>1) or string of infohash(es)
* @param string $host domain or IP address of the tracker
* @param string $keys keys for the unpacked information
* @param int $start start of the content we want to unpack
* @param int $end end of the content we want to unpack
* @param int $offset offset to the next content part
*
* @return array scraped torrent data
*/
private function udp_scrape_data($response, $hashes, $host, $keys, $start, $end, $offset)
{
$torrents_data = [];
foreach ($hashes as $infohash) {
$byte_string = substr($response, $start, $end);
$data = unpack('N', $byte_string);
$content = $data[1];
if (!empty($content)) {
$results = unpack($keys, $byte_string);
$torrents_data[$infohash] = $results;
} else {
$this->collect_infohash($infohash);
$this->errors[] = 'Invalid infohash (' . $infohash . ') for tracker: ' . $host . '.';
}
$start += $offset;
}
return $torrents_data;
}
/**
* Collects info-hashes that couldn't be scraped.
*
* @param string $infohash infohash that wasn't scraped
*/
private function collect_infohash($infohash)
{
$this->infohashes[] = $infohash;
}
}
<?php
declare(strict_types=1);
/**
* Torrent.
*
* PHP version 7.2+ (with cURL extension enabled)
*
* Features:
* - Decode torrent file or data from local file and distant url
* - Build torrent from source folder/file(s) or distant url
* - Super easy usage & syntax
* - Silent Exception error system
*
* @author Adrien Gibrat <adrien.gibrat@gmail.com>
* @tester Jeong, Anton, dokcharlie, official testers ;) Thanks for your precious feedback
* @copyleft 2010 - Just use it!
*
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License version 3
*
* @version 0.1.0
*/
/**
* Class Torrent.
*/
class Torrent
{
/**
* @const float Default http timeout
*/
public const TIMEOUT = 30;
/**
* @var array List of error occurred
*/
protected static $errors = [];
/**
* @var string
*/
protected $comment;
/**
* @var array
*/
protected $info;
/**
* @var array
*/
protected $httpseeds;
/**
* @var mixed
*/
protected $announce;
/** Read and decode torrent file/data OR build a torrent from source folder/file(s)
* Supported signatures:
* - Torrent(); // get an instance (useful to scrape and check errors)
* - Torrent(string $torrent); // analyze a torrent file
* - Torrent(string $torrent, string $announce);
* - Torrent(string $torrent, array $meta);
* - Torrent(string $file_or_folder); // create a torrent file
* - Torrent(string $file_or_folder, string $announce_url, int $piece_length);
* - Torrent(string $file_or_folder, array $meta, int $piece_length);
* - Torrent(string $file_or_folder, array $meta, int $piece_length, bool $include_hidden);
* - Torrent(array $files_list);
* - Torrent(array $files_list, string $announce_url, int $piece_length);
* - Torrent(array $files_list, array $meta, int $piece_length);
* - Torrent(array $files_list, array $meta, int $piece_length , bool $include_hidden);.
*
* @param mixed $data torrent to read or source folder/file(s) (optional, to get an instance)
* @param mixed $meta announce url or meta information (optional)
* @param int $piece_length (optional)
* @param bool $include_hidden (optional)
*/
public function __construct($data = null, $meta = [], int $piece_length = 256, bool $include_hidden = true)
{
if (is_null($data)) {
self::setError(new Exception('data cannot be empty'));
}
if ($piece_length < 32 || $piece_length > 4096) {
self::setError(new Exception('Invalid piece length, must be between 32 and 4096'));
}
if (is_string($meta)) {
$meta = [
'announce' => $meta,
];
} else {
$list = [];
foreach ($meta as $item) {
$list[] = [
'announce' => $item,
];
}
$meta = $list;
}
if ($this->build($data, $piece_length * 1024, $include_hidden)) {
$this->touch();
} else {
$meta = array_merge($meta, self::decode($data));
}
foreach ($meta as $key => $value) {
$this->{trim($key)} = $value;
}
}
/** Convert the current Torrent instance in torrent format.
*
* @return string encoded torrent data
*/
public function __toString(): string
{
return (string) self::encode($this);
}
/** Return last error message.
*
* @return bool|string last error message or false if none
*/
public function error()
{
return empty(self::$errors) ?
false :
self::$errors[0]->getMessage();
}
/** Return Errors.
*
* @return array|bool error list or false if none
*/
public function errors()
{
return empty(self::$errors) ?
false :
self::$errors;
}
// Getters and setters
/** Getter and setter of torrent announce url / list
* If the argument is a string, announce url is added to announce list (or set as announce if announce is not set)
* If the argument is an array/object, set announce url (with first url) and list (if array has more than one url),
* tiered list supported
* If the argument is false announce url & list are unset.
*
* @param null|mixed $announce list, reset all if false (optional, if omitted it's a getter)
*
* @return null|array|string announce url / list or null if not set
*/
public function announce($announce = null)
{
if (is_null($announce)) {
return $this->{'announce-list'} ?? $this->announce ?? null;
}
$this->touch();
if (is_string($announce) && isset($this->announce)) {
return $this->{'announce-list'} = self::announceList(
$this->{'announce-list'} ?? $this->announce,
$announce
);
}
unset($this->{'announce-list'});
if (is_array($announce) || is_object($announce)) {
if (($this->announce = self::firstAnnounce($announce)) && count($announce) > 1) {
return $this->{'announce-list'} = self::announceList($announce);
}
return $this->announce;
}
if (!isset($this->announce) && $announce) {
return $this->announce = (string) $announce;
}
unset($this->announce);
return null;
}
/** Getter and setter of torrent creation date.
*
* @param null|mixed $timestamp (optional, if omitted it's a getter)
*
* @return null|int timestamp or null if not set
*/
public function creation_date($timestamp = null)
{
return is_null($timestamp) ?
$this->{'creation date'} ?? null :
$this->touch($this->{'creation date'} = (int) $timestamp);
}
/** Getter and setter of torrent comment.
*
* @param null|mixed $comment (optional, if omitted it's a getter)
*
* @return null|string comment or null if not set
*/
public function comment($comment = null)
{
return is_null($comment) ?
$this->comment ?? null :
$this->touch($this->comment = (string) $comment);
}
/** Getter and setter of torrent name.
*
* @param null|mixed $name (optional, if omitted it's a getter)
*
* @return null|string name or null if not set
*/
public function name($name = null)
{
return is_null($name) ?
$this->info['name'] ?? null :
$this->touch($this->info['name'] = (string) $name);
}
/** Getter and setter of private flag.
*
* @param null|mixed $private or not (optional, if omitted it's a getter)
*
* @return bool private flag
*/
public function is_private($private = null): bool
{
return is_null($private) ?
!empty($this->info['private']) :
$this->touch($this->info['private'] = $private ? 1 : 0);
}
/** Getter and setter of torrent source.
*
* @param null|mixed $source (optional, if omitted it's a getter)
*
* @return null|string source or null if not set
*/
public function source($source = null)
{
return is_null($source) ?
$this->info['source'] ?? null :
$this->touch($this->info['source'] = (string) $source);
}
/** Getter and setter of webseed(s) url list ( GetRight implementation ).
*
* @param null|mixed $urls webseed or webseeds mirror list (optional, if omitted it's a getter)
*
* @return null|array|string webseed(s) or null if not set
*/
public function url_list($urls = null)
{
return is_null($urls) ?
$this->{'url-list'} ?? null :
$this->touch($this->{'url-list'} = is_string($urls) ? $urls : (array) $urls);
}
/** Getter and setter of httpseed(s) url list ( BitTornado implementation ).
*
* @param null|mixed $urls httpseed or httpseeds mirror list (optional, if omitted it's a getter)
*
* @return null|array|bool httpseed(s) or null if not set
*/
public function httpseeds($urls = null)
{
return is_null($urls) ?
$this->httpseeds ?? null :
$this->touch($this->httpseeds = (array) $urls);
}
// Analyze BitTorrent
/** Get piece length.
*
* @return int piece length or null if not set
*/
public function piece_length(): ?int
{
return $this->info['piece length'] ?? null;
}
/** Compute hash info.
*
* @return string hash info or null if info not set
*/
public function hash_info(): ?string
{
return isset($this->info) ?
sha1(self::encode($this->info)) :
null;
}
/** List torrent content.
*
* @param null|mixed $precision size precision (optional, if omitted returns sizes in bytes)
*
* @return array file(s) and size(s) list, files as keys and sizes as values
*/
public function content($precision = null): array
{
$files = [];
if (isset($this->info['files']) && is_array($this->info['files'])) {
foreach ($this->info['files'] as $file) {
$files[self::path($file['path'], $this->info['name'])] = $precision ?
self::format($file['length'], $precision) :
$file['length'];
}
} elseif (isset($this->info['name'])) {
$files[$this->info['name']] = $precision ?
self::format($this->info['length'], $precision) :
$this->info['length'];
}
return $files;
}
/** List torrent content pieces and offset(s).
*
* @return array file(s) and pieces/offset(s) list, file(s) as keys and pieces/offset(s) as values
*/
public function offset(): array
{
$files = [];
$size = 0;
if (isset($this->info['files']) && is_array($this->info['files'])) {
foreach ($this->info['files'] as $file) {
$files[self::path($file['path'], $this->info['name'])] = [
'startpiece' => floor($size / $this->info['piece length']),
'offset' => fmod($size, $this->info['piece length']),
'size' => $size += $file['length'],
'endpiece' => floor($size / $this->info['piece length']),
];
}
} elseif (isset($this->info['name'])) {
$files[$this->info['name']] = [
'startpiece' => 0,
'offset' => 0,
'size' => $this->info['length'],
'endpiece' => floor($this->info['length'] / $this->info['piece length']),
];
}
return $files;
}
/** Sum torrent content size.
*
* @param null|mixed $precision size precision (optional, if omitted returns size in bytes)
*
* @return int|string file(s) size
*/
public function size($precision = null)
{
$size = 0;
if (isset($this->info['files']) && is_array($this->info['files'])) {
foreach ($this->info['files'] as $file) {
$size += $file['length'];
}
} elseif (isset($this->info['name'])) {
$size = $this->info['length'];
}
return is_null($precision) ?
$size :
self::format($size, $precision);
}
/**
* @param null|mixed $announce url (optional, to request an alternative tracker BUT required for static call)
* @param null|mixed $hash_info (optional, required ONLY for static call)
* @param mixed $timeout in seconds (optional, default to self::timeout 30s)
*
* @throws Exception
*
* @return array|bool tracker torrent statistics
*/
public function scrape($announce = null, $hash_info = null, $timeout = self::TIMEOUT)
{
$scraper = new Scraper();
try {
return $scraper->scrape($hash_info ?? $this->hash_info(), $announce ?? $this->announce(), null, $timeout);
} catch (Exception $e) {
return $scraper->get_errors();
}
}
// Save and Send
/** Save torrent file to disk.
*
* @param null|mixed $filename name of the file (optional)
*
* @return bool|int file has been saved or not
*/
public function save($filename = null)
{
return file_put_contents(is_null($filename) ?
$this->info['name'] . '.torrent' : $filename, self::encode($this));
}
/** Send torrent file to client.
*
* @param null|mixed $filename name of the file (optional)
*/
public function send($filename = null): void
{
$data = self::encode($this);
header('Content-type: application/x-bittorrent');
header('Content-Length: ' . strlen($data));
header('Content-Disposition: attachment; filename="' . (is_null($filename) ?
$this->info['name'] . '.torrent' : $filename) . '"');
exit($data);
}
/** Get magnet link.
*
* @param mixed $html encode ampersand, default true (optional)
*
* @return string magnet link
*/
public function magnet($html = true): string
{
$ampersand = $html ? '&' : '&';
return sprintf(
'magnet:?xt=urn:btih:%2$s%1$sdn=%3$s%1$sxl=%4$d%1$str=%5$s',
$ampersand,
$this->hash_info(),
urlencode($this->name()),
$this->size(),
implode($ampersand . 'tr=', self::untier($this->announce()))
);
}
// Encode BitTorrent
/** Encode torrent data.
*
* @param mixed $mixed data to encode
*
* @return string torrent encoded data
*/
public static function encode($mixed): ?string
{
switch (gettype($mixed)) {
case 'integer':
case 'double':
return self::encodeInteger($mixed);
case 'object':
$mixed = get_object_vars($mixed);
// no break
case 'array':
return self::encodeArray($mixed);
default:
return self::encodeString((string) $mixed);
}
}
// Public Helpers
/** Helper to format size in bytes to human readable.
*
* @param mixed $size in bytes
* @param mixed $precision precision after comma
*
* @return string formatted size in appropriate unit
*/
public static function format($size, $precision = 2): string
{
$units = [
'octets',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
];
while (($next = next($units)) && $size > 1024) {
$size /= 1024;
}
return round($size, $precision) . ' ' . ($next ? prev($units) : end($units));
}
/** Helper to return filesize (even bigger than 2Gb -linux only- and distant files size).
*
* @param mixed $file path
*
* @return bool|float filesize or false if error
*/
public static function filesize($file)
{
if (is_file($file)) {
return (float) sprintf('%u', @filesize($file));
}
if ($content_length = preg_grep($pattern = '#^Content-Length:\s+(\d+)$#i', (array) @get_headers($file))) {
return (int) preg_replace($pattern, '$1', reset($content_length));
}
return 0;
}
/** Helper to open file to read (even bigger than 2Gb, linux only).
*
* @param mixed $file path
* @param null|mixed $size (optional)
*
* @return bool|resource file handle or false if error
*/
public static function fopen($file, $size = null)
{
if ((is_null($size) ? self::filesize($file) : $size) <= 2 * (1024 ** 3)) {
return fopen($file, 'rb');
}
if (PHP_OS !== 'Linux') {
return self::setError(new Exception('File size is greater than 2GB. This is only supported under Linux'));
}
if (!is_readable($file)) {
return false;
}
return popen('cat ' . escapeshellarg(realpath($file)), 'r');
}
/** Helper to scan directories files and sub directories recursively.
*
* @param string $dir directory path
* @param bool $include_hidden
*
* @return array directory content list
*/
public static function scandir($dir, $include_hidden): array
{
$paths = $ignored = [];
$ignored[] = '/torrent-rw/vendor';
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$dir,
RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::SELF_FIRST
);
if (!$include_hidden) {
foreach ($iterator as $name => $object) {
if (is_dir($name) && basename($name)[0] === '.') {
$ignored[] = $name;
}
}
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$dir,
RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $name => $object) {
if (!$include_hidden) {
foreach ($ignored as $ignore) {
if (preg_match('#' . $ignore . '#', $name)) {
continue 2;
}
}
if (basename($name)[0] === '.') {
continue;
}
}
if (is_dir($name)) {
continue;
}
$paths[] = $name;
}
return $paths;
}
/** Helper to check if string is an url (http).
*
* @param mixed $url to check
*
* @return bool is string an url
*/
public static function is_url($url): bool
{
return (bool) filter_var($url, FILTER_VALIDATE_URL);
}
/** Helper to check if url exists.
*
* @param mixed $url to check
*
* @return bool does the url exist or not
*/
public static function url_exists($url): bool
{
return self::is_url($url) ?
(bool) self::filesize($url) :
false;
}
/** Helper to check if a file is a torrent.
*
* @param mixed $file path
* @param mixed $timeout http timeout (optional, default to self::timeout 30s)
*
* @return bool is the file a torrent or not
*/
public static function is_torrent($file, $timeout = self::TIMEOUT): bool
{
return (($start = self::file_get_contents($file, $timeout, 0, 11))
&& 'd8:announce' === $start)
|| 'd10:created' === $start
|| 'd13:creatio' === $start
|| 'd13:announc' === $start
|| 'd12:_info_l' === $start
|| strpos($start, 'd7:comment') === 0 // @see https://github.com/adriengibrat/torrent-rw/issues/32
|| strpos($start, 'd4:info') === 0
|| strpos($start, 'd9:') === 0; // @see https://github.com/adriengibrat/torrent-rw/pull/17
}
/** Helper to get (distant) file content.
*
* @param mixed $file path
* @param mixed $timeout http timeout (optional, default to self::timeout 30s)
* @param null|mixed $offset starting offset (optional, default to null)
* @param null|mixed $length content length (optional, default to null)
*
* @return bool|string file content or false if error
*/
public static function file_get_contents($file, $timeout = self::TIMEOUT, $offset = null, $length = null)
{
if (is_file($file) || ini_get('allow_url_fopen')) {
$context = !is_file($file) && $timeout ?
stream_context_create(['http' => ['timeout' => $timeout]]) :
null;
return !is_null($offset) ? $length ?
@file_get_contents($file, false, $context, $offset, $length) :
@file_get_contents($file, false, $context, $offset) :
@file_get_contents($file, false, $context);
}
if (!function_exists('curl_init')) {
return self::setError(new Exception('Install CURL or enable "allow_url_fopen"'));
}
$handle = curl_init($file);
if ($timeout) {
curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);
}
if ($offset || $length) {
curl_setopt($handle, CURLOPT_RANGE, $offset . '-' . ($length ? $offset + $length - 1 : null));
}
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($handle);
$size = curl_getinfo($handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($handle);
return ($offset && $size === -1) || ($length && $length !== $size) ? $length ?
substr($content, $offset, $length) :
substr($content, $offset) :
$content;
}
/** Flatten announces list.
*
* @param mixed $announces list
*
* @return array flattened announces list
*/
public static function untier($announces): array
{
$list = [];
foreach ((array) $announces as $tier) {
is_array($tier) ?
$list = array_merge($list, self::untier($tier)) :
array_push($list, $tier);
}
return $list;
}
// Decode BitTorrent
/** Decode torrent data or file.
*
* @param mixed $string data or file path to decode
*
* @return array decoded torrent data
*/
protected static function decode($string): array
{
$data = is_file($string) || self::url_exists($string) ?
self::file_get_contents($string) :
$string;
return (array) self::decodeData($data);
}
// Internal Helpers
/** Build torrent info.
*
* @param mixed $data source folder/file(s) path
* @param mixed $piece_length
* @param mixed $include_hidden include hidden files
*
* @return array|bool torrent info or false if data isn't folder/file(s)
*/
protected function build($data, $piece_length, $include_hidden)
{
if (is_null($data)) {
return false;
}
if (is_array($data) && self::isList($data)) {
return $this->info = $this->files($data, $piece_length);
}
if (is_dir((string) $data)) {
return $this->info = $this->folder($data, $piece_length, $include_hidden);
}
if ((is_file((string) $data) || self::url_exists($data)) && !self::is_torrent($data)) {
return $this->info = $this->file($data, $piece_length);
}
return false;
}
/** Set torrent creator and creation date.
*
* @param null $void
*
* @return bool
*/
protected function touch($void = null): bool
{
$this->{'created by'} = 'Torrent RW PHP Class - http://github.com/adriengibrat/torrent-rw';
$this->{'creation date'} = time();
return true;
}
/** Add an error to errors stack.
*
* @param mixed $exception error to add
* @param mixed $message return error message or not (optional, default to false)
*
* @return bool|string return false or error message if requested
*/
protected static function setError($exception, $message = false)
{
return (array_unshift(self::$errors, $exception) && $message) ? $exception->getMessage() : false;
}
/** Build announce list.
*
* @param mixed $announce announce url / list
* @param mixed $merge announce url / list to add (optional)
*
* @return array announce list (array of arrays)
*/
protected static function announceList($announce, $merge = []): array
{
return array_map(static function ($a) {
return (array) $a;
}, array_merge((array) $announce, (array) $merge));
}
/** Get the first announce url in a list.
*
* @param mixed $announce list (array of arrays if tiered trackers)
*
* @return string first announce url
*/
protected static function firstAnnounce($announce): string
{
while (is_array($announce)) {
$announce = reset($announce);
}
return $announce;
}
/** Helper to pack data hash.
*
* @param mixed $data
*
* @return string packed data hash
*/
protected static function pack(&$data): string
{
return pack('H*', sha1($data)) . ($data = null);
}
/** Helper to build file path.
*
* @param mixed $path
* @param mixed $folder base path
*
* @return string real file path
*/
protected static function path($path, $folder): string
{
array_unshift($path, $folder);
return implode(DIRECTORY_SEPARATOR, $path);
}
/** Helper to explode file path.
*
* @param mixed $path
*
* @return array file path
*/
protected static function pathExplode($path): array
{
return explode(DIRECTORY_SEPARATOR, $path);
}
/** Helper to test if an array is a list.
*
* @param mixed $array to test
*
* @return bool is the array a list or not
*/
protected static function isList($array): bool
{
foreach (array_keys($array) as $key) {
if (!is_int($key)) {
return false;
}
}
return true;
}
/** Encode torrent string.
*
* @param mixed $string to encode
*
* @return string encoded string
*/
private static function encodeString($string): string
{
return strlen($string) . ':' . $string;
}
/** Encode torrent integer.
*
* @param mixed $integer to encode
*
* @return string encoded integer
*/
private static function encodeInteger($integer): string
{
return 'i' . $integer . 'e';
}
/** Encode torrent dictionary or list.
*
* @param mixed $array to encode
*
* @return string encoded dictionary or list
*/
private static function encodeArray($array): string
{
if (self::isList($array)) {
$return = 'l';
foreach ($array as $value) {
$return .= self::encode($value);
}
} else {
ksort($array, SORT_STRING);
$return = 'd';
foreach ($array as $key => $value) {
$return .= self::encode((string) $key) . self::encode($value);
}
}
return $return . 'e';
}
/**
* @param mixed $data
*
* @return array|int|string
*/
private static function decodeData(&$data)
{
switch (self::char($data)) {
case 'i':
$data = substr($data, 1);
return self::decodeInteger($data);
case 'l':
$data = substr($data, 1);
return self::decodeList($data);
case 'd':
$data = substr($data, 1);
return self::decodeDictionary($data);
default:
return self::decodeString($data);
}
}
/** Decode torrent dictionary.
*
* @param mixed $data to decode
*
* @return array|string decoded dictionary
*/
private static function decodeDictionary(&$data)
{
$dictionary = [];
$previous = null;
while ('e' !== ($char = self::char($data))) {
if (false === $char) {
return self::setError(new Exception('Unterminated dictionary'));
}
if (!ctype_digit($char)) {
return self::setError(new Exception('Invalid dictionary key'));
}
$key = self::decodeString($data);
if (isset($dictionary[$key])) {
return self::setError(new Exception('Duplicate dictionary key'));
}
if ($key < $previous) {
self::setError(new Exception('Missorted dictionary key'));
}
$dictionary[$key] = self::decodeData($data);
$previous = $key;
}
$data = substr($data, 1);
return $dictionary;
}
/** Decode torrent list.
*
* @param mixed $data to decode
*
* @return array|string decoded list
*/
private static function decodeList(&$data)
{
$list = [];
while ('e' !== ($char = self::char($data))) {
if (false === $char) {
return self::setError(new Exception('Unterminated list'));
}
$list[] = self::decodeData($data);
}
$data = substr($data, 1);
return $list;
}
/** Decode torrent string.
*
* @param mixed $data to decode
*
* @return string decoded string
*/
private static function decodeString(&$data): string
{
if ('0' === self::char($data) && ':' !== substr($data, 1, 1)) {
self::setError(new Exception('Invalid string length, leading zero'));
}
if (!$colon = @strpos($data, ':')) {
return self::setError(new Exception('Invalid string length, colon not found'));
}
$length = (int) substr($data, 0, $colon);
if ($length + $colon + 1 > strlen($data)) {
return self::setError(new Exception('Invalid string, input too short for string length'));
}
$string = substr($data, $colon + 1, $length);
$data = substr($data, $colon + $length + 1);
return $string;
}
/** Decode torrent integer.
*
* @param mixed $data to decode
*
* @return int decoded integer
*/
private static function decodeInteger(&$data): int
{
$start = 0;
$end = strpos($data, 'e');
if (0 === $end) {
self::setError(new Exception('Empty integer'));
}
if ('-' === self::char($data)) {
++$start;
}
if ($end > $start + 1 && '0' === substr($data, $start, 1)) {
self::setError(new Exception('Leading zero in integer'));
}
if (!ctype_digit(substr($data, $start, $start ? $end - 1 : $end))) {
self::setError(new Exception('Non-digit characters in integer'));
}
$integer = substr($data, 0, $end);
$data = substr($data, $end + 1);
return (int) $integer;
}
/** Build pieces depending on piece length from a file handler.
*
* @param mixed $handle file handle
* @param mixed $piece_length
* @param mixed $last piece
*
* @return string pieces
*/
private function pieces($handle, $piece_length, $last = true)
{
static $piece, $length;
if (empty($length)) {
$length = $piece_length;
}
$pieces = null;
while (!feof($handle)) {
if (($length = strlen($piece .= fread($handle, $length))) === $piece_length) {
$pieces .= self::pack($piece);
} elseif (($length = $piece_length - $length) < 0) {
return self::setError(new Exception('Invalid piece length!'));
}
}
fclose($handle);
return $pieces . ($last && $piece ? self::pack($piece) : null);
}
/** Build torrent info from single file.
*
* @param mixed $file path
* @param mixed $piece_length
*
* @return array|string torrent info
*/
private function file($file, $piece_length)
{
if (!$handle = self::fopen($file, $size = self::filesize($file))) {
return self::setError(new Exception('Failed to open file: "' . $file . '"'));
}
if (self::is_url($file)) {
$this->url_list($file);
}
$path = self::pathExplode($file);
return [
'length' => $size,
'name' => end($path),
'piece length' => $piece_length,
'pieces' => $this->pieces($handle, $piece_length),
];
}
/** Build torrent info from files.
*
* @param mixed $files
* @param mixed $piece_length
*
* @return array torrent info
*/
private function files($files, $piece_length): array
{
sort($files);
usort($files, static function ($a, $b) {
return strrpos($a, DIRECTORY_SEPARATOR) - strrpos($b, DIRECTORY_SEPARATOR);
});
$first = current($files);
if (!self::is_url($first)) {
$files = array_map('realpath', $files);
} else {
$this->url_list(dirname($first) . DIRECTORY_SEPARATOR);
}
$files_path = array_map('self::pathExplode', $files);
$root = array_intersect_assoc(...$files_path);
$pieces = null;
$info_files = [];
$count = count($files) - 1;
foreach ($files as $i => $file) {
if (!$handle = self::fopen($file, $filesize = self::filesize($file))) {
self::setError(new Exception('Failed to open file: "' . $file . '" discarded'));
continue;
}
$pieces .= $this->pieces($handle, $piece_length, $count === $i);
$info_files[] = [
'length' => $filesize,
'path' => array_diff_assoc($files_path[$i], $root),
];
}
return [
'files' => $info_files,
'name' => end($root),
'piece length' => $piece_length,
'pieces' => $pieces,
];
}
/** Build torrent info from folder content.
*
* @param mixed $dir path
* @param mixed $piece_length
* @param mixed $include_hidden
*
* @return array torrent info
*/
private function folder($dir, $piece_length, $include_hidden): array
{
return $this->files(self::scandir($dir, $include_hidden), $piece_length);
}
/** Helper to return the first char of encoded data.
*
* @param mixed $data encoded data
*
* @return bool|string first char of encoded data or false if empty data
*/
private static function char($data)
{
return empty($data) ?
false :
substr($data, 0, 1);
}
}
if (!is_array($annlist)) {
$annlist = array(array($announce));
}
foreach ($annlist as $ann) {
foreach ($ann as $val) {
if (strtolower(substr($val, 0, 4)) != "udp:") {
DB::run("INSERT INTO `announce` (`torrent`, `url`) VALUES (?, ?)", [$id, $val]);
}
}
}
$message = sprintf(Lang::T("TORRENT_UPLOAD_EXTERNAL"), $name, $id);
// scrape external
$torrent = new Torrent "uploads/$id.torrent");
try {
$scraped = $torrent->scrape();
} catch (Exception $e) {
$scraped = $torrent->errors();
exit();
}
$myarray = array_shift($scraped);
$seeders = $leechers = $completed = 0;
if ($myarray['seeders'] > 0) {
$seeders = $myarray['seeders'];
}
if ($myarray['leechers'] > 0) {
$leechers = $myarray['leechers'];
}
if ($myarray['completed'] > 0) {
$completed = $myarray['completed'];
}
if ($seeders !== null) {
// Update the Torrent
SQL_Query_exec("
UPDATE torrents
SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible = 'yes'
WHERE id = $id");
}
if ($external == 'yes' && $site_config['UPLOADSCRAPE']) { if ($external == 'yes' && $site_config['UPLOADSCRAPE']) {
$torrent = new Torrent( "uploads/$id.torrent");
try {
$scraped = $torrent->scrape();
} catch (Exception $e) {
$scraped = $torrent->errors();
exit();
}
$myarray = array_shift($scraped);
$seeders = $leechers = $completed = 0;
if ($myarray['seeders'] > 0) {
$seeders = $myarray['seeders'];
}
if ($myarray['leechers'] > 0) {
$leechers = $myarray['leechers'];
}
if ($myarray['completed'] > 0) {
$completed = $myarray['completed'];
}
if ($seeders !== null) {
// Update the Torrent
SQL_Query_exec("
UPDATE torrents
SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible = 'yes'
WHERE id = $id");
}
}
//END SCRAPE
$seeders1 = $leechers1 = $downloaded1 = null;
$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
while ($trow = mysqli_fetch_assoc($tres)) {
$ann = $trow["url"];
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = preg_replace("/^announce/", "scrape", $path);
$tracker = implode("/", $tracker)."/".$path;
if ($oldpath == $path) {
continue; // Scrape not supported, ignored
}
// TPB's tracker is dead. Use openbittorrent instead
if (preg_match("/thepiratebay.org/i", $tracker) || preg_match("/prq.to/", $tracker)) {
$tracker = "http://tracker.openbittorrent.com/scrape";
}
$stats = torrent_scrape_url($tracker, $row["info_hash"]);
if ($stats['seeds'] != -1) {
$seeders1 += $stats['seeds'];
$leechers1 += $stats['peers'];
$downloaded1 += $stats['downloaded'];
SQL_Query_exec("UPDATE `announce` SET `online` = 'yes', `seeders` = $stats[seeds], `leechers` = $stats[peers], `times_completed` = $stats[downloaded] WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
} else {
SQL_Query_exec("UPDATE `announce` SET `online` = 'no' WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
}
}
$resu = SQL_Query_exec("SELECT id, info_hash FROM torrents WHERE external = 'yes' AND id = $id");
while ($rowu = mysqli_fetch_assoc($resu)) {
$torrent = new Torrent("uploads/$rowu[id].torrent");
try {
$scraped = $torrent->scrape();
} catch (Exception $e) {
$scraped = $torrent->errors();
exit();
}
$myarray = array_shift($scraped);
$seeders = $leechers = $completed = 0;
if ($myarray['seeders'] > 0) {
$seeders = $myarray['seeders'];
}
if ($myarray['leechers'] > 0) {
$leechers = $myarray['leechers'];
}
if ($myarray['completed'] > 0) {
$completed = $myarray['completed'];
}
if ($seeders !== null) {
// Update the Torrent
SQL_Query_exec("
UPDATE torrents
SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible = 'yes'
WHERE id = $id");
} else {
// Its Dead :(
SQL_Query_exec("UPDATE torrents SET last_action = get_date_time( WHERE id=$rowu['id']");
}
<?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;
}
}
<?php
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";
//Connection request
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp, $packet);
//Connection response
$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);
//Scrape request
$hashes = '';
foreach ($infohash as $hash) {
$hashes .= pack('H*', $hash);
}
$packet = $current_connid . pack("N", 2) . pack("N", $transaction_id) . $hashes;
fwrite($fp, $packet);
//Scrape response
$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);
// Todo check for error string if response = 3
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);
}
}
<?php
/*
Torrent HTTP Scraper
v1.0
2010 by Johannes Zinnau
johannes@johnimedia.de
Licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License
http://creativecommons.org/licenses/by-sa/3.0/
It would be very nice if you send me your changes on this class, so that i can include them if they are improve it.
Thanks!
Usage:
```
try{
$timeout = 2;
//Read only 4MiB of the scrape response
$maxread = 1024 * 4;
$scraper = new httptscraper($timeout,$maxread);
$ret = $scraper->scrape('http://tracker.tld:port/announce',array('0000000000000000000000000000000000000000'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
```
*/
/**
* Class HttpScraper
* @package Scrapers\Trackers
*/
class Httpscraper extends Tscraper
{
/**
* @var int
*/
protected $maxreadsize;
/**
* HttpScraper constructor.
* @param int $timeout
* @param int $maxreadsize
*/
public function __construct($timeout = 2, $maxreadsize = 4096)
{
$this->maxreadsize = $maxreadsize;
parent::__construct($timeout);
}
/* $url: Tracker url like: http://tracker.tld:port/announce or http://tracker.tld:port/scrape
$infohash: Infohash string or array. 40 char long infohash.
*/
/**
* @param string $url
* @param string $info_hash
* @return array
* @throws Exception\ScraperException
*/
public function scrape($url, $info_hash)
{
if (!is_array($info_hash)) {
$info_hash = array($info_hash);
}
foreach ($info_hash as $hash) {
if (!preg_match('#^[a-f0-9]{40}$#i', $hash)) {
throw new ScraperException('Invalid infohash: ' . $hash . '.');
}
}
$url = trim($url);
if (preg_match('%(http://.*?/)announce([^/]*)$%i', $url, $m)) {
$url = $m[1] . 'scrape' . $m[2];
} elseif (preg_match('%(http://.*?/)scrape([^/]*)$%i', $url, $m)) {
} else {
throw new ScraperException('Invalid tracker url: ' . $url);
}
$sep = preg_match('/\?.{1,}?/i', $url) ? '&' : '?';
$request_url = $url;
foreach ($info_hash as $hash) {
$request_url .= $sep . 'info_hash=' . rawurlencode(pack('H*', $hash));
$sep = '&';
}
ini_set('default_socket_timeout', $this->timeout);
$rh = @fopen($request_url, 'r');
if (!$rh) {
throw new ScraperException('Could not open HTTP connection.', 0, true);
}
stream_set_timeout($rh, $this->timeout);
$return = '';
$pos = 0;
while (!feof($rh) && $pos < $this->maxreadsize) {
$return .= fread($rh, 1024);
}
fclose($rh);
if (!substr($return, 0, 1) == 'd') {
throw new ScraperException('Invalid scrape response.');
}
$arr_scrape_data = Bencode::decode($return);
$torrents = array();
foreach ($info_hash as $hash) {
$ehash = pack('H*', $hash);
if (isset($arr_scrape_data['files'][$ehash])) {
$torrents[$hash] = array(
'infohash' => $hash,
'seeders' => (int) $arr_scrape_data['files'][$ehash]['complete'],
'completed' => (int) $arr_scrape_data['files'][$ehash]['downloaded'],
'leechers' => (int) $arr_scrape_data['files'][$ehash]['incomplete'],
);
} else {
$torrents[$hash] = false;
}
}
return $torrents;
}
}
//EXTERNAL SCRAPE
if ($external == 'yes' && UPLOADSCRAPE) {
$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;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $id]);
} }
//END SCRAPE
if (!is_array($annlist)) {
$annlist = array(array($announce));
}
foreach ($annlist as $ann) {
foreach ($ann as $val) {
if (strtolower(substr($val, 0, 4)) != "udp:") {
SQL_Query_exec("INSERT INTO `announce` (`torrent`, `url`) VALUES($id, ".sqlesc($val).")");
}
}
}
$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;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $id]);
}
while ($trow = mysqli_fetch_assoc($tres)) {
$ann = $trow["url"];
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = preg_replace("/^announce/", "scrape", $path);
$tracker = implode("/", $tracker)."/".$path;
if ($oldpath == $path) {
continue; // Scrape not supported, ignored
}
// TPB's tracker is dead. Use openbittorrent instead
if (preg_match("/thepiratebay.org/i", $tracker) || preg_match("/prq.to/", $tracker)) {
$tracker = "http://tracker.openbittorrent.com/scrape";
}
$stats = torrent_scrape_url($tracker, $row["info_hash"]);
if ($stats['seeds'] != -1) {
$seeders1 += $stats['seeds'];
$leechers1 += $stats['peers'];
$downloaded1 += $stats['downloaded'];
SQL_Query_exec("UPDATE `announce` SET `online` = 'yes', `seeders` = $stats[seeds], `leechers` = $stats[peers], `times_completed` = $stats[downloaded] WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
} else {
SQL_Query_exec("UPDATE `announce` SET `online` = 'no' WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
}
}
while ($trow = mysqli_fetch_assoc($tres)) {
$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;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $tres["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 {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $tres["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();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $tres['id']]);
} else {
DB::run("
UPDATE torrents
SET last_action = ?
WHERE id=?", [TimeDate::get_date_time(), $tres['id']]);
}
$s = preg_replace("/\[youtube\]([^\s'\"<>]+?)\[\/youtube\]/i", 'handleyoutube("$1")', $s);
$s = preg_replace("/\[youtube\]([^\s'\"<>]+?)\[\/youtube\]/Usi", 'handleyoutube("$1")', $s);
Propaganda:Dear M-Jay,Noticed you worked on the edit function of a forum topic.Please also look at the quote option, both here and also in latest code does not appear to work for me.Also, when I tried to delete the newly created topic, I was not able to. "1 is the last post in topic" was the response - and then refreshed without deleting the actual topic.
textbbcode();
print("<textarea name="descr" rows="10" cols="50"></textarea>");
print("<textarea name="descr" rows="20" cols="50">".htmlspecialchars($row["descr"])."</textarea>");
/**
* View Forum.
*/
public function viewforum()
{
$this->validForumUser();
$forumid = Input::get("forumid");
if (!$this->valid->validId($forumid)) {
Session::flash('info', Lang::T("FORUMS_DENIED"), URLROOT . "/forums");
}
// Get forum name
$res = DB::run("SELECT name, minclassread, guest_read FROM forum_forums WHERE id=?", [$forumid]);
$arr = $res->fetch(PDO::FETCH_ASSOC);
$forumname = $arr["name"];
if (!$forumname || $_SESSION['class'] < $arr["minclassread"] && $arr["guest_read"] == "no") {
Session::flash('info', Lang::T("FORUMS_NOT_PERMIT"), URLROOT . "/forums");
}
// Pagination
$count = get_row_count("forum_topics", "WHERE forumid=$forumid");
list($pagertop, $pagerbottom, $limit) = pager(25, $count, URLROOT . "/forums/viewforum&forumid=$forumid&");
// Get topics data and display category
$topicsres = DB::run("SELECT * FROM forum_topics WHERE forumid=$forumid ORDER BY sticky, lastpost DESC $limit")->fetchAll();
$data = [
'title' => 'Forums',
'topicsres' => $topicsres,
'forumname' => $forumname,
'forumid' => $forumid,
'pagerbottom' => $pagerbottom,
];
$this->view('forum/viewforum', $data, 'user');
}
array(1) { [0]=> array(9) {
["id"]=> int(2)
["userid"]=> int(1)
["subject"]=> string(11) "subject name"
["locked"]=> string(2) "no"
["forumid"]=> int(3)
["lastpost"]=> int(8)
["moved"]=> string(2) "no"
["sticky"]=> string(2) "no"
["views"]=> int(65) } }
<?php
forumheader($data['forumname']);
if ($_SESSION['loggedin'] == true) {
?>
<table class='table table-striped'><tr><td>
<div align='right'><a href='<?php echo URLROOT; ?>/forums/newtopic&forumid=<?php echo $data['forumid']; ?>'>
<button type='submit' class='btn btn-sm btn-warning'>New Post</button></a></div>
</td></tr></table>
<?php
}
if ($data['topicsres'] > 0) {
?>
<div class="row">
<div class="col-lg-12">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row card-header">
<div class="col-md-1">
Read
</div>
<div class="col-md-4">
Topic
</div>
<div class="col-md-1 d-none d-sm-block">
Replies
</div>
<div class="col-md-1 d-none d-sm-block">
Views
</div>
<div class="col-md-1 d-none d-sm-block">
Author
</div>
<div class="col-md-2 d-none d-sm-block">
Last Post
</div>
<?php
if ($_SESSION["edit_forum"] == "yes" || $_SESSION["delete_forum"] == "yes") {
?>
<div class="col-md-2 d-none d-sm-block">
Moderate
</div>
<?php
}
print("</div>");
foreach ($data['topicsres'] as $topicarr) {
//////// ALL THIS ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
$topicid = $topicarr["id"];
$topic_userid = $topicarr["userid"];
$locked = $topicarr["locked"] == "yes";
$moved = $topicarr["moved"] == "yes";
$sticky = $topicarr["sticky"] == "yes";
//---- Get reply count
$res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=$topicid");
$arr = $res->fetch(PDO::FETCH_LAZY);
$posts = $arr[0];
$replies = max(0, $posts - 1);
//---- Get userID and date of last post
$res = DB::run("SELECT * FROM forum_posts WHERE topicid=$topicid ORDER BY id DESC LIMIT 1");
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lppostid = $arr["id"];
$lpuserid = (int) $arr["userid"];
$lpadded = TimeDate::utc_to_tz($arr["added"]);
//------ Get name of last poster
if ($lpuserid > 0) {
$res = DB::run("SELECT * FROM users WHERE id=$lpuserid");
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lpusername = "<a href='" . URLROOT . "/profile?id=$lpuserid'>" . Users::coloredname($arr['username']) . "</a>";
} else {
$lpusername = "Deluser";
}
} else {
$lpusername = "Deluser";
}
//------ Get author
if ($topic_userid > 0) {
$res = DB::run("SELECT username FROM users WHERE id=$topic_userid");
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lpauthor = "<a href='" . URLROOT . "/profile?id=$topic_userid'>" . Users::coloredname($arr['username']) . "</a>";
} else {
$lpauthor = "Deluser";
}
} else {
$lpauthor = "Deluser";
}
// Topic Views
$viewsq = DB::run("SELECT views FROM forum_topics WHERE id=$topicid");
$viewsa = $viewsq->fetch(PDO::FETCH_LAZY);
$views = $viewsa[0];
// End
//---- Print row
if ($_SESSION) {
$r = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$_SESSION[id] AND topicid=$topicid");
$a = $r->fetch(PDO::FETCH_LAZY);
}
$new = !$a || $lppostid > $a[0];
$topicpic = ($locked ? ($new ? "folder_locked_new" : "folder_locked") : ($new ? "folder_new" : "folder"));
$subject = ($sticky ? "<b>" . Lang::T("FORUMS_STICKY") . ": </b>" : "") . "<a href='" . URLROOT . "/topic?topicid=$topicid'><b>" .
encodehtml(stripslashes($topicarr["subject"])) . "</b></a>$topicpages";
?>
<div class="row border border-primary">
<div class="col-md-1 d-none d-sm-block">
<img src='<?php echo URLROOT; ?>/assets/images/forum/<?php echo $topicpic ?>.png' alt='' />
</div>
<div class="col-md-4">
<?php echo $subject; ?>
</div>
<div class="col-md-1 d-none d-sm-block">
<?php echo $replies; ?>
</div>
<div class="col-md-1 d-none d-sm-block">
<?php echo $views; ?>
</div>
<div class="col-md-1 d-none d-sm-block">
<?php echo $lpauthor; ?>
</div>
<div class="col-md-2">
<span class='small'>by <?php echo $lpusername; ?><br /><span style='white-space: nowrap'><?php echo $lpadded; ?></span></span>
</div>
<?php
if ($_SESSION["edit_forum"] == "yes" || $_SESSION["delete_forum"] == "yes") {
print("<div class='col-md-2 d-none d-sm-block'>");
if ($locked) {
print("<a href='" . URLROOT . "/forums/unlocktopic&forumid=$data[forumid]&topicid=$topicid&page=$page' title='Unlock'><img src='" . URLROOT . "/assets/images/forum/topic_unlock.png' alt='UnLock Topic' /></a>\n");
} else {
print("<a href='" . URLROOT . "/forums/locktopic&forumid=$data[forumid]&topicid=$topicid&page=$page' title='Lock'><img src='" . URLROOT . "/assets/images/forum/topic_lock.png' alt='Lock Topic' /></a>\n");
}
print("<a href='" . URLROOT . "/forums/deletetopic&topicid=$topicid&sure=0' title='Delete'><img src='" . URLROOT . "/assets/images/forum/topic_delete.png' alt='Delete Topic' /></a>\n");
if ($sticky) {
print("<a href='" . URLROOT . "/forums/unsetsticky&forumid=$data[forumid]&topicid=$topicid&page=$page' title='UnStick'><img src='" . URLROOT . "/assets/images/forum/older_sticky_new.png' alt='Unstick Topic' /></a>\n");
} else {
print("<a href='" . URLROOT . "/forums/setsticky&forumid=$data[forumid]&topicid=$topicid&page=$page' title='Stick'><img src='" . URLROOT . "/assets/images/forum/folder_sticky.png' alt='Stick Topic' /></a>\n");
}
print("</div>");
}
print("</div>");
}
print("</div></div></div>");
print ($data['pagerbottom']);
} else {
print("<p align='center'>No topics found</p>\n");
}
$data = [
'title' => Lang::T("LOGIN")
];
$this->view('user/login', $data, 'user');$bigdata[
'lppostid' => $arr["id"],
'topic_userid' = $topicarr["userid"],
etc.............
] foreach ($data['topicsres'] as $topicarr) {
$topicid = $topicarr["id"];
$topic_userid = $topicarr["userid"];
$locked = $topicarr["locked"] == "yes";
$moved = $topicarr["moved"] == "yes";
$sticky = $topicarr["sticky"] == "yes";
//---- Get reply count
$res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=$topicid");
$arr = $res->fetch(PDO::FETCH_LAZY);
$posts = $arr[0];
$replies = max(0, $posts - 1);
//---- Get userID and date of last post
$res = DB::run("SELECT * FROM forum_posts WHERE topicid=$topicid ORDER BY id DESC LIMIT 1");
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lppostid = $arr["id"];
$lpuserid = (int) $arr["userid"];
$lpadded = TimeDate::utc_to_tz($arr["added"]);
//------ Get name of last poster
if ($lpuserid > 0) {
$res = DB::run("SELECT * FROM users WHERE id=$lpuserid");
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lpusername = "<a href='" . URLROOT . "/profile?id=$lpuserid'>" . Users::coloredname($arr['username']) . "</a>";
} else {
$lpusername = "Deluser";
}
} else {
$lpusername = "Deluser";
}
//------ Get author
if ($topic_userid > 0) {
$res = DB::run("SELECT username FROM users WHERE id=$topic_userid");
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$lpauthor = "<a href='" . URLROOT . "/profile?id=$topic_userid'>" . Users::coloredname($arr['username']) . "</a>";
} else {
$lpauthor = "Deluser";
}
} else {
$lpauthor = "Deluser";
}
// Topic Views
$viewsq = DB::run("SELECT views FROM forum_topics WHERE id=$topicid");
$viewsa = $viewsq->fetch(PDO::FETCH_LAZY);
$views = $viewsa[0];
// End
//---- Print row
if ($_SESSION) {
$r = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$_SESSION[id] AND topicid=$topicid");
$a = $r->fetch(PDO::FETCH_LAZY);
}
$new = !$a || $lppostid > $a[0];
$topicpic = ($locked ? ($new ? "folder_locked_new" : "folder_locked") : ($new ? "folder_new" : "folder"));
$subject = ($sticky ? "<b>" . Lang::T("FORUMS_STICKY") . ": </b>" : "") . "<a href='" . URLROOT . "/topic?topicid=$topicid'><b>" .
encodehtml(stripslashes($topicarr["subject"])) . "</b></a>$topicpages";
?> Quote:- How to create custom "card-header" and "card-body" for your login/recover/signup pages?
$this->view('user/login', $data, 'user');$this->view('user/login', $data, 'admin');$this->view('user/login', $data); <div class="row justify-content-center">
<form method="post" action="<?php echo URLROOT; ?>/login/submit" autocomplete="off">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>" />
<div class="form-group">
<label for="username"><?php echo Lang::T("USERNAME"); ?></label>
<input id="username" type="text" class="form-control" name="username" minlength="3" maxlength="25" required autofocus>
</div>
<div class="form-group">
<label for="password"><?php echo Lang::T("PASSWORD"); ?></label>
<input id="password" type="password" class="form-control" name="password" minlength="6" maxlength="16" required data-eye>
</div>
<div class="form-group">
<?php (new Captcha)->html(); ?>
<button type="submit" class="btn btn-warning btn-block"><?php echo Lang::T("LOGIN"); ?></button>
<center><i><?php echo Lang::T("COOKIES"); ?></i></center>
</div>
<div class="margin-top20 text-center">
<a href="<?php echo URLROOT; ?>/signup"><?php echo Lang::T("SIGNUP"); ?></a> |
<a href="<?php echo URLROOT; ?>/recover"><?php echo Lang::T("RECOVER_ACCOUNT"); ?></a>
</div>
</form>
</div>
Style::header($data['title']);
Style::begin($data['title']);
<div class="row justify-content-center">
<form method="post" action="<?php echo URLROOT; ?>/login/submit" autocomplete="off">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>" />
<div class="form-group">
<label for="username"><?php echo Lang::T("USERNAME"); ?></label>
<input id="username" type="text" class="form-control" name="username" minlength="3" maxlength="25" required autofocus>
</div>
<div class="form-group">
<label for="password"><?php echo Lang::T("PASSWORD"); ?></label>
<input id="password" type="password" class="form-control" name="password" minlength="6" maxlength="16" required data-eye>
</div>
<div class="form-group">
<?php (new Captcha)->html(); ?>
<button type="submit" class="btn btn-warning btn-block"><?php echo Lang::T("LOGIN"); ?></button>
<center><i><?php echo Lang::T("COOKIES"); ?></i></center>
</div>
<div class="margin-top20 text-center">
<a href="<?php echo URLROOT; ?>/signup"><?php echo Lang::T("SIGNUP"); ?></a> |
<a href="<?php echo URLROOT; ?>/recover"><?php echo Lang::T("RECOVER_ACCOUNT"); ?></a>
</div>
</form>
</div>
Style::end();
Style::footer();
<?php
class U2
{
public static function begin($caption = "-", $align = "justify")
{
$blockId = 'f-' . sha1($caption);
?>
<div class="card">
<div class="card-header">
<?php echo $caption ?>
<a data-toggle="collapse" href="#" class="showHide" id="<?php echo $blockId; ?>" style="float: right;"></a>
</div>
<div class="card-body slidingDiv<?php echo $blockId; ?>">
<?php
}
public static function end()
{
?>
</div>
</div>
<?php
}
Style::header($data['title']);
U2::begin($data['title']);
// login template code
U2::end();
Style::footer();
mysql_query("UPDATE `torrents` SET `descr` = '".mysql_real_escape_string ($filelist). "' WHERE `id` = $id";);
$filesindesc = implode(", ", $filelist);
mysql_query("UPDATE `torrents` SET `descr` = '".mysql_real_escape_string ($filesindesc). "' WHERE `id` = $id";);
$querypm = "FROM ".$from_is.(($where_is == "")?" ":" WHERE $where_is ");
$select_is = "u.id, u.username, u.email, u.status, u.added, u.last_access, u.ip,
u.class, u.uploaded, u.downloaded, u.donated, u.modcomment, u.enabled, u.warned, u.invited_by";
$querypm = "FROM ".$from_is.(($where_is == "")?" ":" WHERE u.class < $CURUSER[class] AND $where_is ");
$select_is = "u.id, u.username, u.email, u.status, u.added, u.last_access, u.ip,
u.class, u.uploaded, u.downloaded, u.donated, u.modcomment, u.enabled, u.warned, u.invited_by";
datetime NOT NULL DEFAULT '0000-00-00 00:00:00'datetime DEFAULT NULL'0000-00-00 00:00:00'NULLfunction classlist()
{
$ret = array();
$res = $this->pdo->run("SELECT * FROM groups ORDER BY group_id ASC");
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
$ret[] = $row;
}
return $ret;
}function classlist()
{
$ret = array();
$res = $this->pdo->run("SELECT * FROM `groups` ORDER BY group_id ASC");
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
$ret[] = $row;
}
return $ret;
}
class Scrape extends Controller
{
public function __construct()
{
Auth::user();
$this->torrentModel = $this->model('Torrent');
$this->valid = new Validation();
$this->logsModel = $this->model('Logs');
}
public function index()
{
$id = $_GET['id'];
$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 = TORRENTDIR;
//$TorrentInfo = array();
$Tor = new Parse();
//$TorrentInfo = Parse::torr("$torrent_dir/$rowu[id].torrent");
$TorrentInfo = $Tor->torr("$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;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper(); //$timeout
$stats = $udp->scrape($tracker, $rowu["info_hash"]);
foreach ($stats as $idu => $scrape) {
//print_r($scrape); echo '<br>above upd'; exit();
$seeders += intval(strip_tags($scrape['seeders']));
$leechers += intval(strip_tags($scrape['leechers']));
$downloaded += intval(strip_tags($scrape['completed']));
}
DB::run("
UPDATE `announce`
SET `online` = ?, `seeders` = ?, `leechers` = ?, `times_completed` = ?
WHERE `url` = ?
AND `torrent` = ?",
['yes', $stats['seeds'], $stats['peers'], $stats['downloaded'], $ann, $rowu['id']]);
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $rowu['id']]);
Redirect::autolink(URLROOT . "/torrents/read?id=$id", Lang::T("The Tracker is Udp take note"));
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $rowu["info_hash"]);
foreach ($stats as $idu => $scrape) {
// print_r($scrape); echo '<br>above http'; exit();
$seeders += intval(strip_tags($scrape['seeders']));
$leechers += intval(strip_tags($scrape['leechers']));
$downloaded += intval(strip_tags($scrape['completed']));
}
DB::run("
UPDATE `announce`
SET `online` = ?, `seeders` = ?, `leechers` = ?, `times_completed` = ?
WHERE `url` = ?
AND `torrent` = ?",
['yes', $stats['seeds'], $stats['peers'], $stats['downloaded'], $ann, $rowu['id']]);
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $rowu['id']]);
Redirect::autolink(URLROOT . "/torrents/read?id=$id", Lang::T("The Tracker is http take note"));
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
}
}
}
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/// die($seeders);$this->view('user/login', $data, 'user');$this->view('user/login', $data, 'admin');$this->view('user/login', $data); Integrity constraint violation: 1062 Duplicate entry '01c489e0d72604e2432f' for key 'info_hash'