/** * Fetches all relevant information from the file and generates a * .torrent */ public function toEncoded() { $infoArray["name"] = $this->name; $infoArray["piece length"] = $this->pieceLength; $infoArray["length"] = filesize($this->filename); $this->ensureSHA1Loaded(); $infoArray["pieces"] = $this->concattedSHA1; $infoDictionary = new BElement(BDictionary::toEncoded($infoArray)); $this->infoHash = sha1($infoDictionary->toEncoded(), true); $metainfoArray = array("announce" => $this->trackerURL, "info" => $infoDictionary); $metainfoArray["url-list"] = new BElement(BList::toEncoded($this->webseeds)); $metainfoDictionary = BDictionary::toEncoded($metainfoArray); return $metainfoDictionary; }
/** * Returns the decoded array from $str * @throws an IllegalArgumentException in the case * that the string is malformed. */ public static function toList($str) { if (substr($str, 0, 1) != "l" || substr($str, -1, 1) != "e") { throw new IllegalArgumentException("BEncoded list does not start with l or end with e."); } $value = substr($str, 1, -1); // Scan through encoded list and decode everything $list = array(); $i = 0; $lastI = 0; while ($i < strlen($value)) { $curChar = substr($value, $i, 1); if ($curChar == "i") { // We just saw an Integer $endPos = strpos($value, "e", $i); // Search for the end of it if ($endPos === false) { throw new IllegalArgumentException("BEncoded list contains non-terminated integer"); } $list[] = BInteger::toInteger(substr($value, $i, $endPos - $i + 1)); $i = $endPos + 1; } elseif (is_numeric($curChar)) { // A number means we just saw a string starting $seperatorPos = strpos($value, ":", $i); // Search for the seperator if ($seperatorPos === false) { throw new IllegalArgumentException("BEncoded list contains malformed string with no length specified"); } $totalLength = substr($value, $i, $seperatorPos - $i); $list[] = BString::toString(substr($value, $i, $seperatorPos - $i + $totalLength + 1)); $i = $seperatorPos + $totalLength + 1; } elseif ($curChar == "d" || $curChar == "l") { // Found a dictionary or list // Scan for end of it $listLength = BList::getListLength(substr($value, $i)); if ($curChar == "d") { $list[] = BDictionary::toArray(substr($value, $i, $listLength)); } else { $list[] = BList::toList(substr($value, $i, $listLength)); } $i += $listLength; } if ($i == $lastI) { throw new IllegalArgumentException("BEncoded list contains malfomed or unrecognized content"); } $lastI = $i; } return $list; }
function trackerError($error) { echo BDictionary::toEncoded(array("failure_reason" => $error)); exit; }