Ejemplo n.º 1
2
 if (mysql_errno() == 1062) {
     show_error_msg(T_("UPLOAD_FAILED"), T_("UPLOAD_ALREADY_UPLOADED"), 1);
 }
 //Update the members uploaded torrent count
 /*if ($ret){
 		SQL_Query_exec("UPDATE users SET torrents = torrents + 1 WHERE id = $userid");*/
 if ($id == 0) {
     unlink("{$torrent_dir}/{$fname}");
     $message = T_("UPLOAD_NO_ID");
     show_error_msg(T_("UPLOAD_FAILED"), $message, 1);
 }
 rename("{$torrent_dir}/{$fname}", "{$torrent_dir}/{$id}.torrent");
 // Edit Torrent Comment
 require_once "backend/BDecode.php";
 require_once "backend/BEncode.php";
 $dict = BDecode(file_get_contents($site_config["torrent_dir"] . "/{$id}.torrent"));
 $dict['comment'] = "Torrent downloaded from " . $site_config['SITENAME'];
 file_put_contents($site_config["torrent_dir"] . "/{$id}.torrent", BEncode($dict));
 // End Edit Torrent Comment
 if (count($filelist)) {
     foreach ($filelist as $file) {
         $dir = '';
         $size = $file["length"];
         $count = count($file["path"]);
         for ($i = 0; $i < $count; $i++) {
             if ($i + 1 == $count) {
                 $fname = $dir . $file["path"][$i];
             } else {
                 $dir .= $file["path"][$i] . "/";
             }
         }
 $scrape_metadata = @file_get_contents($scrape_url);
 if ($scrape_metadata == false) {
     if ($extlogtype >= EXTLOG_VERBOSE) {
         error_log("FAILED.\r\n", 3, $extlogfile);
     }
 } else {
     if ($extlogtype >= EXTLOG_VERBOSE) {
         error_log("done\r\n", 3, $extlogfile);
     }
     if ($extlogtype >= EXTLOG_VERBOSE) {
         error_log("\t\t\tValidating /scrape data... ", 3, $extlogfile);
     }
     /*
      * Decode the scrape response
      */
     $decoded_scrape = BDecode($scrape_metadata);
     if (!$decoded_scrape) {
         if ($extlogtype >= EXTLOG_VERBOSE) {
             error_log("FAILED.\r\n", 3, $extlogfile);
         }
     } else {
         if ($extlogtype >= EXTLOG_VERBOSE) {
             error_log("done\r\n", 3, $extlogfile);
         }
         /*
          * Now the fun begins... walk through the decoded output and see if the info_hash is in
          * the output, for all of the torrents that belong to this tracker.
          */
         if ($extlogtype >= EXTLOG_VERBOSE) {
             error_log("\t\t\t\tLooking for " . $scrape_info["info_hash"] . "... ", 3, $extlogfile);
         }
Ejemplo n.º 3
0
function _wobi_addWebseedfiles($torrent_file_path, $relative_path, $httplocation, $hash)
{
    $prefix = WOBI_PREFIX;
    $fd = fopen($torrent_file_path, "rb") or die(errorMessage() . "File upload error 1</p>");
    $alltorrent = fread($fd, filesize($torrent_file_path));
    fclose($fd);
    $array = BDecode($alltorrent);
    // Add in Bittornado HTTP seeding spec
    //
    //add information into database
    $info = $array["info"] or die("Invalid torrent file.");
    $fsbase = $relative_path;
    // We need single file only!
    mysql_query("INSERT INTO " . $prefix . "webseedfiles (info_hash,filename,startpiece,endpiece,startpieceoffset,fileorder) values (\"{$hash}\", \"" . mysql_real_escape_string($fsbase) . "\", 0, " . (strlen($array["info"]["pieces"]) / 20 - 1) . ", 0, 0)");
    // Edit torrent file
    //
    $data_array = $array;
    $data_array["httpseeds"][0] = WOBI_URL . "/seed.php";
    //$data_array["url-list"][0] = $httplocation;
    $to_write = BEncode($data_array);
    //write torrent file
    $write_httpseed = fopen($torrent_file_path, "wb");
    fwrite($write_httpseed, $to_write);
    fclose($write_httpseed);
    //add in piecelength and number of pieces
    $query = "UPDATE " . $prefix . "summary SET piecelength=\"" . $info["piece length"] . "\", numpieces=\"" . strlen($array["info"]["pieces"]) / 20 . "\" WHERE info_hash=\"" . $hash . "\"";
    quickQuery($query);
}
Ejemplo n.º 4
0
 function insertTorrent($torrent, $info_hash, $filename, $user, $cat)
 {
     global $TABLE_PREFIX, $TORRENTSDIR, $DBDT;
     require_once dirname(__FILE__) . "/../../include/BDecode.php";
     require_once dirname(__FILE__) . "/../../include/BEncode.php";
     $fd = fopen($torrent, "rb") or die('Impossible d ouvrire le torrent');
     $alltorrent = fread($fd, filesize($torrent));
     $array = BDecode($alltorrent);
     // Announce
     $announce = str_replace(array("\r\n", "\r", "\n"), "", $array["announce"]);
     // Dipslay all tracker announce
     $announces = array();
     for ($i = 0; $i < count($array["announce-list"]); $i++) {
         $current = $array["announce-list"][$i];
         if (is_array($current)) {
             $announces[$current[0]] = array("seeds" => 0, "leeches" => 0, "downloaded" => 0);
         } else {
             $announces[$current] = array("seeds" => 0, "leeches" => 0, "downloaded" => 0);
         }
     }
     $announces[$announce] = array("seeds" => 0, "leeches" => 0, "downloaded" => 0);
     // description not writen by user, we get info directly from torrent.
     if (isset($array["comment"])) {
         $info = mysqli_real_escape_string($DBDT, htmlspecialchars($array["comment"]));
     } else {
         $info = "";
     }
     // Size
     if (isset($array["info"]) && $array["info"]) {
         $upfile = $array["info"];
     } else {
         $upfile = 0;
     }
     if (isset($upfile["length"])) {
         $size = (double) $upfile["length"];
     } else {
         if (isset($upfile["files"])) {
             // multifiles torrent
             $size = 0;
             foreach ($upfile["files"] as $file) {
                 $size += (double) $file["length"];
             }
         } else {
             $size = "0";
         }
     }
     // Query :p
     $now = date("Y-m-d H:i:s");
     $query = "INSERT INTO {$TABLE_PREFIX}files (info_hash, announces, filename, url, info, category, data, size, comment, external,announce_url, uploader,anonymous, bin_hash)\n                  VALUES (\n                          '{$info_hash}',\n                          '" . mysqli_real_escape_string($DBDT, serialize($announces)) . "',\n                          '" . mysqli_real_escape_string($DBDT, $filename) . "',\n                          '{$TORRENTSDIR}/{$info_hash}.btf',\n                          '{$info}',\n                          '{$cat}',\n                          '{$now}',\n                          '{$size}',\n                          '" . mysqli_real_escape_string($DBDT, $filename) . "',\n                          'yes',\n                          '{$announce}',\n                          '{$user}',\n                          'false',\n                          '0x{$info_hash}'\n                          )";
     $result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die(is_object($GLOBALS["___mysqli_ston"]) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false));
 }
Ejemplo n.º 5
0
function scrape($url, $infohash = '')
{
    global $TABLE_PREFIX;
    if (isset($url)) {
        $extannunce = str_replace('announce', 'scrape', urldecode($url));
        if ($infohash != '') {
            $ihash = array();
            $ihash = explode('\',\'', $infohash);
            $info_hash = '';
            foreach ($ihash as $myihash) {
                $info_hash .= '&info_hash=' . escapeURL($myihash);
            }
            $info_hash = substr($info_hash, 1);
            $stream = get_remote_file($extannunce . '?' . $info_hash);
        } else {
            $stream = get_remote_file($extannunce);
        }
        $stream = trim(stristr($stream, 'd5:files'));
        if (strpos($stream, 'd5:files') === false) {
            $ret = do_sqlquery('UPDATE ' . $TABLE_PREFIX . 'files SET lastupdate=NOW() WHERE announce_url="' . $url . '"' . ($infohash == '' ? '' : ' AND info_hash IN ("' . $infohash . '")'));
            write_log('FAILED update external torrent ' . ($infohash == '' ? '' : '(infohash: ' . $infohash . ')') . ' from ' . $url . ' tracker (not connectable)', '');
            return;
        }
        $array = BDecode($stream);
        if (!isset($array) || $array == false || !isset($array['files'])) {
            $ret = do_sqlquery('UPDATE ' . $TABLE_PREFIX . 'files SET lastupdate=NOW() WHERE announce_url="' . $url . '"' . ($infohash == '' ? '' : ' AND info_hash IN ("' . $infohash . '")'));
            write_log('FAILED update external torrent ' . ($infohash == '' ? '' : '(infohash: ' . $infohash . ')') . ' from ' . $url . ' tracker (not bencode data)', '');
            return;
        }
        $files = $array['files'];
        if (!is_array($files)) {
            $ret = do_sqlquery('UPDATE ' . $TABLE_PREFIX . 'files SET lastupdate=NOW() WHERE announce_url="' . $url . '"' . ($infohash = '' ? '' : ' AND info_hash IN ("' . $infohash . '")'));
            write_log('FAILED update external torrent ' . ($infohash == '' ? '' : '(infohash: ' . $infohash . ')') . ' from ' . $url . ' tracker (probably deleted torrent(s))', '');
            return;
        }
        foreach ($files as $hash => $data) {
            $seeders = $data['complete'];
            $leechers = $data['incomplete'];
            $completed = isset($data['downloaded']) ? $data['downloaded'] : 0;
            $torrenthash = bin2hex(stripslashes($hash));
            $ret = do_sqlquery('UPDATE ' . $TABLE_PREFIX . 'files SET lastupdate=NOW(), lastsuccess=NOW(), seeds=' . $seeders . ', leechers=' . $leechers . ', finished=' . $completed . ' WHERE announce_url = "' . $url . '"' . ($hash == '' ? '' : ' AND info_hash="' . $torrenthash . '";'));
            if (mysql_affected_rows() == 1) {
                write_log('SUCCESS update external torrent from ' . $url . ' tracker (infohash: ' . $torrenthash . ')', '');
            }
        }
    }
}
Ejemplo n.º 6
0
} else {
    $row["rating"] = rating_bar("" . $_GET["id"] . "", 5, 'static');
}
$row["rating"];
# <!--
##################################################################
########################################################################-->
$row["size"] = makesize($row["size"]);
// files in torrent - by Lupin 20/10/05
require_once dirname(__FILE__) . "/include/BDecode.php";
if (file_exists($row["url"])) {
    $torrenttpl->set("DISPLAY_FILES", TRUE, TRUE);
    $ffile = fopen($row["url"], "rb");
    $content = fread($ffile, filesize($row["url"]));
    fclose($ffile);
    $content = BDecode($content);
    $numfiles = 0;
    if (isset($content["info"]) && $content["info"]) {
        $thefile = $content["info"];
        if (isset($thefile["length"])) {
            $dfiles[$numfiles]["filename"] = htmlspecialchars($thefile["name"]);
            $dfiles[$numfiles]["size"] = makesize($thefile["length"]);
            $numfiles++;
        } elseif (isset($thefile["files"])) {
            foreach ($thefile["files"] as $singlefile) {
                $dfiles[$numfiles]["filename"] = htmlspecialchars(implode("/", $singlefile["path"]));
                $dfiles[$numfiles]["size"] = makesize($singlefile["length"]);
                $numfiles++;
            }
        } else {
            // can't be but...
Ejemplo n.º 7
0
function ParseTorrent($filename)
{
    require_once "BDecode.php";
    require_once "BEncode.php";
    $TorrentInfo = array();
    global $array;
    //check file type is a torrent
    $torrent = explode(".", $filename);
    $fileend = end($torrent);
    $fileend = strtolower($fileend);
    if ($fileend == "torrent") {
        $parseme = @file_get_contents("{$filename}");
        if ($parseme == FALSE) {
            show_error_msg(T_("ERROR"), T_("PARSE_CONTENTS"), 1);
        }
        if (!isset($parseme)) {
            show_error_msg(T_("ERROR"), T_("PARSE_OPEN"), 1);
        } else {
            $array = BDecode($parseme);
            if ($array === FALSE) {
                show_error_msg(T_("ERROR"), T_("PARSE_DECODE"), 1);
            } else {
                if (!@count($array['info'])) {
                    show_error_msg(T_("ERROR"), T_("PARSE_OPEN"), 1);
                } else {
                    //Get Announce URL
                    $TorrentInfo[0] = $array["announce"];
                    //Get Announce List Array
                    if (isset($array["announce-list"])) {
                        $TorrentInfo[6] = $array["announce-list"];
                    }
                    //Read info, store as (infovariable)
                    $infovariable = $array["info"];
                    // Calculates SHA1 Hash
                    $infohash = sha1(BEncode($infovariable));
                    $TorrentInfo[1] = $infohash;
                    // Calculates date from UNIX Epoch
                    $makedate = date('r', $array["creation date"]);
                    $TorrentInfo[2] = $makedate;
                    // The name of the torrent is different to the file name
                    $TorrentInfo[3] = $infovariable['name'];
                    //Get File List
                    if (isset($infovariable["files"])) {
                        // Multi File Torrent
                        $filecount = "";
                        //Get filenames here
                        $TorrentInfo[8] = $infovariable["files"];
                        foreach ($infovariable["files"] as $file) {
                            $filecount += "1";
                            $multiname = $file['path'];
                            //Not needed here really
                            $multitorrentsize = $file['length'];
                            $torrentsize += $file['length'];
                        }
                        $TorrentInfo[4] = $torrentsize;
                        //Add all parts sizes to get total
                        $TorrentInfo[5] = $filecount;
                        //Get file count
                    } else {
                        // Single File Torrent
                        $torrentsize = $infovariable['length'];
                        $TorrentInfo[4] = $torrentsize;
                        //Get file count
                        $TorrentInfo[5] = "1";
                    }
                    // Get Torrent Comment
                    if (isset($array['comment'])) {
                        $TorrentInfo[7] = $array['comment'];
                    }
                }
            }
        }
    }
    return $TorrentInfo;
}
Ejemplo n.º 8
0
include "BDecode.php";
if (isset($_GET['info_hash']) && isset($_GET['data'])) {
    $info_hash = $_GET['info_hash'];
    // Checks hash is ok
    if (strlen($info_hash) != 20) {
        $info_hash = stripcslashes($_GET['info_hash']);
    }
    if (strlen($info_hash) != 20) {
        die("HASHFAIL");
    }
    $info_hash = bin2hex($info_hash);
    if (!file_exists($info_hash) && !file_exists("./multiseed/{$info_hash}")) {
        die("EXPIRED");
    }
    $data = urldecode($_GET['data']);
    $bdata = @BDecode($data);
    // $bdata is an array of ip addresses:ports:time
    if (!$bdata) {
        die("CORRUPT");
    }
    $handle = fopen($info_hash, "rb+");
    flock($handle, LOCK_EX);
    $peer_num = intval(filesize($info_hash) / 7);
    $data = fread($handle, $peer_num * 7);
    $peer = array();
    foreach ($bdata as $ip) {
        $iparray = explode(":", $ip);
        $ip2 = $iparray[0];
        $port = $iparray[1];
        $time = $iparray[2];
        $peer_ip = explode('.', $ip2);
function addTorrent()
{
    global $dbhost, $dbuser, $dbpass, $database;
    global $_POST, $_FILES;
    require_once "funcsv2.php";
    require_once "BDecode.php";
    require_once "BEncode.php";
    $hash = strtolower($_POST["hash"]);
    $db = mysql_connect($dbhost, $dbuser, $dbpass) or die("<p class=\"error\">Couldn't connect to database. contact the administrator</p>");
    mysql_select_db($database) or die("<p class=\"error\">Can't open the database.</p>");
    if (isset($_FILES["torrent"])) {
        if ($_FILES["torrent"]["error"] != 4) {
            $fd = fopen($_FILES["torrent"]["tmp_name"], "rb") or die("<p class=\"error\">File upload error 1</p>\n");
            is_uploaded_file($_FILES["torrent"]["tmp_name"]) or die("<p class=\"error\">File upload error 2</p>\n");
            $alltorrent = fread($fd, filesize($_FILES["torrent"]["tmp_name"]));
            $array = BDecode($alltorrent);
            if (!$array) {
                echo "<p class=\"error\">There was an error handling your uploaded torrent. The parser didn't like it.</p>";
                endOutput();
                exit;
            }
            $hash = @sha1(BEncode($array["info"]));
            fclose($fd);
            unlink($_FILES["torrent"]["tmp_name"]);
        }
    }
    if (isset($_POST["filename"])) {
        $filename = clean($_POST["filename"]);
    } else {
        $filename = "";
    }
    if (isset($_POST["url"])) {
        $url = clean($_POST["url"]);
    } else {
        $url = "";
    }
    if (isset($_POST["info"])) {
        $info = clean($_POST["info"]);
    } else {
        $info = "";
    }
    if (isset($_POST["autoset"])) {
        if (strcmp($_POST["autoset"], "enabled") == 0) {
            if (strlen($filename) == 0 && isset($array["info"]["name"])) {
                $filename = $array["info"]["name"];
            }
            if (strlen($info) == 0 && isset($array["info"]["piece length"])) {
                $info = $array["info"]["piece length"] / 1024 * (strlen($array["info"]["pieces"]) / 20) / 1024;
                $info = round($info, 2) . " MB";
                if (isset($array["comment"])) {
                    $info .= " - " . $array["comment"];
                }
            }
        }
        $filename = mysql_escape_string($filename);
        $url = mysql_escape_string($url);
        $info = mysql_escape_string($info);
        if (strlen($hash) != 40 || !verifyHash($hash)) {
            echo "<p class=\"error\">Error: Info hash must be exactly 40 hex bytes.</p>";
            endOutput();
        }
        $query = "INSERT INTO BTPHP_namemap (info_hash, filename, url, info) VALUES (\"{$hash}\", \"{$filename}\", \"{$url}\", \"{$info}\")";
        $status = makeTorrent($hash, true);
        quickQuery($query);
        if ($status) {
            echo "<p class=\"error\">Torrent was added successfully.</p>";
        } else {
            echo "<p class=\"error\">There were some errors. Check if this torrent had been added previously.</p>";
        }
    }
    endOutput();
}
/**
 * setFileVars
 */
function transfer_setFileVars()
{
    global $cfg, $tmpl, $transfer, $transferLabel, $ch;
    // set vars for transfer
    $transferFilesList = array();
    switch ($ch->type) {
        case "torrent":
            require_once "inc/classes/BDecode.php";
            $tFile = $cfg["transfer_file_path"] . $transfer;
            if ($fd = @fopen($tFile, "rd")) {
                $alltorrent = @fread($fd, @filesize($tFile));
                $btmeta = @BDecode($alltorrent);
                @fclose($fd);
            }
            $transferSizeSum = 0;
            if (isset($btmeta) && is_array($btmeta) && isset($btmeta['info'])) {
                if (array_key_exists('files', $btmeta['info'])) {
                    foreach ($btmeta['info']['files'] as $filenum => $file) {
                        $name = is_array($file['path']) ? implode("/", $file['path']) : $file['path'];
                        $size = isset($file['length']) && is_numeric($file['length']) ? $file['length'] : 0;
                        $transferSizeSum += $size;
                        array_push($transferFilesList, array('name' => $name, 'size' => $size != 0 ? formatBytesTokBMBGBTB($size) : 0));
                    }
                } else {
                    $size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
                    $transferSizeSum += $size;
                    array_push($transferFilesList, array('name' => $btmeta["info"]["name"], 'size' => formatBytesTokBMBGBTB($size)));
                }
            }
            if (empty($transferFilesList)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', count($btmeta['info']['files']));
            } else {
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', count($transferFilesList));
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
        case "wget":
            $ch = ClientHandler::getInstance('wget');
            $ch->setVarsFromFile($transfer);
            $transferSizeSum = 0;
            if (!empty($ch->url)) {
                require_once "inc/classes/SimpleHTTP.php";
                $size = SimpleHTTP::getRemoteSize($ch->url);
                $transferSizeSum += $size;
                array_push($transferFilesList, array('name' => $ch->url, 'size' => formatBytesTokBMBGBTB($size)));
            }
            if (empty($transferFilesList)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', 0);
            } else {
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', count($transferFilesList));
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
        case "nzb":
            require_once "inc/classes/NZBFile.php";
            $nzb = new NZBFile($transfer);
            $transferSizeSum = 0;
            if (empty($nzb->files)) {
                $tmpl->setvar('transferFilesString', "Empty");
                $tmpl->setvar('transferFileCount', 0);
            } else {
                foreach ($nzb->files as $file) {
                    $transferSizeSum += $file['size'];
                    array_push($transferFilesList, array('name' => $file['name'], 'size' => formatBytesTokBMBGBTB($file['size'])));
                }
                $tmpl->setloop('transferFilesList', $transferFilesList);
                $tmpl->setvar('transferFileCount', $nzb->filecount);
            }
            $tmpl->setvar('transferSizeSum', $transferSizeSum > 0 ? formatBytesTokBMBGBTB($transferSizeSum) : 0);
            return;
    }
}
Ejemplo n.º 11
0
$friendlyext = ".torrent";
$name = $friendlyname . "[" . $friendlyurl . "]" . $friendlyext;
SQL_Query_exec("UPDATE torrents SET hits = hits + 1 WHERE id = {$id}");
require_once "backend/BEncode.php";
require_once "backend/BDecode.php";
//if user dont have a passkey generate one, only if tracker is set to members only
if ($site_config["MEMBERSONLY"]) {
    if (strlen($CURUSER['passkey']) != 32) {
        $rand = array_sum(explode(" ", microtime()));
        $CURUSER['passkey'] = md5($CURUSER['username'] . $rand . $CURUSER['secret'] . $rand * mt_rand());
        SQL_Query_exec("UPDATE users SET passkey='{$CURUSER['passkey']}' WHERE id={$CURUSER['id']}");
    }
}
if ($row["external"] != 'yes' && $site_config["MEMBERSONLY"]) {
    // local torrent so add passkey
    $dict = BDecode(file_get_contents($fn));
    $dict['announce'] = sprintf($site_config["PASSKEYURL"], $CURUSER["passkey"]);
    unset($dict['announce-list']);
    $data = BEncode($dict);
    //header('Content-Disposition: attachment; filename="'.$name.'"');
    header('Content-Disposition: attachment; filename=' . sqlesc($name) . '');
    //header('Content-Length: ' . strlen($data));
    header("Content-Type: application/x-bittorrent");
    print $data;
} else {
    // external torrent so no passkey needed
    //header('Content-Disposition: attachment; filename="'.$name.'"');
    header('Content-Disposition: attachment; filename=' . sqlesc($name) . '');
    header('Content-Length: ' . filesize($fn));
    header("Content-Type: application/x-bittorrent");
    readfile($fn);
Ejemplo n.º 12
0
/**
 * Scrape torrent and return stats
 *
 * @param $scrape
 *   string: Scrape URL
 * @param $hash
 *   string: SHA1 hash (info_hash) of torrent
 * @return
 *   array:
 *     All -1 if failed
 *     - seeds: integer - number of seeders
 *     - leechers: integer - number of leechers
 *     - downloaded: integer - number of complete downloads
 *
 */
function torrent_scrape_url($scrape, $hash)
{
    if (function_exists("curl_exec")) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $scrape . '?info_hash=' . escape_url($hash));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $fp = curl_exec($ch);
        curl_close($ch);
    } else {
        ini_set('default_socket_timeout', 10);
        $fp = @file_get_contents($scrape . '?info_hash=' . escape_url($hash));
    }
    $ret = array();
    if ($fp) {
        $stats = BDecode($fp);
        $binhash = pack("H*", $hash);
        $binhash = addslashes($binhash);
        $seeds = $stats['files'][$binhash]['complete'];
        $peers = $stats['files'][$binhash]['incomplete'];
        $downloaded = $stats['files'][$binhash]['downloaded'];
        $ret['seeds'] = $seeds;
        $ret['peers'] = $peers;
        $ret['downloaded'] = $downloaded;
    }
    if ($ret['seeds'] === null) {
        $ret['seeds'] = -1;
        $ret['peers'] = -1;
        $ret['downloaded'] = -1;
    }
    return $ret;
}
Ejemplo n.º 13
0
 $zip = zip_open($_FILES["zipfile"]["tmp_name"]);
 if ($zip == true) {
     $db = mysql_connect($dbhost, $dbuser, $dbpass) or die(errorMessage() . "Couldn't connect to the database, contact the administrator</p>");
     mysql_select_db($database) or die(errorMessage() . "Can't open the database.</p>");
     while ($zip_entry = zip_read($zip)) {
         echo "Name: " . zip_entry_name($zip_entry) . "<br>\n";
         if (substr(zip_entry_name($zip_entry), -8) == ".torrent") {
             $error_status = true;
             if (zip_entry_open($zip, $zip_entry, "r")) {
                 //read in file from zip
                 $buffer = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                 //go through each torrent file and add it if possible
                 require_once "BDecode.php";
                 require_once "BEncode.php";
                 $tracker_url = $website_url . substr($_SERVER['REQUEST_URI'], 0, -16) . "announce.php";
                 $array = BDecode($buffer);
                 if (!$array) {
                     echo errorMessage() . "Error: The parser was unable to load this torrent.</p>\n";
                     $error_status = false;
                 }
                 if (strtolower($array["announce"]) != $tracker_url) {
                     echo errorMessage() . "Error: The tracker announce URL does not match this:<br>{$tracker_url}<br>Please re-create and re-upload the torrent.</p>\n";
                     $error_status = false;
                 }
                 if (function_exists("sha1")) {
                     $hash = @sha1(BEncode($array["info"]));
                 } else {
                     echo errorMessage() . "Error: It looks like you do not have a hash function available, this will not work.</p>\n";
                     $error_status = false;
                 }
                 //figure out total size of all files in torrent, needed for insertion into database
Ejemplo n.º 14
0
$serversig = $_SERVER['SERVER_SIGNATURE'];
echo "Anatomic P2P Supertracker HTML Frontend Version 0.1 BETA on: <br> {$serversig}.<br><br>\r\nThis script lists the status of some of the other supertrackers registered with this supertracker<BR><BR>";
include "BDecode.php";
function ping($url)
{
    $url = urldecode($url);
    $url .= "?ping=1";
    $pull = @file_get_contents($url);
    if ($pull === "PONG") {
        return TRUE;
    } else {
        return FALSE;
    }
}
$data = @file_get_contents("strackers.dat");
$data = BDecode($data);
if (is_array($data) != 1) {
    die("Corrupted Tracker Data");
}
$number = count($data);
if ($number != 0) {
    $counter = 0;
    foreach ($data as $tracker) {
        $counter += "1";
        $tracker = urldecode($tracker);
        // might be neccessary
        if (ping($tracker) === FALSE) {
            $number -= "1";
            echo "{$counter}.  ";
            echo $tracker;
            print "         NO VALID RESPONSE RECEIVED";
Ejemplo n.º 15
0
                 $filename .= $info["files"][$fileno]["path"][0];
             }
             $filename = mysql_real_escape_string($filename);
             mysql_query("INSERT INTO " . $prefix . "webseedfiles (info_hash,filename,startpiece,endpiece,startpieceoffset,fileorder) values (\"{$hash}\", \"{$filename}\", {$startpiece}, {$pieceno}, {$startoffset}, {$fileno})");
             $fileno++;
         }
     } else {
         //single file
         mysql_query("INSERT INTO " . $prefix . "webseedfiles (info_hash,filename,startpiece,endpiece,startpieceoffset,fileorder) values (\"{$hash}\", \"" . mysql_real_escape_string($fsbase) . "\", 0, " . (strlen($array["info"]["pieces"]) / 20 - 1) . ", 0, 0)");
     }
 }
 if ($_POST["getrightseed"] == "enabled" || $_POST["httpseed"] == "enabled") {
     //edit torrent file
     $read_httpseed = fopen("torrents/" . $filename . ".torrent", "rb");
     $binary_data = fread($read_httpseed, filesize("torrents/" . $filename . ".torrent"));
     $data_array = BDecode($binary_data);
     if ($_POST["httpseed"] == "enabled") {
         $data_array["httpseeds"][0] = $website_url . substr($_SERVER['REQUEST_URI'], 0, -15) . "seed.php";
     }
     if ($_POST["getrightseed"] == "enabled") {
         $data_array["url-list"][0] = $_POST["httpftplocation"];
     }
     $to_write = BEncode($data_array);
     fclose($read_httpseed);
     //write torrent file
     $write_httpseed = fopen("torrents/" . $filename . ".torrent", "wb");
     fwrite($write_httpseed, $to_write);
     fclose($write_httpseed);
 }
 //add in piecelength and number of pieces
 $query = "UPDATE " . $prefix . "summary SET piecelength=\"" . $info["piece length"] . "\", numpieces=\"" . strlen($array["info"]["pieces"]) / 20 . "\" WHERE info_hash=\"" . $hash . "\"";
Ejemplo n.º 16
0
Archivo: wobi.php Proyecto: j3k0/Wobi
function _wobi_addTorrent($torrent_file_path, $torrent_file_url, $file_path, $file_url)
{
    require "config.php";
    $tracker_url = WOBI_TRACKER_URL;
    $httpseed = true;
    $tmp1 = explode("/wp-content/", $file_path);
    $relative_path = "../../" . $tmp1[1];
    $getrightseed = false;
    $httpftplocation = $file_url;
    $target_path = "torrents/";
    $autoset = true;
    $filename = "";
    // $file_path; // Extracted from torrent (if $autoset)
    $url = "{$file_url}";
    // Extracted from torrent (if $autoset)
    $hash = "";
    // Extracted from torrent (if $autoset)
    // TODO: Only if not already connected.
    // $db = mysql_connect($dbhost, $dbuser, $dbpass) or die(errorMessage() . "Couldn't connect to the database, contact the administrator.</p>");
    // mysql_select_db($database) or die(errorMessage() . "Can't open the database.</p>");
    require_once "funcsv2.php";
    require_once "BDecode.php";
    require_once "BEncode.php";
    // Check for errors, we don't care right?
    $fd = fopen($torrent_file_path, "rb") or die(_wobi_errorMessage() . "File upload error 1</p>\n");
    // is_uploaded_file($torrent_file_path) or die(_wobi_errorMessage() . "File upload error 2</p>\n");
    $alltorrent = fread($fd, filesize($torrent_file_path));
    $array = BDecode($alltorrent);
    if (!$array) {
        $wobi_error = _wobi_errorMessage() . "Error: The parser was unable to load your torrent.  Please re-create and re-upload the torrent.</p>\n";
        return false;
    }
    if (strtolower($array["announce"]) != $tracker_url) {
        $wobi_error = _wobi_errorMessage() . "Error: The tracker announce URL does not match this:<br>{$tracker_url}<br>Please re-create and re-upload the torrent.</p>\n";
        return false;
    }
    if ($httpseed && $relative_path == "") {
        $wobi_error = _wobi_errorMessage() . "Error: HTTP seeding was checked however no relative path was given.</p>\n";
        return false;
    }
    if ($httpseed && $relative_path != "") {
        if (Substr($relative_path, -1) == "/") {
            if (!is_dir($relative_path)) {
                $wobi_error = _wobi_errorMessage() . "Error: HTTP seeding relative path ends in / but is not a valid directory.</p>\n";
                return false;
            }
        } else {
            if (!is_file($relative_path)) {
                $wobi_error = _wobi_errorMessage() . "Error: HTTP seeding relative path is not a valid file.</p>\n";
                return false;
            }
        }
    }
    if ($getrightseed && $httpftplocation == "") {
        $wobi_error = _wobi_errorMessage() . "Error: GetRight HTTP seeding was checked however no URL was given.</p>\n";
        return false;
    }
    if ($getrightseed && (Substr($httpftplocation, 0, 7) != "http://" && Substr($httpftplocation, 0, 6) != "ftp://")) {
        $wobi_error = _wobi_errorMessage() . "Error: GetRight HTTP seeding URL must start with http:// or ftp://</p>\n";
        return false;
    }
    $hash = @sha1(BEncode($array["info"]));
    fclose($fd);
    $target_path = $target_path . basename($torrent_file_path);
    $move_torrent = rename($torrent_file_path, $target_path);
    if ($move_torrent == false) {
        $wobi_error = errorMessage() . "Unable to move {$torrent_file_path} to torrents/</p>\n";
    }
    if (!empty($filename)) {
        // XXX can probably remove this...
        $filename = clean($filename);
    }
    if (!empty($url)) {
        // XXX and this
        $url = clean($url);
    }
    if ($autoset) {
        if (strlen($filename) == 0 && isset($array["info"]["name"])) {
            $filename = $array["info"]["name"];
        }
    }
    //figure out total size of all files in torrent
    $info = $array["info"];
    $total_size = 0;
    if (isset($info["files"])) {
        foreach ($info["files"] as $file) {
            $total_size = $total_size + $file["length"];
        }
    } else {
        $total_size = $info["length"];
    }
    //Validate torrent file, make sure everything is correct
    $filename = mysql_escape_string($filename);
    $filename = htmlspecialchars(clean($filename));
    $url = htmlspecialchars(mysql_escape_string($url));
    if (strlen($hash) != 40 || !verifyHash($hash)) {
        $wobi_error = _wobi_errorMessage() . "Error: Info hash must be exactly 40 hex bytes.</p>\n";
        return false;
    }
    if (Substr($url, 0, 7) != "http://" && $url != "") {
        $wobi_error = _wobi_errorMessage() . "Error: The Torrent URL does not start with http:// Make sure you entered a correct URL.</p>\n";
        return false;
    }
    $query = "INSERT INTO " . $prefix . "namemap (info_hash, filename, url, size, pubDate) VALUES (\"{$hash}\", \"{$filename}\", \"{$url}\", \"{$total_size}\", \"" . date('D, j M Y h:i:s') . "\")";
    $status = makeTorrent($hash, true);
    quickQuery($query);
    chmod($target_path, 0644);
    if ($status) {
        $wobi_error = "<p class=\"success\">Torrent was added successfully.</p>\n";
        require_once "wobi_functions.php";
        _wobi_addWebseedfiles($target_path, $relative_path, $httpftplocation, $hash);
        return true;
    } else {
        $wobi_error = _wobi_errorMessage() . "There were some errors. Check if this torrent has been added previously.</p>\n";
        return false;
    }
}
Ejemplo n.º 17
0
function addTorrent()
{
    require "config.php";
    $tracker_url = $website_url . substr($_SERVER['REQUEST_URI'], 0, -15) . "announce.php";
    $hash = strtolower($_POST["hash"]);
    $db = mysql_connect($dbhost, $dbuser, $dbpass) or die(errorMessage() . "Couldn't connect to the database, contact the administrator</p>");
    mysql_select_db($database) or die(errorMessage() . "Can't open the database.</p>");
    require_once "funcsv2.php";
    require_once "BDecode.php";
    require_once "BEncode.php";
    if ($_FILES["torrent"]["error"] != 4) {
        $fd = fopen($_FILES["torrent"]["tmp_name"], "rb") or die(errorMessage() . "File upload error 1</p>\n");
        is_uploaded_file($_FILES["torrent"]["tmp_name"]) or die(errorMessage() . "File upload error 2</p>\n");
        $alltorrent = fread($fd, filesize($_FILES["torrent"]["tmp_name"]));
        $array = BDecode($alltorrent);
        if (!$array) {
            echo errorMessage() . "Error: The parser was unable to load your torrent.  Please re-create and re-upload the torrent.</p>\n";
            endOutput();
            exit;
        }
        if (strtolower($array["announce"]) != $tracker_url) {
            echo errorMessage() . "Error: The tracker announce URL does not match this:<br>{$tracker_url}<br>Please re-create and re-upload the torrent.</p>\n";
            endOutput();
            exit;
        }
        if ($_POST["httpseed"] == "enabled" && $_POST["relative_path"] == "") {
            echo errorMessage() . "Error: HTTP seeding was checked however no relative path was given.</p>\n";
            endOutput();
            exit;
        }
        if ($_POST["httpseed"] == "enabled" && $_POST["relative_path"] != "") {
            if (Substr($_POST["relative_path"], -1) == "/") {
                if (!is_dir($_POST["relative_path"])) {
                    echo errorMessage() . "Error: HTTP seeding relative path ends in / but is not a valid directory.</p>\n";
                    endOutput();
                    exit;
                }
            } else {
                if (!is_file($_POST["relative_path"])) {
                    echo errorMessage() . "Error: HTTP seeding relative path is not a valid file.</p>\n";
                    endOutput();
                    exit;
                }
            }
        }
        if ($_POST["getrightseed"] == "enabled" && $_POST["httpftplocation"] == "") {
            echo errorMessage() . "Error: GetRight HTTP seeding was checked however no URL was given.</p>\n";
            endOutput();
            exit;
        }
        if ($_POST["getrightseed"] == "enabled" && (Substr($_POST["httpftplocation"], 0, 7) != "http://" && Substr($_POST["httpftplocation"], 0, 6) != "ftp://")) {
            echo errorMessage() . "Error: GetRight HTTP seeding URL must start with http:// or ftp://</p>\n";
            endOutput();
            exit;
        }
        $hash = @sha1(BEncode($array["info"]));
        fclose($fd);
        $target_path = "torrents/";
        $target_path = $target_path . basename(clean($_FILES['torrent']['name']));
        $move_torrent = move_uploaded_file($_FILES["torrent"]["tmp_name"], $target_path);
        if ($move_torrent == false) {
            echo errorMessage() . "Unable to move " . $_FILES["torrent"]["tmp_name"] . " to torrents/</p>\n";
        }
    }
    if (isset($_POST["filename"])) {
        $filename = clean($_POST["filename"]);
    } else {
        $filename = "";
    }
    if (isset($_POST["url"])) {
        $url = clean($_POST["url"]);
    } else {
        $url = "";
    }
    if (isset($_POST["autoset"])) {
        if (strcmp($_POST["autoset"], "enabled") == 0) {
            if (strlen($filename) == 0 && isset($array["info"]["name"])) {
                $filename = $array["info"]["name"];
            }
        }
    }
    //figure out total size of all files in torrent
    $info = $array["info"];
    $total_size = 0;
    if (isset($info["files"])) {
        foreach ($info["files"] as $file) {
            $total_size = $total_size + $file["length"];
        }
    } else {
        $total_size = $info["length"];
    }
    //Validate torrent file, make sure everything is correct
    $filename = mysql_escape_string($filename);
    $filename = htmlspecialchars(clean($filename));
    $url = htmlspecialchars(mysql_escape_string($url));
    if (strlen($hash) != 40 || !verifyHash($hash)) {
        echo errorMessage() . "Error: Info hash must be exactly 40 hex bytes.</p>\n";
        endOutput();
    }
    if (Substr($url, 0, 7) != "http://" && $url != "") {
        echo errorMessage() . "Error: The Torrent URL does not start with http:// Make sure you entered a correct URL.</p>\n";
        endOutput();
    }
    $query = "INSERT INTO " . $prefix . "namemap (info_hash, filename, url, size, pubDate) VALUES (\"{$hash}\", \"{$filename}\", \"{$url}\", \"{$total_size}\", \"" . date('D, j M Y h:i:s') . "\")";
    $status = makeTorrent($hash, true);
    quickQuery($query);
    if ($status) {
        echo "<p class=\"success\">Torrent was added successfully.</p>\n";
        echo "<a href=\"newtorrents.php\"><img src=\"images/add.png\" border=\"0\" class=\"icon\" alt=\"Add Torrent\" title=\"Add Torrent\" /></a><a href=\"newtorrents.php\">Add Another Torrent</a><br>\n";
        //rename torrent file to match filename
        rename("torrents/" . clean($_FILES['torrent']['name']), "torrents/" . $filename . ".torrent");
        //make torrent file readable by all
        chmod("torrents/" . $filename . ".torrent", 0644);
        //run RSS generator
        require_once "rss_generator.php";
        //Display information from DumpTorrentCGI.php
        require_once "torrent_functions.php";
    } else {
        echo errorMessage() . "There were some errors. Check if this torrent has been added previously.</p>\n";
        //delete torrent file if it doesn't exist in database
        $query = "SELECT COUNT(*) FROM " . $prefix . "summary WHERE info_hash = '{$hash}'";
        $results = mysql_query($query) or die(errorMessage() . "Can't do SQL query - " . mysql_error() . "</p>");
        $data = mysql_fetch_row($results);
        if ($data[0] == 0) {
            if (file_exists("torrents/" . $_FILES['torrent']['name'])) {
                unlink("torrents/" . $_FILES['torrent']['name']);
            }
        }
        //make torrent file readable by all
        chmod("torrents/" . $filename . ".torrent", 0644);
        endOutput();
    }
}
Ejemplo n.º 18
0
    unset($dict['nodes']);
    // remove cached peers (Bitcomet & Azareus)
    unset($dict['info']['crc32']);
    // remove crc32
    unset($dict['info']['ed2k']);
    // remove ed2k
    unset($dict['info']['md5sum']);
    // remove md5sum
    unset($dict['info']['sha1']);
    // remove sha1
    unset($dict['info']['tiger']);
    // remove tiger
    unset($dict['azureus_properties']);
    // remove azureus properties
}
$dict = BDecode(BEncode($dict));
// double up on the becoding solves the occassional misgenerated infohash
$dict['comment'] = "Торрент создан для '{$SITENAME}'";
// change torrent comment
$dict['created by'] = "{$CURUSER['username']}";
// change created by
$dict['publisher'] = "{$CURUSER['username']}";
// change publisher
$dict['publisher.utf-8'] = "{$CURUSER['username']}";
// change publisher.utf-8
$dict['publisher-url'] = "{$DEFAULTBASEURL}/userdetails.php?id={$CURUSER['id']}";
// change publisher-url
$dict['publisher-url.utf-8'] = "{$DEFAULTBASEURL}/userdetails.php?id={$CURUSER['id']}";
// change publisher-url.utf-8
$infohash = sha1(BEncode($dict['info']));
if ($multi_torrent == 'yes') {
/**
 * gets datapath of a transfer.
 *
 * @param $transfer name of the torrent
 * @return var with transfer-datapath or empty string
 */
function getTransferDatapath($transfer)
{
    global $cfg, $db, $transfers;
    if (isset($transfers['settings'][$transfer]['datapath'])) {
        return $transfers['settings'][$transfer]['datapath'];
    } else {
        $datapath = $db->GetOne("SELECT datapath FROM tf_transfers WHERE transfer = " . $db->qstr($transfer));
        if (empty($datapath)) {
            if (substr($transfer, -8) == ".torrent") {
                // this is a torrent-client
                require_once 'inc/classes/BDecode.php';
                $ftorrent = $cfg["transfer_file_path"] . $transfer;
                $alltorrent = @file_get_contents($ftorrent);
                if ($alltorrent == "") {
                    return "";
                }
                $btmeta = @BDecode($alltorrent);
                $datapath = empty($btmeta['info']['name']) ? "" : trim($btmeta['info']['name']);
            } else {
                if (substr($transfer, -5) == ".wget") {
                    // this is wget.
                    $datapath = ".";
                } else {
                    if (substr($transfer, -4) == ".nzb") {
                        // This is nzbperl.
                        $datapath = ".";
                    } else {
                        $datapath = "";
                    }
                }
            }
        }
        $transfers['settings'][$transfer]['datapath'] = $datapath;
        return $datapath;
    }
}
Ejemplo n.º 20
0
     }
 } else {
     // search other supernodes
     $data = @file_get_contents("strackers.dat");
     $status = 0;
     foreach ($data as $stracker) {
         $stracker .= "?pull=" . urlencode(pack("H*", $info_hash));
         $fp = fopen($stracker, "rb");
         $stream = "";
         if ($fp) {
             while (!feof($fp)) {
                 $stream .= @fread($fp, 128);
             }
         }
         fclose($fp);
         $returned = BDecode($stream);
         if ($returned == FALSE) {
             continue;
         }
         shuffle($returned);
         $status = 1;
         $tracker = $returned[0];
         break;
     }
     if ($status == 0) {
         er('No tracker can be found for the torrent');
     }
     // this block is executed if a tracker was (miraculously) found
     $handle = fopen("/hashes/{$info_hash}", "w");
     fwrite($handle, $tracker);
     fclose($handle);
Ejemplo n.º 21
0
/**
 * gets size of data of a torrent
 *
 * @param $torrent name of the torrent
 * @return int with size of data of torrent.
 *         -1 if error
 *         4096 if dir (lol ~)
 *         string with file/dir-name if doesnt exist. (lol~)
 */
function getTorrentDataSize($torrent)
{
    global $cfg;
    require_once 'BDecode.php';
    $ftorrent = $cfg["torrent_file_path"] . $torrent;
    $fd = fopen($ftorrent, "rd");
    $alltorrent = fread($fd, filesize($ftorrent));
    $btmeta = BDecode($alltorrent);
    $name = $btmeta['info']['name'];
    if (trim($name) != "") {
        // load torrent-settings from db to get data-location
        loadTorrentSettingsToConfig($torrent);
        if (!isset($cfg["savepath"]) || empty($cfg["savepath"])) {
            $cfg["savepath"] = $cfg["path"] . getOwner($torrent) . '/';
        }
        $name = $cfg["savepath"] . $name;
        # this is from dir.php - its not a function, and we need to call it several times
        $tData = stripslashes(stripslashes($name));
        if (!ereg("(\\.\\.\\/)", $tData)) {
            $fileSize = file_size($tData);
            return $fileSize;
        }
    }
    return -1;
}
if (isset($_POST["decode"])) {
    /*
     * First, if someone decided to paste the /announce url, replace it with /scrape.
     */
    if (strcmp(substr($_POST["scrapeurl"], strlen($_POST["scrapeurl"]) - 9, 9), "/announce") == 0) {
        $_POST["scrapeurl"] = substr($_POST["scrapeurl"], 0, strlen($_POST["scrapeurl"]) - 9) . "/scrape";
    }
    /*
     * Try to get the contents from the requested tracker
     */
    $contents = @file_get_contents($_POST["scrapeurl"]);
    /*
     * If something was retrieved, attempt to decode it
     */
    if ($contents != false) {
        $details = BDecode($contents);
    } else {
        /*
         * Nothing retrived, set to an empty string, so script falls through with an error
         */
        $details = "";
    }
    /*
     * HTML output & headers
     */
    echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n";
    echo "<HTML>\r\n<HEAD>\r\n";
    echo "\t<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=us-ascii\">\r\n";
    echo "\t<META NAME=\"Author\" CONTENT=\"danomac\">\r\n";
    echo "\t<TITLE>{$phpbttracker_id} {$phpbttracker_ver} - Scrape output analyzer results</TITLE>\r\n";
    echo "</HEAD>\r\n<BODY>\r\n";
Ejemplo n.º 23
0
/**
 * File Prio Form
 *
 * @param $transfer
 * @param $withForm
 * @return string
 */
function getFilePrioForm($transfer, $withForm = false)
{
    /*
    	global $cfg;
    	$prioFileName = $cfg["transfer_file_path"].$transfer.".prio";
    	require_once('inc/classes/BDecode.php');
    	$retVal = "";
    	// theme-switch
    	if ((strpos($cfg["theme"], '/')) === false) {
    		$retVal .= '<link rel="StyleSheet" href="themes/'.$cfg["theme"].'/css/dtree.css" type="text/css" />';
    		$retVal .= '<script type="text/javascript">var dtree_path_images = "themes/'.$cfg["theme"].'/images/dtree/";</script>';
    	} else {
    		$retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
    		$retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    	}
    	$retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    	$ftorrent = $cfg["transfer_file_path"].$transfer;
    	$fp = @fopen($ftorrent, "rd");
    	$alltorrent = @fread($fp, @filesize($ftorrent));
    	@fclose($fp);
    	$btmeta = @BDecode($alltorrent);
    	$torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
    	$dirnum = (array_key_exists('files',$btmeta['info'])) ? count($btmeta['info']['files']) : 0;
    	if (@is_readable($prioFileName)) {
    		$prio = explode(',', @file_get_contents($prioFileName));
    		$prio = array_splice($prio,1);
    	} else {
    		$prio = array();
    		for ($i=0; $i<$dirnum; $i++)
    			$prio[$i] = -1;
    	}
    */
    global $cfg;
    require_once 'inc/classes/BDecode.php';
    $retVal = "";
    // theme-switch
    if (strpos($cfg["theme"], '/') === false) {
        $retVal .= '<link rel="StyleSheet" href="themes/' . $cfg["theme"] . '/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/' . $cfg["theme"] . '/images/dtree/";</script>';
    } else {
        $retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    }
    $retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    $isTransmissionTorrent = false;
    if ($cfg["transmission_rpc_enable"]) {
        require_once 'inc/functions/functions.rpc.transmission.php';
        $isTransmissionTorrent = isTransmissionTransfer($transfer);
    }
    $files = array();
    if ($isTransmissionTorrent) {
        $allFilesResponse = getTransmissionTransfer($transfer, array('files'));
        $allFiles = $allFilesResponse['files'];
        $wantedFilesResponse = getTransmissionTransfer($transfer, array('wanted'));
        $wantedFiles = $wantedFilesResponse['wanted'];
        $dirnum = count($allFiles);
        // make sure this is in here otherwhise you will loose alot of time debugging your code on what is missing (the filetree selection is not displayed)
        $tree = new dir("/", $dirnum, -1);
        foreach ($allFiles as $file) {
            $fileparts = explode("/", $file[name]);
            $filesize = $file[length];
            $fileprops = array('length' => $filesize, 'path' => $fileparts);
            array_push($files, $fileprops);
        }
        $filescount = count($files);
        foreach ($files as $filenum => $file) {
            $depth = count($file['path']);
            $branch =& $tree;
            for ($i = 0; $i < $depth; $i++) {
                if ($i != $depth - 1) {
                    $d =& $branch->findDir($file['path'][$i]);
                    if ($d) {
                        $branch =& $d;
                    } else {
                        $dirnum++;
                        $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, -1));
                        $branch =& $d;
                    }
                } else {
                    $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $wantedFiles[$filenum] == 1 ? 1 : -1));
                }
            }
        }
        $aTorrent = getTransmissionTransfer($transfer, array("pieceCount", "pieceSize", "totalSize", "dateCreated", "downloadDir", "comment"));
        #$torrent_size = $aTorrent[pieceSize] * $aTorrent[pieceCount];
        $torrent_size = $aTorrent['totalSize'];
        $torrent_chunksize = $aTorrent['pieceSize'];
        $torrent_directoryname = $aTorrent['downloadDir'];
        $torrent_announceurl = $aTorrent['comment'];
        $torrent_creationdate = $aTorrent['dateCreated'];
        $torrent_filescount = $filescount;
    } else {
        $prioFileName = $cfg["transfer_file_path"] . $transfer . ".prio";
        $ftorrent = $cfg["transfer_file_path"] . $transfer;
        $fp = @fopen($ftorrent, "rd");
        $alltorrent = @fread($fp, @filesize($ftorrent));
        @fclose($fp);
        $btmeta = @BDecode($alltorrent);
        $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
        $dirnum = array_key_exists('files', $btmeta['info']) ? count($btmeta['info']['files']) : 0;
        if (@is_readable($prioFileName)) {
            $prio = explode(',', @file_get_contents($prioFileName));
            $prio = array_splice($prio, 1);
        } else {
            $prio = array();
            for ($i = 0; $i < $dirnum; $i++) {
                $prio[$i] = -1;
            }
        }
        $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
        if (array_key_exists('files', $btmeta['info'])) {
            foreach ($btmeta['info']['files'] as $filenum => $file) {
                $depth = count($file['path']);
                $branch =& $tree;
                for ($i = 0; $i < $depth; $i++) {
                    if ($i != $depth - 1) {
                        $d =& $branch->findDir($file['path'][$i]);
                        if ($d) {
                            $branch =& $d;
                        } else {
                            $dirnum++;
                            $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                            $branch =& $d;
                        }
                    } else {
                        $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                    }
                }
            }
        }
        $torrent_chunksize = $btmeta[info]['piece length'];
        $torrent_directoryname = $btmeta[info][name];
        $torrent_announceurl = $btmeta[announce];
        $torrent_creationdate = $btmeta['creation date'];
        $torrent_filescount = count($btmeta['info']['files']);
    }
    $retVal .= "<table><tr>";
    $retVal .= "<tr><td width=\"110\">Metainfo File:</td><td>" . $transfer . "</td></tr>";
    $retVal .= "<tr><td>Directory Name:</td><td>" . $torrent_directoryname . "</td></tr>";
    $retVal .= "<tr><td>Announce URL:</td><td>" . $torrent_announceurl . "</td></tr>";
    if (array_key_exists('comment', $btmeta)) {
        $retVal .= "<tr><td valign=\"top\">Comment:</td><td>" . tfb_htmlencode($btmeta['comment']) . "</td></tr>";
    }
    $retVal .= "<tr><td>Created:</td><td>" . ($torrent_creationdate == 0 ? 'n/a' : date("F j, Y, g:i a", $torrent_creationdate)) . "</td></tr>";
    $retVal .= "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")</td></tr>";
    $retVal .= "<tr><td>Chunk size:</td><td>" . $torrent_chunksize . " (" . @formatBytesTokBMBGBTB($torrent_chunksize) . ")</td></tr>";
    if (array_key_exists('files', $btmeta['info']) || count($files) > 0) {
        $retVal .= "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
        $retVal .= "</table><br>\n";
        if ($withForm) {
            $retVal .= "<form name=\"priority\" action=\"dispatcher.php?action=setFilePriority&riid=_referer_\" method=\"POST\" >";
            $retVal .= "<input type=\"hidden\" name=\"transfer\" value=\"" . $transfer . "\" >";
        }
        $retVal .= "<script type=\"text/javascript\">\n";
        $retVal .= "var sel = 0;\n";
        $retVal .= "d = new dTree('d');\n";
        $retVal .= $tree->draw(-1);
        $retVal .= "document.write(d);\n";
        $retVal .= "sel = getSizes();\n";
        $retVal .= "drawSel();\n";
        $retVal .= "</script>\n";
        $retVal .= "<input type=\"hidden\" name=\"filecount\" value=\"" . $torrent_filescount . "\">";
        $retVal .= "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
        $retVal .= "<br>";
        if ($withForm) {
            $retVal .= '<input type="submit" value="Save" >';
            $retVal .= "<br>";
            $retVal .= "</form>";
        }
    } else {
        $retVal .= "</table><br>";
        $retVal .= $btmeta['info']['name'] . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")";
    }
    // return
    return $retVal;
}
/**
 * File Prio Form
 *
 * @param $transfer
 * @param $withForm
 * @return string
 */
function getFilePrioForm($transfer, $withForm = false)
{
    global $cfg;
    $prioFileName = $cfg["transfer_file_path"] . $transfer . ".prio";
    require_once 'inc/classes/BDecode.php';
    $retVal = "";
    // theme-switch
    if (strpos($cfg["theme"], '/') === false) {
        $retVal .= '<link rel="StyleSheet" href="themes/' . $cfg["theme"] . '/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/' . $cfg["theme"] . '/images/dtree/";</script>';
    } else {
        $retVal .= '<link rel="StyleSheet" href="themes/tf_standard_themes/css/dtree.css" type="text/css" />';
        $retVal .= '<script type="text/javascript">var dtree_path_images = "themes/tf_standard_themes/images/dtree/";</script>';
    }
    $retVal .= '<script type="text/javascript" src="js/dtree.js"></script>';
    $ftorrent = $cfg["transfer_file_path"] . $transfer;
    $fp = @fopen($ftorrent, "rd");
    $alltorrent = @fread($fp, @filesize($ftorrent));
    @fclose($fp);
    $btmeta = @BDecode($alltorrent);
    $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
    $dirnum = array_key_exists('files', $btmeta['info']) ? count($btmeta['info']['files']) : 0;
    if (@is_readable($prioFileName)) {
        $prio = explode(',', @file_get_contents($prioFileName));
        $prio = array_splice($prio, 1);
    } else {
        $prio = array();
        for ($i = 0; $i < $dirnum; $i++) {
            $prio[$i] = -1;
        }
    }
    $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
    if (array_key_exists('files', $btmeta['info'])) {
        foreach ($btmeta['info']['files'] as $filenum => $file) {
            $depth = count($file['path']);
            $branch =& $tree;
            for ($i = 0; $i < $depth; $i++) {
                if ($i != $depth - 1) {
                    $d =& $branch->findDir($file['path'][$i]);
                    if ($d) {
                        $branch =& $d;
                    } else {
                        $dirnum++;
                        $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                        $branch =& $d;
                    }
                } else {
                    $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                }
            }
        }
    }
    $retVal .= "<table><tr>";
    $retVal .= "<tr><td width=\"110\">Metainfo File:</td><td>" . $transfer . "</td></tr>";
    $retVal .= "<tr><td>Directory Name:</td><td>" . $btmeta['info']['name'] . "</td></tr>";
    $retVal .= "<tr><td>Announce URL:</td><td>" . $btmeta['announce'] . "</td></tr>";
    if (array_key_exists('comment', $btmeta)) {
        $retVal .= "<tr><td valign=\"top\">Comment:</td><td>" . tfb_htmlencode($btmeta['comment']) . "</td></tr>";
    }
    $retVal .= "<tr><td>Created:</td><td>" . date("F j, Y, g:i a", $btmeta['creation date']) . "</td></tr>";
    $retVal .= "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")</td></tr>";
    $retVal .= "<tr><td>Chunk size:</td><td>" . $btmeta['info']['piece length'] . " (" . @formatBytesTokBMBGBTB($btmeta['info']['piece length']) . ")</td></tr>";
    if (array_key_exists('files', $btmeta['info'])) {
        $retVal .= "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
        $retVal .= "</table><br>\n";
        if ($withForm) {
            $retVal .= "<form name=\"priority\" action=\"dispatcher.php?action=setFilePriority&riid=_referer_\" method=\"POST\" >";
            $retVal .= "<input type=\"hidden\" name=\"transfer\" value=\"" . $transfer . "\" >";
        }
        $retVal .= "<script type=\"text/javascript\">\n";
        $retVal .= "var sel = 0;\n";
        $retVal .= "d = new dTree('d');\n";
        $retVal .= $tree->draw(-1);
        $retVal .= "document.write(d);\n";
        $retVal .= "sel = getSizes();\n";
        $retVal .= "drawSel();\n";
        $retVal .= "</script>\n";
        $retVal .= "<input type=\"hidden\" name=\"filecount\" value=\"" . count($btmeta['info']['files']) . "\">";
        $retVal .= "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
        $retVal .= "<br>";
        if ($withForm) {
            $retVal .= '<input type="submit" value="Save" >';
            $retVal .= "<br>";
            $retVal .= "</form>";
        }
    } else {
        $retVal .= "</table><br>";
        $retVal .= $btmeta['info']['name'] . $torrent_size . " (" . @formatBytesTokBMBGBTB($torrent_size) . ")";
    }
    // return
    return $retVal;
}
Ejemplo n.º 25
0
function showMetaInfo($torrent, $allowSave = false)
{
    global $cfg;
    if (empty($torrent) || !file_exists($cfg["torrent_file_path"] . $torrent)) {
        echo _NORECORDSFOUND;
    } elseif ($cfg["enable_file_priority"]) {
        $prioFileName = $cfg["torrent_file_path"] . getAliasName($torrent) . ".prio";
        require_once 'BDecode.php';
        echo '<link rel="StyleSheet" href="dtree.css" type="text/css" /><script type="text/javascript" src="dtree.js"></script>';
        $ftorrent = $cfg["torrent_file_path"] . $torrent;
        $fp = fopen($ftorrent, "rd");
        if (!$fp) {
            // Not able to open file
            echo _NORECORDSFOUND;
        } else {
            $alltorrent = fread($fp, filesize($ftorrent));
            fclose($fp);
            $btmeta = BDecode($alltorrent);
            $torrent_size = $btmeta["info"]["piece length"] * (strlen($btmeta["info"]["pieces"]) / 20);
            if (array_key_exists('files', $btmeta['info'])) {
                $dirnum = count($btmeta['info']['files']);
            } else {
                $dirnum = 0;
            }
            if (is_readable($prioFileName)) {
                $prio = split(',', file_get_contents($prioFileName));
                $prio = array_splice($prio, 1);
            } else {
                $prio = array();
                for ($i = 0; $i < $dirnum; $i++) {
                    $prio[$i] = -1;
                }
            }
            $tree = new dir("/", $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1);
            if (array_key_exists('files', $btmeta['info'])) {
                foreach ($btmeta['info']['files'] as $filenum => $file) {
                    $depth = count($file['path']);
                    $branch =& $tree;
                    for ($i = 0; $i < $depth; $i++) {
                        if ($i != $depth - 1) {
                            $d =& $branch->findDir($file['path'][$i]);
                            if ($d) {
                                $branch =& $d;
                            } else {
                                $dirnum++;
                                $d =& $branch->addDir(new dir($file['path'][$i], $dirnum, isset($prio[$dirnum]) ? $prio[$dirnum] : -1));
                                $branch =& $d;
                            }
                        } else {
                            $branch->addFile(new file($file['path'][$i] . " (" . $file['length'] . ")", $filenum, $file['length'], $prio[$filenum]));
                        }
                    }
                }
            }
            echo "<table><tr>";
            echo "<tr><td width=\"110\">Metainfo File:</td><td>" . $torrent . "</td></tr>";
            echo "<tr><td>Directory Name:</td><td>" . htmlentities($btmeta['info']['name'], ENT_QUOTES) . "</td></tr>";
            echo "<tr><td>Announce URL:</td><td>" . htmlentities($btmeta['announce'], ENT_QUOTES) . "</td></tr>";
            if (array_key_exists('comment', $btmeta)) {
                echo "<tr><td valign=\"top\">Comment:</td><td>" . htmlentities($btmeta['comment'], ENT_QUOTES) . "</td></tr>";
            }
            echo "<tr><td>Created:</td><td>" . date("F j, Y, g:i a", $btmeta['creation date']) . "</td></tr>";
            echo "<tr><td>Torrent Size:</td><td>" . $torrent_size . " (" . formatBytesToKBMGGB($torrent_size) . ")</td></tr>";
            echo "<tr><td>Chunk size:</td><td>" . $btmeta['info']['piece length'] . " (" . formatBytesToKBMGGB($btmeta['info']['piece length']) . ")</td></tr>";
            if (array_key_exists('files', $btmeta['info'])) {
                echo "<tr><td>Selected size:</td><td id=\"sel\">0</td></tr>";
                echo "</table><br>\n";
                if ($allowSave) {
                    echo "<form name=\"priority\" action=\"index.php\" method=\"POST\" >";
                    echo "<input type=\"hidden\" name=\"torrent\" value=\"" . $torrent . "\" >";
                    echo "<input type=\"hidden\" name=\"setPriorityOnly\" value=\"true\" >";
                }
                echo "<script type=\"text/javascript\">\n";
                echo "var sel = 0;\n";
                echo "d = new dTree('d');\n";
                $tree->draw(-1);
                echo "document.write(d);\n";
                echo "sel = getSizes();\n";
                echo "drawSel();\n";
                echo "</script>\n";
                echo "<input type=\"hidden\" name=\"filecount\" value=\"" . count($btmeta['info']['files']) . "\">";
                echo "<input type=\"hidden\" name=\"count\" value=\"" . $dirnum . "\">";
                echo "<br>";
                if ($allowSave) {
                    echo '<input type="submit" value="Save" >';
                    echo "<br>";
                }
                echo "</form>";
            } else {
                echo "</table><br>";
                echo htmlentities($btmeta['info']['name'] . $torrent_size . " (" . formatBytesToKBMGGB($torrent_size) . ")", ENT_QUOTES);
            }
        }
    } else {
        $result = shell_exec("cd " . $cfg["torrent_file_path"] . "; " . $cfg["pythonCmd"] . " -OO " . $cfg["btshowmetainfo"] . " " . escapeshellarg($torrent));
        echo "<pre>";
        echo htmlentities($result, ENT_QUOTES);
        echo "</pre>";
    }
}
Ejemplo n.º 26
0
 function gOOGLE($htmlLine)
 {
     $tmpVal = substr($htmlLine, strpos($htmlLine, "<a"));
     $tmpVal = trim($tmpVal);
     if (strlen($tmpVal) > 0) {
         $this->Data = $htmlLine;
         $tmpVal2 = substr($tmpVal, strpos($tmpVal, "href=\"") + strlen("href=\""));
         $this->torrentFile = substr($tmpVal2, 0, strpos($tmpVal2, "\""));
         $html = FetchHTMLNoWaitNoFollow($this->torrentFile);
         // Make sure we have a torrent file
         if (strpos($html, "d8:") === false) {
             // We don't have a Torrent File... it is something else
             $this->torrentFile = "";
         } else {
             $array = BDecode($html);
             $this->torrentSize = formatBytesToKBMGGB($array["info"]["piece length"] * (strlen($array["info"]["pieces"]) / 20));
             $this->torrentName = $array['info']['name'];
             $this->fileCount = count($array['info']['files']);
             $this->torrentDisplayName = $array['info']['name'];
             if (array_key_exists('comment', $array)) {
                 $this->torrentDisplayName .= " [" . $array['comment'] . "]";
             }
         }
         /*
                     $this->Seeds = $this->cleanLine($tmpListArr["4"]);  // Seeds
                     $this->Peers = $this->cleanLine($tmpListArr["5"]);  // Peers
         */
         if ($this->Peers == '') {
             $this->Peers = "N/A";
             if (empty($this->Seeds)) {
                 $this->Seeds = "N/A";
             }
         }
         if ($this->Seeds == '') {
             $this->Seeds = "N/A";
         }
         if (strlen($this->torrentDisplayName) > 50) {
             $this->torrentDisplayName = substr($this->torrentDisplayName, 0, 50) . "...";
         }
     }
 }
Ejemplo n.º 27
0
    stdfoot();
    exit;
}
if (isset($_FILES["torrent"])) {
    if ($_FILES["torrent"]["error"] != 4) {
        $fd = fopen($_FILES["torrent"]["tmp_name"], "rb") or stderr($language["ERROR"], $language["FILE_UPLOAD_ERROR_1"]);
        is_uploaded_file($_FILES["torrent"]["tmp_name"]) or stderr($language["ERROR"], $language["FILE_UPLOAD_ERROR_2"]);
        $length = filesize($_FILES["torrent"]["tmp_name"]);
        if ($length) {
            $alltorrent = fread($fd, $length);
        } else {
            err_msg($language["ERROR"], $language["FILE_UPLOAD_ERROR_3"]);
            stdfoot();
            exit;
        }
        $array = BDecode($alltorrent);
        if (!isset($array)) {
            err_msg($language["ERROR"], $language["ERR_PARSER"]);
            stdfoot();
            exit;
        }
        if (!$array) {
            err_msg($language["ERROR"], $language["ERR_PARSER"]);
            stdfoot();
            exit;
        }
        if (in_array($array["announce"], $TRACKER_ANNOUNCEURLS) && $DHT_PRIVATE) {
            $array["info"]["private"] = 1;
            $hash = sha1(BEncode($array["info"]));
        } else {
            $hash = sha1(BEncode($array["info"]));
Ejemplo n.º 28
0
function getDownloadSize($torrent)
{
    $rtnValue = "";
    if (file_exists($torrent)) {
        include_once "BDecode.php";
        $fd = fopen($torrent, "rd");
        $alltorrent = fread($fd, filesize($torrent));
        $array = BDecode($alltorrent);
        fclose($fd);
        $rtnValue = $array["info"]["piece length"] * (strlen($array["info"]["pieces"]) / 20);
    }
    return $rtnValue;
}
Ejemplo n.º 29
-1
 /**
  * get torrent from URL. Has support for specific sites
  *
  * @param $durl
  * @return string
  */
 function instance_getTorrent($durl)
 {
     global $cfg;
     // (re)set state
     $this->state = SIMPLEHTTP_STATE_NULL;
     // (re)set redir-count
     $this->redirectCount = 0;
     // Initialize file name:
     $this->filename = "";
     $domain = parse_url($durl);
     // Check we have a remote URL:
     if (!isset($domain["host"])) {
         // Not a remote URL:
         $msg = "The torrent requested for download (" . $durl . ") is not a remote torrent. Please enter a valid remote torrent URL such as http://example.com/example.torrent\n";
         AuditAction($cfg["constants"]["error"], $msg);
         array_push($this->messages, $msg);
         // state
         $this->state = SIMPLEHTTP_STATE_ERROR;
         // return empty data:
         return $data = "";
     }
     if (strtolower(substr($domain["path"], -8)) != ".torrent") {
         /*
         	In these cases below, we check for torrent URLs that have to be manipulated in some
         	way to obtain the torrent content.  These are sites that perhaps use redirection or
         	URL rewriting in some way.
         */
         // Check known domain types
         // mininova
         if (strpos(strtolower($domain["host"]), "mininova") !== false) {
             // Sample (http://www.mininova.org/rss.xml):
             // http://www.mininova.org/tor/2254847
             // <a href="/get/2281554">FreeLinux.ISO.iso.torrent</a>
             // If received a /tor/ get the required information
             if (strpos($durl, "/tor/") !== false) {
                 // Get the contents of the /tor/ to find the real torrent name
                 $data = $this->instance_getData($durl);
                 // Check for the tag used on mininova.org
                 if (preg_match("/<a href=\"\\/get\\/[0-9].[^\"]+\">(.[^<]+)<\\/a>/i", $data, $data_preg_match)) {
                     // This is the real torrent filename
                     $this->filename = $data_preg_match[1];
                 }
                 // Change to GET torrent url
                 $durl = str_replace("/tor/", "/get/", $durl);
             }
             // Now fetch the torrent file
             $data = $this->instance_getData($durl);
             // demonoid
         } elseif (strpos(strtolower($domain["host"]), "demonoid") !== false) {
             // Sample (http://www.demonoid.com/rss/0.xml):
             // http://www.demonoid.com/files/details/241739/6976998/
             // <a href="/files/download/HTTP/241739/6976998">...</a>
             // If received a /details/ page url, change it to the download url
             if (strpos($durl, "/details/") !== false) {
                 // Need to make it grab the torrent
                 $durl = str_replace("/details/", "/download/HTTP/", $durl);
             }
             // Now fetch the torrent file
             $data = $this->instance_getData($durl);
             // isohunt
         } elseif (strpos(strtolower($domain["host"]), "isohunt") !== false) {
             // Sample (http://isohunt.com/js/rss.php):
             $treferer = "http://" . $domain["host"] . "/btDetails.php?id=";
             // http://isohunt.com/torrent_details/7591035/
             // http://isohunt.com/download/7591035/
             // If the url points to the details page, change it to the download url
             if (strpos($durl, "/torrent_details/") !== false) {
                 // Need to make it grab the torrent
                 $durl = str_replace("/torrent_details/", "/download/", $durl);
             }
             // old one, but still works:
             // http://isohunt.com/btDetails.php?ihq=&id=8464972
             // http://isohunt.com/download.php?mode=bt&id=8837938
             // If the url points to the details page, change it to the download url
             if (strpos(strtolower($durl), "/btdetails.php?") !== false) {
                 // Need to make it grab the torrent
                 $durl = str_replace("/btDetails.php?", "/download.php?", $durl) . "&mode=bt";
             }
             // Now fetch the torrent file
             $data = $this->instance_getData($durl, $treferer);
             // details.php
         } elseif (strpos(strtolower($durl), "details.php?") !== false) {
             // Sample (http://www.bitmetv.org/rss.php?passkey=123456):
             // http://www.bitmetv.org/details.php?id=18435&hit=1
             // Strip final &hit=1 if present, since it only ever returns a 302
             // redirect to the same URL without the &hit=1.
             $durl2 = preg_replace('/&hit=1$/', '', $durl);
             $treferer = "http://" . $domain["host"] . "/details.php?id=";
             $data = $this->instance_getData($durl2, $treferer);
             // Sample (http://www.bitmetv.org/details.php?id=18435)
             // download.php/18435/SpiderMan%20Season%204.torrent
             if (preg_match("/(download.php.[^\"]+)/i", $data, $data_preg_match)) {
                 $torrent = substr($data_preg_match[0], 0, -1);
                 $turl2 = "http://" . $domain["host"] . "/" . $torrent;
                 $data = $this->instance_getData($turl2);
             } else {
                 $msg = "Error: could not find link to torrent file in {$durl}";
                 AuditAction($cfg["constants"]["error"], $msg);
                 array_push($this->messages, $msg);
                 // state
                 $this->state = SIMPLEHTTP_STATE_ERROR;
                 // return empty data:
                 return $data = "";
             }
             // torrentspy
         } elseif (strpos(strtolower($domain["host"]), "torrentspy") !== false) {
             // Sample (http://torrentspy.com/rss.asp):
             // http://www.torrentspy.com/torrent/1166188/gentoo_livedvd_i686_installer_2007_0
             $treferer = "http://" . $domain["host"] . "/download.asp?id=";
             $data = $this->instance_getData($durl, $treferer);
             // If received a /download.asp?, a /directory.asp?mode=torrentdetails
             // or a /torrent/, extract real torrent link
             if (strpos($durl, "/download.asp?") !== false || strpos($durl, "/directory.asp?mode=torrentdetails") !== false || strpos($durl, "/torrent/") !== false) {
                 // Check for the tag used in download details page
                 if (preg_match("#<a\\s+id=\"downloadlink0\"[^>]*?\\s+href=\"(http[^\"]+)\"#i", $data, $data_preg_match)) {
                     // This is the real torrent download link
                     $durl = $data_preg_match[1];
                     // Follow it
                     $data = $this->instance_getData($durl);
                 }
             }
             // download.asp
         } elseif (strpos(strtolower($durl), "download.asp?") !== false) {
             $treferer = "http://" . $domain["host"] . "/download.asp?id=";
             $data = $this->instance_getData($durl, $treferer);
             // default
         } else {
             // Fallback case for any URL not ending in .torrent and not matching the above cases:
             $data = $this->instance_getData($durl);
         }
     } else {
         $data = $this->instance_getData($durl);
     }
     // Make sure we have a torrent file
     if (strpos($data, "d8:") === false) {
         // We don't have a Torrent File... it is something else.  Let the user know about it:
         $msg = "Content returned from {$durl} does not appear to be a valid torrent.";
         AuditAction($cfg["constants"]["error"], $msg);
         array_push($this->messages, $msg);
         // Display the first part of $data if debuglevel higher than 1:
         if ($cfg["debuglevel"] > 1) {
             if (strlen($data) > 0) {
                 array_push($this->messages, "Displaying first 1024 chars of output: ");
                 array_push($this->messages, htmlentities(substr($data, 0, 1023)), ENT_QUOTES);
             } else {
                 array_push($this->messages, "Output from {$durl} was empty.");
             }
         } else {
             array_push($this->messages, "Set debuglevel > 2 in 'Admin, Webapps' to see the content returned from {$durl}.");
         }
         $data = "";
         // state
         $this->state = SIMPLEHTTP_STATE_ERROR;
     } else {
         // If the torrent file name isn't set already, do it now:
         if (!isset($this->filename) || strlen($this->filename) == 0) {
             // Get the name of the torrent, and make it the filename
             if (preg_match("/name([0-9][^:]):(.[^:]+)/i", $data, $data_preg_match)) {
                 $filelength = $data_preg_match[1];
                 $file_name = $data_preg_match[2];
                 $this->filename = substr($file_name, 0, $filelength) . ".torrent";
             } else {
                 require_once 'inc/classes/BDecode.php';
                 $btmeta = @BDecode($data);
                 $this->filename = is_array($btmeta) && !empty($btmeta['info']) && !empty($btmeta['info']['name']) ? trim($btmeta['info']['name']) . ".torrent" : "";
             }
         }
         // state
         $this->state = SIMPLEHTTP_STATE_OK;
     }
     return $data;
 }
Ejemplo n.º 30
-1
function apms_get_torrent($attach, $path = '')
{
    global $g5;
    $arr = array();
    $torrent = array();
    if ($path) {
        $j = 0;
        for ($i = 0; $i < count($attach); $i++) {
            if (isset($attach[$i]['source']) && $attach[$i]['source'] && $attach[$i]['view']) {
                continue;
            }
            $ext = apms_get_ext($attach[$i]['source']);
            if ($ext != 'torrent') {
                continue;
            }
            $arr[$j] = $path . '/' . $attach[$i]['file'];
            $j++;
        }
    } else {
        if (!$attach['torrent']) {
            return;
        }
        $j = 0;
        for ($i = 0; $i < count($attach); $i++) {
            if ($attach[$i]['ext'] != "6") {
                continue;
            }
            $arr[$j] = G5_DATA_PATH . '/item/' . $attach[$i]['id'] . '/' . $attach[$i]['file'];
            $j++;
        }
    }
    require_once G5_LIB_PATH . '/apms.torrent.lib.php';
    for ($i = 0; $i < count($arr); $i++) {
        $torrent_file = file_get_contents($arr[$i]);
        $torrent_array = BDecode($torrent_file);
        $torrent_hash = sha1(BEncode($torrent_array['info']));
        $torrent[$i]['name'] = $torrent_array['info']['name'];
        $torrent[$i]['magnet'] = 'magnet:?xt=urn:btih:' . $torrent_hash;
        for ($k = 0; $k < count($torrent_array['announce-list']); $k++) {
            $torrent[$i]['tracker'][$k] = $torrent_array['announce-list'][$k][0];
        }
        $torrent[$i]['comment'] = $torrent_array['comment'];
        $torrent[$i]['date'] = $torrent_array['creation date'];
        $torrent[$i]['is_size'] = $torrent_array['info']['length'] ? true : false;
        if ($torrent[$i]['is_size']) {
            $torrent[$i]['info']['name'] = $torrent_array['info']['name'];
            $torrent[$i]['info']['size'] = get_filesize($torrent_array['info']['length']);
        } else {
            $total_size = 0;
            for ($k = 0; $k < count($torrent_array['info']['files']); $k++) {
                for ($l = 0; $l < count($torrent_array['info']['files'][$k]['path']); $l++) {
                    $torrent[$i]['info']['file'][$k]['name'][$l] = $torrent_array['info']['files'][$k]['path'][$l];
                }
                $torrent[$i]['info']['file'][$k]['size'] = get_filesize($torrent_array['info']['files'][$k]['length']);
                $total_size = $total_size + $torrent_array['info']['files'][$k]['length'];
            }
            $torrent[$i]['info']['total_size'] = get_filesize($total_size);
        }
    }
    return $torrent;
}