<?php


/*
 * Pauses for countdown timer in file hosts
 * @param int The number of seconds to count down
 * @param string The text you want to display when counting down
 * @param string The text you want to display when count down is complete
 * @param bool
 * @return bool
 */


/*
 * Function to check if geturl function has completed successfully
 */
include ("includes/settings.php");

function split_string($string, $delineator, $desired, $type)
    {
    # Case insensitive parse, convert string and delineator to lower case
    $lc_str = strtolower($string);
	$marker = strtolower($delineator);
    
    # Return text BEFORE the delineator
    if($desired == BEFORE)
        {
        if($type == EXCL)  // Return text ESCL of the delineator
            $split_here = strpos($lc_str, $marker);
        else               // Return text INCL of the delineator
            $split_here = strpos($lc_str, $marker)+strlen($marker);
        
        $parsed_string = substr($string, 0, $split_here);
        }
    # Return text AFTER the delineator
    else
        {
        if($type==EXCL)    // Return text ESCL of the delineator
            $split_here = strpos($lc_str, $marker) + strlen($marker);
        else               // Return text INCL of the delineator
            $split_here = strpos($lc_str, $marker) ;
        
        $parsed_string =  substr($string, $split_here, strlen($string));
        }
    return $parsed_string;
    }
	function return_between($string, $start, $stop, $type)
    {
    $temp = split_string($string, $start, AFTER, $type);
    return split_string($temp, $stop, BEFORE, $type);
    }
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, $PHP_SELF, $AUTH, $IS_FTP, $FtpBytesTotal, $FtpBytesReceived, $FtpTimeStart, $FtpChunkSize, $Resume, $bytesReceived, $fs, $force_name, $options;
    $scheme .= "://";

    if (($post !== 0) && ($scheme == "http://" || $scheme == "https://")) {
        $method = "POST";
        $postdata = formpostdata($post);
        $length = strlen($postdata);
        $content_tl = "Content-Type: application/x-www-form-urlencoded" . $nn . "Content-Length: " . $length . $nn;
    } else {
        $method = "GET";
        $postdata = "";
        $content_tl = "";
    }

    $cookies = "";
    if ($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://";
        $port = 443;
    }

    if ($proxy) {
        list ( $proxyHost, $proxyPort ) = explode(":", $proxy);
        $host = $host . ($port != 80 && $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 = $method . " " . str_replace(" ", "%20", $url) . " HTTP/1.1" . $nn . "Host: " . $host . $nn . "User-Agent: Opera/9.80 (Windows NT 6.1; U; en-US) Presto/2.10.229 Version/11.61" . $nn . "Accept: */*" . $nn . "Accept-Language: en-us;q=0.7,en;q=0.3" . $nn . "Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7" . $nn . "Pragma: no-cache" . $nn . "Cache-Control: no-cache" . $nn . ($Resume ["use"] === TRUE ? "Range: bytes=" . $Resume ["from"] . "-" . $nn : "") . $http_auth . $proxyauth . $referer . ($XMLRequest ? "X-Requested-With: XMLHttpRequest" . $nn : "") . $cookies . "Connection: Close" . $nn . $content_tl . $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 = $proxyHost ? $proxyHost : $host;
        $dis_port = $proxyPort ? $proxyPort : $port;
		echo'<div class="progress_container">';
        html_error(sprintf(lang(88), $dis_host, $dis_port));
		  echo "</div>";
    }

    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>";
            printf(lang(90), $host, $port);
            echo "</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);

    #########################################################################

    $NoDownload = FALSE;
    if ($saveToFile) {
        if (!isset($_GET['dis_plug']) || $_GET ['dis_plug'] != "on") {
            foreach ($GLOBALS['host'] as $site => $file) {
                if (preg_match("/^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}(:\d+)?$/", $host)) break;
                if (preg_match("/^(.+\.)?" . str_replace('.', '\.', $site) . "(:\d+)?$/i", $host)) {
                    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')) {
                        $GLOBALS['lang'][300] = '';
                        $hostClass = new $class();
                        $hostClass->CheckBack($header);
                    }
                }
            }
        }            
        if (preg_match('/^HTTP\/1\.(?:0|1) ([0-9]+) .*/', $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) {
                
				   echo '<div class="progress_container"><strong>';
				   echo $lastError = lang(93);
				                    echo "</strong><br>";
        echo "<a href=\"remote.php\">"."<img src=\"images/red-back.png\" border=\"0\" /></a></div>";
        include("templates/footer.php");
                       exit;
            } 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, "Content-Length:", "\n"));

        global $options;
        if ($options['file_size_limit'] > 0) {
            if ($bytesTotal > $options['file_size_limit'] * 1024 * 1024) {
                $lastError = lang(336) . bytesToKbOrMbOrGb($options['file_size_limit'] * 1024 * 1024) . ".";
                return false;
            }
        }
        $redir = "";
        if (trim(preg_match('/[^\-]Location: *(.+)(\r|\n)+/i', $header, $redir))) {
            $redirect = $redir [1];
            $lastError = sprintf(lang(95), $redirect);
            return FALSE;
        }
        if (in_array(cut_str($header, "WWW-Authenticate: ", " "), array("Basic", "Digest"))) {
            $lastError = lang(96);
            return FALSE;
        }
        $ContentType = trim(cut_str($header, "Content-Type:", "\n"));
        if (stristr($host, "rapidshare") && stristr($ContentType, "text/html") && stristr($header, "404 Not Found")) {
            unset($saveToFile);
            $NoDownload = TRUE;
        } elseif (stristr($host, "megaupload") && stristr($ContentType, "text/html")) {
            unset($saveToFile);
            $NoDownload = TRUE;
        }
        if ($Resume ["use"] === TRUE && !stristr($header, "Content-Range:")) {
            if (stristr($header, "503 Limit Exceeded")) {
                $lastError = lang(97);
            } else {
                $lastError = lang(98);
            }
            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);
                $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.
            echo '<script type="text/javascript">parent.nextlink();</script>';
            $firstme = link_for_file($saveToFile);
            $second="<img src=\"templates/youtube/images/download.jpg\">";
            echo "<a href=\"$firstme\">$second</a>";
            exit ();
        }
	


        if (@file_exists($saveToFile) && $Resume ["use"] === TRUE) {
            $fs = @fopen($saveToFile, "ab");
            if (!$fs) {
			echo '<div class="progress_container"><strong>';
                $lastError = sprintf(lang(101), basename($saveToFile), dirname($saveToFile)) . '<br />' . lang(102) . '<br /><a href="javascript:location.reload();">' . lang(103) . '</a>';
				echo '</strong></div">';
                return FALSE;
            }
        } else {
            if (@file_exists($saveToFile)) {
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $options['download_dir'].time() . "_" . basename($saveToFile);
            }
			 if (@!file_exists($saveToFile)) {
                $saveToFile = dirname($saveToFile) . PATH_SPLITTER . $options['download_dir'].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) {
			echo '<div class="progress_container"><strong>';
                $lastError = sprintf(lang(101), basename($saveToFile), dirname($saveToFile)) . '<br />' . lang(102) . '<br /><a href="javascript:location.reload();">' . lang(103) . '</a>';
				echo '</strong></div">';
                    return FALSE;
                }
            }
        }
		$original_name= return_between(basename($saveToFile), '_', '.', 'EXCL') ;  // get the file name without the time()
		include ("includes/settings.php");
		
		$ext = pathinfo(basename($saveToFile), PATHINFO_EXTENSION);
		
              if (!in_array(end(explode(".", strtolower($ext))), $allowedExtensions) && !stristr($host, "youtube"))
                  {
				 
				  echo $host;
                    echo '<div class="progress_container"><strong>'.$ext.'</strong><br> is an invalid file type!<br>Supported files are:<br><strong>';
                    foreach ($allowedExtensions as $value) { echo $value . "<br>"; }
                    echo "</strong><br>";
        echo "<a href=\"remote.php\">"."<img src=\"images/red-back.png\" border=\"0\" /></a></div>";
		echo $url;
        include("templates/footer.php");
                       exit;
                  }

				  
//echo $original_name.$ext."<br>";
        flock($fs, LOCK_EX);
        if ($Resume ["use"] === TRUE && stristr($header, "Content-Range:")) {
            list ( $temp, $Resume ["range"] ) = explode(" ", trim(cut_str($header, "Content-Range:", "\n")));
            list ( $Resume ["range"], $fileSize ) = explode("/", $Resume ["range"]);
            $fileSize = bytesToKbOrMbOrGb($fileSize);
        } else {
            $fileSize = bytesToKbOrMbOrGb($bytesTotal);
        }
		if ( round($fileSize)> ini_get("memory_limit") ){
		$allowed_size=round(ini_get("memory_limit"));
		echo '<div style="text-align: center">';
		echo "the uploaded file size is ".round($fileSize)." MB";
		echo " the file size is bigger than the upload limit <br>";
		echo "the allowed upload size is $allowed_size MB";
		 echo "<a href=\"remote.php\">"."<img src=\"images/red-back.png\" border=\"0\" /></a>";
		echo '</div>';
        include("templates/footer.php");
                       exit;
		}
        $chunkSize = GetChunkSize($bytesTotal);
        if (strpos(basename($saveToFile),'YT') !== false) {
        $youtube_title = substr(basename($saveToFile), 0, -25);  
        }else{
        $youtube_title = substr(basename($saveToFile), 0, -4);    
        }
        $youtube_title = str_replace('_', ' ', $youtube_title);
		//include ('templates/header_remote.php');       // casue 2 header in transload
		echo'<div class="progress_container">';
		if ($saveTggoFile= "") {
echo 'gggg';
exit();	
}
		$original_name=str_replace(array("_","-"), " ", $original_name);
        echo(lang(104) . $original_name .'<br />'. lang(56) . $fileSize . '<br />');

        //$scriptStarted = false;
        require ('templates/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 = $header;
    }

    $time = $last = $lastChunkTime = 0;
    do {  // don't remove
        $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 > - 1) {
                $bytesReceived += $bytesSaved;
            } else {
                $lastError = sprintf(lang(105), $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 ($NoDownload) {
            if (stristr($host, "rapidshare")) {
                is_present($page, "You have reached the limit for Free users", lang(107), 0);
                is_present($page, "The download session has expired", lang(108), 0);
                is_present($page, "Wrong access code.", lang(109), 0);
                is_present($page, "You have entered a wrong code too many times", lang(110), 0);
                print $page;
            } elseif (stristr($host, "megaupload")) {
                is_present($page, "Download limit exceeded", lang(111), 0);
                print $page;
            }
        } else {
            return $page;
        }
    }
}




function GetChunkSize($fsize) {
    if ($fsize <= 1024 * 1024) {
        return 4096;
    }
    if ($fsize <= 1024 * 1024 * 10) {
        return 4096 * 10;
    }
    if ($fsize <= 1024 * 1024 * 40) {
        return 4096 * 30;
    }
    if ($fsize <= 1024 * 1024 * 80) {
        return 4096 * 47;
    }
    if ($fsize <= 1024 * 1024 * 120) {
        return 4096 * 65;
    }
    if ($fsize <= 1024 * 1024 * 150) {
        return 4096 * 70;
    }
    if ($fsize <= 1024 * 1024 * 200) {
        return 4096 * 85;
    }
    if ($fsize <= 1024 * 1024 * 250) {
        return 4096 * 100;
    }
    if ($fsize <= 1024 * 1024 * 300) {
        return 4096 * 115;
    }
    if ($fsize <= 1024 * 1024 * 400) {
        return 4096 * 135;
    }
    if ($fsize <= 1024 * 1024 * 500) {
        return 4096 * 170;
    }
    if ($fsize <= 1024 * 1024 * 1000) {
        return 4096 * 200;
    }
    return 4096 * 210;
}
function is_page($lpage) {
    global $lastError;
    if (!$lpage) {
        html_error(lang(84) . "<br />$lastError", 0);
    }
}
function CookiesToStr($cookie=array()) {
    if (count($cookie) == 0) return '';
    $cookies = "";
    foreach ($cookie as $k => $v) {
        $cookies .= "$k=$v; ";
    }
    // Remove the last ';'
    $cookies = substr($cookies, 0, -2);
    return $cookies;
}
?>
