Location: PHPKode > scripts > Torrent Pieces Hash Verification > torrent-pieces-hash-verification/class.torrentfile.php
<?php
/**
 * Describes a torrent file
 * 
 * @author Charalampos Pournaris
 */
class TorrentFile {
	/**
	 * The filename's path on the disk
	 *
	 * @var string
	 */
	private $filepath = '';
	
	/**
	 * Size of the file (not used atm)
	 *
	 * @var integer
	 */
	private $filesize = 0;
	
	/**
	 * Torrent pieces array
	 *
	 * @var array
	 */
	private $pieces = array();
	
	/**
	 * Piece size used to create the torrent
	 *
	 * @var integer
	 */
	public static $piece_size = 0;
	
	/**
	 * An array with all the produced hashes
	 *
	 * @var array
	 */
	public static $hashes = array();
	
	/**
	 * Partial data from previous pieces (binary)
	 *
	 * @var string
	 */
	private $partial_data = '';
	
	/**
	 * The file resource
	 *
	 * @var resource
	 */
	private $file_pointer = null;
	
	/**
	 * Total bytes read for this torrent file
	 *
	 * @var integer
	 */
	private $readb_total = 0;
	
	/**
	 * TorrentFile constructor and initialization
	 *
	 * @param string $filepath
	 * @param integer $filesize
	 * @param array $pieces
	 */
	public function __construct($filepath, $filesize, &$pieces) {		
		$this->filepath = $filepath;
		$this->filesize = $filesize;
		$this->pieces = $pieces;
	}
	
	/**
	 * Open the file
	 *
	 * @return boolean
	 */
	public function open() {
		$this->file_pointer = @fopen($this->filepath, 'rb');
		
		if (!$this->file_pointer) {
			return false;
		}
		
		return true;
	}
	
	/**
	 * Close the file
	 *
	 */
	public function close() {
		if ($this->file_pointer)
			fclose($this->file_pointer);
	}
	
	/**
	 * Read all the associated pieces for this file
	 *
	 * @param string $partial_data
	 */
	public function read($partial_data='') {
		$data = '';
		$partial_data_length = 0;
		
		if (!empty($partial_data)) {
			$partial_data_length = strlen($partial_data);
		}
		
		foreach ($this->pieces as $piece) {			
			
			if ($piece->getPieceLength() == 0) continue;
			
			$data = fread($this->file_pointer, $piece->getPieceLength());
			
			$readb = strlen($data);
			
			$this->readb_total += $readb;
			
			if ($piece->isFullPiece() || ($piece->isPartialPiece() && ($piece->getRemaining() == 0)) ) {	
				self::$hashes[$piece->getPieceId()] = sha1($partial_data.$data);

				$partial_data = '';
			} elseif ($piece->isPartialPiece()) {
				$this->partial_data = $partial_data.$data;
			}			
		}		
	}
	
	/**
	 * Get the hashes array produced for this file
	 *
	 * @return array
	 */
	public function getHashes() {
		return $this->hashes;
	}
	
	/**
	 * Get file's partial (remaining) data from an incomplete piece
	 *
	 * @return string
	 */
	public function getPartialData() {
		return $this->partial_data;
	}		
}

?>
Return current item: Torrent Pieces Hash Verification