protected function _getTest($path, $length, $type, $status, $expected, $message = null, $encoding = null)
 {
     $this->prepareForRequest();
     $context = new stdClass();
     $context->request = new org_tubepress_api_http_HttpRequest(org_tubepress_api_http_HttpRequest::HTTP_METHOD_GET, $this->_server . "/{$path}");
     $context->request->setHeader(org_tubepress_api_http_HttpRequest::HTTP_HEADER_USER_AGENT, 'TubePress');
     $result = $this->_sut->execute($context);
     $this->assertTrue($result, "Command did not return true that it had handled request ({$result})");
     $response = $context->response;
     $this->assertTrue($response instanceof org_tubepress_api_http_HttpResponse, 'Reponse is not of type HttpResponse');
     $actualContentType = $response->getHeaderValue(org_tubepress_api_http_HttpMessage::HTTP_HEADER_CONTENT_TYPE);
     $this->assertTrue($actualContentType === $type || $actualContentType === "{$type}; charset=utf-8", "Expected Content-Type {$type} but got {$actualContentType}");
     $encoded = $response->getHeaderValue(org_tubepress_api_http_HttpMessage::HTTP_HEADER_CONTENT_ENCODING);
     $this->assertEquals($encoding, $encoded, "Expected encoding {$encoding} but got {$encoded}");
     $this->assertEquals($status, $response->getStatusCode(), "Expected status code {$status} but got " . $response->getStatusCode());
     $entity = $response->getEntity();
     $this->assertTrue($entity instanceof org_tubepress_api_http_HttpEntity);
     if ($response->getHeaderValue(org_tubepress_api_http_HttpResponse::HTTP_HEADER_TRANSFER_ENCODING) === 'chunked') {
         $data = @http_chunked_decode($entity->getContent());
         if ($data === false) {
             $data = $entity->getContent();
         }
     } else {
         $data = $entity->getContent();
     }
     $this->assertEquals($expected, $data);
 }
/**
 * Test Http functions.
 */
function test_functions()
{
    http_cache_last_modified();
    http_chunked_decode();
    http_deflate();
    http_inflate();
    http_build_cookie();
    http_date();
    http_get_request_body_stream();
    http_get_request_body();
    http_get_request_headers();
    http_match_etag();
    http_match_modified();
    http_match_request_header();
    http_support();
    http_negotiate_charset();
    http_negotiate_content_type();
    http_negotiate_language();
    ob_deflatehandler();
    ob_etaghandler();
    ob_inflatehandler();
    http_parse_cookie();
    http_parse_headers();
    http_parse_message();
    http_parse_params();
    http_persistent_handles_clean();
    http_persistent_handles_count();
    http_persistent_handles_ident();
    http_get();
    http_head();
    http_post_data();
    http_post_fields();
    http_put_data();
    http_put_file();
    http_put_stream();
    http_request_body_encode();
    http_request_method_exists();
    http_request_method_name();
    http_request_method_register();
    http_request_method_unregister();
    http_request();
    http_redirect();
    http_send_content_disposition();
    http_send_content_type();
    http_send_data();
    http_send_file();
    http_send_last_modified();
    http_send_status();
    http_send_stream();
    http_throttle();
    http_build_str();
    http_build_url();
}
 /**
  * Send a HTTP request to a URI using HTTP extension.
  *
  * Does not support non-blocking.
  *
  * @param string    $url  The URL to handle.
  * @param str|array $args Optional. Override the defaults.
  *
  * @return array 'headers', 'body', 'cookies' and 'response' keys.
  */
 protected function _doExecute($url, $args)
 {
     switch ($args[org_tubepress_impl_http_HttpClientChain::ARGS_METHOD]) {
         case org_tubepress_api_http_HttpClient::HTTP_METHOD_POST:
             $args[org_tubepress_impl_http_HttpClientChain::ARGS_METHOD] = HTTP_METH_POST;
             break;
         case org_tubepress_api_http_HttpClient::HTTP_METHOD_PUT:
             $args[org_tubepress_impl_http_HttpClientChain::ARGS_METHOD] = HTTP_METH_PUT;
             break;
         case org_tubepress_api_http_HttpClient::HTTP_METHOD_GET:
         default:
             $args[org_tubepress_impl_http_HttpClientChain::ARGS_METHOD] = HTTP_METH_GET;
     }
     $urlAsArray = parse_url($url);
     if ('http' != $urlAsArray['scheme'] && 'https' != $urlAsArray['scheme']) {
         $url = preg_replace('|^' . preg_quote($urlAsArray['scheme'], '|') . '|', 'http', $url);
     }
     $sslVerify = isset($args[org_tubepress_impl_http_HttpClientChain::ARGS_SSL_VERIFY]) && $args[org_tubepress_impl_http_HttpClientChain::ARGS_SSL_VERIFY];
     $args[org_tubepress_impl_http_HttpClientChain::ARGS_TIMEOUT] = (int) ceil($args[org_tubepress_impl_http_HttpClientChain::ARGS_TIMEOUT]);
     $options = array('timeout' => $args[org_tubepress_impl_http_HttpClientChain::ARGS_TIMEOUT], 'connecttimeout' => $args[org_tubepress_impl_http_HttpClientChain::ARGS_TIMEOUT], 'redirect' => 5, 'useragent' => $args[org_tubepress_impl_http_HttpClientChain::ARGS_USER_AGENT], 'headers' => $args[org_tubepress_impl_http_HttpClientChain::ARGS_HEADERS], 'ssl' => array('verifypeer' => $sslVerify, 'verifyhost' => $sslVerify));
     $strResponse = @http_request($args[org_tubepress_impl_http_HttpClientChain::ARGS_METHOD], $url, $args[org_tubepress_impl_http_HttpClientChain::ARGS_BODY], $options, $info);
     // Error may still be set, Response may return headers or partial document, and error
     // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
     if (false === $strResponse || !empty($info['error'])) {
         throw new Exception($info['response_code'] . ': ' . $info['error']);
     }
     $headersBody = self::_breakRawStringResponseIntoHeaderAndBody($strResponse);
     $theHeaders = $headersBody[org_tubepress_impl_http_HttpClientChain::ARGS_HEADERS];
     $theBody = $headersBody[org_tubepress_impl_http_HttpClientChain::ARGS_BODY];
     unset($headersBody);
     $theHeaders = self::_getProcessedHeaders($theHeaders);
     if (!empty($theBody) && isset($theHeaders['headers']['transfer-encoding']) && 'chunked' == $theHeaders['headers']['transfer-encoding']) {
         $theBody = @http_chunked_decode($theBody);
     }
     if (true === $args['decompress'] && true === org_tubepress_impl_http_clientimpl_Encoding::shouldDecode($theHeaders['headers'])) {
         $theBody = http_inflate($theBody);
     }
     return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theHeaders['response'], 'cookies' => $theHeaders['cookies']);
 }
Beispiel #4
0
function run_request($Request, &$Response)
{
    list(, $host) = explode('Host: ', $Request, 2);
    list($host, ) = explode("\r\n", $host, 2);
    list($host, $port) = explode(':', $host, 2);
    $open = fsockopen($host, $port);
    fputs($open, $Request);
    while (!feof($open)) {
        $Result .= fgets($open, 4096);
    }
    fclose($open);
    list($Response, $Html) = @explode("\r\n\r\n", $Result, 2);
    if (preg_match("/transfer\\-encoding\\: chunked/i", $Response)) {
        $Html = http_chunked_decode($Html);
    }
    if (preg_match("/Content\\-Encoding\\: gzip/i", $Response)) {
        $Response = preg_replace("/Content\\-Encoding: gzip\\s+/isU", "", $Response);
        $Html = gzinflate(substr($Html, 10));
    }
    return $Html;
}
Beispiel #5
0
 /**
  * Send a HTTP request to a URI using HTTP extension.
  *
  * Does not support non-blocking.
  *
  * @access public
  * @since 2.7
  *
  * @param string $url
  * @param str|array $args Optional. Override the defaults.
  * @return array 'headers', 'body', and 'response' keys.
  */
 function request($url, $args = array())
 {
     $defaults = array('method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null);
     $r = wp_parse_args($args, $defaults);
     if (isset($r['headers']['User-Agent'])) {
         $r['user-agent'] = $r['headers']['User-Agent'];
         unset($r['headers']['User-Agent']);
     } else {
         if (isset($r['headers']['user-agent'])) {
             $r['user-agent'] = $r['headers']['user-agent'];
             unset($r['headers']['user-agent']);
         }
     }
     switch ($r['method']) {
         case 'POST':
             $r['method'] = HTTP_METH_POST;
             break;
         case 'HEAD':
             $r['method'] = HTTP_METH_HEAD;
             break;
         case 'GET':
         default:
             $r['method'] = HTTP_METH_GET;
     }
     $arrURL = parse_url($url);
     if ('http' != $arrURL['scheme'] || 'https' != $arrURL['scheme']) {
         $url = str_replace($arrURL['scheme'], 'http', $url);
     }
     $options = array('timeout' => $r['timeout'], 'connecttimeout' => $r['timeout'], 'redirect' => $r['redirection'], 'useragent' => $r['user-agent'], 'headers' => $r['headers']);
     if (!defined('WP_DEBUG') || defined('WP_DEBUG') && false === WP_DEBUG) {
         //Emits warning level notices for max redirects and timeouts
         $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
     } else {
         $strResponse = http_request($r['method'], $url, $r['body'], $options, $info);
     }
     //Emits warning level notices for max redirects and timeouts
     if (false === $strResponse || !empty($info['error'])) {
         //Error may still be set, Response may return headers or partial document, and error contains a reason the request was aborted, eg, timeout expired or max-redirects reached
         return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
     }
     if (!$r['blocking']) {
         return array('headers' => array(), 'body' => '', 'response' => array('code', 'message'));
     }
     list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
     $theHeaders = WP_Http::processHeaders($theHeaders);
     if (!empty($theBody) && isset($theHeaders['headers']['transfer-encoding']) && 'chunked' == $theHeaders['headers']['transfer-encoding']) {
         if (!defined('WP_DEBUG') || defined('WP_DEBUG') && false === WP_DEBUG) {
             $theBody = @http_chunked_decode($theBody);
         } else {
             $theBody = http_chunked_decode($theBody);
         }
     }
     if (true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders)) {
         $theBody = http_inflate($theBody);
     }
     $theResponse = array();
     $theResponse['code'] = $info['response_code'];
     $theResponse['message'] = get_status_header_desc($info['response_code']);
     return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse);
 }
Beispiel #6
0
function putfile($host, $port, $url, $referer, $cookie, $file, $filename, $proxy = 0, $pauth = 0, $upagent = 0, $scheme = 'http')
{
    global $nn, $lastError, $fp, $fs;
    if (empty($upagent)) {
        $upagent = rl_UserAgent;
    }
    $scheme = strtolower("{$scheme}://");
    if (!is_readable($file)) {
        $lastError = sprintf(lang(65), $file);
        return FALSE;
    }
    $fileSize = getSize($file);
    if (!empty($cookie)) {
        if (is_array($cookie)) {
            $cookies = count($cookie) > 0 ? CookiesToStr($cookie) : 0;
        } else {
            $cookies = trim($cookie);
        }
    }
    if ($scheme == 'https://') {
        if (!extension_loaded('openssl')) {
            html_error('You need to install/enable PHP\'s OpenSSL extension to support uploading via HTTPS.');
        }
        $scheme = 'tls://';
        if ($port == 0 || $port == 80) {
            $port = 443;
        }
    }
    if (!empty($referer) && ($pos = strpos("\r\n", $referer)) !== 0) {
        $origin = parse_url($pos ? substr($referer, 0, $pos) : $referer);
        $origin = strtolower($origin['scheme']) . '://' . strtolower($origin['host']) . (!empty($origin['port']) && $origin['port'] != defport(array('scheme' => $origin['scheme'])) ? ':' . $origin['port'] : '');
    } else {
        $origin = ($scheme == 'tls://' ? 'https://' : $scheme) . $host . ($port != 80 && ($scheme != 'tls://' || $port != 443) ? ':' . $port : '');
    }
    if ($proxy) {
        list($proxyHost, $proxyPort) = explode(':', $proxy, 2);
        $host = $host . ($port != 80 && ($scheme != 'tls://' || $port != 443) ? ':' . $port : '');
        $url = "{$scheme}{$host}{$url}";
    }
    if ($scheme != 'tls://') {
        $scheme = '';
    }
    $request = array();
    $request[] = 'PUT ' . str_replace(' ', '%20', $url) . ' HTTP/1.1';
    $request[] = "Host: {$host}";
    $request[] = "User-Agent: {$upagent}";
    $request[] = 'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1';
    $request[] = 'Accept-Language: en-US,en;q=0.9';
    $request[] = 'Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7';
    if (!empty($referer)) {
        $request[] = "Referer: {$referer}";
    }
    if (!empty($cookies)) {
        $request[] = "Cookie: {$cookies}";
    }
    if (!empty($pauth)) {
        $request[] = "Proxy-Authorization: Basic {$pauth}";
    }
    $request[] = "X-File-Name: {$filename}";
    $request[] = "X-File-Size: {$fileSize}";
    $request[] = "Origin: {$origin}";
    $request[] = 'Content-Disposition: attachment';
    $request[] = 'Content-Type: multipart/form-data';
    $request[] = "Content-Length: {$fileSize}";
    $request[] = 'Connection: Close';
    $request = implode($nn, $request) . $nn . $nn;
    $errno = 0;
    $errstr = '';
    $hosts = (!empty($proxyHost) ? $scheme . $proxyHost : $scheme . $host) . ':' . (!empty($proxyPort) ? $proxyPort : $port);
    $fp = @stream_socket_client($hosts, $errno, $errstr, 120, STREAM_CLIENT_CONNECT);
    if (!$fp) {
        if (!function_exists('stream_socket_client')) {
            html_error('[ERROR] stream_socket_client() is disabled.');
        }
        $dis_host = !empty($proxyHost) ? $proxyHost : $host;
        $dis_port = !empty($proxyPort) ? $proxyPort : $port;
        html_error(sprintf(lang(88), $dis_host, $dis_port));
    }
    if ($errno || $errstr) {
        $lastError = $errstr;
        return false;
    }
    if ($proxy) {
        echo '<p>' . sprintf(lang(89), $proxyHost, $proxyPort) . '<br />PUT: <b>' . htmlspecialchars($url) . "</b>...<br />\n";
    } else {
        echo '<p>' . sprintf(lang(90), $host, $port) . '</p>';
    }
    echo lang(104) . ' <b>' . htmlspecialchars($filename) . '</b>, ' . lang(56) . ' <b>' . bytesToKbOrMbOrGb($fileSize) . '</b>...<br />';
    $GLOBALS['id'] = md5(time() * rand(0, 10));
    require TEMPLATE_DIR . '/uploadui.php';
    flush();
    $timeStart = microtime(true);
    $chunkSize = GetChunkSize($fileSize);
    fwrite($fp, $request);
    fflush($fp);
    $fs = fopen($file, 'r');
    $totalsend = $time = $lastChunkTime = 0;
    while (!feof($fs) && !$errno && !$errstr) {
        $data = fread($fs, $chunkSize);
        if ($data === false) {
            fclose($fs);
            fclose($fp);
            html_error(lang(112));
        }
        $sendbyte = @fwrite($fp, $data);
        fflush($fp);
        if ($sendbyte === false || strlen($data) > $sendbyte) {
            fclose($fs);
            fclose($fp);
            html_error(lang(113));
        }
        $totalsend += $sendbyte;
        $time = microtime(true) - $timeStart;
        $chunkTime = $time - $lastChunkTime;
        $chunkTime = $chunkTime > 0 ? $chunkTime : 1;
        $lastChunkTime = $time;
        $speed = round($sendbyte / 1024 / $chunkTime, 2);
        $percent = round($totalsend / $fileSize * 100, 2);
        echo "<script type='text/javascript'>pr('{$percent}', '" . bytesToKbOrMbOrGb($totalsend) . "', '{$speed}');</script>\n";
        flush();
    }
    if ($errno || $errstr) {
        $lastError = $errstr;
        return false;
    }
    fclose($fs);
    fflush($fp);
    $llen = 0;
    $header = '';
    do {
        $header .= fgets($fp, 16384);
        $len = strlen($header);
        if (!$header || $len == $llen) {
            $lastError = lang(91);
            stream_socket_shutdown($fp, STREAM_SHUT_RDWR);
            fclose($fp);
            return false;
        }
        $llen = $len;
    } while (strpos($header, $nn . $nn) === false);
    // Array for active stream filters
    $sFilters = array();
    if (stripos($header, "\nTransfer-Encoding: chunked") !== false && in_array('dechunk', stream_get_filters())) {
        $sFilters['dechunk'] = stream_filter_append($fp, 'dechunk', STREAM_FILTER_READ);
    }
    // Add built-in dechunk filter
    $page = '';
    do {
        $data = @fread($fp, 16384);
        if ($data == '') {
            break;
        }
        $page .= $data;
    } while (!feof($fp) && strlen($data) > 0);
    stream_socket_shutdown($fp, STREAM_SHUT_RDWR);
    fclose($fp);
    if (stripos($header, "\nTransfer-Encoding: chunked") !== false && empty($sFilters['dechunk']) && function_exists('http_chunked_decode')) {
        $dechunked = http_chunked_decode($page);
        if ($dechunked !== false) {
            $page = $dechunked;
        }
        unset($dechunked);
    }
    $page = $header . $page;
    return $page;
}
Beispiel #7
0
function geturl($host, $port, $url, $referer = 0, $cookie = 0, $post = 0, $saveToFile = 0, $proxy = 0, $pauth = 0, $auth = 0, $scheme = 'http', $resume_from = 0, $XMLRequest = 0)
{
    global $nn, $lastError, $Resume, $bytesReceived, $fp, $fs, $force_name, $options;
    $scheme .= '://';
    if ($post !== 0 && ($scheme == 'http://' || $scheme == 'https://')) {
        $method = 'POST';
        $postdata = is_array($post) ? formpostdata($post) : $post;
        $length = strlen($postdata);
        $content_tl = "Content-Type: application/x-www-form-urlencoded{$nn}" . "Content-Length: {$length}{$nn}";
    } else {
        $method = 'GET';
        $content_tl = $postdata = '';
    }
    $cookies = '';
    if (!empty($cookie)) {
        if (is_array($cookie)) {
            if (count($cookie) > 0) {
                $cookies = 'Cookie: ' . CookiesToStr($cookie) . $nn;
            }
        } else {
            $cookies = 'Cookie: ' . trim($cookie) . $nn;
        }
    }
    $referer = $referer ? "Referer: {$referer}{$nn}" : '';
    if ($scheme == 'https://') {
        $scheme = 'ssl://';
        if ($port == 0 || $port == 80) {
            $port = 443;
        }
    }
    if ($proxy) {
        list($proxyHost, $proxyPort) = explode(':', $proxy, 2);
        $host = $host . ($port != 80 && ($scheme != 'ssl://' || $port != 443) ? ':' . $port : '');
        $url = $scheme . $host . $url;
    }
    if ($scheme != 'ssl://') {
        $scheme = '';
    }
    $http_auth = !empty($auth) ? "Authorization: Basic {$auth}{$nn}" : '';
    $proxyauth = !empty($pauth) ? "Proxy-Authorization: Basic {$pauth}{$nn}" : '';
    $request = array();
    $request[] = $method . ' ' . str_replace(' ', '%20', $url) . ' HTTP/1.1';
    $request[] = "Host: {$host}";
    $request[] = 'User-Agent: Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.12';
    $request[] = 'Accept: */*';
    $request[] = 'Accept-Language: en-US;q=0.7,en;q=0.3';
    $request[] = 'Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7';
    $request[] = 'Pragma: no-cache';
    $request[] = 'Cache-Control: no-cache';
    if ($Resume['use'] === TRUE) {
        $request[] = 'Range: bytes=' . $Resume['from'] . '-';
    }
    if ($XMLRequest) {
        $request[] = 'X-Requested-With: XMLHttpRequest';
    }
    $request = implode($nn, $request) . $nn . $http_auth . $proxyauth . $referer . $cookies . $content_tl . 'Connection: Close' . $nn . $nn . $postdata;
    $errno = 0;
    $errstr = '';
    $hosts = (!empty($proxyHost) ? $scheme . $proxyHost : $scheme . $host) . ':' . (!empty($proxyPort) ? $proxyPort : $port);
    $fp = @stream_socket_client($hosts, $errno, $errstr, 120, STREAM_CLIENT_CONNECT);
    //$fp = @fsockopen($proxyHost ? $scheme.$proxyHost : $scheme.$host, $proxyPort ? $proxyPort : $port, $errno, $errstr, 15);
    if (!$fp) {
        $dis_host = !empty($proxyHost) ? $proxyHost : $host;
        $dis_port = !empty($proxyPort) ? $proxyPort : $port;
        html_error(sprintf(lang(88), $dis_host, $dis_port));
    }
    if ($errno || $errstr) {
        $lastError = $errstr;
        return false;
    }
    if ($saveToFile) {
        if ($proxy) {
            echo '<p>' . sprintf(lang(89), $proxyHost, $proxyPort) . '<br />';
            echo 'GET: <b>' . $url . "</b>...<br />\n";
        } else {
            echo '<p>' . sprintf(lang(90), $host, $port) . '</p>';
        }
    }
    #########################################################################
    fputs($fp, $request);
    fflush($fp);
    $timeStart = getmicrotime();
    // Rewrote the get header function according to the proxy script
    // Also made sure it goes faster and I think 8192 is the best value for retrieving headers
    // Oops.. The previous function hooked up everything and now I'm returning it back to normal
    $llen = 0;
    $header = '';
    do {
        $header .= fgets($fp, 16384);
        $len = strlen($header);
        if (!$header || $len == $llen) {
            $lastError = lang(91);
            return false;
        }
        $llen = $len;
    } while (strpos($header, $nn . $nn) === false);
    #########################################################################
    if ($saveToFile) {
        if (!isset($_GET['dis_plug']) || $_GET['dis_plug'] != 'on') {
            $cbhost = strpos($host, ':') !== false ? substr($host, 0, strpos($host, ':')) : $host;
            // Remove the port that may be added when it's using proxy
            $chkhost = preg_match('/^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$/', $cbhost) ? false : true;
            if (!empty($referer)) {
                $cbrefhost = str_ireplace('www.', '', cut_str($referer, 'Referer: ', "\r\n"));
                $cbrefhost = parse_url($cbrefhost, PHP_URL_HOST);
                $chkref = empty($cbrefhost) || preg_match('/^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$/', $cbrefhost) ? false : ($chkhost && strtolower($cbhost) == strtolower($cbrefhost) ? false : true);
            } else {
                $chkref = false;
            }
            $found = false;
            if ($chkhost || $chkref) {
                foreach ($GLOBALS['host'] as $site => $file) {
                    if ($chkhost && host_matches($site, $cbhost)) {
                        $found = true;
                    } elseif ($chkref && host_matches($site, $cbrefhost)) {
                        $found = true;
                    }
                    if ($found) {
                        require_once HOST_DIR . 'DownloadClass.php';
                        require_once HOST_DIR . "download/{$file}";
                        $class = substr($file, 0, -4);
                        $firstchar = substr($file, 0, 1);
                        if ($firstchar > 0) {
                            $class = "d{$class}";
                        }
                        if (!class_exists($class) || !method_exists($class, 'CheckBack')) {
                            break;
                        }
                        // is_callable(array($class , 'CheckBack'))
                        $hostClass = new $class(false);
                        $hostClass->CheckBack($header);
                        break;
                    }
                }
            }
            unset($cbhost, $cbrefhost, $chkhost, $chkref, $found);
        }
        if (preg_match('/^HTTP\\/1\\.[0|1] (\\d+) .*/', $header, $responsecode) && ($responsecode[1] == 404 || $responsecode[1] == 403)) {
            // Do some checking, please, at least tell them what error it was
            if ($responsecode[1] == 403) {
                $lastError = lang(92);
            } elseif ($responsecode[1] == 404) {
                $lastError = lang(93);
            } else {
                // Weird, it shouldn't come here...
                $lastError = lang(94);
            }
            return false;
        }
        //$bytesTotal = intval ( trim ( cut_str ( $header, "Content-Length:", "\n" ) ) );
        $bytesTotal = trim(cut_str($header, "\nContent-Length: ", "\n"));
        global $options;
        if ($options['file_size_limit'] > 0 && $bytesTotal > $options['file_size_limit'] * 1024 * 1024) {
            $lastError = lang(336) . bytesToKbOrMbOrGb($options['file_size_limit'] * 1024 * 1024) . '.';
            return false;
        }
        if (stripos($header, "\nLocation: ") !== false && preg_match('/\\nLocation: ([^\\r\\n]+)/i', $header, $redir)) {
            $redirect = trim($redir[1]);
            $lastError = sprintf(lang(95), $redirect);
            return FALSE;
        }
        if (in_array(cut_str($header, "\nWWW-Authenticate: ", ' '), array('Basic', 'Digest'))) {
            $lastError = lang(96);
            return FALSE;
        }
        //$ContentType = trim (cut_str($header, "\nContent-Type:", "\n")); // Unused
        if ($Resume['use'] === TRUE && stripos($header, "\nContent-Range: ") === false) {
            $lastError = stripos($header, '503 Limit Exceeded') !== false ? lang(97) : lang(98);
            return FALSE;
        }
        if ($force_name) {
            $FileName = $force_name;
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $FileName;
        } else {
            $ContentDisposition = trim(cut_str($header, "\nContent-Disposition: ", "\n")) . "\n";
            if ($ContentDisposition && stripos($ContentDisposition, 'filename=') !== false) {
                $FileName = trim(trim(trim(trim(trim(cut_str($ContentDisposition, 'filename=', "\n")), '='), '?'), ';'), '"');
                if (strpos($FileName, '/') !== false) {
                    $FileName = basename($FileName);
                }
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $FileName;
            }
        }
        if (!empty($options['rename_prefix'])) {
            $File_Name = $options['rename_prefix'] . '_' . basename($saveToFile);
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $File_Name;
        }
        if (!empty($options['rename_suffix'])) {
            $ext = strrchr(basename($saveToFile), '.');
            $before_ext = explode($ext, basename($saveToFile));
            $File_Name = $before_ext[0] . '_' . $options['rename_suffix'] . $ext;
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $File_Name;
        }
        if ($options['rename_underscore']) {
            $File_Name = str_replace(array(' ', '%20'), '_', basename($saveToFile));
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $File_Name;
        }
        $filetype = strrchr($saveToFile, '.');
        if (is_array($options['forbidden_filetypes']) && in_array(strtolower($filetype), $options['forbidden_filetypes'])) {
            if ($options['forbidden_filetypes_block']) {
                $lastError = sprintf(lang(82), $filetype);
                return false;
            } else {
                $saveToFile = str_replace($filetype, $options['rename_these_filetypes_to'], $saveToFile);
            }
        }
        if (@file_exists($saveToFile) && $options['bw_save']) {
            // Skip in audl.
            if (isset($_GET['audl'])) {
                echo '<script type="text/javascript">parent.nextlink();</script>';
            }
            html_error(lang(99) . ': ' . link_for_file($saveToFile), 0);
        }
        if (@file_exists($saveToFile) && $Resume['use'] === TRUE) {
            $fs = @fopen($saveToFile, 'ab');
            if (!$fs) {
                $lastError = sprintf(lang(101), basename($saveToFile), dirname($saveToFile)) . '<br />' . lang(102) . '<br /><a href="javascript:location.reload();">' . lang(103) . '</a>';
                return FALSE;
            }
        } else {
            if (@file_exists($saveToFile)) {
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . time() . '_' . basename($saveToFile);
            }
            $fs = @fopen($saveToFile, 'wb');
            if (!$fs) {
                $secondName = dirname($saveToFile) . PATH_SPLITTER . str_replace(':', '', str_replace('?', '', basename($saveToFile)));
                $fs = @fopen($secondName, 'wb');
                if (!$fs) {
                    $lastError = sprintf(lang(101), basename($saveToFile), dirname($saveToFile)) . '<br />' . lang(102) . '<br /><a href="javascript:location.reload();">' . lang(103) . '</a>';
                    return FALSE;
                }
            }
        }
        flock($fs, LOCK_EX);
        if ($Resume['use'] === TRUE && stripos($header, "\nContent-Range: ") !== false) {
            list($temp, $Resume['range']) = explode(' ', trim(cut_str($header, "\nContent-Range: ", "\n")));
            list($Resume['range'], $fileSize) = explode('/', $Resume['range']);
            $fileSize = bytesToKbOrMbOrGb($fileSize);
        } else {
            $fileSize = bytesToKbOrMbOrGb($bytesTotal);
        }
        $chunkSize = GetChunkSize($bytesTotal);
        echo lang(104) . ' <b>' . basename($saveToFile) . '</b>, ' . lang(56) . ' <b>' . $fileSize . '</b>...<br />';
        //$scriptStarted = false;
        require_once TEMPLATE_DIR . '/transloadui.php';
        if ($Resume['use'] === TRUE) {
            $received = bytesToKbOrMbOrGb(filesize($saveToFile));
            $percent = round($Resume['from'] / ($bytesTotal + $Resume['from']) * 100, 2);
            echo '<script type="text/javascript">pr(' . "'" . $percent . "', '" . $received . "', '0');</script>";
            //$scriptStarted = true;
            flush();
        }
    } else {
        $page = '';
    }
    $time = $last = $lastChunkTime = 0;
    do {
        $data = @fread($fp, $saveToFile ? $chunkSize : 16384);
        // 16384 saw this value in Pear HTTP_Request2 package // (fix - szal) using this actually just causes massive cpu usage for large files, too much data is flushed to the browser!)
        if ($data == '') {
            break;
        }
        if ($saveToFile) {
            $bytesSaved = fwrite($fs, $data);
            if ($bytesSaved !== false && strlen($data) == $bytesSaved) {
                //if ($bytesSaved > - 1) {
                $bytesReceived += $bytesSaved;
            } else {
                $lastError = sprintf(lang(105), basename($saveToFile));
                unlink($saveToFile);
                return false;
            }
            if ($bytesReceived >= $bytesTotal) {
                $percent = 100;
            } else {
                $percent = @round(($bytesReceived + $Resume['from']) / ($bytesTotal + $Resume['from']) * 100, 2);
            }
            if ($bytesReceived > $last + $chunkSize) {
                $received = bytesToKbOrMbOrGb($bytesReceived + $Resume['from']);
                $time = getmicrotime() - $timeStart;
                $chunkTime = $time - $lastChunkTime;
                $chunkTime = $chunkTime ? $chunkTime : 1;
                $lastChunkTime = $time;
                $speed = @round($chunkSize / 1024 / $chunkTime, 2);
                /*if (!$scriptStarted) {
                			echo('<script type="text/javascript">');
                			$scriptStarted = true;
                		}*/
                echo '<script type="text/javascript">pr(' . "'" . $percent . "', '" . $received . "', '" . $speed . "');</script>";
                $last = $bytesReceived;
            }
        } else {
            $page .= $data;
        }
    } while (strlen($data) > 0);
    //echo('</script>');
    if ($saveToFile) {
        flock($fs, LOCK_UN);
        fclose($fs);
        if ($bytesReceived <= 0) {
            $lastError = lang(106);
            fclose($fp);
            return FALSE;
        }
    }
    fclose($fp);
    if ($saveToFile) {
        return array('time' => sec2time(round($time)), 'speed' => @round($bytesTotal / 1024 / (getmicrotime() - $timeStart), 2), 'received' => true, 'size' => $fileSize, 'bytesReceived' => $bytesReceived + $Resume['from'], 'bytesTotal' => $bytesTotal + $Resume['from'], 'file' => $saveToFile);
    } else {
        if (stripos($header, "\nTransfer-Encoding: chunked") !== false && function_exists('http_chunked_decode')) {
            $dechunked = http_chunked_decode($page);
            if ($dechunked !== false) {
                $page = $dechunked;
            }
            unset($dechunked);
        }
        $page = $header . $page;
        return $page;
    }
}
Beispiel #8
0
 /**
  * Executes CURL async request.
  *
  * @param string $url URL.
  * @param array $params List of request params.
  * @param string $type Type of the request (GET, POST, ...).
  * @param int $timeout Timeout in seconds.
  *
  * @return type
  */
 public static function curlRequestAsync($url, $params, $type = self::POST, $timeout = 30)
 {
     $postParams = array();
     foreach ($params as $key => &$val) {
         if (is_array($val)) {
             $val = implode(',', $val);
         }
         $postParams[] = $key . '=' . urlencode($val);
     }
     $postString = implode('&', $postParams);
     $parts = parse_url($url);
     $port = isset($parts['port']) ? (int) $parts['port'] : 80;
     $fp = fsockopen($parts['host'], $port, $errno, $errstr, $timeout);
     // Data goes in the path for a GET request
     if ($type == self::GET) {
         $parts['path'] .= '?' . $postString;
     }
     $request = "{$type} " . $parts['path'] . " HTTP/1.1\r\n";
     $request .= "Host: " . $parts['host'] . "\r\n";
     if ($type == self::POST) {
         $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
         $request .= "Content-Length: " . strlen($postString) . "\r\n";
     }
     $request .= "Connection: Close\r\n";
     $request .= "\r\n";
     // Data goes in the request body for a POST request
     if ($type == self::POST && isset($postString)) {
         $request .= $postString;
     }
     fwrite($fp, $request);
     $response = "";
     while (!feof($fp) && ($result = fgets($fp))) {
         $response .= $result;
     }
     fclose($fp);
     list($respHeader, $respBody) = preg_split("/\\R\\R/", $response, 2);
     $headers = array_map(array('self', "pair"), explode("\r\n", $respHeader));
     $headerList = array();
     foreach ($headers as $value) {
         $headerList[$value['key']] = $value['value'];
     }
     return array('request' => $request, 'response' => array('header' => $respHeader, 'headerList' => $headerList, 'body' => trim(http_chunked_decode($respBody))), 'errno' => $errno, 'errstr' => $errstr);
 }
Beispiel #9
0
 private function unchunk2($chunk)
 {
     if (!function_exists('http-chunked-decode')) {
         $pos = 0;
         $len = strlen($chunk);
         $dechunk = null;
         while ($pos < $len && ($chunkLenHex = substr($chunk, $pos, ($newlineAt = strpos($chunk, "\n", $pos + 1)) - $pos))) {
             if (!$this->is_hex($chunkLenHex)) {
                 //trigger_error('Value is not properly chunk encoded', E_USER_WARNING);
                 return $chunk;
             }
             $pos = $newlineAt + 1;
             $chunkLen = hexdec(rtrim($chunkLenHex, "\r\n"));
             $dechunk .= substr($chunk, $pos, $chunkLen);
             $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1;
         }
         return $dechunk;
     } else {
         return http_chunked_decode($result);
     }
 }
Beispiel #10
0
 /**
  * Parses the raw response
  *
  * @throws HTTPResponseException
  * @param string $data
  */
 protected function parse($data)
 {
     $pos = strpos($data, "\r\n\r\n");
     if (!$pos) {
         throw new HTTPResponseException("Couldn't parse response header!");
     }
     $header = substr($data, 0, $pos);
     $body = substr($data, $pos + 4);
     $this->parse_header($header);
     $enc = $this->get_header('content-encoding');
     if ($this->get_header('transfer-encoding') === 'chunked') {
         $body = http_chunked_decode($body);
     }
     $this->data = $body;
     unset($body, $header);
 }
Beispiel #11
0
function geturl($host, $port, $url, $referer = 0, $cookie = 0, $post = 0, $saveToFile = 0, $proxy = 0, $pauth = 0, $auth = 0, $scheme = "http", $resume_from = 0, $XMLRequest = 0)
{
    global $nn, $lastError, $Resume, $bytesReceived, $fs, $force_name, $options, $L, $visitors, $ada_acc;
    $scheme .= '://';
    if ($post !== 0 && ($scheme == 'http://' || $scheme == 'https://')) {
        $method = 'POST';
        $postdata = is_array($post) ? formpostdata($post) : $post;
        $length = strlen($postdata);
        $content_tl = "Content-Type: application/x-www-form-urlencoded{$nn}" . "Content-Length: {$length}{$nn}";
    } else {
        $method = 'GET';
        $content_tl = $postdata = '';
    }
    $cookies = '';
    if (!empty($cookie)) {
        if (is_array($cookie)) {
            if (count($cookie) > 0) {
                $cookies = 'Cookie: ' . CookiesToStr($cookie) . $nn;
            }
        } else {
            $cookies = 'Cookie: ' . trim($cookie) . $nn;
        }
    }
    $referer = $referer ? "Referer: {$referer}{$nn}" : '';
    if ($scheme == 'https://') {
        $scheme = 'ssl://';
        if ($port == 0 || $port == 80) {
            $port = 443;
        }
    }
    if ($proxy) {
        list($proxyHost, $proxyPort) = explode(':', $proxy, 2);
        $host = $host . ($port != 80 && ($scheme != 'ssl://' || $port != 443) ? ':' . $port : '');
        $url = $scheme . $host . $url;
    }
    if ($scheme != 'ssl://') {
        $scheme = '';
    }
    $http_auth = !empty($auth) ? "Authorization: Basic {$auth}{$nn}" : '';
    $proxyauth = !empty($pauth) ? "Proxy-Authorization: Basic {$pauth}{$nn}" : '';
    $request = array();
    $request[] = $method . ' ' . str_replace(' ', '%20', $url) . ' HTTP/1.1';
    $request[] = "Host: {$host}";
    $request[] = 'User-Agent: Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.12';
    $request[] = 'Accept: */*';
    $request[] = 'Accept-Language: en-US;q=0.7,en;q=0.3';
    $request[] = 'Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7';
    $request[] = 'Pragma: no-cache';
    $request[] = 'Cache-Control: no-cache';
    if ($Resume['use'] === TRUE) {
        $request[] = 'Range: bytes=' . $Resume['from'] . '-';
    }
    if ($XMLRequest) {
        $request[] = 'X-Requested-With: XMLHttpRequest';
    }
    $request = implode($nn, $request) . $nn . $http_auth . $proxyauth . $referer . $cookies . $content_tl . 'Connection: Close' . $nn . $nn . $postdata;
    if (isset($options['mip_enabled']) && $options['mip_enabled']) {
        $mip_action = "download";
        echo "<p>Multi IP Enabled</b>...<br />\n";
        if (file_exists(CLASS_DIR . "mip.php")) {
            @(include CLASS_DIR . "mip.php");
        }
    } else {
        $errno = 0;
        $errstr = '';
        $hosts = (!empty($proxyHost) ? $scheme . $proxyHost : $scheme . $host) . ':' . (!empty($proxyPort) ? $proxyPort : $port);
        $fp = @stream_socket_client($hosts, $errno, $errstr, 120, STREAM_CLIENT_CONNECT);
    }
    if (!$fp) {
        $dis_host = !empty($proxyHost) ? $proxyHost : $host;
        $dis_port = !empty($proxyPort) ? $proxyPort : $port;
        html_error($L->sprintf($L->say['_couldnt_con_to'], $dis_host, $dis_port));
    }
    if ($errno || $errstr) {
        $lastError = $errstr;
        return false;
    }
    if ($saveToFile) {
        if ($proxy) {
            echo '<p>' . $L->sprintf($L->say['_con_proxy'], $proxyHost, $proxyPort) . '<br />';
            echo "GET: <b>" . $url . "</b>...<br />\n";
        } else {
            echo "<p>";
            echo $L->sprintf($L->say['_con_to'], $host, $port) . '<br />';
            echo isset($options['mip_enabled']) && $options['mip_enabled'] ? "using IP: " . $mip_ip . "<br />\n" : "";
        }
    }
    #########################################################################
    fputs($fp, $request);
    fflush($fp);
    $timeStart = getmicrotime();
    // Rewrote the get header function according to the proxy script
    // Also made sure it goes faster and I think 8192 is the best value for retrieving headers
    // Oops.. The previous function hooked up everything and now I'm returning it back to normal
    $llen = 0;
    $header = '';
    do {
        $header .= fgets($fp, 16384);
        $len = strlen($header);
        if (!$header || $len == $llen) {
            $lastError = $L->say['_noheader'];
            return false;
        }
        $llen = $len;
    } while (strpos($header, $nn . $nn) === false);
    #########################################################################
    if ($saveToFile) {
        if (!isset($_GET['dis_plug']) || $_GET['dis_plug'] != 'on') {
            $cbhost = strpos($host, ':') !== false ? substr($host, 0, strpos($host, ':')) : $host;
            // Remove the port that may be added when it's using proxy
            $chkhost = preg_match('/^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$/', $cbhost) ? false : true;
            if (!empty($referer)) {
                $cbrefhost = str_ireplace('www.', '', cut_str($referer, 'Referer: ', "\r\n"));
                $cbrefhost = parse_url($cbrefhost, PHP_URL_HOST);
                $chkref = empty($cbrefhost) || preg_match('/^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$/', $cbrefhost) ? false : ($chkhost && strtolower($cbhost) == strtolower($cbrefhost) ? false : true);
            } else {
                $chkref = false;
            }
            $found = false;
            if ($chkhost || $chkref) {
                foreach ($GLOBALS['host'] as $site => $file) {
                    if ($chkhost && host_matches($site, $cbhost)) {
                        $found = true;
                    } elseif ($chkref && host_matches($site, $cbrefhost)) {
                        $found = true;
                    }
                    if ($found) {
                        if ($options['limitbyIP']) {
                            if ($ada_acc) {
                                global $premium_acc;
                                if (preg_match('|^(?:.+\\.)?(.+\\..+)$|i', $cbhost, $prematch) || preg_match('|^(?:.+\\.)?(.+\\..+)$|i', $cbrefhost, $prematch)) {
                                    $prematch = str_replace('.', '_', $prematch[1]);
                                    if (!empty($premium_acc[$prematch])) {
                                        $fname = basename($saveToFile) . "." . rand(1, 1000);
                                        $limitedfile = $visitors->userip . $fname;
                                        $ret = mkdir($visitors->tmp_dir . $limitedfile, 0777);
                                    }
                                }
                            }
                        }
                        require_once HOST_DIR . 'DownloadClass.php';
                        require_once HOST_DIR . "download/{$file}";
                        $class = substr($file, 0, -4);
                        $firstchar = substr($file, 0, 1);
                        if ($firstchar > 0) {
                            $class = "d{$class}";
                        }
                        if (!class_exists($class) || !method_exists($class, 'CheckBack')) {
                            break;
                        }
                        // is_callable(array($class , 'CheckBack'))
                        $hostClass = new $class(false);
                        $hostClass->CheckBack($header);
                        break;
                    }
                }
                unset($cbhost, $cbrefhost, $chkhost, $chkref, $found);
            }
        }
        if (preg_match('/^HTTP\\/1\\.[0|1] (\\d+) .*/', $header, $responsecode) && ($responsecode[1] == 404 || $responsecode[1] == 403)) {
            // Do some checking, please, at least tell them what error it was
            if ($responsecode[1] == 403) {
                $lastError = $L->say['_page_notfound'];
            } elseif ($responsecode[1] == 404) {
                $lastError = $L->say['_forbidden_access'];
            } else {
                // Weird, it shouldn't come here...
                $lastError = $L->say['_notfound_forbidden'];
            }
            return false;
        }
        $bytesTotal = trim(cut_str($header, "Content-Length:", "\n"));
        if ($options['maxlimitsize'] > 0) {
            if ($bytesTotal > $options['maxlimitsize'] * 1024 * 1024) {
                $lastError = $L->sprintf($L->say['_sorry_tobig'], bytesToKbOrMbOrGb($bytesTotal), $options["maxlimitsize"]);
                return false;
            }
        }
        if ($options['minlimitsize'] > 0) {
            if ($bytesTotal < $options['minlimitsize'] * 1024 * 1024) {
                $lastError = $L->sprintf($L->say['_sorry_tosmall'], bytesToKbOrMbOrGb($bytesTotal), $options["minlimitsize"]);
                return false;
            }
        }
        // check storage limit (it is in MB)
        if ($options['storage_limit'] > 0) {
            $serverfiles = calcUsedSpace();
            if ($serverfiles + $bytesTotal > $options['storage_limit'] * 1024 * 1024) {
                $lastError = $L->sprintf($L->say['_sorry_insuficient_storage'], bytesToKbOrMbOrGb($serverfiles), $options["storage_limit"]);
                return false;
            }
        }
        if (stripos($header, "\nLocation: ") !== false && preg_match('/\\nLocation: ([^\\r\\n]+)/i', $header, $redir)) {
            $redirect = trim($redir[1]);
            $lastError = $L->sprintf($L->say['_error_redirectto'], $redirect);
            return FALSE;
        }
        if (in_array(cut_str($header, "WWW-Authenticate: ", " "), array("Basic", "Digest"))) {
            $lastError = $L->say['_req_auth'];
            return FALSE;
        }
        //$ContentType = trim(cut_str($header, "Content-Type:", "\n"));
        if ($Resume['use'] === TRUE && stripos($header, "\nContent-Range: ") === false) {
            $lastError = stripos($header, '503 Limit Exceeded') !== false ? $L->say['_error_resume'] : $L->say['_error_noresume'];
            return FALSE;
        }
        if ($force_name) {
            $FileName = $force_name;
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $FileName;
        } else {
            $ContentDisposition = trim(cut_str($header, "Content-Disposition:", "\n")) . "\n";
            if ($ContentDisposition && stripos($ContentDisposition, "filename=") !== false) {
                $FileName = trim(trim(trim(trim(trim(cut_str($ContentDisposition, "filename=", "\n")), "="), "?"), ";"), '"');
                if (strpos($FileName, "/") !== false) {
                    $FileName = basename($FileName);
                }
                if (preg_match("/UTF\\-8\\?B\\?(.*)\$/i", $FileName, $b64)) {
                    $FileName = preg_replace("/[^a-zA-Z0-9\\-\\.]/", "_", base64_decode($b64[1]));
                }
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $FileName;
            }
        }
        if (!empty($options["add_ext_5city"]) || !empty($options['rename_suffix']) || !empty($options['rename_prefix']) || $options['rename_underscore']) {
            if (!empty($options["add_ext_5city"])) {
                $ext = str_replace(".", "", $options["add_ext_5city"]);
                $File_Name = basename($saveToFile) . "." . $options["add_ext_5city"];
            }
            if (!empty($options['rename_prefix'])) {
                $File_Name = $options['rename_prefix'] . '_' . basename($saveToFile);
            }
            if (!empty($options['rename_suffix'])) {
                $ext = strrchr(basename($saveToFile), ".");
                $before_ext = explode($ext, basename($saveToFile));
                $File_Name = $before_ext[0] . '_' . $options['rename_suffix'] . $ext;
            }
            if ($options['rename_underscore']) {
                $File_Name = str_replace(array(' ', '%20'), '_', basename($saveToFile));
            }
            $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $File_Name;
        }
        $filetype = strrchr($saveToFile, ".");
        if (is_array($options['forbidden_filetypes']) && in_array(strtolower($filetype), $options['forbidden_filetypes'])) {
            if ($options['forbidden_filetypes_block']) {
                $lastError = $L->sprintf($L->say['_forbid_filetype'], $filetype);
                return false;
            } else {
                $saveToFile = str_replace($filetype, $options['rename_these_filetypes_to'], $saveToFile);
            }
        }
        if (@file_exists($saveToFile) && $options['bw_save']) {
            html_error($L->say['_download'] . ': ' . link_for_file($saveToFile), 0);
        }
        if (@file_exists($saveToFile) && $Resume["use"] === TRUE) {
            $fs = @fopen($saveToFile, "ab");
            if (!$fs) {
                $lastError = $L->sprintf($L->say['_error_cantsave'], basename($saveToFile)) . '<br />' . $L->say['_error_trychmod'] . '<br /><a href="javascript:location.reload();">' . $L->say['_error_tryagain'] . '</a>';
                return FALSE;
            }
        } else {
            if (@file_exists($saveToFile)) {
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . TIME_NOW . "_" . basename($saveToFile);
            }
            $fs = @fopen($saveToFile, "wb");
            if (!$fs) {
                $secondName = dirname($saveToFile) . PATH_SPLITTER . str_replace(":", "", str_replace("?", "", basename($saveToFile)));
                $fs = @fopen($secondName, "wb");
                if (!$fs) {
                    $lastError = $L->sprintf($L->say['_error_cantsave'], basename($saveToFile)) . '<br />' . $L->say['_error_trychmod'] . '<br /><a href="javascript:location.reload();">' . $L->say['_error_tryagain'] . '</a>';
                    return FALSE;
                }
            }
        }
        flock($fs, LOCK_EX);
        if ($Resume['use'] === TRUE && stripos($header, "\nContent-Range: ") !== false) {
            list($temp, $Resume['range']) = explode(' ', trim(cut_str($header, "\nContent-Range: ", "\n")));
            list($Resume['range'], $fileSize) = explode('/', $Resume['range']);
            $fileSize = bytesToKbOrMbOrGb($fileSize);
        } else {
            $fileSize = bytesToKbOrMbOrGb($bytesTotal);
        }
        $chunkSize = GetChunkSize($bytesTotal);
        $File_Name = basename($saveToFile);
        if (!empty($options["add_ext_5city"])) {
            $ext = "." . get_extension(basename($saveToFile));
            $File_Name = str_replace($ext, "", basename($saveToFile));
        }
        echo $L->sprintf($L->say['_saveprogres'], $File_Name, $ext, $fileSize) . '<br />';
        //$scriptStarted = false;
        require_once TEMPLATE_DIR . 'transloadui.php';
        if ($Resume['use'] === TRUE) {
            $received = bytesToKbOrMbOrGb(filesize($saveToFile));
            $percent = round($Resume['from'] / ($bytesTotal + $Resume['from']) * 100, 2);
            echo '<script type="text/javascript">pr(' . "'" . $percent . "', '" . $received . "', '0');</script>";
            //$scriptStarted = true;
            flush();
        }
    } else {
        $page = "";
    }
    $time = $last = $lastChunkTime = 0;
    do {
        $data = @fread($fp, $saveToFile ? $chunkSize : 16384);
        // 16384 saw this value in Pear HTTP_Request2 package // (fix - szal) using this actually just causes massive cpu usage for large files, too much data is flushed to the browser!)
        if ($data == '') {
            break;
        }
        if ($saveToFile) {
            $bytesSaved = fwrite($fs, $data);
            if ($bytesSaved !== false && strlen($data) == $bytesSaved) {
                //if ($bytesSaved > - 1) {
                $bytesReceived += $bytesSaved;
            } else {
                $lastError = $L->sprintf($L->say['_error_imposible_record'], $saveToFile);
                unlink($saveToFile);
                return false;
            }
            if ($bytesReceived >= $bytesTotal) {
                $percent = 100;
            } else {
                $percent = @round(($bytesReceived + $Resume['from']) / ($bytesTotal + $Resume['from']) * 100, 2);
            }
            if ($bytesReceived > $last + $chunkSize) {
                $received = bytesToKbOrMbOrGb($bytesReceived + $Resume['from']);
                $time = getmicrotime() - $timeStart;
                $chunkTime = $time - $lastChunkTime;
                $chunkTime = $chunkTime ? $chunkTime : 1;
                $lastChunkTime = $time;
                $speed = @round($chunkSize / 1024 / $chunkTime, 2);
                /* if (!$scriptStarted) {
                	  echo('<script type="text/javascript">');
                	  $scriptStarted = true;
                	  } */
                echo "<script type='text/javascript'>pr('" . $percent . "', '" . $received . "', '" . $speed . "');</script>";
                $last = $bytesReceived;
            }
        } else {
            $page .= $data;
        }
    } while (strlen($data) > 0);
    //echo('</script>');
    if ($saveToFile) {
        flock($fs, LOCK_UN);
        fclose($fs);
        if ($bytesReceived <= 0) {
            $lastError = $L->say['_error_misc'];
            fclose($fp);
            return FALSE;
        }
    }
    fclose($fp);
    if ($saveToFile) {
        return array('time' => sec2time(round($time)), 'speed' => @round($bytesTotal / 1024 / (getmicrotime() - $timeStart), 2), 'received' => true, 'size' => $fileSize, 'bytesReceived' => $bytesReceived + $Resume['from'], 'bytesTotal' => $bytesTotal + $Resume['from'], 'file' => $saveToFile);
    } else {
        if (stripos($header, "\nTransfer-Encoding: chunked") !== false && function_exists('http_chunked_decode')) {
            $dechunked = http_chunked_decode($page);
            if ($dechunked !== false) {
                $page = $dechunked;
            }
            unset($dechunked);
        }
        $page = $header . $page;
        return $page;
    }
}
Beispiel #12
0
 public function CheckBack($header)
 {
     $statuscode = intval(substr($header, 9, 3));
     if ($statuscode == 302) {
         $length = trim(cut_str($header, "\r\nContent-Length: ", "\r\n"));
         if (empty($length) || strlen($length) <= 6 && intval($length) <= 102400) {
             global $fp, $PHP_SELF;
             $page = '';
             while (strlen($data = @fread($fp, 16384)) > 0) {
                 $page .= $data;
             }
             if (stripos($header, "\r\nTransfer-Encoding: chunked") !== false && function_exists('http_chunked_decode')) {
                 $dechunked = http_chunked_decode($page);
                 if ($dechunked !== false) {
                     $page = $dechunked;
                 }
                 unset($dechunked);
             }
             $page = $header . $page;
             if (stripos($page, "\nyou need to wait 5 minutes between downloads") !== false) {
                 insert_timer(10, 'Auto retry download:');
                 //echo '<script type="text/javascript">location.reload();</script>';
                 echo "<center><form name='retryf' action='{$PHP_SELF}' method='POST'>\n";
                 if (!empty($_GET['proxy'])) {
                     $_GET['useproxy'] = 'on';
                 }
                 $post = array();
                 // I can't reload because firefox shows an anoying alertbox.
                 $post['filename'] = $_GET['filename'];
                 if (!empty($_GET['force_name'])) {
                     $post['force_name'] = $_GET['force_name'];
                 }
                 $post['host'] = $_GET['host'];
                 $post['path'] = $_GET['path'];
                 if (!empty($_GET['link'])) {
                     $post['link'] = $_GET['link'];
                 }
                 if (!empty($_GET['referer'])) {
                     $post['referer'] = $_GET['referer'];
                 }
                 if (!empty($_GET['post'])) {
                     $post['post'] = $_GET['post'];
                 }
                 $post = array_merge($this->DefaultParamArr(), array_map('urlencode', $post));
                 foreach ($post as $name => $input) {
                     echo "<input type='hidden' name='{$name}' id='{$name}' value='{$input}' />\n";
                 }
                 echo "<input type='submit' value='Try Again' />\n";
                 echo "</form></center><script type='text/javascript'>document.retryf.submit();</script><br />\n";
                 html_error('You need to wait 5 minutes between downloads.');
             } elseif (stripos($page, "\ndownload link expired") !== false) {
                 echo "<center><form action='{$PHP_SELF}' method='POST'>\n";
                 $post = $this->DefaultParamArr(cut_str($header, 'Location: ', "\r\n"));
                 $post['premium_acc'] = 'on';
                 foreach ($post as $name => $input) {
                     echo "<input type='hidden' name='{$name}' id='{$name}' value='{$input}' />\n";
                 }
                 echo "<input type='submit' value='Download Again' />\n";
                 echo "</form></center><br />\n";
                 html_error('Download link has expired.');
             }
         }
     }
 }
Beispiel #13
0
 public function CheckBack($header)
 {
     if (stripos($header, "\nContent-Type: text/html") !== false) {
         global $fp, $sFilters;
         if (empty($fp) || !is_resource($fp)) {
             html_error('[filesflash_com] Cannot check download error.');
         }
         $is_chunked = stripos($header, "\nTransfer-Encoding: chunked") !== false;
         if (!isset($sFilters) || !is_array($sFilters)) {
             $sFilters = array();
         }
         if ($is_chunked && empty($sFilters['dechunk']) && in_array('dechunk', stream_get_filters())) {
             $sFilters['dechunk'] = stream_filter_append($fp, 'dechunk', STREAM_FILTER_READ);
         }
         $body = stream_get_contents($fp);
         if ($is_chunked && empty($sFilters['dechunk']) && function_exists('http_chunked_decode')) {
             $dechunked = http_chunked_decode($body);
             if ($dechunked !== false) {
                 $body = $dechunked;
             }
             unset($dechunked);
         }
         is_present($body, 'Your IP address is not valid for this link.', '[filesflash_com] Your IP address is not valid for this link.');
         is_present($body, 'Your IP address is already downloading another link.', '[filesflash_com] Your IP address is already downloading another link.');
         is_present($body, 'Your link has expired.', '[filesflash_com] Your link has expired.');
         is_present($body, 'Interrupted free downloads cannot be resumed.', '[filesflash_com] Interrupted free downloads cannot be resumed.');
         html_error('[filesflash_com] Unknown download error.');
     }
 }
Beispiel #14
0
 /**
  * 解析 chunked 分块内容.
  * 
  * @access private
  * @param string $chunkedContent 分块内容.
  * @return string 不是分块, 原始内容.
  */
 private function _decodeChunked($chunkedContent)
 {
     if (function_exists('http_chunked_decode')) {
         $res = http_chunked_decode($chunkedContent);
         return FALSE === $res ? $chunkedContent : $res;
     }
     /*
      * 自己理解的 chunked 的格式为: 
      * 					第 1 段: 16进制大小字符\r\n
      * 							正文内容\r\n
      * 					第 2 段: 16进制大小字符\r\n
      * 							正文内容\r\n
      * 					结束:	0\r\n
      */
     $pos = 0;
     $len = strlen($chunkedContent);
     $decode = '';
     while ($pos < $len) {
         $offset = strpos($chunkedContent, "\n", $pos) - $pos;
         // 内容长度的 16 进制字符长度.
         $hex = substr($chunkedContent, $pos, $offset + 1);
         // 表示内容长度的 16 进制字符, 包含 \r\n.
         $len_hex = hexdec(rtrim(ltrim($hex, "0"), "\r\n")) + 2;
         // 内容长度, 转换为整数字节数.
         if (empty($len_hex)) {
             // 为空, 表示 chunked 已完成, 取到 0 时才会中止.
             break;
         }
         $decode .= rtrim(substr($chunkedContent, $pos + $offset + 1, $len_hex), "\r\n");
         // 拼接内容.
         $pos += $offset + $len_hex + 1;
     }
     return $decode;
 }
Beispiel #15
0
 private function encode_respond($buffer)
 {
     debugger($buffer, 'Buffer Entity');
     $header = $body = '';
     $p = strpos($buffer, "\r\n\r\n");
     // 去除头部信息
     if ($p > 0) {
         $header = substr($buffer, 0, $p);
         if ($p + 4 < strlen($buffer)) {
             $body = substr($buffer, $p + 4);
         }
     }
     // 如果header为续传标记则继续去除头部信息
     if ($header = 'HTTP/1.1 100 Continue') {
         $p = strpos($body, "\r\n\r\n");
         if ($p > 0) {
             $header = substr($body, 0, $p);
             if ($p + 4 < strlen($body)) {
                 $body = substr($body, $p + 4);
             }
         }
     }
     /*
     $body_without_header = '';
     $p2 = strpos( $buffer, "<?xml" ); 	// 第一次出现XML标记的位置
     if( $p2 > 1 )
     {
     	if( $p2-1 < strlen($buffer) )
     	{
     		$body_without_header = substr( $buffer,$p2-1 );
     	}
     }
     */
     try {
         if ($this->_header['Accept-Encoding'] == 'gzip,deflate') {
             $body = @gzdecode($body);
             if (!$body) {
                 trigger_error('返回体解析错误', E_USER_WARNING);
             }
         }
         if ($this->_header['Transfer-Encoding'] == 'chunked') {
             $body = @http_chunked_decode($body);
         }
     } catch (Exception $e) {
         trigger_error($e);
     }
     return $body;
 }
Beispiel #16
0
 /**
  * Send a HTTP request to a URI using HTTP extension.
  *
  * Does not support non-blocking.
  *
  * @access public
  * @since 2.7
  *
  * @param string $url
  * @param str|array $args Optional. Override the defaults.
  * @return array 'headers', 'body', 'cookies' and 'response' keys.
  */
 function request($url, $args = array())
 {
     $defaults = array('method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array());
     $r = wp_parse_args($args, $defaults);
     if (isset($r['headers']['User-Agent'])) {
         $r['user-agent'] = $r['headers']['User-Agent'];
         unset($r['headers']['User-Agent']);
     } else {
         if (isset($r['headers']['user-agent'])) {
             $r['user-agent'] = $r['headers']['user-agent'];
             unset($r['headers']['user-agent']);
         }
     }
     // Construct Cookie: header if any cookies are set
     WP_Http::buildCookieHeader($r);
     switch ($r['method']) {
         case 'POST':
             $r['method'] = HTTP_METH_POST;
             break;
         case 'HEAD':
             $r['method'] = HTTP_METH_HEAD;
             break;
         case 'PUT':
             $r['method'] = HTTP_METH_PUT;
             break;
         case 'GET':
         default:
             $r['method'] = HTTP_METH_GET;
     }
     $arrURL = parse_url($url);
     if ('http' != $arrURL['scheme'] || 'https' != $arrURL['scheme']) {
         $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url);
     }
     $is_local = isset($args['local']) && $args['local'];
     $ssl_verify = isset($args['sslverify']) && $args['sslverify'];
     if ($is_local) {
         $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify);
     } elseif (!$is_local) {
         $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify);
     }
     $options = array('timeout' => $r['timeout'], 'connecttimeout' => $r['timeout'], 'redirect' => $r['redirection'], 'useragent' => $r['user-agent'], 'headers' => $r['headers'], 'ssl' => array('verifypeer' => $ssl_verify, 'verifyhost' => $ssl_verify));
     // The HTTP extensions offers really easy proxy support.
     $proxy = new WP_HTTP_Proxy();
     if ($proxy->is_enabled() && $proxy->send_through_proxy($url)) {
         $options['proxyhost'] = $proxy->host();
         $options['proxyport'] = $proxy->port();
         $options['proxytype'] = HTTP_PROXY_HTTP;
         if ($proxy->use_authentication()) {
             $options['proxyauth'] = $proxy->authentication();
             $options['proxyauthtype'] = HTTP_AUTH_BASIC;
         }
     }
     if (!WP_DEBUG) {
         //Emits warning level notices for max redirects and timeouts
         $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info);
     } else {
         $strResponse = http_request($r['method'], $url, $r['body'], $options, $info);
     }
     //Emits warning level notices for max redirects and timeouts
     // Error may still be set, Response may return headers or partial document, and error
     // contains a reason the request was aborted, eg, timeout expired or max-redirects reached.
     if (false === $strResponse || !empty($info['error'])) {
         return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']);
     }
     if (!$r['blocking']) {
         return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array());
     }
     list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2);
     $theHeaders = WP_Http::processHeaders($theHeaders);
     if (!empty($theBody) && isset($theHeaders['headers']['transfer-encoding']) && 'chunked' == $theHeaders['headers']['transfer-encoding']) {
         if (!WP_DEBUG) {
             $theBody = @http_chunked_decode($theBody);
         } else {
             $theBody = http_chunked_decode($theBody);
         }
     }
     if (true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers'])) {
         $theBody = http_inflate($theBody);
     }
     $theResponse = array();
     $theResponse['code'] = $info['response_code'];
     $theResponse['message'] = get_status_header_desc($info['response_code']);
     return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']);
 }
Beispiel #17
0
/**
 * Download file using fsockopen
 *
 * @since 3.0
 * @param type $sourceFile
 * @param type $fileout
 */
function download_fsockopen($sourceFile, $fileout = null, $post_data = null)
{
    // parse URL
    $aUrl = parse_url($sourceFile);
    $host = $aUrl['host'];
    if ('localhost' == strtolower($host)) {
        $host = '127.0.0.1';
    }
    $link = $aUrl['path'] . (isset($aUrl['query']) ? '?' . $aUrl['query'] : '');
    if (empty($link)) {
        $link .= '/';
    }
    $fp = @fsockopen($host, 80, $errno, $errstr, 30);
    if (!$fp) {
        return false;
    } else {
        $ua = @$_SERVER['HTTP_USER_AGENT'] . ' Osclass (v.' . osc_version() . ')';
        $out = ($post_data != null && is_array($post_data) ? "POST" : "GET") . " {$link} HTTP/1.1\r\n";
        $out .= "Host: {$host}\r\n";
        $out .= "User-Agent: {$ua}\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= "\r\n";
        if ($post_data != null && is_array($post_data)) {
            $out .= http_build_query($post_data);
        }
        fwrite($fp, $out);
        $contents = '';
        while (!feof($fp)) {
            $contents .= fgets($fp, 1024);
        }
        fclose($fp);
        // check redirections ?
        // if (redirections) then do request again
        $aResult = processResponse($contents);
        $headers = processHeaders($aResult['headers']);
        $location = @$headers['location'];
        if (isset($location) && $location != "") {
            $aUrl = parse_url($headers['location']);
            $host = $aUrl['host'];
            if ('localhost' == strtolower($host)) {
                $host = '127.0.0.1';
            }
            $requestPath = $aUrl['path'] . (isset($aUrl['query']) ? '?' . $aUrl['query'] : '');
            if (empty($requestPath)) {
                $requestPath .= '/';
            }
            download_fsockopen($host, $requestPath, $fileout);
        } else {
            $body = $aResult['body'];
            $transferEncoding = @$headers['transfer-encoding'];
            if ($transferEncoding == 'chunked') {
                $body = http_chunked_decode($aResult['body']);
            }
            if ($fileout != null) {
                $ff = @fopen($fileout, 'w+');
                if ($ff !== FALSE) {
                    fwrite($ff, $body);
                    fclose($ff);
                    return true;
                } else {
                    return false;
                }
            } else {
                return $body;
            }
        }
    }
}
Beispiel #18
0
 /**
  * @param string $varBody
  * @return mixed|void
  */
 public function send($varBody = '')
 {
     $data = $varBody;
     if (is_array($data)) {
         $data = http_build_query($data);
     }
     if ($this->option['method'] == 'POST') {
         if ($data == '') {
             $data = $this->__buildPostData();
             //http_build_query($this->postdata);
         }
         $this->option['content'] = $data;
         if (!isset($this->httpheader['Content-Type'])) {
             if ($this->__isBinary) {
                 $this->httpheader['Content-Type'] = 'Content-Type: multipart/form-data; boundary=' . $this->__boundary;
             } else {
                 $this->httpheader['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
             }
         }
         $this->httpheader['Content-Length'] = 'Content-Length: ' . strlen($data);
     }
     $this->httpheader[] = 'Host: ' . $this->parsed_url['host'];
     //$this->httpheader[] = 'Referer: ' . 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     $this->httpheader[] = 'Connection: close';
     if (!isset($this->httpheader['Accept'])) {
         if (isset($_SERVER['HTTP_ACCEPT'])) {
             $this->httpheader['Accept'] = 'Accept:' . $_SERVER['HTTP_ACCEPT'];
         }
     }
     if (!isset($this->httpheader['Accept-Language'])) {
         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
             $this->httpheader['Accept-Language'] = 'Accept-Language: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE'];
         }
     }
     if ($this->isgzip == true) {
         $this->httpheader['Accept-Encoding'] = 'Accept-Encoding: gzip';
     }
     $this->option['header'] = implode("\r\n", $this->httpheader);
     ZBlogException::SuspendErrorHook();
     $socket = fsockopen(($this->scheme == 'https' ? 'ssl://' : '') . $this->parsed_url['host'], $this->port, $this->errno, $this->errstr, $this->timeout);
     ZBlogException::SuspendErrorHook();
     if (!$socket) {
         return;
     }
     $url = $this->option['method'] . ' ' . ($this->parsed_url['path'] == '' ? '/' : $this->parsed_url['path']);
     if (isset($this->parsed_url["query"])) {
         $url .= "?" . $this->parsed_url["query"];
     }
     fwrite($socket, $url . ' HTTP/1.0' . "\r\n");
     fwrite($socket, $this->option['header'] . "\r\n");
     fwrite($socket, "\r\n");
     if (isset($this->option['content'])) {
         fwrite($socket, $this->option['content'] . "\r\n");
         fwrite($socket, "\r\n");
     }
     while (!feof($socket)) {
         $this->responseText .= fgets($socket, 128);
     }
     $this->responseHeader = substr($this->responseText, 0, strpos($this->responseText, "\r\n\r\n"));
     $this->responseText = substr($this->responseText, strpos($this->responseText, "\r\n\r\n") + 4);
     $this->responseHeader = explode("\r\n", $this->responseHeader);
     $i = $this->maxredirs;
     if ($this->maxredirs > 0) {
         if (strstr($this->responseHeader[0], ' 301 ') || strstr($this->responseHeader[0], ' 302 ') || strstr($this->responseHeader[0], ' 303 ') || strstr($this->responseHeader[0], ' 307 ')) {
             fclose($socket);
             $url = $this->getResponseHeader('Location');
             $this->canreinit = false;
             $this->open('Get', $url);
             $this->setMaxRedirs($i - 1);
             $this->canreinit = true;
             return $this->send();
         }
     }
     if ($this->getResponseHeader('Transfer-Encoding') == 'chunked') {
         if (!function_exists('http_chunked_decode')) {
             $this->responseText = $this->http_chunked_decode($this->responseText);
         } else {
             $this->responseText = http_chunked_decode($this->responseText);
         }
     }
     if ($this->getResponseHeader('Content-Encoding') == 'gzip') {
         if (!function_exists('gzdecode')) {
             $this->responseText = $this->gzdecode($this->responseText);
         } else {
             $this->responseText = gzdecode($this->responseText);
         }
     }
     if (isset($this->responseHeader[0])) {
         $this->statusText = $this->responseHeader[0];
         $a = explode(' ', $this->statusText);
         if (isset($a[0])) {
             $this->responseVersion = $a[0];
         }
         if (isset($a[1])) {
             $this->status = $a[1];
         }
         unset($this->responseHeader[0]);
     }
     fclose($socket);
 }
Beispiel #19
0
/**
 * Download file using fsockopen
 *
 * @since 3.0
 * @param type $sourceFile
 * @param type $fileout
 */
function download_fsockopen($sourceFile, $fileout = null)
{
    // parse URL
    $aUrl = parse_url($sourceFile);
    $host = $aUrl['host'];
    if ('localhost' == strtolower($host)) {
        $host = '127.0.0.1';
    }
    $link = $aUrl['path'] . (isset($aUrl['query']) ? '?' . $aUrl['query'] : '');
    if (empty($link)) {
        $link .= '/';
    }
    $fp = @fsockopen($host, 80, $errno, $errstr, 30);
    if (!$fp) {
    } else {
        $out = "GET {$link} HTTP/1.1\r\n";
        $out .= "Host: {$host}\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= "\r\n";
        fwrite($fp, $out);
        $contents = '';
        while (!feof($fp)) {
            $contents .= fgets($fp, 1024);
        }
        // check redirections ?
        // if (redirections) then do request again
        $aResult = processResponse($contents);
        $headers = processHeaders($aResult['headers']);
        $location = @$headers['location'];
        if (isset($location) && $location != "") {
            $aUrl = parse_url($headers['location']);
            $host = $aUrl['host'];
            if ('localhost' == strtolower($host)) {
                $host = '127.0.0.1';
            }
            $requestPath = $aUrl['path'] . (isset($aUrl['query']) ? '?' . $aUrl['query'] : '');
            if (empty($requestPath)) {
                $requestPath .= '/';
            }
            download_fsockopen($host, $requestPath, $fileout);
        } else {
            $body = $aResult['body'];
            $transferEncoding = @$headers['transfer-encoding'];
            if ($transferEncoding == 'chunked') {
                $body = http_chunked_decode($aResult['body']);
            }
            if ($fileout != null) {
                $ff = @fopen($fileout, 'w+');
                fwrite($ff, $body);
                fclose($ff);
            } else {
                return $body;
            }
        }
        fclose($fp);
    }
}