Built on the technologies developed and maintained by April-Child.com Copyright (c)2007 Petr Krontorad, April-Child.com. Author: Petr Krontorad, petr@krontorad.com All rights reserved. ------------------------------------------------------------------------------------------
Exemplo n.º 1
0
function paste_content()
{
    include 'lib/amy/simple_http.php';
    $url = parse_url($_REQUEST['frame_url']);
    $headers = array();
    $params = array();
    $query = explode('=', $url['query']);
    $n = sizeof($query);
    for ($i = 0; $i < $n; $i += 2) {
        $params[$query[$i]] = $query[$i + 1];
    }
    $response = SimpleHTTP::send('GET', $url['host'], 80, $url['path'], $params, $headers);
    echo $response['body'];
}
 function makeRequest($request, $useAlt = false)
 {
     $refererURI = isset($_SESSION['lastOutBoundURI']) ? $_SESSION['lastOutBoundURI'] : "http://" . $this->mainURL;
     $request = $useAlt ? "http://" . $this->altURL . $request : "http://" . $this->mainURL . $request;
     // require SimpleHTTP
     require_once "inc/classes/SimpleHTTP.php";
     // get data
     $this->htmlPage = SimpleHTTP::getData($request, $refererURI);
     // return
     return SimpleHTTP::getState() == SIMPLEHTTP_STATE_OK;
 }
/**
 * (internal) Function with which metafiles are downloaded and injected
 *
 * @param $url url to download
 * @param $type
 */
function _dispatcher_processDownload($url, $type = 'torrent', $ext = '.torrent')
{
    global $cfg;
    $filename = "";
    $downloadMessages = array();
    if (!empty($url)) {
        $arURL = explode("/", $url);
        $filename = urldecode($arURL[count($arURL) - 1]);
        // get the file name
        $filename = str_replace(array("'", ","), "", $filename);
        $filename = stripslashes($filename);
        // Check to see if url has something like ?passkey=12345
        // If so remove it.
        if (($point = strrpos($filename, "?")) !== false) {
            $filename = substr($filename, 0, $point);
        }
        $ret = strrpos($filename, ".");
        if ($ret === false) {
            $filename .= $ext;
        } else {
            if (!strcmp(strtolower(substr($filename, -strlen($ext))), $ext) == 0) {
                $filename .= $ext;
            }
        }
        $url = str_replace(" ", "%20", $url);
        // This is to support Sites that pass an id along with the url for downloads.
        $tmpId = tfb_getRequestVar("id");
        if (!empty($tmpId)) {
            $url .= "&id=" . $tmpId;
        }
        // retrieve the file
        require_once "inc/classes/SimpleHTTP.php";
        $content = "";
        switch ($type) {
            default:
            case 'torrent':
                $content = SimpleHTTP::getTorrent($url);
                break;
            case 'nzb':
                $content = SimpleHTTP::getNzb($url);
                break;
        }
        if (SimpleHTTP::getState() == SIMPLEHTTP_STATE_OK && strlen($content) > 0) {
            $fileNameBackup = $filename;
            $filename = SimpleHTTP::getFilename();
            if ($filename != "") {
                $filename = strpos($filename, $ext) !== false ? tfb_cleanFileName($filename) : tfb_cleanFileName($filename . $ext);
            }
            if ($filename == "" || $filename === false || transferExists($filename)) {
                $filename = tfb_cleanFileName($fileNameBackup);
                if ($filename === false || transferExists($filename)) {
                    $filename = tfb_cleanFileName($url . $ext);
                    if ($filename === false || transferExists($filename)) {
                        $filename = tfb_cleanFileName(md5($url . strval(@microtime())) . $ext);
                        if ($filename === false || transferExists($filename)) {
                            // Error
                            array_push($downloadMessages, "failed to get a valid transfer-filename for " . $url);
                        }
                    }
                }
            }
            if (empty($downloadMessages)) {
                // no messages
                // check if content contains html
                if ($cfg['debuglevel'] > 0) {
                    if (strpos($content, "<br />") !== false) {
                        AuditAction($cfg["constants"]["debug"], "download-content contained html : " . htmlentities(addslashes($url), ENT_QUOTES));
                    }
                }
                if (is_file($cfg["transfer_file_path"] . $filename)) {
                    // Error
                    array_push($downloadMessages, "the file " . $filename . " already exists on the server.");
                } else {
                    // write to file
                    $handle = false;
                    $handle = @fopen($cfg["transfer_file_path"] . $filename, "w");
                    if (!$handle) {
                        array_push($downloadMessages, "cannot open " . $filename . " for writing.");
                    } else {
                        $result = @fwrite($handle, $content);
                        @fclose($handle);
                        if ($result === false) {
                            array_push($downloadMessages, "cannot write content to " . $filename . ".");
                        }
                    }
                }
            }
        } else {
            $msgs = SimpleHTTP::getMessages();
            if (count($msgs) > 0) {
                $downloadMessages = array_merge($downloadMessages, $msgs);
            }
        }
        if (empty($downloadMessages)) {
            // no messages
            AuditAction($cfg["constants"]["url_upload"], $filename);
            // inject
            injectTransfer($filename);
            // instant action ?
            $actionId = tfb_getRequestVar('aid');
            if ($actionId > 1) {
                $ch = ClientHandler::getInstance(getTransferClient($filename));
                switch ($actionId) {
                    case 3:
                        $ch->start($filename, false, true);
                        break;
                    case 2:
                        $ch->start($filename, false, false);
                        break;
                }
                if (count($ch->messages) > 0) {
                    $downloadMessages = array_merge($downloadMessages, $ch->messages);
                }
            }
        }
    } else {
        array_push($downloadMessages, "Invalid Url : " . $url);
    }
    if (count($downloadMessages) > 0) {
        AuditAction($cfg["constants"]["error"], $cfg["constants"]["url_upload"] . " :: " . $filename);
        @error("There were Problems", "", "", $downloadMessages);
    }
}
Exemplo n.º 4
0
 public static function normalizeTXID($txid)
 {
     return trim(SimpleHTTP::get('https://blockchain.info/q/hashtontxid/' . $txid));
 }
/**
 * get the full size of a transfer
 *
 * @param $transfer
 * @return int
 */
function getTransferSize($transfer)
{
    global $cfg;
    // client-switch
    if (substr($transfer, -8) == ".torrent") {
        // this is a t-client
        $file = $cfg["transfer_file_path"] . $transfer;
        if ($fd = @fopen($file, "rd")) {
            require_once "inc/classes/BDecode.php";
            $alltorrent = @fread($fd, @filesize($file));
            $array = BDecode($alltorrent);
            @fclose($fd);
        }
        return isset($array["info"]["piece length"]) && isset($array["info"]["pieces"]) ? $array["info"]["piece length"] * (strlen($array["info"]["pieces"]) / 20) : 0;
    } else {
        if (substr($transfer, -5) == ".wget") {
            // this is wget.
            $ch = ClientHandler::getInstance('wget');
            $ch->setVarsFromFile($transfer);
            require_once "inc/classes/SimpleHTTP.php";
            return SimpleHTTP::getRemoteSize($ch->url);
        } else {
            if (substr($transfer, -4) == ".nzb") {
                // this is nzbperl.
                require_once "inc/classes/NZBFile.php";
                $nzb = new NZBFile($transfer);
                return $nzb->size;
            }
        }
    }
    return 0;
}
Exemplo n.º 6
0
 /**
  * download and save a torrent-file
  *
  * @return boolean
  */
 function _saveTorrent($url, $title)
 {
     global $cfg;
     $content = SimpleHTTP::getTorrent($url);
     if (SimpleHTTP::getState() == SIMPLEHTTP_STATE_OK) {
         // filename
         $filename = SimpleHTTP::getFilename();
         if ($filename != "") {
             $filename = strpos($filename, ".torrent") !== false ? tfb_cleanFileName($filename) : tfb_cleanFileName($filename . ".torrent");
         }
         if ($filename == "" || $filename === false || transferExists($filename)) {
             $filename = tfb_cleanFileName($title . ".torrent");
             if ($filename === false || transferExists($filename)) {
                 $filename = tfb_cleanFileName($url . ".torrent");
                 if ($filename === false || transferExists($filename)) {
                     $filename = tfb_cleanFileName(md5($url . strval(@microtime())) . ".torrent");
                     if ($filename === false || transferExists($filename)) {
                         // Error
                         $msg = "failed to get a valid transfer-filename for " . $url;
                         array_push($this->messages, $msg);
                         AuditAction($cfg["constants"]["error"], "Rssd downloadMetafile-Error : " . $msg);
                         $this->_outputError($msg . "\n");
                         return false;
                     }
                 }
             }
         }
         // file
         $file = $this->_dirSave . $filename;
         // check if file already exists
         if (@is_file($file)) {
             // Error
             $msg = "the file " . $file . " already exists in " . $this->_dirSave;
             array_push($this->messages, $msg);
             AuditAction($cfg["constants"]["error"], "Rssd downloadMetafile-Error : " . $msg);
             $this->_outputError($msg . "\n");
             return false;
         }
         // write file
         $handle = false;
         $handle = @fopen($file, "w");
         if (!$handle) {
             $msg = "cannot open " . $file . " for writing.";
             array_push($this->messages, $msg);
             AuditAction($cfg["constants"]["error"], "Rssd downloadMetafile-Error : " . $msg);
             $this->_outputError($msg . "\n");
             return false;
         }
         $result = @fwrite($handle, $content);
         @fclose($handle);
         if ($result === false) {
             $msg = "cannot write content to " . $file . ".";
             array_push($this->messages, $msg);
             AuditAction($cfg["constants"]["error"], "Rssd downloadMetafile-Error : " . $msg);
             $this->_outputError($msg . "\n");
             return false;
         }
         // add to file-array
         array_push($this->_filesSaved, array('url' => $url, 'title' => $title, 'filename' => $filename, 'file' => $file));
         // output
         $this->_outputMessage("torrent saved : \n url: " . $url . "\n file: " . $file . "\n");
         // return
         return true;
     } else {
         // last op was not ok
         $msgs = SimpleHTTP::getMessages();
         $this->_outputError("could not download torrent with title " . $title . " from url " . $url . " : \n" . implode("\n", $msgs));
         return false;
     }
 }
Exemplo n.º 7
0
 function Parse($rss_url)
 {
     // Load RSS file
     require_once "inc/classes/SimpleHTTP.php";
     $rss_content = SimpleHTTP::getData($rss_url);
     if (SimpleHTTP::getState() != SIMPLEHTTP_STATE_OK) {
         // last op was not ok
         // log
         global $cfg;
         $msgs = SimpleHTTP::getMessages();
         AuditAction($cfg["constants"]["error"], "lastRSS: could not download feed-data from url " . $rss_url . " (" . implode("; ", $msgs) . ")");
         // return false
         return false;
     }
     // result-array
     $result = array();
     // document encoding
     $result['encoding'] = $this->my_preg_match("'encoding=[\\'\"](.*?)[\\'\"]'si", $rss_content);
     // if document codepage is specified, use it
     if ($result['encoding'] != '') {
         $this->rsscp = $result['encoding'];
         // This is used in my_preg_match()
     } else {
         // otherwise use the default codepage
         $this->rsscp = $this->default_cp;
         // This is used in my_preg_match()
     }
     // CHANNEL info
     if (preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel)) {
         foreach ($this->_channeltags as $channeltag) {
             $temp = $this->my_preg_match("'<{$channeltag}.*?>(.*?)</{$channeltag}>'si", $out_channel[1]);
             if ($temp != '') {
                 $result[$channeltag] = $temp;
             }
             // Set only if not empty
         }
     }
     // If date_format is specified and lastBuildDate is valid
     if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !== -1) {
         // convert lastBuildDate to specified date format
         $result['lastBuildDate'] = date($this->date_format, $timestamp);
     }
     // TEXTINPUT info
     preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
     // This a little strange regexp means:
     // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beginning tag)
     if (isset($out_textinfo[2])) {
         foreach ($this->_textinputtags as $textinputtag) {
             $temp = $this->my_preg_match("'<{$textinputtag}.*?>(.*?)</{$textinputtag}>'si", $out_textinfo[2]);
             if ($temp != '') {
                 $result['textinput_' . $textinputtag] = $temp;
             }
             // Set only if not empty
         }
     }
     // IMAGE info
     preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
     if (isset($out_imageinfo[1])) {
         foreach ($this->_imagetags as $imagetag) {
             $temp = $this->my_preg_match("'<{$imagetag}.*?>(.*?)</{$imagetag}>'si", $out_imageinfo[1]);
             if ($temp != '') {
                 $result['image_' . $imagetag] = $temp;
             }
             // Set only if not empty
         }
     }
     // ITEMS
     preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
     $rss_items = $items[2];
     $i = 0;
     $result['items'] = array();
     // create array even if there are no items
     foreach ($rss_items as $rss_item) {
         // If number of items is lower then limit: parse one item
         if ($i < $this->items_limit || $this->items_limit == 0) {
             foreach ($this->_itemtags as $itemtag) {
                 $temp = $this->my_preg_match("'<{$itemtag}.*?>(.*?)</{$itemtag}>'si", $rss_item);
                 if ($temp != '') {
                     $result['items'][$i][$itemtag] = $temp;
                 }
                 // Set only if not empty
             }
             // Strip HTML tags and other bullshit from DESCRIPTION
             if ($this->stripHTML && $result['items'][$i]['description']) {
                 $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
             }
             // Strip HTML tags and other bullshit from TITLE
             if ($this->stripHTML && $result['items'][$i]['title']) {
                 $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
             }
             // If date_format is specified and pubDate is valid
             if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !== -1) {
                 // convert pubDate to specified date format
                 $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
             }
             // Item counter
             $i++;
         }
     }
     $result['items_count'] = $i;
     return $result;
 }
Exemplo n.º 8
0
 function makeRequest($request, $useAlt = false)
 {
     $refererURI = isset($_SESSION['lastOutBoundURI']) ? $_SESSION['lastOutBoundURI'] : "http://" . $this->mainURL;
     $request = $useAlt ? "http://" . $this->altURL . $request : "http://" . $this->mainURL . $request;
     // get data
     require_once "inc/classes/SimpleHTTP.php";
     $http = SimpleHTTP::getInstance();
     //utf-8 prefered
     $http->charset = $this->cfg['_CHARSET'];
     $http->method = $this->method;
     $http->postquery = $this->postquery;
     $this->htmlPage = $http->instance_getData($request, $refererURI);
     $this->htmlPage = setCharset($this->htmlPage, $http->charset);
     $this->lastRequest = $request;
     // return
     return $http->state == SIMPLEHTTP_STATE_OK;
 }
Exemplo n.º 9
0
 private function calculateBalance($confirmations = false)
 {
     $addr = $this->addr->get();
     $blockHeight = 0;
     if ($confirmations !== false) {
         $blockHeight = intval(HTTP::get('https://blockchain.info/q/getblockcount'));
     }
     Debug::log('Block height: ' . $blockHeight);
     $balance = 0;
     foreach ($this->txs as $tx) {
         if ($tx['double_spend']) {
             Debug::log('Double spend: ' . $tx['tx_index']);
             continue;
         }
         foreach ($tx['inputs'] as $in) {
             if (isset($in['prev_out']['addr'])) {
                 if ($confirmations !== false) {
                     if (!isset($tx['block_height'])) {
                         if ($confirmations !== 0) {
                             continue 2;
                         }
                     }
                     $blockReq = $tx['block_height'] + $confirmations;
                     if ($blockReq > $blockHeight) {
                         continue 2;
                     }
                 }
             }
         }
         foreach ($tx['out'] as $out) {
             if ($out['addr'] !== $addr) {
                 continue;
             }
             $balance += $out['value'];
         }
     }
     return Amount::fromSatoshis($balance);
 }
Exemplo n.º 10
0
function _dir_WgetFile($url, $target_dir)
{
    require_once 'inc/functions/functions.core.tfb.php';
    global $cfg;
    $filename = "";
    $downloadMessages = array();
    if (!empty($url)) {
        $arURL = explode("/", $url);
        $filename = urldecode($arURL[count($arURL) - 1]);
        // get the file name
        $filename = str_replace(array("'", ","), "", $filename);
        $filename = stripslashes($filename);
        // Check to see if url has something like ?passkey=12345
        // If so remove it.
        if (($point = strrpos($filename, "?")) !== false) {
            $filename = substr($filename, 0, $point);
        }
        $ret = strrpos($filename, ".");
        $url = str_replace(" ", "%20", $url);
        // This is to support Sites that pass an id along with the url for downloads.
        $tmpId = tfb_getRequestVar("id");
        if (!empty($tmpId)) {
            $url .= "&id=" . $tmpId;
        }
        // retrieve the file
        require_once "inc/classes/SimpleHTTP.php";
        $content = SimpleHTTP::getData($url);
        if (SimpleHTTP::getState() == SIMPLEHTTP_STATE_OK && strlen($content) > 0) {
            $fileNameBackup = $filename;
            $filename = SimpleHTTP::getFilename();
            if ($filename != "") {
                $filename = _dir_cleanFileName($filename);
            }
            if ($filename == "" || $filename === false) {
                $filename = _dir_cleanFileName($fileNameBackup);
                if ($filename === false || $filename == "") {
                    $filename = _dir_cleanFileName(SimpleHTTP::getRealUrl($url));
                    if ($filename === false || $filename == "") {
                        $filename = _dir_cleanFileName(md5($url . strval(@microtime())));
                        if ($filename === false || $filename == "") {
                            // Error
                            array_push($downloadMessages, "failed to get a valid filename for " . $url);
                        }
                    }
                }
            }
            if (empty($downloadMessages)) {
                // no messages
                // check if content contains html
                if ($cfg['debuglevel'] > 0) {
                    if (strpos($content, "<br />") !== false) {
                        AuditAction($cfg["constants"]["debug"], "download-content contained html : " . htmlentities(addslashes($url), ENT_QUOTES));
                    }
                }
                if (is_file($target_dir . $filename)) {
                    // Error
                    array_push($downloadMessages, "the file " . $filename . " already exists on the server.");
                } else {
                    // write to file
                    $handle = false;
                    $handle = @fopen($target_dir . $filename, "w");
                    if (!$handle) {
                        array_push($downloadMessages, "cannot open " . $target_dir . $filename . " for writing.");
                    } else {
                        $result = @fwrite($handle, $content);
                        @fclose($handle);
                        if ($result === false) {
                            array_push($downloadMessages, "cannot write content to " . $filename . ".");
                        }
                    }
                }
            }
        } else {
            $msgs = SimpleHTTP::getMessages();
            if (count($msgs) > 0) {
                $downloadMessages = array_merge($downloadMessages, $msgs);
            }
        }
        if (empty($downloadMessages)) {
            // no messages
            AuditAction($cfg["constants"]["url_upload"], $filename);
        }
    } else {
        array_push($downloadMessages, "Invalid Url : " . $url);
    }
    if (count($downloadMessages) > 0) {
        AuditAction($cfg["constants"]["error"], $cfg["constants"]["url_upload"] . " :: " . $filename);
        @error("There were Problems", "", "", $downloadMessages);
    }
}
/**
 * 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;
    }
}
Exemplo n.º 12
0
 /**
  * get size from URL.
  *
  * @param $durl
  * @return int
  */
 function getRemoteSize($durl)
 {
     global $instanceSimpleHTTP;
     // initialize if needed
     if (!isset($instanceSimpleHTTP)) {
         SimpleHTTP::initialize();
     }
     // call instance-method
     return $instanceSimpleHTTP->instance_getRemoteSize($durl);
 }
Exemplo n.º 13
0
 public static function save_resource($project_url, $ticket, $path, $content)
 {
     $url = fix_parse_url($project_url);
     $response = SimpleHTTP::send('POST', $url['host'], $url['port'], $url['path'], array('a' => 'save_resource', 'ticket' => $ticket, 'path' => $path, 'content' => $content));
     if ('200' != $response['status_code']) {
         throw new Exception("Invalid status code `{$response['status_code']}' returned from server `{$url['host']}'.");
     }
     $content = trim($response['body']);
     if ('' === $content) {
         throw new Exception("Unable to save project resource, no content returned from `{$url['host']}{$url['path']}'.");
     }
     if ('#S#' != substr($content, 0, 3)) {
         throw new Exception("Error while saving resource: Message from {$url['host']}{$url['path']}: " . substr($content, 3));
     }
     return true;
 }
Exemplo n.º 14
0
/**
 * (internal) Function with which metafiles are downloaded and injected
 *
 * @param $url url to download
 * @param $type
 */
function _dispatcher_processDownload($url, $type = 'torrent', $ext = '.torrent')
{
    global $cfg;
    $filename = "";
    $downloadMessages = array();
    $origurl = $url;
    // Added by deadeyes; copied as later $url gets changed
    if (!empty($url)) {
        $hash = false;
        // Added by deadeyes to detect a magnet link
        if ($type === 'torrent' && strlen(stristr($url, 'magnet:')) > 0) {
            $client = getTransferClient('magnet.torrent');
            // We have a magnet link :D
            if ($client == 'transmissionrpc' && $cfg["transmission_rpc_enable"]) {
                require_once 'inc/functions/functions.rpc.transmission.php';
                $hash = addTransmissionTransfer($cfg['uid'], $url, $cfg['path'] . $cfg['user']);
                if (isHash($hash)) {
                    startTransmissionTransfer($hash);
                }
            }
            if (($client == 'vuzerpc' || $client == 'azureus') && $cfg["vuze_rpc_enable"]) {
                require_once 'inc/functions/functions.rpc.vuze.php';
                $hash = addVuzeMagnetTransfer($cfg['uid'], $url, $cfg['transfer_file_path']);
            }
            if ($cfg['debuglevel'] > 0) {
                AuditAction($cfg["constants"]["debug"], "Download Magnet ({$client}) : {$hash} " . htmlentities(addslashes($url), ENT_QUOTES));
            }
        }
        if (!$hash) {
            // not a magnet torrent..
            $arURL = explode("/", $url);
            $filename = urldecode($arURL[count($arURL) - 1]);
            // get the file name
            $filename = str_replace(array("'", ","), "", $filename);
            $filename = stripslashes($filename);
            // Check to see if url has something like ?passkey=12345
            // If so remove it.
            if (($point = strrpos($filename, "?")) !== false) {
                $filename = substr($filename, 0, $point);
            }
            $ret = strrpos($filename, ".");
            if ($ret === false) {
                $filename .= $ext;
            } else {
                if (!strcmp(strtolower(substr($filename, -strlen($ext))), $ext) == 0) {
                    $filename .= $ext;
                }
            }
            $url = str_replace(" ", "%20", $url);
            // This is to support Sites that pass an id along with the url for downloads.
            $tmpId = tfb_getRequestVar("id");
            if (!empty($tmpId)) {
                $url .= "&id=" . $tmpId;
            }
            // retrieve the file
            require_once "inc/classes/SimpleHTTP.php";
            $content = "";
            switch ($type) {
                default:
                case 'torrent':
                    $content = SimpleHTTP::getTorrent($url);
                    break;
                case 'nzb':
                    $content = SimpleHTTP::getNzb($url);
                    break;
            }
            if (SimpleHTTP::getState() == SIMPLEHTTP_STATE_OK && strlen($content) > 0) {
                $fileNameBackup = $filename;
                $filename = SimpleHTTP::getFilename();
                if ($filename != "") {
                    $filename = strpos($filename, $ext) !== false ? tfb_cleanFileName($filename) : tfb_cleanFileName($filename . $ext);
                }
                if (empty($filename) || transferExists($filename)) {
                    $filename = substr($cfg['user'], 0, 3) . "_" . date('ymdHis') . "_" . sprintf('%x', crc32($filename)) . $ext;
                }
                /*
                if (($filename == "") || ($filename === false) || (transferExists($filename))) {
                	$filename = tfb_cleanFileName($fileNameBackup);
                	if (($filename === false) || (transferExists($filename))) {
                		$filename = tfb_cleanFileName($url.$ext);
                		if (($filename === false) || (transferExists($filename))) {
                			$filename = tfb_cleanFileName(md5($url.strval(@microtime())).$ext);
                			if (($filename === false) || (transferExists($filename))) {
                				// Error
                				array_push($downloadMessages , "failed to get a valid transfer-filename for ".$url);
                			}
                		}
                	}
                }
                */
                if (empty($downloadMessages)) {
                    // no messages
                    // check if content contains html
                    if ($cfg['debuglevel'] > 0) {
                        if (strpos($content, "<br />") !== false) {
                            AuditAction($cfg["constants"]["debug"], "download-content contained html : " . htmlentities(addslashes($url), ENT_QUOTES));
                        }
                    }
                    if (is_file($cfg["transfer_file_path"] . $filename)) {
                        // Error
                        array_push($downloadMessages, "the file " . $filename . " already exists on the server.");
                    } else {
                        // write to file
                        $handle = false;
                        $handle = @fopen($cfg["transfer_file_path"] . $filename, "w");
                        if (!$handle) {
                            array_push($downloadMessages, "cannot open " . $filename . " for writing.");
                        } else {
                            $result = @fwrite($handle, $content);
                            @fclose($handle);
                            if ($result === false) {
                                array_push($downloadMessages, "cannot write content to " . $filename . ".");
                            }
                        }
                    }
                }
            } else {
                $msgs = SimpleHTTP::getMessages();
                if (count($msgs) > 0) {
                    $downloadMessages = array_merge($downloadMessages, $msgs);
                }
            }
            if (empty($downloadMessages) && is_file($cfg["transfer_file_path"] . $filename)) {
                // no messages
                AuditAction($cfg["constants"]["url_upload"], $filename);
                // inject
                injectTransfer($filename);
                // instant action ?
                $actionId = tfb_getRequestVar('aid');
                if ($actionId > 1) {
                    $ch = ClientHandler::getInstance(getTransferClient($filename));
                    switch ($actionId) {
                        case 3:
                            $ch->start($filename, false, true);
                            break;
                        case 2:
                            $ch->start($filename, false, false);
                            break;
                    }
                    if (count($ch->messages) > 0) {
                        $downloadMessages = array_merge($downloadMessages, $ch->messages);
                    }
                }
            }
        }
    } else {
        array_push($downloadMessages, "Invalid Url : " . $url);
    }
    if (count($downloadMessages) > 0) {
        AuditAction($cfg["constants"]["error"], $cfg["constants"]["url_upload"] . " :: " . $filename);
        @error("There were Problems", "", "", $downloadMessages);
    }
}
Exemplo n.º 15
0
 public static function send($method, $hostname, $port, $url_path, $data = array(), $headers = array())
 {
     $method = strtoupper($method);
     if (!in_array($method, array('GET', 'POST', 'PROPFIND', 'OPTIONS', 'PUT', 'MKCOL'))) {
         $method = 'GET';
     }
     if (!is_numeric($port)) {
         $port = 80;
     }
     $s_data = array();
     if (!is_array($data)) {
         $s_data = $data;
     } else {
         foreach ($data as $key => $value) {
             $s_data[] = $key . '=' . urlencode($value);
         }
         $s_data = implode('&', $s_data);
     }
     if ('GET' == $method && 0 != strlen($s_data)) {
         $url_path .= '?' . $s_data;
         $s_data = '';
     }
     $status_code = '';
     if (!($s = @fsockopen($hostname, $port))) {
         $body = '';
         $headers = array();
         $status_code = '500';
         $status = 'HTTP/1.1 500 Internal server error or host unreachable.';
     } else {
         $content_type = 'application/x-www-form-urlencoded';
         if (isset($headers['Content-Type'])) {
             $content_type = $headers['Content-Type'];
             unset($headers['Content-Type']);
         }
         fputs($s, $method . ' ' . $url_path . " HTTP/1.1\r\n");
         fputs($s, "Host: {$hostname}\r\n");
         fputs($s, "Content-Type: {$content_type}\r\n");
         fputs($s, "Content-Length: " . strlen($s_data) . "\r\n");
         fputs($s, "Accept-Encoding: compress, gzip\r\n");
         fputs($s, "User-Agent: Gecko MSIE AppleWebKit KHTML Opera Win Mac Linux (April-Child.com simple HTTP client)\r\n");
         foreach ($headers as $name => $value) {
             fputs($s, "{$name}: {$value}\r\n");
         }
         fputs($s, "Connection: close\r\n\r\n");
         fputs($s, $s_data);
         $response = '';
         while (!feof($s)) {
             $response .= fgets($s, 128);
         }
         fclose($s);
         $headers = array();
         $body = '';
         if (false !== ($ix = strpos($response, "\r\n\r\n"))) {
             $raw_headers = explode("\r\n", substr($response, 0, $ix));
             $status = array_shift($raw_headers);
             preg_match_all('|\\d{3}|', $status, $m);
             $status_code = $m[0][0];
             foreach ($raw_headers as $header) {
                 $pair = explode(':', $header);
                 $headers[trim(strtolower($pair[0]))] = trim($pair[1]);
             }
             $body = SimpleHTTP::decode_body($headers, substr($response, $ix + 4));
         }
     }
     return array('status' => $status, 'status_code' => $status_code, 'headers' => $headers, 'body' => $body);
 }
Exemplo n.º 16
0
 public function save($path, $content)
 {
     $path = $this->get_encoded_path($path);
     $headers = array('Depth' => $depth, 'Authorization' => 'Basic ' . base64_encode($this->username . ':' . $this->password));
     $response = SimpleHTTP::send('PUT', $this->host, $this->port, $path, $content, $headers);
     return '2' == substr($response['status_code'] . '', 0, 1);
 }