コード例 #1
0
ファイル: process_upload.php プロジェクト: b3b0y/repository
 function filesize_r($dir)
 {
     @($dh = opendir($dir));
     $size = 0;
     while ($file = @readdir($dh)) {
         if ($file != "." and $file != "..") {
             $path = $dir . "/" . $file;
             if (is_dir($path)) {
                 $size += filesize_r($path);
                 // recursive in sub-folders
             } elseif (is_file($path)) {
                 $size += filesize($path);
                 // add file
             }
         }
     }
     @closedir($dh);
     return $size;
 }
コード例 #2
0
ファイル: http.php プロジェクト: navaneet31/Mine
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, $sFilters;
    $scheme = strtolower($scheme) . '://';
    if ($post !== 0 && ($scheme == 'http://' || $scheme == 'https://')) {
        $method = 'POST';
        $postdata = is_array($post) ? formpostdata($post) : $post;
    } else {
        $method = 'GET';
        $postdata = '';
    }
    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 downloading via HTTPS.');
        }
        $scheme = 'tls://';
        if ($port == 0 || $port == 80) {
            $port = 443;
        }
    }
    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[] = $method . ' ' . str_replace(' ', '%20', $url) . ' HTTP/1.1';
    $request[] = "Host: {$host}";
    $request[] = 'User-Agent: ' . rl_UserAgent;
    $request[] = 'Accept: */*';
    $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}";
    }
    $request[] = 'Pragma: no-cache';
    $request[] = 'Cache-Control: no-cache';
    //	if ($Resume['use'] === TRUE) $request[] = 'Range: bytes=' . $Resume['from'] . '-';
    if (!empty($auth)) {
        $request[] = "Authorization: Basic {$auth}";
    }
    if (!empty($pauth)) {
        $request[] = "Proxy-Authorization: Basic {$pauth}";
    }
    if ($method == 'POST') {
        if (!empty($referer) && stripos($referer, "\nContent-Type: ") === false) {
            $request[] = 'Content-Type: application/x-www-form-urlencoded';
        }
        $request[] = 'Content-Length: ' . strlen($postdata);
    }
    if ($XMLRequest) {
        $request[] = 'X-Requested-With: XMLHttpRequest';
    }
    $request[] = 'Connection: Close';
    $request = implode($nn, $request) . $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) {
        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 ($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>';
        }
    }
    #########################################################################
    fwrite($fp, $request);
    fflush($fp);
    $timeStart = microtime(true);
    // 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);
            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())) {
        // Add built-in dechunk filter
        $sFilters['dechunk'] = stream_filter_append($fp, 'dechunk', STREAM_FILTER_READ);
        if (!$sFilters['dechunk'] && $saveToFile) {
            html_error('Unknown error while initializing dechunk filter, cannot continue download.');
        }
    }
    #########################################################################
    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 = stripos($referer, 'www.') === 0 ? substr($referer, 4) : $referer;
                $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;
                        break;
                    } elseif ($chkref && host_matches($site, $cbrefhost)) {
                        $found = true;
                        break;
                    }
                }
            }
            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')) {
                    // is_callable(array($class , 'CheckBack'))
                    $hostClass = new $class(false);
                    $hostClass->CheckBack($header);
                }
            }
            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 $user, $options;
        ////////////////////////////////speedplli start////////////////////////////
        if ($user['traffic'] > 0) {
            if ($bytesTotal > $user['traffic'] && $user['traffic'] != 0) {
                $lastError = sprintf(lang(461), bytesToKbOrMbOrGb($bytesTotal), bytesToKbOrMbOrGb($user['traffic']));
                return false;
            }
        }
        $file_size_disc = filesize_r($options['download_dir']);
        $disc = $options['disc_space'];
        $disc_size = $disc - $file_size_disc;
        if ($bytesTotal > $disc_size && $options['disc_space'] != 0) {
            $lastError = lang(462);
            return false;
        }
        ////////////////////////////////speedplli end//////////////////////////////
        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;
        } else {
            $ContentDisposition = cut_str($header, "\nContent-Disposition: ", "\n");
            if (!empty($ContentDisposition) && stripos($ContentDisposition, 'filename') !== false) {
                if (preg_match("@filename\\*=UTF-8''((?:[\\w\\-\\.]|%[0-F]{2})+)@i", $ContentDisposition, $fn)) {
                    $FileName = rawurldecode($fn[1]);
                } elseif (preg_match('@filename=\\"?([^\\r\\n\\"\\;]+)\\"?@i', $ContentDisposition, $fn)) {
                    $FileName = $fn[1];
                } else {
                    $FileName = $saveToFile;
                }
            } else {
                $FileName = $saveToFile;
            }
        }
        $FileName = str_replace(array_merge(range(chr(0), chr(31)), str_split("<>:\"/|?*\\")), '', basename(trim($FileName)));
        if (!empty($options['rename_prefix'])) {
            $FileName = $options['rename_prefix'] . '_' . $FileName;
        }
        if (!empty($options['rename_suffix'])) {
            $ext = strrchr($FileName, '.');
            $before_ext = explode($ext, $FileName);
            $FileName = $before_ext[0] . '_' . $options['rename_suffix'] . $ext;
        }
        if ($options['rename_underscore']) {
            $FileName = str_replace(array(' ', '%20'), '_', $FileName);
        }
        $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $FileName;
        $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));
        }
        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']);
            $org_filesize = $fileSize;
            //By speedplli
            $fileSize = bytesToKbOrMbOrGb($fileSize);
        } else {
            $fileSize = bytesToKbOrMbOrGb($bytesTotal);
        }
        $org_filesize = $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();
        }
        //Stop Button
        echo '
		<div id="Stop-Button">
		<form method="post" action="' . $PHP_SELF . '">
		<input type="hidden" id="delete_file" name="delete_file" value="' . base64_encode($saveToFile) . '" />
		<input type="submit" value="Stop Download" />
		</form>
		</div>';
    } 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 = microtime(true) - $timeStart;
                $chunkTime = $time - $lastChunkTime;
                $chunkTime = $chunkTime > 0 ? $chunkTime : 1;
                $lastChunkTime = $time;
                $speed = @round(($bytesReceived - $last) / 1024 / $chunkTime, 2);
                echo "<script type='text/javascript'>pr('{$percent}', '{$received}', '{$speed}');</script>";
                $last = $bytesReceived;
            }
            if (!empty($bytesTotal) && $bytesReceived + $chunkSize > $bytesTotal) {
                $chunkSize = $bytesTotal - $bytesReceived;
            }
        } else {
            $page .= $data;
        }
    } while (!feof($fp) && strlen($data) > 0);
    if ($saveToFile) {
        flock($fs, LOCK_UN);
        fclose($fs);
        if ($bytesReceived <= 0) {
            $lastError = lang(106);
            stream_socket_shutdown($fp, STREAM_SHUT_RDWR);
            fclose($fp);
            return FALSE;
        }
    }
    stream_socket_shutdown($fp, STREAM_SHUT_RDWR);
    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, 'org_filesize' => $org_filesize);
    } else {
        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;
    }
}