public function __construct ( $data = null, $meta = array(), $piece_length = 256 ) {
if ( is_null( $data ) )
return false;
if ( $piece_length < 32 || $piece_length > 4096 )
return self::set_error( new Exception( 'Invalid piece lenth, must be between 32 and 4096' ) );
if ( is_string( $meta ) )
$meta = array( 'announce' => $meta );
if ( $this->build( $data, $piece_length * 1024 ) )
$this->touch();
else
$meta = array_merge( $meta, $this->decode( $data ) );
foreach( $meta as $key => $value )
$this->{$key} = $value;
}
/** Convert the current Torrent instance in torrent format
* @return string encoded torrent data
*/
public function __toString() {
return $this->encode( $this );
}
/** Return last error message
* @return string|boolean last error message or false if none
*/
public function error() {
return empty( self::$errors ) ?
false :
self::$errors[0]->getMessage();
}
/** Return Errors
* @return array|boolean 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|false|string|array announce url / list, reset all if false (optional, if omitted it's a getter)
* @return string|array|null announce url / list or null if not set
*/
public function announce ( $announce = null ) {
if ( is_null( $announce ) )
return ! isset( $this->{'announce-list'} ) ?
isset( $this->announce ) ? $this->announce : null :
$this->{'announce-list'};
$this->touch();
if ( is_string( $announce ) && isset( $this->announce ) )
return $this->{'announce-list'} = self::announce_list( isset( $this->{'announce-list'} ) ? $this->{'announce-list'} : $this->announce, $announce );
unset( $this->{'announce-list'} );
if ( is_array( $announce ) || is_object( $announce ) )
if ( ( $this->announce = self::first_announce( $announce ) ) && count( $announce ) > 1 )
return $this->{'announce-list'} = self::announce_list( $announce );
else
return $this->announce;
if ( ! isset( $this->announce ) && $announce )
return $this->announce = (string) $announce;
unset( $this->announce );
}
/** Getter and setter of torrent comment
* @param null|string comment (optional, if omitted it's a getter)
* @return string|null comment or null if not set
*/
public function comment ( $comment = null ) {
return is_null( $comment ) ?
isset( $this->comment ) ? $this->comment : null :
$this->touch( $this->comment = (string) $comment );
}
/** Getter and setter of torrent name
* @param null|string name (optional, if omitted it's a getter)
* @return string|null name or null if not set
*/
public function name ( $name = null ) {
return is_null( $name ) ?
isset( $this->info['name'] ) ? $this->info['name'] : null :
$this->touch( $this->info['name'] = (string) $name );
}
/** Getter and setter of private flag
* @param null|boolean is private or not (optional, if omitted it's a getter)
* @return boolean private flag
*/
public function is_private ( $private = null ) {
return is_null( $private ) ?
! empty( $this->info['private'] ) :
$this->touch( $this->info['private'] = $private ? 1 : 0 );
}
/** Getter and setter of webseed(s) url list ( GetRight implementation )
* @param null|string|array webseed or webseeds mirror list (optional, if omitted it's a getter)
* @return string|array|null webseed(s) or null if not set
*/
public function url_list ( $urls = null ) {
return is_null( $urls ) ?
isset( $this->{'url-list'} ) ? $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|string|array httpseed or httpseeds mirror list (optional, if omitted it's a getter)
* @return array|null httpseed(s) or null if not set
*/
public function httpseeds ( $urls = null ) {
return is_null( $urls ) ?
isset( $this->httpseeds ) ? $this->httpseeds : null :
$this->touch( $this->httpseeds = (array) $urls );
}
/**** Analyze BitTorrent ****/
/** Get piece length
* @return integer piece length or null if not set
*/
public function piece_length () {
return isset( $this->info['piece length'] ) ?
$this->info['piece length'] :
null;
}
/** Compute hash info
* @return string hash info or null if info not set
*/
public function hash_info () {
return isset( $this->info ) ?
sha1( self::encode( $this->info ) ) :
null;
}
/** List torrent content
* @param integer|null 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 ) {
$files = array();
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;
}
/** Request torrent statistics from scrape page
* @param string announce or scrape page url (optional, to request an alternative tracker BUT mandatory for static call)
* @param string torrent hash info (optional: ONLY for static call)
* @return array tracker torrent statistics
*/
/* static */ public function scrape ( $announce = null, $hash_info = null ) {
if ( ! ini_get( 'allow_url_fopen' ) )
return self::set_error( new Exception( '"allow_url_fopen" must be enabled' ) );
$packed_hash = pack('H*', $hash_info ? $hash_info : $this->hash_info() );
$scrape = array();
foreach ( (array) ($announce ? $announce : $this->announce()) as $tier )
foreach ( (array) $tier as $tracker ) {
if ( ! $scrape_data = @file_get_contents( str_ireplace( array( 'udp://', '/announce' ), array( 'http://', '/scrape' ), $tracker ) . '?info_hash=' . urlencode( $packed_hash ) ) )
continue $scrape[$tracker] = self::set_error( new Exception( 'Tracker request failed' ), true );
$stats = self::decode_data( $scrape_data );
$scrape[$tracker] = isset( $stats['files'][$packed_hash] ) ?
$stats['files'][$packed_hash] :
self::set_error( new Exception( 'Invalid scrape data' ), true );
}
return $scrape;
}
/**** Save and Send ****/
/** Save torrent file to disk
* @param null|string name of the file (optional)
* @return boolean file has been saved or not
*/
public function save ( $filename = null ) {
return file_put_contents( is_null( $filename ) ? $this->info['name'] . '.torrent' : $filename, $this->encode( $this ) );
}
/** Set torrent creator and creation date
* @param any param
* @return any param
*/
protected function touch ( $void = null ) {
$this->{'created by'} = 'Torrent PHP Class - Adrien Gibrat';
$this->{'creation date'} = time();
return $void;
}
/** Add an error to errors stack
* @param Exception error to add
* @param boolean return error message or not (optional, default to false)
* @return boolean|string return false or error message if requested
*/
static protected function set_error ( $exception, $message = false ) {
return ( array_unshift( self::$errors, $exception ) && $message ) ? $exception->getMessage() : false;
}
/** Build announce list
* @param string|array announce url / list
* @param string|array announce url / list to add (optionnal)
* @return array announce list (array of arrays)
*/
static protected function announce_list( $announce, $merge = array() ) {
return array_map( create_function( '$a', 'return (array) $a;' ), array_merge( (array) $announce, (array) $merge ) );
}
/** Get the first announce url in a list
* @param array announce list (array of arrays if tiered trackers)
* @return string first announce url
*/
static protected function first_announce( $announce ) {
while ( is_array( $announce ) )
$announce = reset( $announce );
return $announce;
}
/** Helper to pack data hash
* @param string data
* @return string packed data hash
*/
static protected function pack ( & $data ) {
return pack('H*', sha1( $data ) ) . ( $data = '' );
}
/** Helper to test if an array is a list
* @param array array to test
* @return boolean is the array a list or not
*/
static protected function is_list ( $array ) {
foreach ( array_keys( $array ) as $key )
if ( ! is_int( $key ) )
return false;
return true;
}
/** Build torrent info from single file
* @param string file path
* @param integer piece length
* @return array torrent info
*/
private function file ( $file, $piece_length ) {
if ( ! $handle = self::fopen( $file, $size = self::filesize( $file ) ) )
return self::set_error( new Exception( 'Failed to open file: "' . $file . '"' ) );
$pieces = '';
while ( ! feof( $handle ) )
$pieces .= self::pack( fread( $handle, $piece_length ) );
fclose( $handle );
return array(
'length' => $size,
'name' => basename( $file ),
'piece length' => $piece_length,
'pieces' => $pieces
);
}
/** Build torrent info from folder content
* @param string folder path
* @param integer piece length
* @return array torrent info
*/
private function folder ( $dir, $piece_length ) {
return $this->files( self::scandir( $dir ), $piece_length );
}
/** Helper to return the first char of encoded data
* @param string encoded data
* @return string|boolean first char of encoded data or false if empty data
*/
static private function char ( $data ) {
return empty( $data ) ?
false :
substr( $data, 0, 1 );
}
/**** Public Helpers ****/
/** Helper to format size in bytes to human readable
* @param integer size in bytes
* @param integer precision after coma
* @return string formated size in appropriate unit
*/
static public function format ( $size, $precision = 2 ) {
$units = array ('bytes', 'Kb', 'Mb', 'Gb', 'Tb');
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 string file path
* @return double|boolean filesize or false if error
*/
static public function filesize ( $file ) {
if ( is_file( $file ) )
return (double) sprintf( '%u', @filesize( $file ) );
else if ( $content_length = preg_match( $pattern = '#^Content-Length:\s+(\d+)$#i', get_headers_curl( $file ) ) )
return (int) preg_replace( $pattern, '$1', reset( $content_length ) );
}
/** Helper to open file to read (even bigger than 2Gb, linux only)
* @param string file path
* @param integer|double file size (optional)
* @return ressource|boolean file handle or false if error
*/
static public function fopen ( $file, $size = null ) {
if ( ( is_null( $size ) ? self::filesize( $file ) : $size ) <= 2 * pow( 1024, 3 ) )
return fopen( $file, 'r' );
elseif ( PHP_OS != 'Linux' )
return self::set_error( new Exception( 'File size is greater than 2GB. This is only supported under Linux' ) );
elseif ( ! is_readable( $file ) )
return false;
else
return popen( 'cat ' . escapeshellarg( realpath( $file ) ), 'r' );
}
/** Helper to scan directories files and sub directories recursivly
* @param string directory path
* @return array directory content list
*/
static public function scandir ( $dir ) {
$paths = array();
foreach ( scandir( $dir ) as $item )
if ( $item != '.' && $item != '..' )
if ( is_dir( $path = realpath( $dir . DIRECTORY_SEPARATOR . $item ) ) )
$paths = array_merge( self::scandir( $path ), $paths );
else
$paths[] = $path;
return $paths;
}
/** Helper to check if url exists
* @param string url to check
* @return boolean does the url exist or not
*/
/** Helper to check if a file is a torrent
* @param string file location
* @return boolean is the file a torrent or not
*/
static public function is_torrent ( $file ) {
return substr(file_get_contents_curl($file), 0, 11) === 'd8:announce';
}
}
public function encode($data)
{
if (is_array($data))
{
$list = true;
foreach(array_keys($data) as $key)
{
if (!is_int($key))
{
$list = false;
break;
}
}