<?php
/*
* Home page: http://vinaget.us
* Blog:	http://blog.vinaget.us
* Script Name: Vinaget 
* Version: getlink.vn (1.12.2011)
* Description: 
	- Vinaget is script generator premium link that allows you to download files instantly and at the best of your Internet speed.
	- Vinaget is your personal proxy host protecting your real IP to download files hosted on hosters like RapidShare, megaupload, hotfile...
	- You can now download files with full resume support from filehosts using download managers like IDM etc
	- Vinaget is a Free Open Source, supported by a growing community.
* Code LeechViet by VinhNhaTrang
* Developed by ..:: [H] ::..

*/

##################################### Begin class getinfo #####################################
class getinfo {
	// Legacy dual-write: mirror .dat into a separate sqlite DB for fast list/quota.
	public $legacy_sqlite_path = '';
	public $legacy_sqlite_enabled = true;

	function config(){
		$self = strtolower($this->isHttps().$_SERVER['HTTP_HOST'].preg_replace('/\?.*$/', '', isset($_SERVER['REQUEST_URI'])? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']));
		
		include("config.php");
		if(stristr($self,'http://')==true && isset($truehttps)==true && $truehttps == true) {
			$self = str_replace('http://','https://',$self);
			//header("location:".$self);	
			//exit;
			die("<SCRIPT language='Javascript'>document.location.href ='".$self."';</SCRIPT>");
		}
		elseif(stristr($self,'https://')==true && isset($truehttps)==true && $truehttps == false) {
			$self = str_replace('https://','http://',$self);
			die("<SCRIPT language='Javascript'>document.location.href ='".$self."';</SCRIPT>");
		}
		
		//print_r($acc_type);
		$this->self = $self;
		if(!defined('IMG_DOMAIN')){
		  echo '<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=https://'.$homepage.'">';
		  exit;
		}
		
		if (!file_exists(".htaccess")) {
			echo "<CENTER><font color=red size=4>Can't find file <B>.htaccess</B></font></CENTER>";
			exit;
		}
		if(!file_exists($fileinfo_dir.'/info.backup.php') && !file_exists($fileinfo_dir."/info.php")) { 
			$str = "<?php";
			$str .= "\n\$SecureID = \"".$passdefault."\";";
			$str .= "\n\$email = \"\";";
			$str .= "\n\$username = \"\";";
			$str .= "\n\$old = \"\";";
			$str .= "\n\$mobile = \"\";";
			$str .= "\n\$address = \"\";";
			$str .= "\n\$created = ".time().";";
			$str .= "\n\$expired = 0;";
			$str .= "\n?>";

			$clog=fopen($fileinfo_dir."/info.php","a") 
			or die('<CENTER><font color=red size=3>Could not create to file ! Try to chmod the folder "<B>files</B>" to 777</font></CENTER>');
			fwrite($clog,$str);
			fclose($clog);
		}
		if (!file_exists ($fileinfo_dir."/files/")) {
			mkdir($fileinfo_dir."/files/", 0777)  
			or die('<CENTER><font color=red size=4>Could not create folder! Try to chmod the folder "<B>files</B>" to 777</font></CENTER>');
		}
		if(!file_exists($fileinfo_dir."/index.php")) { 
			$clog=fopen($fileinfo_dir."/index.php","a") 
			or die('<CENTER><font color=red size=3>Could not create to file ! Try to chmod the folder "<B>files</B>" to 777</font></CENTER>');
			fwrite($clog,'<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=https://'.$homepage.'">');
			fclose($clog);
		}
		if(!file_exists($fileinfo_dir."/files/index.php")) { 
			$clog=fopen($fileinfo_dir."/files/index.php","a") 
			or die('<CENTER><font color=red size=3>Could not create to file ! Try to chmod the folder "<B>files</B>" to 777</font></CENTER>');
			fwrite($clog,'<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=https://'.$homepage.'">');
			fclose($clog);
		}
		if ($Secure == true) $this->Deny = true;
		if(isset($_COOKIE["secureid"]) && isset($SecureID) && $_COOKIE["secureid"] == md5($SecureID)) {
			$this->Deny = false;
		}
		elseif(isset($_POST["veri"]) && $_POST["veri"]== $this->pw_verified) {
			$this->Deny = false;
		}
		elseif(isset($_GET["autologin"]) && $_GET["autologin"] == $this->pw_autologin) {
			setcookie("secureid",md5($SecureID),time()+3600*24*365);
			$this->Deny = false;
		}


		$this->lang = $lang;
		$this->Secure = $Secure;
		$this->fileinfo_dir = $fileinfo_dir;
		$this->legacy_sqlite_path = rtrim($fileinfo_dir, '/').'/legacy.sqlite';
		$this->fileinfo_ext = $fileinfo_ext;
		$this->fileinfo = $fileinfo;
		$this->download_prefix = $download_prefix;
		$this->banned = explode(' ', '.htaccess .htpasswd .php .php3 .php4 .php5 .phtml .asp .aspx .cgi .pl');    // banned filetypes
		$this->UserAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0';
		$this->unit = 1024; 
		if(isset($limit2MBIP)) $this->limitMBIP = $limitMBIP + $limit2MBIP;
		else $this->limitMBIP = $limitMBIP;
		$this->plusbw = $plusbw;
		$this->maxbw = $maxbw;
		$this->ttl = $ttl;
		$this->max_load = $max_load;
		$this->listfile = $listfile;
		$this->privatef = $privatefile;
		$this->privateip = $privateip;
		$this->passgate = $passgate;
		$this->linkgate = $linkgate;
		$this->megalink = $megalink;
		$this->passmega = $passmega;
		$this->linkmagnet = $linkmagnet;
		$this->passmagnet = $passmagnet;
		$this->infomagnet = $infomagnet;
		if(isset($email)) $this->email = $email;
		if(isset($mobile)) $this->mobile = $mobile;
		if(isset($SecureID)) $this->SecureID = $SecureID;
		if(isset($created)) $this->created = $created;
		if(isset($expired)) $this->expired = $expired;
		$this->linkmail = $linkmail;
		$this->passmail = $passmail;
		$this->mailerror = $mailerror;
		$this->max_ip = $max_ip_login;
		$this->linkreport = $linkreport;
		$this->pathphim = $pathphim;
		$this->facebook = $facebook;
		$this->group = $group;
		#- 2021/03/04 - 20:12:20 (GMT+7) mở gator cho khách gần hết hạn
		if(isset($on_gator)==true && isset($groupgator)==true && isset($this->expired)) {
			if($this->expired - time() < $on_gator*24*60*60) $this->group[] = $groupgator.'.'.date('m.Y', time());
		}
		if(isset($_GET['groupsp'])) { print_r($this->group); exit;}
		#- 2021/03/04 - 20:12:20 (GMT+7) mở gator cho khách gần hết hạn

		$this->acc_type = $acc_type;
		$this->checkisp = $checkisp.'?url='.urlencode($this->self).'&ip=';
		$this->myip = $this->yourip();
		if (!isset($this->mng_normal['other'])) die('Error 1.1: Phiên bản cũ vui lòng liên hệ getlink để cập nhật phiên bản mới hơn');
		if(!isset($this->leechmng)) $this->leechmng = $this->mng_normal['other'];
		if (!isset($this->hosts)) die('Phiên bản cũ vui lòng liên hệ getlink để cập nhật phiên bản mới hơn');
		$this->checkip($this->myip);

	}

	function checkip($ipcheck){
		$this->datamega['user']['ip'] = $ipcheck;
		//check isp and set cookie network
		if(preg_match("/^(\d{1,3}\.\d{1,3}\.\d{1,3})/i", $ipcheck, $value)) $ip = $value[1];
		else $ip = $ipcheck;
		//$ip = '118.71.182';
		if(!isset($_COOKIE['ip']) || !isset($_COOKIE['network'])  || !isset($_COOKIE['country']) || stristr($ip,$_COOKIE['ip']) == false) {

			if($this->getinfo_ip == false) {
				$data = '{"realip":"'.$ipcheck.'","ip":"'.$ip.'","status":"whitelist","host":"'.$ipcheck.'","isp":"fpt","city":"unkown","country":"unkown","time":'.time().'}';
			}
			else $data = $this->curl($this->checkisp.$ipcheck,"","");
			$this->isp_data = $data;
			if(isset($_GET['testisp'])) echo $this->checkisp.$ipcheck.'<BR>'.$data.'<BR>';
			$json = json_decode($data, true);
			if (is_array($json)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$json = json_decode($data, true);
			}
			if(!isset($json['country'])) {
				$data = '{"realip":"'.$ipcheck.'","ip":"'.$ip.'","status":"whitelist","host":"'.$ipcheck.'","isp":"vnpt","city":"unkown","country":"unkown","time":'.time().'}';
				$json = @json_decode($data, true);
				//if(!isset($json['country'])) die('Invalid IP');
			}
			if(stristr($data,'fpt')) $network = 'fpt';
			elseif(stristr($data,'viettel')) $network = 'viettel';
			elseif(stristr($data,'vnpt') || stristr($data,'VIETNAM POSTS')) $network = 'vnpt';
			elseif(stristr($data,'vdc')) $network = 'vnpt';
			else $network = $json['isp'];
			$this->network = $network;
			$this->datamega['user']['network'] = $network;
			$this->datamega['user']['country'] = $json['country'];
			$_COOKIE['ip'] = $ip;
			$_COOKIE['network'] = $network;
			$_COOKIE['country'] = $json['country'];
			setcookie('network',$network,time()+10*60);
			setcookie('ip',$ip,time()+10*60);
			setcookie('country',$json['country'],time()+10*60);
		}
		else {
			$this->datamega['user']['network'] = $_COOKIE['network'];
			$this->datamega['user']['country'] = $_COOKIE['country'];
		}
		//echo $_COOKIE['network'].$_COOKIE['ip'];exit;
		//check isp and set cookie network
	}
	function isHttps(){
		if (array_key_exists("HTTPS", $_SERVER) && 'on' == $_SERVER["HTTPS"]) {
			return 'https://';
		}
		if (array_key_exists("SERVER_PORT", $_SERVER) && 443 == (int)$_SERVER["SERVER_PORT"]) {
			return 'https://';
		}
		if (array_key_exists("HTTP_X_FORWARDED_SSL", $_SERVER) && 'on' == $_SERVER["HTTP_X_FORWARDED_SSL"]) {
			return 'https://';
		}
		if (array_key_exists("HTTP_X_FORWARDED_PROTO", $_SERVER) && 'https' == $_SERVER["HTTP_X_FORWARDED_PROTO"]) {
			return 'https://';
		}
		return 'http://';
	}
	function yourip(){
		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif(isset($_SERVER['HTTP_X_REAL_IP'])) $ip = $_SERVER['HTTP_X_REAL_IP'];
		else $ip = $_SERVER['REMOTE_ADDR'];
		$ip = preg_replace("/(\,.*)/i",'',$ip);
		return $ip;
	}
	function ip_proxy($link_acc){
		$folder_db = '../../../../../accounts/proxy_ip/';
		$ip = $this->myip;
		if(preg_match("/^(\d{1,3}\.\d{1,3}\.\d{1,3})/i", $ip, $value)) $ip = $value[1];
		if (!file_exists ($folder_db)) {
			mkdir($folder_db, 0777)  or die('<CENTER><font color=red size=4>Could not create folder logs ip!</font></CENTER>');
		}
		list($db_proxy, $px_lists, $px_tmp_old) = $this->load_data($folder_db);
		$hash_px = md5($link_acc);
		$time = time();

		if(isset($db_proxy[$hash_px]['logs'][$ip])) return;

		if(isset($db_proxy[$hash_px]['logs']) && count($db_proxy[$hash_px]['logs']) == 5) {
			$logs = $db_proxy[$hash_px]['logs'];
			unset($db_proxy[$hash_px]['logs']);
			$i = 1;
			$compare = $this->datecmp('time'); 
			usort($array, $compare);
			foreach($logs as $key=>$val) {
				if($i == 5) break;
				$db_proxy[$hash_px]['logs'][$val['ip']] = $val;
				$i++;
			}
		}

		$db_proxy[$hash_px]['account'] = $link_acc;
		$db_proxy[$hash_px]['hash'] = $hash_px;
		$db_proxy[$hash_px]['time'] = $time;
		$db_proxy[$hash_px]['status'] = 1;
		$db_proxy[$hash_px]['logs'][$ip]['time'] = $time;
		$db_proxy[$hash_px]['logs'][$ip]['ip'] = $ip;
		if(isset($_SERVER['HTTP_USER_AGENT'])) $db_proxy[$hash_px]['logs'][$ip]['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
		else $db_proxy[$hash_px]['logs'][$ip]['HTTP_USER_AGENT'] = '';

		$file_porxy = $this->rand_filename($folder_db);
		$tmp = @json_encode($db_proxy);
		if($px_tmp_old == $tmp) return;
		$px_tmp_old == $tmp;

		$fh = fopen($file_porxy, 'w') or die('<CENTER><font color=red size=3>Could not open folder proxy data!!!</font></CENTER>');
		fwrite($fh, $tmp);
		fclose($fh);
		@chmod($file_jobs, 0666);
		if (is_array($px_lists) && count($px_lists)) foreach ($px_lists as $file) if (file_exists($file)) @unlink($file);
		$txt = '';
		$db_ip = array();
		foreach($db_proxy as $list_acc) {
			foreach($list_acc['logs'] as $ip_acc=>$time_acc) {
				if(!isset($db_ip[$ip_acc])) {
					$txt .= $ip_acc.".1/24\r\n";
					//$db_ip[$ip_acc] = $ip_acc.'.1/24#'.'	'.date( 'H:i:s- d.m.Y',$time_acc['time']).' | '.$list_acc['account'].' | '.$time_acc['HTTP_USER_AGENT']."\r\n";
					$db_ip[$ip_acc] = $ip_acc.".1/24\r\n";
				}
			}
		}
		$file_txt_logs = $folder_db.'list_ip_porxy.txt';
		if(!empty($txt)) $this->savefile($file_txt_logs,$txt);

		return true;

	}

	function notice(){
		if(!isset($this->bw['timeupdate']) || !isset($this->bw['bwupdate']))  {
			printf($this->lang['notfilebw'],$this->lang['mail_hotro']);
			return;
		}
		//save log ip login to proxy
		$link_acc = str_replace('index.php','',$this->self);
		//$this->ip_proxy($link_acc);
		//save log ip login to proxy
		if(!isset($_COOKIE['ip']) or !isset($_COOKIE['network']) or !isset($_COOKIE['country']) or stristr($this->myip,$_COOKIE['ip'])==false) {
			if(preg_match("/^(\d{1,3}\.\d{1,3}\.\d{1,3})/i", $this->myip, $value)) $ip = $value[1];
			else $ip = $this->myip;
			$data = $this->curl($this->checkisp.$ip,"","");
			$json = json_decode($data, true);
			if (is_array($json)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$json = json_decode($data, true);
			}
			if(stristr($data,'fpt')) $network = 'fpt';
			elseif(stristr($data,'viettel')) $network = 'viettel';
			elseif(stristr($data,'vnpt') || stristr($data,'VIETNAM POSTS')) $network = 'vnpt';
			elseif(stristr($data,'vdc')) $network = 'vnpt';
			else $network = $json['isp'];
			$country = $json['country'];
			$_COOKIE['ip'] = $ip;
			$_COOKIE['network'] = $network;
			$_COOKIE['country'] = $country;

			setcookie('network',$network,time()+10*60);
			setcookie('ip',$ip,time()+10*60);
			setcookie('country',$country,time()+10*60);
		}
		else {
			$ip = $_COOKIE['ip'].'.***';
			$network = $_COOKIE['network'];
			$country = $_COOKIE['country'];
		}
		$show_ip = $ip.' ('.strtoupper($network).' - '.$country.')';
		$time = $this->expired - time();
		$expired = $this->convert_time($time);

		$mydomain = str_replace("my.","",$_SERVER['HTTP_HOST']);
		if($time < 0) $expired = '<b><font color=expired>'.$this->lang['out_time'].'</font></b>';
		elseif($time < 2*24*60*60) $expired = '<b> <span class="expired">'.$expired.'</span></b> <a href="https://'.$mydomain.'/giahan.php?url='.$link_acc.'">'.$this->lang['renewnow'].'</a>';
		elseif($time < 7*24*60*60) $expired = '<b><font color=red>'.$expired.'</font></b> <a href="https://'.$mydomain.'/giahan.php?url='.$link_acc.'">'.$this->lang['renewnow'].'</a>';
		//elseif($time < 2*24*60*60) $expired = '<b> <span class="expired">'.$expired.'</span></b> <a href="./login.php?go=renew">'.$this->lang['renewnow'].'</a>';
		//elseif($time < 7*24*60*60) $expired = '<b><font color=red>'.$expired.'</font></b> <a href="./login.php?go=renew">'.$this->lang['renewnow'].'</a>';
		printf($this->lang['notice'],$this->lang['dontshare'],$this->convertmb($this->total_acc_unless()),$show_ip,count($this->jobs['get']), $expired,$this->limitMBIP/1024);

		//check hết hạn
		if($this->expired < time()+3*24*60*60 && $this->acc_type['reset_bw'] == true && $this->info["logsmail"]["expired"] == false) {
			if((isset($_COOKIE["ck_logout"]) && time() - $_COOKIE["ck_logout"] > 3600*24) || !isset($_COOKIE["ck_logout"])) {
				setcookie('ck_logout',time(),time()+3600*24*365);
				die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=logout';</SCRIPT>");
			}
		}
	}

	function showjson($json){
		if(isset($json['error'])) {
			$error = $json['error'];
			unset($json);
			$json['error'] = $error;
			$json['status'] = false;
		}
		if(!isset($json['status']))  $json['status'] = false;
		if(isset($_GET['callback'])) echo $_GET['callback'] . '(' . json_encode($json) . ')';
		else echo json_encode($json);
		exit;
	}

	function user_info() {
		$json = array();
		if(isset($_GET['info']) && isset($_POST['veri']) && $_POST['veri'] == $this->pw_verified) {
			if($this->info['status']) {
				$json['bandwitdh'] = $this->bw['bandwitdh'];
				$json[$host] = $this->bw[$host];
			}
			else $json['error'] = 'error 1';
		}
		else $json['error'] = 'error 2';
		$this->showjson($json);
	}

	function user_api() {
		$json = array();
		if(isset($_POST['test'])) $test = true;
		else $test = false;	
		if(isset($_GET['api']) && isset($_POST['veri'])  && isset($_POST['data']) && $_POST['veri'] == $this->pw_verified) {
			if($_GET['api'] == 'status'){
				$data = $_POST['data'];
				$page = json_decode($data, true);
				if (is_array($page)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$page = json_decode($data, true);
				}
				if(!is_array($page) || count($page)==0) {
					$json[$hash]['status'] = 999;
					$json[$hash]['result'] = 3;
					echo json_encode($json);
					exit;
				}
				foreach($page as $hash=>$status){
					if(!isset($this->jobs['leech'][$hash]) ) {
						$json[$hash]['result'] = -1;
						continue;
					}
					$job = $this->jobs['leech'][$hash];
					$json[$hash]['status'] = $job['status'];
					if($job['status'] == $status) $json[$hash]['result'] = 1;
					else $json[$hash]['result'] = 0;
				}
			}
		}
		echo json_encode($json);
		exit;
	}

	function update_array($jobs, $update) {
		if(!is_array($update)) return $jobs;
		foreach($update as $key=>$value) {
			if(is_array($value)) {
				if(isset($jobs[$key])) $jobs[$key] = $this->update_array($jobs[$key], $update[$key]);
				elseif(is_array($jobs)) $jobs[$key] = $update[$key];
			}
			else{
				if(is_array($jobs)) $jobs[$key] = $update[$key];
			}
		}
		return $jobs;
	}

	function load_data($pathfile,$fulldata=true){
		if(!file_exists($pathfile)) return;
		$fileinfo_ext = $this->fileinfo_ext;
		$dir = opendir($pathfile);
		$lists = array();
		while ($file = readdir($dir)){
			if (substr($file,-strlen($fileinfo_ext)-1) == "." . $fileinfo_ext){
				$lists[] = $pathfile . $file;
			}
		}
		closedir($dir);
		$data = array();
		if (is_array($lists) && count($lists)){
			sort($lists);
			foreach ($lists as $file){
				$contentsfile = @file_get_contents($file);
				if ($contentsfile === false) continue;
				$jobs_data = json_decode((string)$contentsfile,true);	
				if (is_array($jobs_data)){
					$data = $this->update_array($data, $jobs_data);
				}
			}	
		}
		$tmp_old = json_encode($data);
		if($fulldata) return array($data, $lists, $tmp_old);
		else return $data;
	}

	function rand_filename($folder){
		$namedata = $timeload = explode(" ", microtime());
		$namedata = $namedata[1]*1000 + round($namedata[0]*1000);
		$filename = $folder.$namedata. ".dat";
		if (file_exists($filename)) $this->rand_filename($folder);
		return $filename;
	}

	function autodelfile2($jobs,$ttl=false){
		$delete = array();
		if(isset($ttl)==true && $ttl == true) $ttl = 2*$this->ttl;
		else $ttl = $this->ttl;
		$oldest = time() - $ttl*60;
		foreach ($jobs as $key=>$job) {
			if($key == 'clearfile') continue;
			if ($job['mtime'] < $oldest) {
				$delete[] = $key;
			}
		}
		foreach ($delete as $md5) {
			unset($jobs[$md5]);
		}


		return $jobs;
	}

	function autodelfile(){
		if(isset($this->jobs['get'])) {
			$delete = array();
			$oldest = time() - $this->ttl*60;
			foreach ($this->jobs['get'] as $key=>$job) {
				if($key == 'clearfile') continue;
				if ($job['mtime'] < $oldest) {
					$delete[] = $key;
				}
			}
			foreach ($delete as $md5) {
				unset($this->jobs['get'][$md5]);
			}
			if(is_array($delete) && count($delete)>2) $this->save_jobs();
		}

		if(isset($this->jobs['leech'])) {
			$delete = array();
			$oldest = time() - 2*$this->ttl*60;
			foreach ($this->jobs['leech'] as $key=>$job) {
				if($key == 'clearfile') continue;
				if ($job['mtime'] < $oldest) {
					$delete[] = $key;
				}
			}
			foreach ($delete as $md5) {
				unset($this->jobs['leech'][$md5]);
			}
			if(is_array($delete) && count($delete)>2) $this->save_jobs();
		}
		return;
	}

	function save_jobs(){
		if (!isset($this->jobs) || is_array($this->jobs)==false) die('error 01: not found data');

		// lock to avoid concurrent .dat corruption and keep sqlite mirror consistent
		$lockPath = $this->fileinfo_dir.'/files/.save_jobs.lock';
		$lockFp = @fopen($lockPath, 'c');
		$locked = false;
		if ($lockFp) {
			$start = time();
			while (!( $locked = @flock($lockFp, LOCK_EX | LOCK_NB) )) {
				if (time() - $start >= 5) break;
				usleep(200000); // 200ms
			}
		}

		$file_jobs = $this->rand_filename($this->fileinfo_dir.'/files/');
		$tmp = @json_encode($this->jobs);
		if($this->tmp_old != $tmp) $this->tmp_old = $tmp;
		else {
			if ($locked) @flock($lockFp, LOCK_UN);
			if ($lockFp) @fclose($lockFp);
			return;
		}

		// write .dat (legacy)
		$fh = fopen($file_jobs, 'w+') or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the folder "<B>'.$this->fileinfo_dir.'</B>" to 777</font></CENTER>');
		fwrite($fh, $tmp);
		fclose($fh);
		@chmod($file_jobs, 0666);

		// mirror into legacy sqlite (fail-open)
		if ($this->legacy_sqlite_enabled) {
			$db = $this->legacy_sqlite_connect();
			if ($db) {
				$this->legacy_sqlite_upsert_jobs($db, $file_jobs);
			}
		}

		// cleanup old dat files
		if (is_array($this->lists) && count($this->lists)) foreach ($this->lists as $file) if (file_exists($file)) @unlink($file);

		if ($locked) @flock($lockFp, LOCK_UN);
		if ($lockFp) @fclose($lockFp);
		return true;
	}

	function load_info(){
		if(isset($this->info)) return;
		$this->info_data = @file_get_contents($this->fileinfo_dir."/".$this->fileinfo);
		$this->info = @json_decode($this->info_data, true);	
		if (!is_array($this->info)){
			$this->info = array();
			$this->info_data = 'vng';
		}
	}
	function save_info(){
		if (!isset($this->info) || is_array($this->info)==false) return;
		$tmp = json_encode($this->info);
		if ($tmp != $this->info_data){
			$this->info_data = $tmp;
			$fh = fopen($this->fileinfo_dir."/".$this->fileinfo, 'w') 
			or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the folder "<B>'.$this->fileinfo_dir.'</B>" to 777</font></CENTER>');
			fwrite($fh, $this->info_data) 
			or die('<CENTER><font color=red size=3>Could not write file ! Try to chmod the folder "<B>'.$this->fileinfo_dir.'</B>" to 777</font></CENTER>');
			fclose($fh);
			@chmod($this->fileinfo_dir."/".$this->fileinfo, 0666);
			return true;	
		}
	}

	// ----- Legacy dual-write helpers (legacy.sqlite) -----
	function legacy_log($msg) {
		$log = rtrim($this->fileinfo_dir,'/')."/sqlite_dualwrite.log";
		@file_put_contents($log, date('Y-m-d H:i:s')." | ".$msg."\n", FILE_APPEND);
	}

	function legacy_norm_url($url) {
		$u = trim((string)$url);
		$u = preg_replace('~^https?://rg\\.to/file/~i', 'https://rapidgator.net/file/', $u);
		$u = preg_replace('~\\.html$~i', '', $u);
		return $u;
	}

	function legacy_norm_url_for_uniqueness($url) {
		$u = $this->legacy_norm_url($url);
		$u = preg_replace('~^https?://~i', '', $u);
		$u = preg_replace('~^www\\.~i', '', $u);
		$u = preg_replace('~/$~', '', $u);
		return $u;
	}

	function legacy_status_text($statusCode) {
		$s = (int)$statusCode;
		if ($s === 1 || $s === 3) return 'ready';
		if ($s === 4) return 'failed';
		if ($s === 5 || $s === 6 || $s === 7) return 'rejected';
		return 'processing';
	}

	function legacy_sqlite_connect() {
		if (!$this->legacy_sqlite_enabled) return null;
		$path = $this->legacy_sqlite_path;
		if (empty($path)) return null;
		try {
			$db = new PDO('sqlite:' . $path);
			$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->exec('PRAGMA journal_mode=WAL;');
			$db->exec('PRAGMA synchronous=NORMAL;');
			return $db;
		} catch (Exception $e) {
			$this->legacy_log('sqlite_connect_fail | ' . $e->getMessage());
			return null;
		}
	}

	function legacy_sqlite_ensure_schema($db) {
		try {
			$db->exec('CREATE TABLE IF NOT EXISTS legacy_jobs (
				job_id TEXT PRIMARY KEY,
				origin_url TEXT,
				norm_url TEXT,
				host TEXT,
				status TEXT,
				status_code TEXT,
				filename TEXT,
				size_text TEXT,
				size_bytes INTEGER,
				bw_charge_bytes INTEGER,
				mtime INTEGER,
				path TEXT,
				hash10 TEXT,
				direct_url TEXT,
				owner TEXT,
				client_ip TEXT,
				client_network TEXT,
				job_type TEXT,
				showfile INTEGER,
				releech INTEGER,
				speed TEXT,
				source_file TEXT,
				source_key TEXT,
				meta_json TEXT,
				created_at INTEGER,
				updated_at INTEGER
			);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy_created_at ON legacy_jobs(created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy_host_created_at ON legacy_jobs(host,created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy_norm_created_at ON legacy_jobs(norm_url,created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy_status ON legacy_jobs(status);');

			// v2: preserve .dat keys exactly (some keys are <32hex> + suffix digits)
			$db->exec('CREATE TABLE IF NOT EXISTS legacy_jobs2 (
				job_key TEXT PRIMARY KEY,
				base_id TEXT,
				origin_url TEXT,
				norm_url TEXT,
				host TEXT,
				status TEXT,
				status_code TEXT,
				filename TEXT,
				size_text TEXT,
				size_bytes INTEGER,
				bw_charge_bytes INTEGER,
				mtime INTEGER,
				path TEXT,
				hash10 TEXT,
				direct_url TEXT,
				owner TEXT,
				client_ip TEXT,
				client_network TEXT,
				job_type TEXT,
				showfile INTEGER,
				releech INTEGER,
				speed TEXT,
				source_file TEXT,
				meta_json TEXT,
				created_at INTEGER,
				updated_at INTEGER
			);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy2_created_at ON legacy_jobs2(created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy2_host_created_at ON legacy_jobs2(host,created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy2_norm_created_at ON legacy_jobs2(norm_url,created_at);');
			$db->exec('CREATE INDEX IF NOT EXISTS idx_legacy2_status ON legacy_jobs2(status);');
		} catch (Exception $e) {
			$this->legacy_log('sqlite_schema_fail | ' . $e->getMessage());
		}
	}

	function legacy_sqlite_upsert_jobs($db, $file_jobs) {
		if (!$db) return;
		$this->legacy_sqlite_ensure_schema($db);

		$sourceFile = basename((string)$file_jobs);
		$now = time();
		$count = 0;

		try {
			$db->beginTransaction();
			$stmt = $db->prepare('INSERT INTO legacy_jobs(
				job_id, origin_url, norm_url, host, status, status_code, filename, size_text, size_bytes, bw_charge_bytes,
				mtime, path, hash10, direct_url, owner, client_ip, client_network, job_type, showfile, releech, speed,
				source_file, source_key, meta_json, created_at, updated_at
			) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
			ON CONFLICT(job_id) DO UPDATE SET
				origin_url=excluded.origin_url,
				norm_url=excluded.norm_url,
				host=excluded.host,
				status=excluded.status,
				status_code=excluded.status_code,
				filename=excluded.filename,
				size_text=excluded.size_text,
				size_bytes=excluded.size_bytes,
				bw_charge_bytes=excluded.bw_charge_bytes,
				mtime=excluded.mtime,
				path=excluded.path,
				hash10=excluded.hash10,
				direct_url=excluded.direct_url,
				owner=excluded.owner,
				client_ip=excluded.client_ip,
				client_network=excluded.client_network,
				job_type=excluded.job_type,
				showfile=excluded.showfile,
				releech=excluded.releech,
				speed=excluded.speed,
				source_file=excluded.source_file,
				source_key=excluded.source_key,
				meta_json=excluded.meta_json,
				updated_at=excluded.updated_at
			');

			$stmt2 = $db->prepare('INSERT INTO legacy_jobs2(
				job_key, base_id, origin_url, norm_url, host, status, status_code, filename, size_text, size_bytes, bw_charge_bytes,
				mtime, path, hash10, direct_url, owner, client_ip, client_network, job_type, showfile, releech, speed,
				source_file, meta_json, created_at, updated_at
			) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
			ON CONFLICT(job_key) DO UPDATE SET
				base_id=excluded.base_id,
				origin_url=excluded.origin_url,
				norm_url=excluded.norm_url,
				host=excluded.host,
				status=excluded.status,
				status_code=excluded.status_code,
				filename=excluded.filename,
				size_text=excluded.size_text,
				size_bytes=excluded.size_bytes,
				bw_charge_bytes=excluded.bw_charge_bytes,
				mtime=excluded.mtime,
				path=excluded.path,
				hash10=excluded.hash10,
				direct_url=excluded.direct_url,
				owner=excluded.owner,
				client_ip=excluded.client_ip,
				client_network=excluded.client_network,
				job_type=excluded.job_type,
				showfile=excluded.showfile,
				releech=excluded.releech,
				speed=excluded.speed,
				source_file=excluded.source_file,
				meta_json=excluded.meta_json,
				updated_at=excluded.updated_at
			');

			foreach (['leech','get'] as $sec) {
				if (!isset($this->jobs[$sec]) || !is_array($this->jobs[$sec])) continue;
				foreach ($this->jobs[$sec] as $job_id => $job) {
					if (!is_array($job) || $job_id == 'clearfile') continue;
					$source_key = (string)$job_id;
					// Normalize legacy key: sometimes .dat uses md5 + suffix (e.g. <32hex>1)
					$base_id = $source_key;
					if (preg_match('/^([a-f0-9]{32})\d+$/i', $source_key, $m)) {
						$base_id = $m[1];
					}
					$url = isset($job['url']) ? $job['url'] : '';
					$norm = $this->legacy_norm_url_for_uniqueness($url);
					$host = isset($job['host']) ? $job['host'] : '';
					$status_code = isset($job['status']) ? $job['status'] : '';
					$status = $this->legacy_status_text($status_code);
					$filename = isset($job['filename']) ? $job['filename'] : '';
					$size_text = isset($job['size']) ? $job['size'] : '';
					$size_bytes = isset($job['msize']) ? (int)$job['msize'] : 0;
					$bw_bytes = isset($job['bwtam']) ? (int)$job['bwtam'] : 0;
					$mtime = isset($job['mtime']) ? (int)$job['mtime'] : 0;
					$path = isset($job['path']) ? $job['path'] : '';
					$hash10 = isset($job['hash']) ? $job['hash'] : '';
					$direct_url = '';
					if (isset($job['directlink']) && is_array($job['directlink']) && !empty($job['directlink']['url'])) $direct_url = $job['directlink']['url'];
					$owner = isset($job['owner']) ? $job['owner'] : '';
					$client_ip = isset($job['ip']) ? $job['ip'] : '';
					$client_network = isset($job['network']) ? $job['network'] : '';
					$job_type = ($sec === 'get') ? 'get' : 'leech';
					$showfile = isset($job['showfile']) ? (int)$job['showfile'] : 1;
					$releech = isset($job['releech']) ? (int)$job['releech'] : 0;
					$speed = isset($job['speed']) ? (string)$job['speed'] : '';

					$meta = $job;
					foreach (['url','hash','host','type','status','filename','size','msize','bwtam','directlink','path','mtime','speed','ip','network','owner','showfile','releech'] as $kk) {
						if (isset($meta[$kk])) unset($meta[$kk]);
					}
					$meta_json = !empty($meta) ? json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : null;

					$stmt->execute([
						(string)$base_id,
						(string)$url,
						(string)$norm,
						(string)$host,
						(string)$status,
						(string)$status_code,
						(string)$filename,
						(string)$size_text,
						(int)$size_bytes,
						(int)$bw_bytes,
						(int)$mtime,
						(string)$path,
						(string)$hash10,
						(string)$direct_url,
						(string)$owner,
						(string)$client_ip,
						(string)$client_network,
						(string)$job_type,
						(int)$showfile,
						(int)$releech,
						(string)$speed,
						(string)$sourceFile,
						(string)$source_key,
						$meta_json,
						(int)($mtime or $now),
						(int)$now
					]);

					// v2 table: keep job_key identical to .dat key
					$stmt2->execute([
						(string)$source_key,
						(string)$base_id,
						(string)$url,
						(string)$norm,
						(string)$host,
						(string)$status,
						(string)$status_code,
						(string)$filename,
						(string)$size_text,
						(int)$size_bytes,
						(int)$bw_bytes,
						(int)$mtime,
						(string)$path,
						(string)$hash10,
						(string)$direct_url,
						(string)$owner,
						(string)$client_ip,
						(string)$client_network,
						(string)$job_type,
						(int)$showfile,
						(int)$releech,
						(string)$speed,
						(string)$sourceFile,
						$meta_json,
						(int)($mtime or $now),
						(int)$now
					]);

					$count += 1;
				}
			}
			$db->commit();
			$this->legacy_log('sqlite_upsert_ok | file=' . $sourceFile . ' | jobs=' . $count);
		} catch (Exception $e) {
			try { $db->rollBack(); } catch (Exception $e2) {}
			$this->legacy_log('sqlite_upsert_fail | file=' . $sourceFile . ' | ' . $e->getMessage());
		}
	}

	function legacy_sqlite_read_jobs2($maxRowsPerType = 50000) {
		if (!$this->legacy_sqlite_enabled) return null;
		$db = $this->legacy_sqlite_connect();
		if (!$db) return null;
		try {
			$this->legacy_sqlite_ensure_schema($db);
			$jobs = array('get' => array(), 'leech' => array());
			$types = array('get','leech');
			foreach ($types as $t) {
				$limit = (int)$maxRowsPerType;
				if ($limit <= 0) $limit = 50000;
				$stmt = $db->prepare('SELECT job_key, origin_url, host, status_code, filename, size_text, size_bytes, bw_charge_bytes, mtime, path, hash10, direct_url, owner, client_ip, client_network, showfile, releech, speed, meta_json FROM legacy_jobs2 WHERE job_type=? ORDER BY mtime DESC LIMIT ' . $limit);
				$stmt->execute(array($t));
				while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
					$job_key = isset($row['job_key']) ? (string)$row['job_key'] : '';
					if ($job_key === '' || $job_key === 'clearfile') continue;

					$job = array();
					$job['url'] = isset($row['origin_url']) ? (string)$row['origin_url'] : '';
					$job['host'] = isset($row['host']) ? (string)$row['host'] : '';
					$job['status'] = isset($row['status_code']) ? (int)$row['status_code'] : 0;
					$job['filename'] = isset($row['filename']) ? (string)$row['filename'] : '';
					$job['size'] = isset($row['size_text']) ? (string)$row['size_text'] : '';
					$job['msize'] = isset($row['size_bytes']) ? (int)$row['size_bytes'] : 0;
					$job['bwtam'] = isset($row['bw_charge_bytes']) ? (int)$row['bw_charge_bytes'] : 0;
					$job['mtime'] = isset($row['mtime']) ? (int)$row['mtime'] : 0;
					$job['path'] = isset($row['path']) ? (string)$row['path'] : '';
					$job['hash'] = isset($row['hash10']) ? (string)$row['hash10'] : '';
					$job['owner'] = isset($row['owner']) ? (string)$row['owner'] : '';
					$job['ip'] = isset($row['client_ip']) ? (string)$row['client_ip'] : '';
					$job['network'] = isset($row['client_network']) ? (string)$row['client_network'] : '';
					$job['showfile'] = isset($row['showfile']) ? (int)$row['showfile'] : 1;
					$job['releech'] = isset($row['releech']) ? (int)$row['releech'] : 0;
					$job['speed'] = isset($row['speed']) ? (string)$row['speed'] : '';

					$direct = isset($row['direct_url']) ? (string)$row['direct_url'] : '';
					$job['directlink'] = array('url' => $direct);

					// best-effort meta_json merge
					if (!empty($row['meta_json'])) {
						$meta = @json_decode($row['meta_json'], true);
						if (is_array($meta)) {
							foreach ($meta as $mk => $mv) {
								if (!isset($job[$mk])) $job[$mk] = $mv;
							}
						}
					}

					$jobs[$t][$job_key] = $job;
				}
			}

			// keep compatibility
			if (!isset($jobs['get']['clearfile'])) $jobs['get']['clearfile'] = 0;
			// NOTE: do NOT add leech.clearfile; listleech() assumes each entry is an array

			return $jobs;
		} catch (Exception $e) {
			$this->legacy_log('sqlite_read_jobs2_fail | ' . $e->getMessage());
			return null;
		}
	}

	function legacy_sqlite_purge_old($db, $maxAgeSeconds = 2678400) {
		if (!$db) return;
		$cutoff = time() - (int)$maxAgeSeconds;
		try {
			$stmt = $db->prepare('DELETE FROM legacy_jobs WHERE mtime > 0 AND mtime < ?');
			$stmt->execute([(int)$cutoff]);
			$stmt2 = $db->prepare('DELETE FROM legacy_jobs2 WHERE mtime > 0 AND mtime < ?');
			$stmt2->execute([(int)$cutoff]);
		} catch (Exception $e) {
			$this->legacy_log('sqlite_purge_fail | ' . $e->getMessage());
		}
	}

	function legacy_sqlite_backfill_maybe($minIntervalSeconds = 300) {
		if (!$this->legacy_sqlite_enabled) return;
		$dir = rtrim($this->fileinfo_dir, '/');
		if (empty($dir)) return;
		$marker = $dir . '/.sqlite_backfill_last';
		$lockPath = $dir . '/.sqlite_backfill.lock';

		$last = 0;
		if (file_exists($marker)) {
			$tmp = @file_get_contents($marker);
			if ($tmp !== false) $last = (int)trim((string)$tmp);
		}
		$now = time();
		if ($last > 0 && ($now - $last) < (int)$minIntervalSeconds) return;

		$lockFp = @fopen($lockPath, 'c+');
		if (!$lockFp) return;
		$locked = @flock($lockFp, LOCK_EX | LOCK_NB);
		if (!$locked) { @fclose($lockFp); return; }

		try {
			$db = $this->legacy_sqlite_connect();
			if (!$db) return;
			$this->legacy_sqlite_upsert_jobs($db, 'backfill');
			$this->legacy_sqlite_purge_old($db, 2678400); // 31 days
			@file_put_contents($marker, (string)$now);
		} catch (Exception $e) {
			$this->legacy_log('sqlite_backfill_fail | ' . $e->getMessage());
		} finally {
			@flock($lockFp, LOCK_UN);
			@fclose($lockFp);
		}
	}

	function savefile($file,$data,$type='w+') { 

		$fh = fopen($file, $type) 
		or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the file "<B>'.$file.'</B>" to 666</font></CENTER>');
		fwrite($fh, $data) 
		or die('<CENTER><font color=red size=3>Could not write file ! Try to chmod the file "<B>'.$file.'</B>" to 666</font></CENTER>');
		fclose($fh);
		@chmod($file, 0666);
	}
	 #- 18/09/2024
    function update_bw($lasttime, $lastbw){
		if (!is_numeric($lasttime)) return die('giá trị thời gian không đúng');
		if (!is_numeric($lastbw)) return die('giá trị băng thông không đúng');
		$time = time();
		$newbw = 0;
		//check gia hạn account
		if(!isset($this->info["logsmail"]["expired"])) $this->info["logsmail"]["expired"] = false;
		if($this->expired > $time+3*24*60*60 && $this->acc_type['reset_bw'] == true && $this->info["logsmail"]["expired"] == true) {
			$this->info["logsmail"]["expired"] = false;
			$this->save_info();
		}

		# update account bw
		if(isset($this->info["status"]) && $this->info["status"] == "true")  {
			$datenow = date('z',$time) + 366*(date('Y',$time) - date('Y',$lasttime));
			if(!isset($this->acc_type['reset_bw'])) die('Vui lòng cập nhật lại file config.php mới nhất');
			if($this->acc_type['type'] == 'star') {
				$newbw = 0;
			}
			else if($datenow - date('z',$lasttime) > 0 AND isset($this->expired) AND $this->expired > $time) {
				if($this->acc_type['reset_bw'] == true && $this->info["status"] == "true") {
					if($datenow - date('z',$lasttime) >=2) $newbw = $lastbw + $this->limitMBIP*1024*1024*2;
					elseif($datenow - date('z',$lasttime) == 1) $newbw = $lastbw + $this->limitMBIP*1024*1024;
					if($newbw > $this->maxbw*1024*1024) $newbw = $this->maxbw*1024*1024;
				}
				else $newbw = $lastbw;
			}
		}
		return $newbw;
	}

	function load_bw(){
		if(isset($_POST['test']) OR isset($_GET['test'])) $test = true;
		else $test = false;		
		$timenow = time();
		$daynow = date('d.m.Y', $timenow);
		$timeupdate = time();
		$dayupdate = date('d.m.Y', $timeupdate);
		if(isset($this->bw)) return;
		$file_bw = $this->fileinfo_dir."/bw.dat";
		$file_bwbk = $this->fileinfo_dir."/bw.dat.bk";
		$file_info = $this->fileinfo_dir."/".$this->fileinfo;
		$old_fld_bw = $this->fileinfo_dir."/bw/";
		$fld_bw = $this->fileinfo_dir.$this->bw_dir;
		$file_logbw = $fld_bw.'logbw.txt';
		$txtlog = false;

		//convert old data bw - "bw.dat"
		if (file_exists($file_bw)){

			$this->bw = array();
			$bw_data = @file_get_contents($file_bw);
			$old_bw = @json_decode($bw_data, true);

			if(isset($this->info["bandwitdh"])) {
				if(date('d.m.Y', $this->info["bandwitdh"]["time"]) != $dayupdate) {
					$newbw = $this->update_bw($this->info["bandwitdh"]["time"], $this->info["bandwitdh"]["value"]);
				}
				else {
					$timeupdate = $this->info["bandwitdh"]["time"];
					$dayupdate = date('d.m.Y', $timeupdate);
					$newbw = $this->info["bandwitdh"]["value"] + $this->total_acc_used();
				}
				

				$this->bw['timeupdate'] = $timeupdate;
				$this->bw['bwupdate'] = $newbw;
				$txtlog = date('d.m.Y - H:i:s',$timeupdate).'|chuyển đổi từ file bw cũ (bw.dat); bw='.$this->convertmb($newbw).'|'.$timeupdate.'|'.$this->bw['bwupdate'];
				$this->bw["logs"][$timeupdate] = $txtlog;

			}
			else {
				$valuebw = $this->limitMBIP*1024*1024 + $this->plusbw*1024*1024;
				$newbw = $valuebw;
				$this->bw['timeupdate'] = $timeupdate;
				$this->bw['bwupdate'] = $newbw;
				$txtlog = date('d.m.Y - H:i:s',$timeupdate).'|Reset bw do mất dữ liệu khi chuyển đổi từ file bw cũ (bw.dat); bw='.$this->convertmb($newbw).'|'.$timeupdate.'|'.$this->bw['bwupdate'];
				$this->bw["logs"][$timeupdate] = $txtlog;
			}
			if(!file_exists ($fld_bw)) { 
				mkdir($fld_bw, 0777)  or die('<CENTER><font color=red size=4>Could not create folder! Try to chmod the folder "<B>'.$this->bw_dir.'</B>" to 777</font></CENTER>');

				if(!file_exists($fld_bw."index.php")) { 
					$clog=fopen($fld_bw."index.php","a") 
					or die('<CENTER><font color=red size=3>Could not create to file ! Try to chmod the folder "<B>bw</B>" to 777</font></CENTER>');
					fwrite($clog,'<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=https://getlink.vn">');
					fclose($clog);
				}
			}
			$this->bw_data = '';
			$this->save_bw(false, $txtlog);
			//rename bw.dat --> bw.dat.bk
			$fh = fopen($file_bw.'.bk', 'w+') or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the folder "<B>'.$this->fileinfo_dir.'</B>" to 777</font></CENTER>');
			fwrite($fh, $bw_data);
			fclose($fh);
			@chmod($file_bw.'.bk', 0666);
			@unlink($file_bw);
		}
		//convert from '/bw/' to /bwplus/
		elseif(file_exists($old_fld_bw) && !file_exists ($fld_bw))  {
			$bk_bw = $this->load_data($old_fld_bw, false);
			
			if(!isset($bk_bw["time"]) || !isset($bk_bw["total"]) || !is_numeric($bk_bw["time"]) || !is_numeric($bk_bw["total"])){
				if($test) {echo '<pre>';print_r($bk_bw);echo '</pre>';}
				die('error data bw (000)');
			}

			$timeupdate = $bk_bw["time"];
			$dayupdate = date('d.m.Y', $timeupdate);
			$total_bw = 0;
			//echo '<pre>';print_r($bk_bw);echo '</pre>';
			if(isset($bk_bw['acc'])) {
				$total_bw = 0;
				foreach($bk_bw['acc'] as $hash=>$value) {
					if(strlen($hash) > 32) {
						foreach($bk_bw['acc'][$hash] as $time=>$value) {
							$bk_bw['acc'][substr($hash,0,32)][$time] = $bk_bw['acc'][$hash][$time];
						}
						unset($bk_bw['acc'][$hash]);
					}
				}
				foreach($bk_bw['acc'] as $hash=>$value) {
					$max = 0;
					foreach($bk_bw['acc'][$hash] as $time=>$value) {
						if($max < $time) $max = $time;
					}
					
					if(isset($this->jobs['get'][$hash]) or isset($this->jobs['leech'][$hash])) {
						if(isset($bk_bw['acc'][$hash][$max])) $total_bw = $total_bw + abs($bk_bw['acc'][$hash][$max]);
					}
				}
				$total_bw = $bk_bw["total"] - $total_bw;
			}
			if(!isset($bk_bw['acc']) or count($bk_bw['acc']) == 0) {
				$total_bw = $bk_bw["total"];
			}
			$newbw = $total_bw;
			if($test) {
				echo $this->convertmb($total_bw).'<BR>'.$this->convertmb($this->total_acc_used()).'<BR>'.$this->convertmb($newbw);
				exit;
			}
			$this->bw['timeupdate'] = $timeupdate;
			$this->bw['bwupdate'] = $newbw;
			$txtlog = date('d.m.Y - H:i:s',$timeupdate).'|chuyển đổi từ folder /bw/; bw='.$this->convertmb($newbw).'|'.$timeupdate.'|'.$this->bw['bwupdate'];
			$this->bw["logs"][$timeupdate] = $txtlog;

			if(!file_exists ($fld_bw)) { 
				mkdir($fld_bw, 0777)  or die('<CENTER><font color=red size=4>Could not create folder! Try to chmod the folder "<B>'.$this->bw_dir.'</B>" to 777</font></CENTER>');

				if(!file_exists($fld_bw."index.php")) { 
					$clog=fopen($fld_bw."index.php","a") 
					or die('<CENTER><font color=red size=3>Could not create to file ! Try to chmod the folder "<B>bw</B>" to 777</font></CENTER>');
					fwrite($clog,'<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=https://getlink.vn">');
					fclose($clog);
				}
			}

			rename(realpath($old_fld_bw),realpath($old_fld_bw).'_bk');

			$this->bw_data = '';
			$this->save_bw(false, $txtlog);
		}
		elseif(file_exists($fld_bw))  {
			@chmod($fld_bw, 0777);
			/*
			if(substr(sprintf('%o', fileperms($fld_bw)), -4) != '0777') {
				echo '<BR><font color="red">'.$file_bw.' CHMOD to 0777</font>';
				return;
			}
			*/
			list($this->bw, $this->listbw, $this->bw_data) = $this->load_data($fld_bw);
			if(!isset($this->bw['timeupdate']) || !isset($this->bw['bwupdate'])){
				//echo '<pre>';	print_r($this->bw);echo '</pre>';
				die('error data bw (999)');
			}
			#backup tổng đầu ngày
			if(!isset($this->bw['time']) or date('d.m.Y', $this->bw['time']) != $daynow) {
				$json = $this->bw_api();
				if(!isset($this->bw['tongdaungay'][$daynow])) {
					$this->bw['tongdaungay'][$daynow] = $json['acc']['daungay'];
					$this->save_bw();
				}
			}
		}
		elseif (!file_exists($this->fileinfo_dir.'/info.backup.dat') && !file_exists($this->fileinfo_dir.'/info.backup.php')) {
			die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=welcome';</SCRIPT>");
		}
		else {
			echo '<BR>not found '.$fld_bw;
			return;
		}
	}

	function domain_name($url) {
		$hosting = 'unknown';
		$schema = parse_url($url);
		if(stristr($url,'magnet:?xt=') || stristr($url,'.torrent')) $hosting = "torrent";
		elseif(isset($schema['host']) == true && stristr($schema['host'],'.')==false) {
			if(preg_match('%(http|https)\:\/\/(www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]+\/%U', $url, $value)) {
				$domain = trim($value[0]);
				$schema = parse_url($domain);
				if(isset($schema['host']) == true && stristr($schema['host'],'.')==true) $hosting = $schema['host'];
			}
			//else $hosting = 'test1'.$schema['host'];
		}
		elseif(isset($schema['host'])) $hosting = $schema['host'];
		//else $hosting = 'test2'.$schema['host'];
	
		if($hosting == 'unknown') {
			foreach($this->filterhost as $keyhost=>$flhost) {
				if(stristr($url,$keyhost)==true) {
					$hosting = $keyhost;
					break;
				}
				else {
					foreach($flhost as $namehost) {
						if(stristr($url,$keyhost)==true) $hosting = $keyhost;
						break;
					}
				}
				if($hosting !== 'unknown') break;
			}
		}
		$hosting = str_replace("www.", "",  $hosting);
		foreach($this->filterhost as $keyhost=>$flhost) {
			if(in_array($hosting, $flhost)==true) {
				$hosting = $keyhost;
				break;
			}
		}
		return $hosting;
	}

	function bw_api($hosting=false) {
		//$url = 'https://ahttps//rapidgator.net/file/d8c566f732fca271b425e9d1c71f5bfc/UD_DayTradingMasteringPriceActionTradingStrategies20242023_12_part04.rar.html';
		//$domain_name = $this->domain_name($url);echo $domain_name;exit;
		if(isset($this->json_bw_api) && is_array($this->json_bw_api)==true) return $this->json_bw_api;
		if(!isset($this->bw['timeupdate'])) die('not found time update code');
		if(isset($_POST['test']) OR isset($_GET['test'])) $test = true;
		else $test = false;	
		$timenow = time();
		$daynow = date('d.m.Y', $timenow);
		$dayupdatecode = date('d.m.Y', $this->bw['timeupdate']);
		$json = array();
		$info = array();
		if(!isset($this->jobs['leech'])) $this->jobs['leech'] = array();
		$files = array();
		$listhash = array();
		$mintime = strtotime($dayupdatecode);
		if($mintime < $this->created) $mintime = $this->created;

		//lọc danh sách files đã leech
		foreach ($this->jobs['leech'] as $key=>$job) {
			if (!is_array($job) || !isset($job['mtime']) || empty($job['url'])) continue;
			if($job['mtime'] < $mintime) {
				$day = date('d.m.Y', $job['mtime']);
				$hash = substr(md5($job['url']),0,10);
				$listhash[$hash] = $job['filename'];
				unset($hash, $day, $job);
				continue;
			}

			//if($hosting == true && $hosting != $job['host']) continue;
			$files[$key] = $job;
			$files[$key]['hash'] = $key;
		}
		$compare = $this->date_az('mtime'); 
		usort($files, $compare);
		if($test) {
			echo '<pre>';print_r($files);echo '</pre>';
			echo '<pre>';print_r($listhash);echo '</pre>';
		}
		$data = array();
		//sắp xếp danh sách files đã leech
		foreach($files as $key=>$job) {
			if(!is_numeric($job['msize']) && $this->convert($job['msize'])>0) {
				$job['msize'] = $this->convert($job['msize']);
				//fix filesize
				$this->jobs['leech'][$job['hash']]['msize'] = $job['msize'];
				$this->save_jobs();
			}
			elseif(!is_numeric($job['msize'])) continue;
			if($job['msize'] < 0) continue;
			if(isset($job['leecherror'])) continue;
			elseif(isset($job['fshare'])) continue;

			$day = date('d.m.Y', $job['mtime']);
			$hash = substr(md5($job['url']),0,10);
			$domain_name = $job['host'];
			if(stristr($domain_name,'.')== false) $domain_name = $this->domain_name($job['url']);

			//if (isset($listhash[$hash]) && (date('z',strtotime($day)) - date('z',strtotime($listhash[$hash])) < 3)){
			if(strlen($job['filename'])>40) $filename = substr($job['filename'],-40);
			else $filename = $job['filename'];
			if (isset($listhash[$hash])){
				$data[$day]['releech'][$domain_name][$job['hash']]['msize'] = $job['msize'];
				$data[$day]['releech'][$domain_name][$job['hash']]['name'] = $filename;
			}
			elseif($job['status'] == 1) {
				$data[$day]['done'][$domain_name][$job['hash']]['msize'] = $job['msize'];
				$data[$day]['done'][$domain_name][$job['hash']]['name'] = $filename;
				$listhash[$hash] = $day;
			}
			elseif(($job['status'] == 0 or $job['status'] == 2)) {
				$data[$day]['leeching'][$domain_name][$job['hash']]['msize'] = $job['msize'];
				$data[$day]['leeching'][$domain_name][$job['hash']]['name'] = $filename;
				$listhash[$hash] = $day;
			}
			unset($day, $job, $hash, $filename);
		}
		
		if($test) {echo '<pre>';print_r($data);echo '</pre>';}
		if(!isset($mintime)) {
			if(isset($_GET['api'])==true && $_GET['api'] == 'bw') die('empty data');
			else return $json;
			//die('empty data');
		}
		$datenow = date('z',$timenow) + 366*(date('Y',$timenow) - date('Y',$mintime));
		$totaldate = $datenow - date('z',$mintime);
		for ($x = 0; $x <= $totaldate; $x++) {
			$timeday = $mintime + $x * 24*60*60;
			$day = date('d.m.Y', $timeday);
			if(!isset($data[$day])) $data[$day] = array();
		}
		$files = array();
		foreach ($data as $key=>$job) {
			$files[$key] = $job;
			$files[$key]['ltime'] = strtotime($key);
			$files[$key]['day'] = $key;
			unset($job, $key);
		}
		$compare = $this->date_az('ltime'); 
		usort($files, $compare);
		unset($data);
		$data = $files;

		$html = '';
		$html .= '<!DOCTYPE html>
				<html>
				<style>
					table, td, tr {
					  border: 1px solid;
					  padding: 8px;
					}

					table {
					  border-collapse: collapse;
					}
					#day tr{background-color: #f2f2f2;}
				}

				</style>
				<body>';
		$html .= '<strong>I. THÔNG TIN TÀI KHOẢN</strong><br>
				<div style="overflow: auto; height: auto; max-height: 450px; width: 480px;">
				<table align="center" cellpadding="3" cellspacing="1" width="100%">
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">'.$this->lang['type'].'</td>
						<td class="flistmouseoff" align="center" width="30%">'.str_replace("#FFFF00","#000",$this->lang['typeacc']).' - '.$this->lang['bwaccday'].'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">Băng thông cộng thêm mỗi ngày</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.$this->convertmb($this->limitMBIP*1024*1024).'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">Cộng thêm ngày đầu tiên</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.$this->convertmb($this->plusbw*1024*1024).'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">'.$this->lang['create'].'</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.date('H:i:s- d.m.Y',$this->created).'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">'.$this->lang['expired'].'</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.date('H:i:s- d.m.Y',$this->expired).'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">'.$this->lang['yourmail'].'</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.$this->email.'</td>
					</tr>
					<tr valign="bottom">
						<td class="flisttblhdr" width="30%">'.$this->lang['updatecode'].'</td>
						<td class="flistmouseoff"  align="center"  width="30%">'.$dayupdatecode.'</td>
					</tr>
				</table>
				</div><BR><BR><strong>II. THỐNG KÊ CHI TIẾT SỬ DỤNG BĂNG THÔNG</strong><br>';
		$html .= '<table>';
		$html .= '<tr style="background-color: #f2f2f2; font-weight:bold" align="center">
				<td style="width:80px">Ngày</td>
				<td style="width:80px">Bổ sung ngày mới</td>
				<td style="width:80px">Bổ sung trong ngày</td>
				<td style="width:80px">Đầu ngày</td>
				<td>Done trong ngày</td>
				<td>Leeching</td>
				<td>ReLeech</td>
				<td style="width:80px">Cuối ngày</td>
				<td style="width:80px">a (âm bw)</td>
				<td style="width:80px">b (dư bw)</td>
				<td style="width:80px">c (trừ vào hôm sau)</td></tr>';
		foreach($data as $day=>$value1) {
			$dataday = $data[$day]['day'];
			$html .= '<tr style="background-color: #f2f2f2" align="center"><td><span style="font-weight:bold; color:red">'.$dataday.'</span></td>
			<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
			//$this->bw
			$total_day_done = 0;
			$total_day_leeching = 0;
			$total_day_releech = 0;
			$json[$dataday] = array();
			$listhost = array();
			if(isset($data[$day]['done'])) {
				foreach($data[$day]['done'] as $host=>$value2){
					$listhost[] = $host;
					if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
					else $limit_host = $this->hosts['other'];
					if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
					else {
						if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
						else $totalbw = $limit_host['bandwidth']*1024*1024;
					}

					$total_done = 0;
					$files_done = 0;
					$total_leeching = 0;
					$files_leeching = 0;
					$total_releech = 0;
					$files_releech = 0;
					$html_done = '';
					$html_leeching = '';
					$html_releech = '';
					if(isset($data[$day]['done'][$host])) {
						$files_done = count($data[$day]['done'][$host]);
						foreach($data[$day]['done'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_done = $total_done + $files['msize'];
								$listhash[$hash] = $day;
								$html_done .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}
						}
					}

					if(isset($data[$day]['leeching'][$host])) {
						$files_leeching = count($data[$day]['leeching'][$host]);
						foreach($data[$day]['leeching'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_leeching = $total_leeching + $files['msize'];
								$listhash[$hash] = $day;
								$html_leeching .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}

						}
					}

					if(isset($data[$day]['releech'][$host])) {
						$files_releech = count($data[$day]['releech'][$host]);
						foreach($data[$day]['releech'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_releech = $total_releech + $files['msize'];
								$listhash[$hash] = $day;
								$html_releech .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}

						}
					}


					$total_day_done = $total_day_done + $total_done;
					$total_day_leeching = $total_day_leeching + $total_leeching;
					$total_day_releech = $total_day_releech + $total_releech;

					$html .= '<tr align="center">';
					//host name
					$html .= '<td>'.$host.'</td>';
					//Bổ sung ngày mới
					$html .= '<td>'.($totalbw>0?$this->convertmb($totalbw):'').'</td>';
					//bổ sung trong ngày (nếu mua thêm)
					$bosungtrongngay = 0;
					if(isset($this->bw[$dataday][$host])) {
						foreach($this->bw[$dataday][$host] as $time=>$msize) {
							if(isset($msize) AND $msize>0) $bosungtrongngay = $bosungtrongngay + $msize;
						}
					}
					$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';
					//đầu ngày
					if(!isset($oldbw[$host]['oldbw'])) $oldbw[$host]['oldbw'] = 0;
					$daungay = $totalbw - $oldbw[$host]['oldbw'];
					$html .= '<td>'.$this->convertmb($daungay).'</td>';
					//done trong ngày
					$html .= '<td>'.($total_done>0?$this->convertmb($total_done):'0').' ('.$files_done.' files)<BR>'.$html_done.'</td>';
					//leeching
					$html .= '<td>'.($files_leeching>0? ($total_leeching>0?$this->convertmb($total_leeching):'0').' ('.$files_leeching.' files)<BR>'.$html_leeching:'').'</td>';
					//releech
					$html .= '<td>'.($files_releech>0? ($total_releech>0?$this->convertmb($total_releech):'0').' ('.$files_releech.' files)<BR>'.$html_releech:'').'</td>';
					#chưa sử dụng
					$unless = $totalbw + $bosungtrongngay - $oldbw[$host]['oldbw'] - $total_done - $total_leeching;
					//bw_used
					$bw_used = 0;
					if(isset($oldbw[$host]['oldbw'])) $bw_used = $total_done + $total_leeching - $bosungtrongngay + abs($oldbw[$host]['oldbw']);
					if($bw_used <0) $bw_used = 0;
					#cuối ngày
					//limit max bw
					$cuoingay = $unless;
					if($cuoingay > $totalbw) $cuoingay = $totalbw;
					$html .= '<td>'.$this->convertmb($cuoingay).'</td>';
					#a (qua limit), b (du bw), c
					if($unless >= 0) {
						$oldbw[$host]['oldbw'] = 0;
						$html .= '<td>0</td><td>'.$this->convertmb($unless).'</td><td>0</td>';
					}
					else {
						$oldbw[$host]['oldbw'] = abs($unless);
						$html .= '<td>'.$this->convertmb(abs($unless)).'</td><td>0</td><td>'.$this->convertmb(abs($unless)).'</td>';
					}
					$html .= '</tr>';

					/* - 05/09/2024
					if($data[$day]['day'] == date('d.m.Y', $timenow)) {
						$json[$host]['used'] = $total_done + $total_leeching;
						$json[$host]['unless'] = $unless - $total_leeching;
					}
					*/
					$json[$dataday][$host]['used'] = $bw_used;
					$json[$dataday][$host]['done'] = $total_done;
					$json[$dataday][$host]['leeching'] = $total_leeching;
					$json[$dataday][$host]['unless'] = $unless;
					$json[$dataday][$host]['daily_bw'] = $totalbw;

					unset($total_done, $total_leeching, $totalbw, $unless,$host, $bosungtrongngay);
				}
				/*
				if(isset($oldbw)) {
					foreach($oldbw as $host=>$value2) {
						if($oldbw[$host]['oldbw'] == 0) continue;
						if(in_array($host, $listhost)) continue;
						$listhost[] = $host;
						if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
						else $limit_host = $this->hosts['other'];
						if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
						else {
							if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
							else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
						}

						$total_leeching = 0;
						$files_leeching = 0;
						$total_releech = 0;
						$files_releech = 0;
						$html_leeching = '';
						$html_releech = '';

						if(isset($data[$day]['leeching'][$host])) {
							$files_leeching = count($data[$day]['leeching'][$host]);
							foreach($data[$day]['leeching'][$host] as $hash=>$files){
								if (!isset($listhash[$hash])) {
									$total_leeching = $total_leeching + $files['msize'];
									$listhash[$hash] = $day;
									$html_leeching .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
								}
							}
						}

						if(isset($data[$day]['releech'][$host])) {
							$files_releech = count($data[$day]['releech'][$host]);
							foreach($data[$day]['releech'][$host] as $hash=>$files){
								if (!isset($listhash[$hash])) {
									$total_releech = $total_releech + $files['msize'];
									$listhash[$hash] = $day;
									$html_releech .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
								}

							}
						}

						$total_day_leeching = $total_day_leeching + $total_leeching;
						$total_day_releech = $total_day_releech + $total_releech;


						$html .= '<tr align="center">';
						//host name
						$html .= '<td>'.$host.'</td>';
						//Bổ sung ngày mới
						$html .= '<td>'.($totalbw>0?$this->convertmb($totalbw):'').'</td>';
						//bổ sung trong ngày (nếu mua thêm)
						$bosungtrongngay = 0;
						if(isset($this->bw[$dataday][$host])) {
							foreach($this->bw[$dataday][$host] as $time=>$msize) {
								if(isset($msize) AND $msize>0) $bosungtrongngay = $bosungtrongngay + $msize;
							}
						}
						$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';
						//đầu ngày
						if(!isset($oldbw[$host]['oldbw'])) $oldbw[$host]['oldbw'] = 0;
						$daungay = $totalbw - $oldbw[$host]['oldbw'];
						$html .= '<td>'.$this->convertmb($daungay).'</td>';

						//done trong ngày
						$html .= '<td></td>';
						//leeching
						$html .= '<td>'.($files_leeching>0? ($total_leeching>0?$this->convertmb($total_leeching):'0').' ('.$files_leeching.' files)<BR>'.$html_leeching:'').'</td>';
						//releech
						$html .= '<td>'.($files_releech>0? ($total_releech>0?$this->convertmb($total_releech):'0').' ('.$files_releech.' files)<BR>'.$html_releech:'').'</td>';

						//chưa sử dụng
						//$unless = $totalbw;
						$unless = $totalbw + $bosungtrongngay - $oldbw[$host]['oldbw'];
						#cuối ngày
						//limit max bw
						$cuoingay = $unless;
						if($cuoingay > $totalbw) $cuoingay = $totalbw;
						$html .= '<td>'.$this->convertmb($cuoingay).'</td>';
						#a (qua limit), b (du bw), c
						if($unless >= 0) {
							$oldbw[$host]['oldbw'] = 0;
							$html .= '<td>0</td><td>'.$this->convertmb($unless).'</td><td>0</td>';
						}
						else {
							$oldbw[$host]['oldbw'] = abs($unless);
							$html .= '<td>'.$this->convertmb(abs($unless)).'</td><td>0</td><td>'.$this->convertmb(abs($unless)).'</td>';
						}
						$html .= '</tr>';

						$json_used = $total_leeching - $bosungtrongngay;
						if($json_used <0) $json_used = 0;
						$json[$dataday][$host]['used'] = $json_used;
						$json[$dataday][$host]['done'] = 0;
						$json[$dataday][$host]['leeching'] = $total_leeching;
						$json[$dataday][$host]['unless'] = $unless;
						$json[$dataday][$host]['daily_bw'] = $totalbw;


						unset($total_leeching, $totalbw, $unless, $host, $bosungtrongngay);
					}
				}
				*/
			}
			if(isset($data[$day]['leeching'])) {
				foreach($data[$day]['leeching'] as $host=>$value2){
					if(in_array($host, $listhost)) continue;
					$listhost[] = $host;
					if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
					else $limit_host = $this->hosts['other'];
					if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
					else {
						if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
						else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
					}


					$total_leeching = 0;
					$files_leeching = 0;
					$total_releech = 0;
					$files_releech = 0;
					$html_leeching = '';
					$html_releech = '';

					if(isset($data[$day]['leeching'][$host])) {
						$files_leeching = count($data[$day]['leeching'][$host]);
						foreach($data[$day]['leeching'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_leeching = $total_leeching + $files['msize'];
								$listhash[$hash] = $day;
								$html_leeching .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}
						}
					}

					if(isset($data[$day]['releech'][$host])) {
						$files_releech = count($data[$day]['releech'][$host]);
						foreach($data[$day]['releech'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_releech = $total_releech + $files['msize'];
								$listhash[$hash] = $day;
								$html_releech .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}

						}
					}

					$total_day_leeching = $total_day_leeching + $total_leeching;
					$total_day_releech = $total_day_releech + $total_releech;

					$html .= '<tr align="center">';
					//host name
					$html .= '<td>'.$host.'</td>';
					//Bổ sung ngày mới
					$html .= '<td>'.($totalbw>0?$this->convertmb($totalbw):'').'</td>';
					//bổ sung trong ngày (nếu mua thêm)
					$bosungtrongngay = 0;
					if(isset($this->bw[$dataday][$host])) {
						foreach($this->bw[$dataday][$host] as $time=>$msize) {
							if(isset($msize) AND $msize>0) $bosungtrongngay = $bosungtrongngay + $msize;
						}
					}
					$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';
					//đầu ngày
					if(!isset($oldbw[$host]['oldbw'])) $oldbw[$host]['oldbw'] = 0;
					$daungay = $totalbw - $oldbw[$host]['oldbw'];
					$html .= '<td>'.$this->convertmb($daungay).'</td>';
					//done trong ngày
					$html .= '<td></td>';
					//leeching
					$html .= '<td>'.($files_leeching>0? ($total_leeching>0?$this->convertmb($total_leeching):'0').' ('.$files_leeching.' files)<BR>'.$html_leeching:'').'</td>';
					//releech
					$html .= '<td>'.($files_releech>0? ($total_releech>0?$this->convertmb($total_releech):'0').' ('.$files_releech.' files)<BR>'.$html_releech:'').'</td>';
					//chưa sử dụng
					$unless = $totalbw + $bosungtrongngay - $total_leeching;
					//bw_used
					$bw_used = 0;
					if(isset($oldbw[$host]['oldbw'])) $bw_used = $total_leeching - $bosungtrongngay + abs($oldbw[$host]['oldbw']);
					if($bw_used <0) $bw_used = 0;
					#cuối ngày
					//limit max bw
					$cuoingay = $unless;
					if($cuoingay > $totalbw) $cuoingay = $totalbw;
					$html .= '<td>'.$this->convertmb($cuoingay).'</td>';
					#a (qua limit), b (du bw), c
					if($unless >= 0) {
						$oldbw[$host]['oldbw'] = 0;
						$html .= '<td>0</td><td>'.$this->convertmb($unless).'</td><td>0</td>';
					}
					else {
						$oldbw[$host]['oldbw'] = abs($unless);
						$html .= '<td>'.$this->convertmb(abs($unless)).'</td><td>0</td><td>'.$this->convertmb(abs($unless)).'</td>';
					}
					$html .= '</tr>';

					/* - 05/09/2024
					if($dataday == date('d.m.Y', $timenow)) {
						$json[$host]['used'] = $total_leeching;
						$json[$host]['unless'] = $unless - $total_leeching;
					}
					*/

					$json[$dataday][$host]['used'] = $bw_used;
					$json[$dataday][$host]['done'] = 0;
					$json[$dataday][$host]['leeching'] = $total_leeching;
					$json[$dataday][$host]['unless'] = $unless;
					$json[$dataday][$host]['daily_bw'] = $totalbw;
					unset($total_leeching, $totalbw, $unless,$host, $bosungtrongngay);
				}
			}

			if(isset($data[$day]['releech'])) {
				foreach($data[$day]['releech'] as $host=>$value2){
					if(in_array($host, $listhost)) continue;
					$listhost[] = $host;
					if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
					else $limit_host = $this->hosts['other'];
					if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
					else {
						if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
						else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
					}


					$total_releech = 0;
					$files_releech = 0;
					$html_releech = '';

					if(isset($data[$day]['releech'][$host])) {
						$files_releech = count($data[$day]['releech'][$host]);
						foreach($data[$day]['releech'][$host] as $hash=>$files){
							if (!isset($listhash[$hash])) {
								$total_releech = $total_releech + $files['msize'];
								$listhash[$hash] = $day;
								$html_releech .= '<i>'.$files['name'].' ('.$this->convertmb($files['msize']).')</i><BR>';
							}

						}
					}
					$total_day_releech = $total_day_releech + $total_releech;

					$html .= '<tr align="center">';
					//host name
					$html .= '<td>'.$host.'</td>';
					//Bổ sung ngày mới
					$html .= '<td>'.($totalbw>0?$this->convertmb($totalbw):'').'</td>';
					//bổ sung trong ngày (nếu mua thêm)
					$bosungtrongngay = 0;
					if(isset($this->bw[$dataday][$host])) {
						foreach($this->bw[$dataday][$host] as $time=>$msize) {
							if(isset($msize) AND $msize>0) $bosungtrongngay = $bosungtrongngay + $msize;
						}
					}
					$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';
					//đầu ngày
					if(!isset($oldbw[$host]['oldbw'])) $oldbw[$host]['oldbw'] = 0;
					$daungay = $totalbw - $oldbw[$host]['oldbw'];
					$html .= '<td>'.$this->convertmb($daungay).'</td>';
					//done trong ngày
					$html .= '<td></td>';
					//leeching
					$html .= '<td></td>';
					//releech
					$html .= '<td>'.($files_releech>0? ($total_releech>0?$this->convertmb($total_releech):'0').' ('.$files_releech.' files)<BR>'.$html_releech:'').'</td>';
					//chưa sử dụng
					//$unless = $totalbw;
					$unless = $totalbw + $bosungtrongngay;
					//bw_used
					$bw_used = 0;
					if(isset($oldbw[$host]['oldbw'])) $bw_used = abs($oldbw[$host]['oldbw']);
					#cuối ngày
					//limit max bw
					$cuoingay = $unless;
					if($cuoingay > $totalbw) $cuoingay = $totalbw;
					$html .= '<td>'.$this->convertmb($cuoingay).'</td>';
					#a (qua limit), b (du bw), c
					if($unless >= 0) {
						$oldbw[$host]['oldbw'] = 0;
						$html .= '<td>0</td><td>'.$this->convertmb($unless).'</td><td>0</td>';
					}
					else {
						$oldbw[$host]['oldbw'] = abs($unless);
						$html .= '<td>'.$this->convertmb(abs($unless)).'</td><td>0</td><td>'.$this->convertmb(abs($unless)).'</td>';
					}
					$html .= '</tr>';


					$json[$dataday][$host]['used'] = $bw_used;
					$json[$dataday][$host]['done'] = 0;
					$json[$dataday][$host]['leeching'] = 0;
					$json[$dataday][$host]['unless'] = $unless;
					$json[$dataday][$host]['daily_bw'] = $totalbw;
					unset($totalbw, $unless,$host, $bosungtrongngay);
				}
			}

			if(isset($oldbw)) {
				foreach($oldbw as $host=>$value2) {
					if(in_array($host, $listhost)) continue;
					if($oldbw[$host]['oldbw'] == 0) continue;
					$listhost[] = $host;
					
					if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
					else $limit_host = $this->hosts['other'];
					if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
					else {
						if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
						else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
					}

					$html .= '<tr align="center">';
					//host name
					$html .= '<td>'.$host.'</td>';
					//Bổ sung ngày mới
					$html .= '<td>'.($totalbw>0?$this->convertmb($totalbw):'').'</td>';
					//bổ sung trong ngày (nếu mua thêm)
					$bosungtrongngay = 0;
					if(isset($this->bw[$dataday][$host])) {
						foreach($this->bw[$dataday][$host] as $time=>$msize) {
							if(isset($msize) AND $msize>0) $bosungtrongngay = $bosungtrongngay + $msize;
						}
					}
					$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';
					//đầu ngày
					if(!isset($oldbw[$host]['oldbw'])) $oldbw[$host]['oldbw'] = 0;
					$daungay = $totalbw - $oldbw[$host]['oldbw'];
					$html .= '<td>'.$this->convertmb($daungay).'</td>';
					//done trong ngày
					$html .= '<td></td>';
					//leeching
					$html .= '<td></td>';
					//releech
					$html .= '<td></td>';
					//bw_used
					$bw_used = 0;
					if(isset($oldbw[$host]['oldbw'])) $bw_used = abs($oldbw[$host]['oldbw']);
					//chưa sử dụng
					//$unless = $totalbw;
					$unless = $totalbw + $bosungtrongngay - $oldbw[$host]['oldbw'];
					#cuối ngày
					//limit max bw
					$cuoingay = $unless;
					if($cuoingay > $totalbw) $cuoingay = $totalbw;
					$html .= '<td>'.$this->convertmb($cuoingay).'</td>';
					#a (qua limit), b (du bw), c
					if($unless >= 0) {
						$oldbw[$host]['oldbw'] = 0;
						$html .= '<td>0</td><td>'.$this->convertmb($unless).'</td><td>0</td>';
					}
					else {
						$oldbw[$host]['oldbw'] = abs($unless);
						$html .= '<td>'.$this->convertmb(abs($unless)).'</td><td>0</td><td>'.$this->convertmb(abs($unless)).'</td>';
					}
					$html .= '</tr>';

					$json[$dataday][$host]['used'] = $bw_used;
					$json[$dataday][$host]['done'] = 0;
					$json[$dataday][$host]['leeching'] = 0;
					$json[$dataday][$host]['unless'] = $unless;
					$json[$dataday][$host]['daily_bw'] = $totalbw;
					unset($totalbw, $unless,$host, $bosungtrongngay);
				}
			}

			//TỔNG
			$html .= '<tr align="center"><td>Tổng</td>';
			$beforeaupdate = $this->bw['timeupdate'] - 24*60*60;
			//bw khi tạo account mới
			if($this->acc_type['reset_bw'] == true) $bw_created = $this->limitMBIP*1024*1024 + $this->plusbw*1024*1024;
			else $bw_created = $this->plusbw*1024*1024;

			//Bổ sung ngày mới
			$bosungngaymoi = 0;
			if($dataday == date('d.m.Y', $this->created)) $bosungngaymoi = $bw_created;
			elseif($this->acc_type['reset_bw'] == true) $bosungngaymoi = $this->limitMBIP*1024*1024;

			$html .= '<td>'.($bosungngaymoi>0?$this->convertmb($bosungngaymoi):'0').'</td>';

			$bosungtrongngay = 0;
			//bổ sung trong ngày (nếu mua thêm)
			if(isset($this->bw[$dataday]['total'])) {
				foreach($this->bw[$dataday]['total'] as $time=>$msize) {
					if(isset($msize) AND is_numeric($msize)==true) $bosungtrongngay = $bosungtrongngay + $msize;
				}
			}

			$html .= '<td>'.($bosungtrongngay>0?$this->convertmb($bosungtrongngay):'').'</td>';

/*
			if($dataday == date('d.m.Y', $beforeaupdate)) {
				$bwcuoingay = $this->bw['bwupdate'] - $bosungtrongngay;
				$html .= '<td></td><td></td><td>'.$this->convertmb($bwcuoingay).'</td><td></td><td></td><td></td><td></td><td></td>';
				continue;
			}
*/
			//đầu ngày
			if(!isset($bwcuoingay)) $bwcuoingay = 0;
			if($dataday == $dayupdatecode) {
				$total_used = 0;
				$listhash = array();
				foreach ($this->jobs['leech'] as $key=>$job) {
					if (!is_array($job) || empty($job['url']) || !isset($job['mtime'])) continue;
					$hash = substr(md5($job['url']),0,10);
					$day = date('d.m.Y', $job['mtime']);
					if (isset($listhash[$hash])) continue;
					else {
						if($this->bw['timeupdate'] > $job['mtime'] AND $job['mtime'] >= strtotime($dayupdatecode)) {
							if($job['status'] == 0 or $job['status'] == 1 or $job['status'] == 2) {
								$total_used = $total_used + $job['msize'];
								$listhash[$hash] = $job['mtime'];
							}
						}
						else {
							$listhash[$hash] = $job['mtime'];
						}
					}
				}

				$tongdaungay = $this->bw['bwupdate'] + $total_used;
			}
			else {
				$tongdaungay = $bwcuoingay + $bosungngaymoi;
				//limit max bw
				if($this->acc_type['reset_bw'] == true && $tongdaungay > $this->maxbw*1024*1024) $tongdaungay = $this->maxbw*1024*1024;
			}
			//xử lý 30 ngày trước
			/*
			if(strtotime($daynow) - strtotime($dataday) > 30*24*60*60) {
				if(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] > $tongdaungay) $html .= '<td><font color="blue">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				elseif(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] < $tongdaungay) $html .= '<td><font color="red">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				else $html .= '<td>'.$this->convertmb($tongdaungay).'</td>';
				//done, leeching, releech
				$html .= '<td></td><td></td><td></td>';
				//cuối ngày
				$daungaysau = strtotime($dataday) + 24*60*60;
				$daungaysau = date('d.m.Y', $daungaysau);
				if(isset($this->bw['tongdaungay'][$daungaysau])) {
					$bwcuoingay = $this->bw['tongdaungay'][$daungaysau] - $bosungngaymoi;
					$html .= '<td>'.$this->convertmb($bwcuoingay).'</td>';
				}
				else $html .= '<td></td>';
				//a, b, c
				$html .= '<td></td><td></td><td></td>';
				$html .= '</tr>';
			}
			*/
			//fix code từ ngày 06.02.2025
			if(strtotime($dataday) - strtotime('06.02.2025') > 0) {
				//tính lại bw cuối ngày theo logs
				$daungaysau = strtotime($dataday) + 24*60*60;
				$daungaysau = date('d.m.Y', $daungaysau);
				if(isset($this->bw['tongdaungay'][$daungaysau])) {
					$bwcuoingay = $this->bw['tongdaungay'][$daungaysau] - $bosungngaymoi;
				}

				if(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] > $tongdaungay) $html .= '<td><font color="blue">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				elseif(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] < $tongdaungay) $html .= '<td><font color="red">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				else $html .= '<td>'.$this->convertmb($tongdaungay).'</td>';
				//update lại $tongdaungay theo logs
				if(isset($this->bw['tongdaungay'][$dataday])) $tongdaungay = $this->bw['tongdaungay'][$dataday];
				//done trong ngày
				$html .= '<td>'.($total_day_done>0?$this->convertmb($total_day_done):'').'</td>';
				//leeching
				$html .= '<td>'.($total_day_leeching>0?$this->convertmb($total_day_leeching):'').'</td>';
				//releech
				$html .= '<td>'.($total_day_releech>0?$this->convertmb($total_day_releech):'').'</td>';
				//bw_used
				if($bwcuoingay<0) $bw_total_used = $total_day_done + $total_day_leeching + abs($bwcuoingay);
				else $bw_total_used = $total_day_done + $total_day_leeching;
				//chưa sử dụng
				$unless = $tongdaungay + $bosungtrongngay - $total_day_done - $total_day_leeching;
				//cuối ngày
				$bwcuoingay = $unless;
				//limit max bw
				if($this->acc_type['reset_bw'] == true && $bwcuoingay > $bw_created) $bwcuoingay = $bw_created;
				$html .= '<td><b>'.(isset($this->bw['tongdaungay'][$daungaysau])?'<font color="black">':'<font color="red">').$this->convertmb($bwcuoingay).'<font></b></td>';
				//a (qua limit), b (du bw), c
				if($bwcuoingay >= 0) {
					$html .= '<td>0</td><td>'.$this->convertmb($bwcuoingay).'</td><td>0</td>';
				}
				else {
					$html .= '<td>'.$this->convertmb(abs($bwcuoingay)).'</td><td>0</td><td>'.$this->convertmb(abs($bwcuoingay)).'</td>';
				}
				$html .= '</tr>';
			}
			else {
				if(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] > $tongdaungay) $html .= '<td><font color="blue">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				elseif(isset($this->bw['tongdaungay'][$dataday]) AND $this->bw['tongdaungay'][$dataday] < $tongdaungay) $html .= '<td><font color="red">'.$this->convertmb($this->bw['tongdaungay'][$dataday]).'/'.$this->convertmb($tongdaungay).'</font></td>';
				else $html .= '<td>'.$this->convertmb($tongdaungay).'</td>';
				//done trong ngày
				$html .= '<td>'.($total_day_done>0?$this->convertmb($total_day_done):'').'</td>';
				//leeching
				$html .= '<td>'.($total_day_leeching>0?$this->convertmb($total_day_leeching):'').'</td>';
				//releech
				$html .= '<td>'.($total_day_releech>0?$this->convertmb($total_day_releech):'').'</td>';
				//bw_used
				if($bwcuoingay<0) $bw_total_used = $total_day_done + $total_day_leeching + abs($bwcuoingay);
				else $bw_total_used = $total_day_done + $total_day_leeching;
				//chưa sử dụng
				$unless = $tongdaungay + $bosungtrongngay - $total_day_done - $total_day_leeching;
				//cuối ngày
				$bwcuoingay = $unless;
				//limit max bw
				if($this->acc_type['reset_bw'] == true && $bwcuoingay > $bw_created) $bwcuoingay = $bw_created;
				$html .= '<td><b>'.$this->convertmb($bwcuoingay).'</b></td>';
				//a (qua limit), b (du bw), c
				if($bwcuoingay >= 0) {
					$html .= '<td>0</td><td>'.$this->convertmb($bwcuoingay).'</td><td>0</td>';
				}
				else {
					$html .= '<td>'.$this->convertmb(abs($bwcuoingay)).'</td><td>0</td><td>'.$this->convertmb(abs($bwcuoingay)).'</td>';
				}
				$html .= '</tr>';
			}
			if($dataday == date('d.m.Y', $timenow)) {
				$json['acc']['used'] = $bw_total_used;
				$json['acc']['unless'] = $bwcuoingay;
				$json['acc']['daungay'] = $tongdaungay;
				$json['acc']['bw_created'] = $bw_created;
				$json['acc']['day'] = $dataday;
			}

		}
		$html .= '<tr style="background-color: #f2f2f2; font-weight:bold" align="center">
				<td style="width:80px">Ngày</td>
				<td style="width:80px">Bổ sung ngày mới</td>
				<td style="width:80px">Bổ sung trong ngày</td>
				<td style="width:80px">Đầu ngày</td>
				<td>Done trong ngày</td>
				<td>Leeching</td>
				<td>ReLeech</td>
				<td style="width:80px">Cuối ngày</td>
				<td style="width:80px">a (âm bw)</td>
				<td style="width:80px">b (dư bw)</td>
				<td style="width:80px">c (trừ vào hôm sau)</td></tr>';			
		$html .= '</table><BR><BR>';
		$this->json_bw_api = $json;
		if(isset($_GET['api'])==true && $_GET['api'] == 'bw' && isset($_GET['show'])==true && $_GET['show'] == 'html') {
			echo $html;
			if($test) {
				echo 'API:<pre>';print_r($json);echo '</pre>';
			}
			echo 'bw:<pre>';print_r($this->bw);echo '</pre>';
		}
		elseif(isset($_GET['api'])==true && $_GET['api'] == 'bw' && isset($_GET['show'])==true && $_GET['show'] == 'json') $this->showjson($json);
		else return $json;
		return $json;
	}


	function total_acc_used() {
		$total = 0;
		$time = time();
		$listhash = array();
		foreach ($this->jobs['leech'] as $key=>$job) {
			$hash = substr(md5($job['url']),0,10);
			$day = date('d.m.Y', $job['mtime']);
			if (isset($listhash[$hash]) && (date('z',strtotime($day)) - date('z',strtotime($listhash[$hash])) <3)) continue;
			else {
				$datenow = date('z',$time) + 366*(date('Y',$time) - date('Y',$job['mtime']));
				if($datenow - date('z',$job['mtime']) == 0) {
					if($job['status'] == 0 or $job['status'] == 1 or $job['status'] == 2) {
						$total = $total + $job['msize'];
						$listhash[$hash] = $job['mtime'];
						//echo $hash.' '.$job['filename'].' '.$job['filename'].' '.$this->convertmb($job['msize']).'<BR>';
					}
				}
				else {
					$listhash[$hash] = $job['mtime'];
				}
			}
		}
		return $total;
	}
	//total host used
	function total_bw_day($host){
		$time = time();
		$json = $this->bw_api($host);
		$daynow = date('d.m.Y', $time);
		if(!isset($json[$daynow][$host]['used'])) return 0;
		else return $json[$daynow][$host]['used'];
	}

	function total_acc_unless(){
		$time = time();
		$json = $this->bw_api();
		if(!isset($json['acc']['unless'])) return 0;
		else {
			//thông báo khi bw account user quá 1000Gb
			if (!isset($_COOKIE['ck_bw'])) {
				goto report_bw;
			}
			$time_check_bw = $time - $_COOKIE['ck_bw'];
			if($time_check_bw > 24*60*60) {
				report_bw:
				if($json['acc']['unless'] > 1000*1024*1024*1024) {
					$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
					$post['user'] = $linklogin;
					$post['email'] = $this->email;
					$post['mobile'] = $this->mobile;
					$post['acc_type'] = $this->acc_type['fullname'];
					$post['url'] = $linklogin;
					$post['status'] = 3;
					$post['md5'] = md5($linklogin);
					$post['host'] = '';
					$post['ip'] = '';
					$post['isp'] = '';
					$post['filename'] = '<font color="red">quá 1000Gb băng thông</font>';
					$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
					setcookie('ck_bw',$time,$time+3600*24*365);
				}
				elseif($json['acc']['unless'] < -5*1024*1024*1024) {
					$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
					$post['user'] = $linklogin;
					$post['email'] = $this->email;
					$post['mobile'] = $this->mobile;
					$post['acc_type'] = $this->acc_type['fullname'];
					$post['url'] = $linklogin;
					$post['status'] = 3;
					$post['md5'] = md5($linklogin);
					$post['host'] = '';
					$post['ip'] = '';
					$post['isp'] = '';
					$post['filename'] = '<font color="red">-5Gb băng thông</font>';
					$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
					setcookie('ck_bw',$time,$time+3600*24*365);
				}
				elseif (!isset($_COOKIE['ck_bw'])) setcookie('ck_bw',$time,$time+3600*24*365);
			}
			return $json['acc']['unless'];
		}

	}

	function save_bw($time=false, $txtlog=false){
		if (!isset($this->bw) || is_array($this->bw)==false) die('error 01: not found bw');
		$fld_bw = $this->fileinfo_dir.$this->bw_dir;
		$file_logbw = $fld_bw.'logbw.txt';

		$file_bw = $this->rand_filename($fld_bw);
		//echo $file_bw.'<BR>';
		if($time==false) $this->bw["time"] = time();
		if($time > 1262304000)  $this->bw["time"] = $time;
		$tmp = @json_encode($this->bw);
		if($this->bw_data != $tmp) $this->bw_data = $tmp;
		elseif($time==false) return;
	
		$fh = fopen($file_bw, 'w+') or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the folder "<B>'.$this->fileinfo_dir.'</B>" to 777</font></CENTER>');
		fwrite($fh, $tmp);
		fclose($fh);

		if(!empty($txtlog)) $this->savefile($file_logbw,$txtlog."\r\n",'a');

		@chmod($file_bw, 0666);
		if (isset($this->listbw) && is_array($this->listbw) && count($this->listbw)>0) foreach ($this->listbw as $file) if (file_exists($file)) @unlink($file);
		return true;
	}

	function get_load($i = 0){
		$load = array('0', '0', '0');
		if (@file_exists('/proc/loadavg')){
			if ($fh = @fopen('/proc/loadavg', 'r')){
				$data = @fread($fh, 15);
				@fclose($fh);
				$load = explode(' ', $data);
			}
		}
		else{
			if ($serverstats = @exec('uptime')){
				if (preg_match('/(?:averages)?\: ([0-9\.]+),?[\s]+([0-9\.]+),?[\s]+([0-9\.]+)/', $serverstats, $matches)){
					$load = array($matches[1], $matches[2], $matches[3]);
				}
			}
		}
		return $i==-1 ? $load : $load[$i];
	}

	function lookup_job($hash){
		//$this->load_jobs();
		foreach ($this->jobs['get'] as $key=>$job)
		{
			if ($job['hash'] == $hash)
			{
				$job['url'] = $key;
				return $job;
			}
		}
		return false;
	}

	function loadphim() {
		$phimdata = @file_get_contents($this->pathphim);
		$phim = @json_decode($phimdata, true);	
		if (!is_array($phim))$phim = array();
		$this->phim = $phim;
		return $phim;
	}
	function checklogin() {
		if(!isset($this->info["status"]) OR !isset($this->created) OR !isset($this->expired)) {
			die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=logout';</SCRIPT>");
		}
		if($this->expired > time() && $this->info["status"] == 'expired') {
			$this->info["status"] = 'true';
			$this->save_info();
		}
		if($this->info["status"] == "locked" ) {
			die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=lock';</SCRIPT>");
		}
		elseif($this->info["status"] == "expired" OR $this->expired < time()){
			if(isset($_POST['get']) or isset($_POST['leech']) or isset($_GET['get']) or isset($_GET['leech'])){
				die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=expired';</SCRIPT>");
			}
			elseif(isset($_POST['leecherror']) && (time() - $this->expired > 24*60*60)){
				die("<SCRIPT language='Javascript'>document.location.href ='./login.php?go=expired';</SCRIPT>");
			}


		}

	}
	function cut_str($str, $left, $right)  {
		$str = substr ( stristr ( $str, $left ), strlen ( $left ) );
		$leftLen = strlen ( stristr ( $str, $right ) );
		$leftLen = $leftLen ? - ($leftLen) : strlen ( $str );
		$str = substr ( $str, 0, $leftLen );
		return $str;
	}
	//new function - 2018/09/9 - 22:02 (GMT+7)
    function Checkjobs($host, $type=false) {
		$heute = 0;
		$newjob = $this->jobs['get'];
		if(isset($this->jobs['leech'])) {
			foreach ($this->jobs['leech'] as $key=>$job) {
				if($type=='error' && isset($this->jobs['leech'][$key]['leecherror'])==false) continue;
				if($type=='fshare' && isset($this->jobs['leech'][$key]['fshare'])==false) continue;
				$newjob[$key] = $job;
			}
		}

		foreach ($newjob as $job){
			if(!isset($job['url'])) {
				//print_r($job);
				continue;

			}
			if(stristr($job['url'],$host)) {
				$datenow = date('z',time()) + 366*(date('Y',time()) - date('Y',$job['mtime']));
				if($datenow - date('z',$job['mtime']) == 0) $heute++;
			}
			elseif(isset($job['host']) && stristr($job['host'],$host)) {
				$datenow = date('z',time()) + 366*(date('Y',time()) - date('Y',$job['mtime']));
				if($datenow - date('z',$job['mtime']) == 0) $heute++;
			}
			else {
				$hosting = $this->domain_name($job['url']);
				if(stristr($hosting,$host)) {
					$datenow = date('z',time()) + 366*(date('Y',time()) - date('Y',$job['mtime']));
					if($datenow - date('z',$job['mtime']) == 0) $heute++;
				}
			}
		}

		return $heute;
	}


	##########

	function site_hash($url){
		if(stristr($url,'magnet')) return 'magnet';
		//elseif(stristr($url,'.torrent')) return 'torrent';
		$domain_name = $this->domain_name($url);
		$site = preg_replace("/(www.|.com|.net|.biz|.info|.org|.us|.vn|.jp|.fr|.in|.to)/","",$domain_name);
		return $site;
	}
	function convert_svtab($svtab){
		if(isset($this->server_tab[$svtab])) {
			 $idtab = $this->server_tab[$svtab][0];
		}
		else $idtab = 'us';
		return $idtab;

	}
	function convert($filesize){
		$filesize = str_replace(",",".",$filesize);
		if(preg_match('/^([0-9]{1,7}+(\.[0-9]{1,2})?)/', $filesize,$value)){
			if(stristr($filesize,"TB"))		$value = $value[1]*1024*1024*1024*1024;
			elseif(stristr($filesize,"GB")) $value = $value[1]*1024*1024*1024;
			elseif(stristr($filesize,"MB")) $value = $value[1]*1024*1024;
			elseif(stristr($filesize,"KB")) $value = $value[1]*1024;
			else $value = $value[1];
		}
		else $value = 0;
		return round($value,0);
	}
	function convertmb($filesize){
		if (!is_numeric($filesize)) return $filesize;
		$soam = false;
		if($filesize<0){
			$filesize = abs($filesize);
			$soam = true;
		}
		if($filesize >= 1024*1024*1024*1024) $value = ($soam ? "-" : "").round($filesize/(1024*1024*1024*1024), 2)." TB";
		elseif($filesize >= 1024*1024*1024) $value = ($soam ? "-" : "").round($filesize/(1024*1024*1024), 2)." GB";
		elseif($filesize >= 1024*1024) $value = ($soam ? "-" : "").round($filesize/(1024*1024), 2)." MB";
		elseif($filesize >= 1024) $value = ($soam ? "-" : "").round($filesize/(1024), 2)." KB";
		else $value = ($soam ? "-" : "").$filesize." Bytes";
		return $value;
	}
	function convert_time($time){
		if($time >= 86400) $time = round($time/(60*24*60), 1)." ".$this->lang['days'];
		elseif(86400 > $time && $time >= 3600) $time = round($time/(60*60), 1)." giờ";
		elseif(3600 > $time && $time >= 60) $time = round($time/60, 1)." ".$this->lang['mins'];
		else $time = $time." ".$this->lang['sec'];

		return $time;
	}
	function size($link,$time=15){
		$link = str_replace(" ","%20",$link);
		$link = str_replace('&amp;','&',$link);
		/*
		$ch = @curl_init();
		curl_setopt($ch, CURLOPT_URL, $link);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_USERAGENT, $this->UserAgent);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_REFERER,$link);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_TIMEOUT, $time); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $time);
		$page = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch); 
		//echo $page;print_r($info);exit;
		if($info['http_code'] == '200') $filesize = $info['download_content_length'];
		else $filesize = -1;
		return $filesize;
		*/

		$port = 80;
		$schema = parse_url(trim($link));
		$host= $schema['host'];
		$scheme = "http://";
		$gach = explode("/", $link);
		list($path1, $path)  = explode($gach[2], $link);
		if(isset($schema['port'])) $port = $schema['port'];
		elseif ($schema['scheme'] == 'https') {
			$scheme = "ssl://";
			$port = 443;
		}

		if ($scheme != "ssl://") {
			$scheme = "";
		}
		$hosts = $scheme . $host . ':' . $port;
		$fp = @stream_socket_client ($hosts, $errno, $errstr, 30);

		if (!$fp) $filesize = -1;
		else {
			$data = "GET {$path} HTTP/1.1\r\n";
			$data .= "User-Agent: ".$this->UserAgent."\r\n";
			$data .= "Host: {$host}\r\n";
			$data .= "Referer: {$link}\r\n";
			$data .= "Accept: */*\r\n";
			$data .= "Connection: Close\r\n\r\n";
			@stream_set_timeout($fp, 30);
			fputs($fp, $data);
			fflush($fp);

			$header = stream_get_line($fp, 1024);
			if(preg_match ('/^HTTP\/1\.(1|0) ([0-9]+) .*/i', $header, $responsecode)) {
				if ($responsecode[2] == 200) $filesize = trim ($this->cut_str ($header, "Content-Length:", "\n" ));
				else $filesize = -1;
			}
			else $filesize = -1;
		}
		//echo "<textarea>".$filesize."\r\n".$header ."</textarea>";exit;
		return $filesize;
	}


}
##################################### End class getinfo #######################################


##################################### Begin class stream_get ##################################
class stream_get extends getinfo {
		function __construct(){
			$this->stream_get();
		}

	function stream_get(){
		$time = time();
		//include("limit.php");
		$this->config();
		if($this->Deny == true) return;
		//$this->load_jobs();
		list($this->jobs, $this->lists, $this->tmp_old) = $this->load_data($this->fileinfo_dir."/files/");
		// Phase B: if .dat is missing/corrupt, fallback read from sqlite (legacy_jobs2)
		$dat_ok = (is_array($this->jobs) && count($this->jobs) > 0);
		if (!$dat_ok) {
			$jobs_db = $this->legacy_sqlite_read_jobs2();
			if (is_array($jobs_db)) {
				$this->jobs = $jobs_db;
				$this->lists = array();
				$this->tmp_old = json_encode($this->jobs);
			}
		}
		if(!isset($this->jobs['get'])) {
			$newdata = $this->jobs;
			unset($this->jobs);
			$this->jobs['get'] = $newdata;
			$this->save_jobs();
		}

		$this->autodelfile(); // clean jobs over time
		// best-effort: keep legacy.sqlite caught up with .dat for safer future reads
		$this->legacy_sqlite_backfill_maybe(300);
		$this->load_info();
		$this->load_bw();
		//echo '<pre>';
		//print_r($this->bw);
		//print_r($this->info);exit;
		if(!isset($this->bw['timeupdate']) || !isset($this->bw['bwupdate']))  die('Đã có phiên bản mới, vui lòng liên hệ getlink để cập nhật account');
		$this->loadphim();
		$this->CheckMBIP();
		$this->cookie = '';
		if (isset($_REQUEST['img'])) $this->showimg($_REQUEST['img']);
		if (isset($_COOKIE['owner'])) $this->owner = $_COOKIE['owner'];
		else{
			$this->owner = intval(rand()*10000);
			setcookie('owner', $this->owner, 0);	
		}

	}
    function CheckMBIP(){
		$this->countMBIP = 0;
		$this->totalMB = 0;
		$timedata =time();
		foreach ($this->jobs['get'] as $job){
			if (!is_array($job) || !isset($job['msize'])) continue;
			$this->totalMB = $this->totalMB + $job['msize'];

		}
	}
	function curl($url,$cookies,$post,$time=60){
		$ch = @curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		if ($cookies) curl_setopt($ch, CURLOPT_COOKIE, $cookies);
		curl_setopt($ch, CURLOPT_USERAGENT, $this->UserAgent);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_REFERER,$url); 
		if ($post){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
		}
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_TIMEOUT, $time); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $time);
		$page = curl_exec( $ch);
		curl_close($ch); 
		return $page;
	}

	function mailreport($subject,$contents){
		$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
		$post['subject'] = $subject;
		$post['contents'] = 
			"Thời gian lỗi: ".date( 'H:i:s- d.m.Y',time())."<BR/>
			Lỗi được tìm thấy từ tài khoản: ".$linklogin."<BR/>
			Mật khẩu: <B>".$this->SecureID."</B><BR>
			Mail: ".$this->email."<BR>
			Mobile: ".$this->mobile."
			".$contents;
		$data = $this->curl($this->linkreport,"secureid=".md5("test"),$post);
		//$data = $this->curl($this->linkmail,"vngcookie=".md5($this->passmail),$post);
	}
	function copyfile($link,$path) {
		if (!file_exists ($this->folderimg)) {
			mkdir($this->folderimg, 0777)  
			or die('<CENTER><font color=red size=4>Could not create folder! Try to chmod the folder "<B>'.$this->folderimg.'</B>" to 777</font></CENTER>');
		}
		$data = $this->curl($link,'','');	
		$handle = fopen($path, "w")
		or die('<CENTER><font color=red size=3>'.__LINE__.' could not open file! Try to chmod the file "<B>'.$path.'</B>" to 666</font></CENTER>');
		fwrite($handle, $data)
		or die('<CENTER><font color=red size=3>'.__LINE__.' could not write file! Try to chmod the file "<B>'.$path.'</B>" to 666</font></CENTER>');
		fclose($handle);
		return true;
	}

	function main(){
		$this->checklogin();
		$checklog = false;
		$url = false;
		krsort($this->info["logs"]);
		foreach($this->info["logs"] as $time => $iplog) {
			if(time() - $time < 7*24*60*60) {
				if(preg_match("/^(\d{1,3}\.\d{1,3}\.)/i",$this->myip, $value)) $ip = trim($value[1]);
				else $ip = trim($this->myip);
				if(stristr($iplog,$ip)) {
					$checklog = true;
					break;
				}
			}
			else break;
		}
		if($checklog == false) die("errorlogin");

		if ($this->get_load() > $this->max_load){
			echo '<center><b><i><font color=red>'.$this->lang['svhload'].'</font></i></b></center>';
			return;
		}
		if (isset($_POST['urllist'])) {
			$url = trim($_POST['urllist']);
			$url = str_replace("\r", "",  $url);
			$url = str_replace("\n", "",  $url);
			$url = str_replace("<", "",  $url);
			$url = str_replace(">", "",  $url);
		}
		if(!preg_match('%(http|https)\:\/\/(www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]+\/%U', $url) AND stristr($url,'magnet:?xt=')==false) {
			printf($this->lang['deadlink'],$url);
			return;
			//die ($this->lang['status3']);
		}
		$dlhtml = "";
		if(isset($_POST['download']) && $_POST['download']=='phim') {
			$dlhtml .= $this->get($url);
			if(stristr($dlhtml,'We do not support')) die ($this->lang['notf_film']);
			elseif(stristr($dlhtml,'title="click') || stristr($dlhtml,'id="errorlimit"')) die($dlhtml);
			elseif(stristr($dlhtml,'Kh&#244;ng th&#7875; get')) die($this->lang['max_film']);
			else die();
			//elseif(!stristr($dlhtml,'font-weight: bold;color:')) die('Phim không tồn tại.');
		}
		elseif(isset($_POST['download']) && ($_POST['download']=='subviet' || $_POST['download'] =='subeng')) {
			$dlhtml .= $this->get($url);
			if(stristr($dlhtml,'title="click')) die($dlhtml);
			elseif(stristr($dlhtml,'We do not support')) $dlhtml = $this->lang['find_sub'];
			elseif(stristr($dlhtml,'subscene.com') == true) {
				$sub = $dlhtml;
				$dlhtml = '<a href="'.$sub.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.($_POST['download']=='subviet'?$this->lang['subviet']:$this->lang['subeng']).'</a>';
				die($dlhtml);
			}
			//elseif(stristr($dlhtml,'We do not support')) die ('Không thể get được phụ đề. Vui lòng thử lại');
			if($_POST['download']=='subviet') $lang = '/vietnamese';
			else $lang = '/english';
			$filename = strtolower(str_replace(" ",'-',$this->phim[$url]['name']));
			$filename = str_replace('(','',$filename);
			$filename = str_replace(')','',$filename);
			$filename = str_replace(',','',$filename);
			$sub = 'http://subscene.com/subtitles/'.substr($filename,0,-5).$lang;
			$data = $this->curl($sub,'','');
			if(stristr($data,'<h1>Page Not Found</h1>')) {
				$sub = 'http://subscene.com/subtitles/'.$filename.$lang;
				$data = $this->curl($sub,'','');
			}
			
			if(stristr($data,'Subtitles for</h1>')) $dlhtml = '<a href="'.$sub.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.($_POST['download']=='subviet'?$this->lang['subviet']:$this->lang['subeng']).'</a>';
			else $dlhtml = $this->lang['find_sub'];
			die($dlhtml);
		}
		elseif (isset($url)&& strlen($url) > 10){
			if(substr($url,0,4)=='www.') $url = "http://".$url;
			if($_POST['download'] == 'leech' && isset($_POST['leecherror'])) $dlhtml .= $this->leecherror($url);
			elseif($_POST['download'] == 'leech' && isset($_POST['leechfshare'])) $dlhtml .= $this->leechfshare($url);
			elseif(isset($_POST['leech'])) $dlhtml .= $this->leech($url);
			elseif(isset($_POST['get'])) $dlhtml .= $this->get($url);
			elseif($this->expired < time()){
				echo '<center>'.$this->lang['get_expired'].'</center>';
				return;
			}
		}
		else $dlhtml .=  "<b><a href=".$url." style='TEXT-DECORATION: none'><font color=red face=Arial size=2 id='Invalidlink'><s>".$url."</s></font></a> <img src=./../../../images/chk_error.png width='15' alt='errorlink'> <font color=#ffcc33><B>".$this->lang['errorlink']."</B></font><BR>";
		if (empty($url)==false)  echo $dlhtml;
	}

	function get($url, $job_url=false){
		$test = false;
		$url = trim($url);
		$time = time();
		if (empty($url)) return;
		if(!isset($_POST['download'])) return;
		$dlhtml = "";
		$hash = md5($url.$this->self);

		$type = array_keys($this->server); //list server --> đã bỏ không sử dụng
		// PHP8 guard: array_rand() on empty array throws ValueError
		$sv_root = 'us';
		if (is_array($this->sv_root) && count($this->sv_root) > 0) {
			$sv_root = array_rand($this->sv_root, 1);
		}
		$type[] = $sv_root;

		if($_POST['download']=='phim' || $_POST['download']=='subviet' || $_POST['download'] =='subeng')  {
			$hashphim = $url;
			$phim = $this->loadphim();
			if(isset($phim[$hashphim])) {
				$url = $phim[$hashphim]['movie'];
				$namemovies = $phim[$hashphim]['name'];
			}
			else die($this->lang['f5_press']);
			if($_POST['download']=='subviet'){
				$sub = str_replace(substr($url,-7),'',$url);
				if(isset($phim[$hashphim]['sub']['viet']) && $phim[$hashphim]['sub']['viet'] != false && stristr($phim[$hashphim]['sub']['viet'],'subscene.com') == true){
					return  $phim[$hashphim]['sub']['viet'];
				}
				elseif(isset($phim[$hashphim]['sub']['viet']) && $phim[$hashphim]['sub']['viet'] != false) $url = $phim[$hashphim]['sub']['viet'];
				elseif($this->size($sub.'.srt') >0 ) $url = $sub.'.srt';
				elseif($this->size($sub.'_VIE.srt') >0 ) $url = $sub.'_VIE.srt';
				else return;
			}
			elseif($_POST['download']=='subeng'){
				$sub = str_replace(substr($url,-7),'',$url);
				if(isset($phim[$hashphim]['sub']['anh']) && $phim[$hashphim]['sub']['anh'] != false && stristr($phim[$hashphim]['sub']['anh'],'subscene.com')){
					return  $phim[$hashphim]['sub']['anh'];
				}
				elseif(isset($phim[$hashphim]['sub']['anh']) && $phim[$hashphim]['sub']['anh'] != false) $url = $phim[$hashphim]['sub']['anh'];
				elseif($this->size($sub.'_ENG.srt') >0) $url = $sub.'_ENG.srt';
				else return;
				
			}
		}

		//print_r($this->jobs['leech'][$hash]);exit;
		//xóa link đã lưu 3 ngày và get lại
		if(isset($this->jobs['get'][$hash])==true  && time() > $this->jobs['get'][$hash]['mtime']+3*24*60*60) {
			unset($this->jobs['get'][$hash]);
		}

		if(isset($this->jobs['leech'][$hash])==true  && time() > $this->jobs['leech'][$hash]['mtime']+2*24*60*60) {
			unset($this->jobs['leech'][$hash]);
		}


		if($_POST['download'] =='phim')  $hash = 'phim_'.$hashphim;
		elseif($_POST['download'] =='subviet')  $hash = 'subviet_'.$hashphim;
		elseif($_POST['download'] =='subeng')  $hash = 'subeng_'.$hashphim;

		// Limit get tối đa 1 link = 4
		if(isset($this->jobs['get'][$hash])==true && $this->jobs['get'][$hash]['speed']> 4 && time() < $this->jobs['get'][$hash]['mtime']+2*60*60) {
			if($_POST['download']=="down" || $_POST['download']=="phim" ) {
				$contents = "link get: $url <BR>Type: ".json_encode($type);
				$this->mailreport("Phát hiện $url get nhiều lần !",$contents);
			}
			$dlhtml .= "<b><a href=".$url." style='TEXT-DECORATION: none'><font color=#ff6600 face=Arial size=2 id='Invalidlink'>".$url."</font></a> <img src=./../../../images/chk_error.png width='15' alt='errorlink'> <font color=#ffcc33><B>".$this->lang['maxget'];
			die($dlhtml);
		}

		if(stristr($url,'magnet:?xt=') || stristr($url,'.torrent')) {
			if(preg_match('%(http|https)\:\/\/torcache.net\/torrent\/(.*)\.torrent\?title\=(.*?)%U', $url, $matches)) {
				$hash = strtolower(trim($matches[2]));
				$name = strtolower(trim($matches[3]));
				$name = str_replace('[kat.cr]','',$name);
				$url = 'magnet:?xt=urn:btih:'.$hash.'&dn='.urlencode($name);
			}
			elseif(stristr($url,'.torrent') && stristr($url,'magnet:?xt=')==false) {
				$data = @file_get_contents($this->infomagnet.'convert.php?url='.urlencode($url));
				$info = json_decode($data, true);
				if (is_array($info)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$info = json_decode($data, true);
				}
				if(!is_array($info)) die('error 1: Sorry, there was an error uploading your file.');
				if(isset($info['error']) && $info['error'] != 'no') die($info['error']);
				$url = $info['magnet'];
				$hash = $info['hash'];
			}
			elseif (preg_match('%magnet\:\?xt\=urn\:btih\:(.*)(\&dn\=)?%U', $url,$value)) $hash = strtolower(substr($url,20,40));
			elseif (preg_match('#^magnet\:\?xt\=urn\:btih\:(.*)#', $url,$value)) $hash = trim($value[1]);
			else die("can't get this file");
			$data = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash);
			$torrent = json_decode($data, true);
			if (is_array($torrent)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$torrent = json_decode($data, true);
			}
			if(is_array($torrent) == true && isset($torrent['gate']) && isset($torrent['status'])) {
				 if(isset($torrent['link']) && stristr($torrent['link'],'http') &&  $torrent['status'] == 'ok') {
					$url = $torrent['link'];
					$host = $this->domain_name($url);
				 }
				 elseif($torrent['status'] == 'leeching') {
					$gateto = $torrent['gate'];
					$url = $torrent['magnet'];
					$host = "torrent";
				 }
				 else $host = "torrent";
			}
			else $host = "torrent";

		}
		elseif(isset($this->leech) && $this->leech == true) $host = 'leech'; //get link leech
		else {
			$filesize = $this->size($url);
			if($filesize > 10*1024) $host = 'dlink';
			else $host = $this->domain_name($url);
		}

		//thay đổi link manager theo hosting - 2023/05/29 -23:04 (GMT+7) 
		if(isset($this->leechrieng) && $this->leechrieng == true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
		elseif(isset($this->leechrieng_on) && in_array($host, $this->leechrieng_on)==true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
		else if(isset($this->mng_normal[$host])) $this->leechmng = $this->mng_normal[$host];

		//echo $this->leechmng;exit;
/*
		if(in_array($host, $this->leechhost)==true) {
			$data = $this->curl($this->leechlink,"auth=".md5($this->leechpass),'user='.$this->self.'&link='.$url);
			//echo $data;
			$page = json_decode($data, true);
			$URL = '';
			if(isset($page['filesize'])) { 
				$filename = $page['filename'];
				$filesize = $page['filesize'];
				$dlhtml .=  "<b><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font></a> => Link của bạn đang được xử lý, getlink sẽ trả kết quả sau 30 phút trong mục leech files</b><BR>";
			}
			elseif(isset($page['error'])) die($page['error']);
			goto savedata;

		}
*/

		if (isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
		else  $limit_host = $this->hosts['other'];
		#tổng băng thông cho nhóm host riêng  = limit1 +limit2
		if(isset($this->hosts2[$host]['bandwidth'])) $totalbw_host = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
		else  $totalbw_host = ($limit_host['bandwidth'])*1024*1024;

		if (isset($limit_host['max_link']) == true && $this->Checkjobs($host) >= $limit_host['max_link']){
			echo '<center><b><i><font color=red>'.sprintf($this->lang['limit_host'],$host, $limit_host['max_link']).'</font></i></b></center>';
			return;
		}



		//limit for reget
		$lefttime_reget = 0;
		if(isset($this->jobs['get'][$hash]['mtime'])) $lefttime_reget = $this->jobs['get'][$hash]['mtime'] + 60*60 - time();
		if(isset($this->jobs['get'][$hash])==true && $lefttime_reget>0 && $this->jobs['get'][$hash]['speed']>2){
			echo '<center><b><i><font color=red>'.sprintf($this->lang['limit_reget'], $this->jobs['get'][$hash]['speed'], $this->convert_time($lefttime_reget)).'</font></i></b></center>';
			return;
		}
		//limit for reget


		//hết băng thông account (khong chan khi tra link leech)
		if ($this->total_acc_unless() <= 0 && isset($this->leech)==false){
			if($test) echo 'bw1<BR>';
			printf($this->lang['outbw'],$this->convertmb($this->total_acc_unless()));
			return;
		}


		# Edited by Kien
		if($host == "oron.com" || $host == "rapidshare.com" || $host == "uploading.com" || $host == "letitbit.net" || $host == "vip-file.com" || $host == "shareflare.net" || $host == "ryushare.com" || $host == "filehaste.com" || $host == "hotfile.com" || $host == "filestay.com" || $host == "filemates.com" || $host == "shragle.com" || $host == "filehost.ws" || $host == "filerose.com" || $host == "cloudnator.com" || $host == "filereactor.com" || $host == "filejungle.com" || $host == "uploadstation.com" || $host == "fileserve.com" || $host == "wupload.com" || $host == "filesonic.com" || $host == "sharingmatrix.com" || $host == "megaupload.com" || $host == "megavideo.com" || $host == "megaporn.com" || $host == "uploadbox.com" || $host == "uploed1.com" || $host == "l1.to") {
			printf($this->lang['siteoff'],$host);
			exit;
		}
		if($host == "upstore.com1" || $host == "upstore.net1" || $host == "upstore1.com")
		{	printf($this->lang['baotri'],$host);
			exit;
		}
		if($host == "extabit.com" || $host == "extabit1.com"){
			printf($this->lang['extabit_1'],$host);
			exit;
		}
		if($host == "ryushare1.com" || $host == "oteupload1.com") {
			printf($this->lang['down_site'],$host);
			exit;
		}
		if($host == "oteupload.com" || $host == "oteupload1.com"){
			printf($this->lang['oteupload_1'],$host);
			exit;
		}
		if($host == "downloadprovider.me" || $host == "usenet.nl" || $host == "usenet.net" || $host == "firstclass-download.com"){
			printf($this->lang['notsp_site'],$host);
			exit;
		}
/*		
		if($this->acc_type['reset_bw'] == false) {
			$support_pre = @file_get_contents('http://getlink.vn/supportpre.txt');
			$list_pre = explode("\n", $support_pre);
			if(is_array($list_pre) && count($list_pre)>0) {
				foreach($list_pre as $sp_pre) {
					if(empty($sp_pre)) continue;
					if (stristr($sp_pre,$host)) {
						printf($this->lang['sitepre'],$host);
						exit;
					}
				}
			}
		}
*/
		# limit bandwidth for host
		
		if(isset($limit_host['daily_bw']) && $limit_host['daily_bw']==true) {
			$max_daily_bw = $limit_host['daily_bw']*1024*1024 + 1*1024*1024*1024; //limit over bw -1Gb
			if ($this->total_bw_day($host) >= $max_daily_bw && isset($this->jobs['get'][$hash])==false && isset($this->jobs['leech'][$hash])==false){
				if($test) echo 'bw2';
				printf($this->lang['max_bw_host'],$this->convertmb($this->total_bw_day($host)),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				return;
			}
		}


		/*6/19/2024
		elseif (isset($limit_host['daily_bw']) && $this->total_bw_day($host) >= $limit_host['daily_bw']*1024*1024){
			if(isset($this->jobs['get'][$hash])== true && $this->jobs['get'][$hash]['status'] !=1){
				if($test) echo 'bw4';
				printf($this->lang['max_bw_host'],$this->convertmb($this->total_bw_day($host)),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				return;
			}

		}
		*/

		# limit bandwidth for host

		if(!isset($_COOKIE['network'])) {
			if(isset($this->jobs['get'][$hash]['ip'])) $this->checkip($this->jobs['get'][$hash]['ip']);
			else $this->checkip($this->myip);
			$this->group[] = $this->network;
		}
		else $this->group[] = $_COOKIE['network'];
		$fields = array(
				'type' => $type,
				'host' => $host,
				'download' => $_POST['download'],
				'group' => json_encode($this->group),
		);
		if(isset($this->leech) && $this->leech == true) {
			$fields['host'] = 'dlink';
			$data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields), 15);
		}
		
		else $data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields));
		//echo '<pre>';print_r($fields);echo $data;exit;
		
		if (stristr($data,'|') && $host == "torrent" && !isset($gateto)) {
			//save gate to Maget links manager
			$data2 = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash.'&gate='.$data);

		}
		$this->datamega['user']['linkacc'] = $this->self;
		$this->datamega['user']['email'] = $this->email;
		$this->datamega['user']['mobile'] = $this->mobile;
		$this->datamega['user']['type'] = $this->acc_type['type'];
		$this->datamega['user']['created'] = $this->created;
		$this->datamega['user']['expired'] = $this->expired;
		$this->datamega['link']['url'] = $url;
		$this->datamega['link']['host'] = $host;

		if (stristr($data,'|')) {
			list($linkhost, $passhost, $server2) = explode('|', $data);
			$this->datamega['link']['gate'] = $linkhost;
			$this->datamega['link']['server2'] = $server2;
		}
		elseif (stristr($data,'not support mirror')) {
			$this->datamega['link']['error'] = 'không hỗ trợ mirror';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '1<pre>';
					print_r($this->datamega);
				}
			die("not support mirror for ".$host);
		}
		else {
			$contents = "link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>type=".json_encode($type)."&host=".$host."&download=".$_POST['download'];
			$this->mailreport("Không tìm thấy host phù hợp cho link $url !",$contents);
			$this->datamega['link']['error'] = 'không có gate hỗ trợ !';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
			if($test) {
				echo '2<pre>';
				print_r($this->datamega);
			}
			printf($this->lang['notsv'],$this->site_hash($url),$this->lang['mail_hotro']);
			return;
		}
		
		if(isset($linkhost)){
			$linklog = str_replace('index.php',"login.php",$this->self);
			foreach($this->firewall as $newfw=>$keyft){
				foreach($keyft as $valueft) $linklog = str_replace($valueft,$newfw,$linklog);
			}
			//echo $linklog;
		
			
			if(stristr($linklog, ':8081')) $linklog = str_replace('https://', 'http://',$linklog);
			$data = $this->curl($linkhost,'secureid='.md5($passhost),'urllist='.urlencode($url).'&server2='.$server2.'&log='.urlencode($linklog).'&mail='.$this->email.'&mobile='.$this->mobile.'&myip='.$this->myip, 120);
			
			if($test) echo "data gate <textarea>".$linkhost."\r\n".$passhost."\r\n".$url."\r\n".str_replace("textarea","",$data).'</textarea><BR>';
			if(stristr($data, 'hoster_unsupported')) echo 'hoster_unsupported';

			if(empty($data)==true) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '3<pre>';
					print_r($this->datamega);
				}

				$this->mailreport("Không load được $server2 !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			elseif(stristr($data,'Please enter Security ID')) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '4<pre>';
					print_r($this->datamega);
				}
				$this->mailreport("Sai mật khẩu login server !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			if(preg_match("/href='(.*?)' style='TEXT-DECORATION\: none' target='(.*?)'\> \<font color='#00CC00'\>(.*?)\<\/font\> \<font color='#FF66FF'\>\((.*?)\)\<\/font\>/i", $data, $content)){
				$mtime = time().rand(0,999);
				$URL = $content[1];
				$URL = str_replace('http://https','https',$URL);
				$URL = str_replace('http://http','http',$URL);
				$this->datamega['link']['premium'] = $URL;
				if(isset($this->leech) && $this->leech == true) {
					$dataleech['dlink'] = $URL;
					return $dataleech;

				}
				/* - 16:58:15 - Sunday, 07 August 2016 [GMT+7]
				$type1 = json_encode($type);
				$type2 = $type;
				if(stristr($type1,'syd') && stristr($type1,'mel')) {
					$input = array("syd", "mel");
					$sv_key = array_rand($input, 1);
					$sv_main = $input[$sv_key];
					foreach($type2 as $key=>$val) if($val ==$sv_main) unset($type2[$key]);
					$URL =  str_replace('://us','://'.$sv_main,$URL);
				}
				elseif(stristr($type1,'syd')) {
					foreach($type2 as $key=>$val) if($val =='syd') unset($type2[$key]);
					$URL =  str_replace('://us','://syd',$URL);
				}
				elseif(stristr($type1,'mel')) {
					foreach($type2 as $key=>$val) if($val =='mel') unset($type2[$key]);
					$URL =  str_replace('://us','://mel',$URL);
				}
				*/
				//$target = $content[2];
				$filename = $content[3];
				$filesize = $content[4];
				$this->datamega['link']['filename'] = $filename;
				$this->datamega['link']['filesize'] = $this->convert($filesize);
				if($test) {
					echo '5<pre>';
					print_r($this->datamega);
				}

				$data = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				//echo $data;
				if($_POST['download'] == "mirror" ) $dlhtml .=  "<b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font></a></b><BR>";
				else {
					//$sv_multi = array_rand($this->server, 1);
					$array_keys = array_keys($this->server);
					$sv_multi = array_shift($array_keys); //get the first key
					//$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
					//$dlhtml .= 'link-multi-server';
					//$dlhtml .="<div><b><a title='click here to download' href='".str_replace('://us','://'.$sv_multi,$URL)."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$sv_multi."' style='color:#ffff00'>(".$this->server[$sv_multi].")</span></a>";
					
					if(isset($_POST['svleech'])) {
						$svleech = $this->convert_svtab($_POST['svleech']);
						if(stristr($svleech,'.')) $newURL = str_replace(parse_url($URL, PHP_URL_HOST),$svleech, $URL);
						else $newURL = str_replace('://us','://'.$svleech,$URL);

						$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
					}
					else {
						$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
					}

					$dlhtml .=  "</b></div>";
				}
				/*
			$svie = false;
			$seng = false;
			$sub = str_replace(substr($file[1],-4),'',$file[1]);
			if($this->size($sub.'.srt') >0 ) $svie = true;
			if($this->size($sub.'_VIE.srt') >0 ) $svie = true;
			if($this->size($sub.'_ENG.srt') >0 ) $svie = true;
				*/
			}
			else {
				$dlhtml .= $data;
				if(!stristr($data,'<font color=#ffcc33 face=Arial size=2>')) $this->datamega['link']['error'] = $data;
				else $this->datamega['link']['error'] = $this->cut_str($data, "<font color=#ffcc33 face=Arial size=2>", "</font>");;
				$megadata = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '5<pre>'.$megadata;
					print_r($this->datamega);
				}
				return $dlhtml;
			}
		}
		savedata:
		$msize = $this->convert($filesize);
		//account hết băng thônng khi leech (khong chan khi tra link leech)
		if ($msize > ($this->total_acc_unless()+100*1024*1024) && isset($this->jobs['get'][$hash])==false && isset($this->leech)==false){
			if(!isset($limit_host['total']) or $limit_host['total'] == true) {
				printf($this->lang['outbw'],$this->convertmb($this->total_acc_unless()));
				if($test) echo 'bw2';
			}

		}

		# limit bandwidth for host

		//if limit daily_bw
		if(isset($limit_host['daily_bw']) && $limit_host['daily_bw']==true) {
			if($this->total_bw_day($host)+$msize >= $limit_host['daily_bw']*1024*1024+100*1024*1024 && isset($this->jobs['get'][$hash])==false) {
				printf($this->lang['max_bw_host'],$this->convertmb($this->total_bw_day($host)+$msize),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				//return;
			}
		}

		# end limit bandwidth for host


		if(isset($URL)){
			if ($hash == false) {
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return $dlhtml;
			}
			if(isset($this->jobs['get'][$hash])==false || (isset($this->jobs['get'][$hash])==true && time() > $this->jobs['get'][$hash]['mtime']+24*60*60)){
				$speed = 1;
			}
			elseif((isset($this->jobs['get'][$hash])==true && $lefttime_reget < 0)) $speed = $this->jobs['get'][$hash]['speed'] - 1;
			else $speed = $this->jobs['get'][$hash]['speed']+1;
			$job = array(
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> isset($hashphim)?$namemovies:$filename,
				'size'	=> $filesize,
				'msize'	=> $msize,
				'mtime'	=> time(),
				'speed'	=> $speed,
				'url'	=> isset($hashphim)?$hashphim:$url,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> $URL,
						'cookies'=> $this->cookie,
					),
			);
			
			$this->jobs['get'][$hash] = $job;
			$this->save_jobs();
			unset($job);
			if($_POST['download'] == 'phim') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:#339900; font-size:16px;" title="'.$this->lang['downfilm'].'">'.$filename.' <font color = "red">('.$filesize.')</font></a>';
				if(isset($this->phim[$hashphim]['count'])) $this->phim[$hashphim]['count'] = $this->phim[$hashphim]['count'] + 1;
				else $this->phim[$hashphim]['count'] = 1;
				$file = $this->pathphim;
				$fh = fopen($file, 'w') 
				or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the file "<B>'.$file.'</B>" to 666</font></CENTER>');
				if(!is_writable($file)) { chmod($file, 0666); }
				fwrite($fh, json_encode($this->phim));
				fclose($fh);
				@chmod($file, 0666);

				return $dhtml;
			}
			elseif($_POST['download']=='subviet') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.$this->lang['subviet'].'</a>';
				return $dhtml;
			}
			elseif($_POST['download']=='subeng') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.$this->lang['subeng'].'</a>';
				return $dhtml;
			}
		}
		
		return $dlhtml;
	}

	function leech($url){
		$test = false;
		$dlhtml = "";
		$url = trim($url);
		$time = time();
		if (empty($url)) return;
		if(!isset($_POST['download'])) return;
		$hash = md5($url.$this->self);
		$type = array_keys($this->server); //list server --> đã bỏ không sử dụng
		// PHP8 guard: array_rand() on empty array throws ValueError
		$sv_root = 'us';
		if (is_array($this->sv_root) && count($this->sv_root) > 0) {
			$sv_root = array_rand($this->sv_root, 1);
		}
		$type[] = $sv_root;


		//xóa link đã lưu 3 ngày và get lại
		if(isset($this->jobs['get'][$hash])==true  && time() > $this->jobs['get'][$hash]['mtime']+3*24*60*60) {
			unset($this->jobs['get'][$hash]);
		}

		if(isset($this->jobs['leech'][$hash])==true  && time() > $this->jobs['leech'][$hash]['mtime']+2*24*60*60) {
			unset($this->jobs['leech'][$hash]);
		}

		// Limit get tối đa 1 link = 4
		if(isset($this->jobs['get'][$hash])==true && $this->jobs['get'][$hash]['speed']> 4 && time() < $this->jobs['get'][$hash]['mtime']+2*60*60) {
			if($_POST['download']=="down" || $_POST['download']=="phim" ) {
				$contents = "link get: $url <BR>Type: ".json_encode($type);
				$this->mailreport("Phát hiện $url get nhiều lần !",$contents);
			}
			$dlhtml .= "<b><a href=".$url." style='TEXT-DECORATION: none'><font color=#ff6600 face=Arial size=2 id='Invalidlink'>".$url."</font></a> <img src=./../../../images/chk_error.png width='15' alt='errorlink'> <font color=#ffcc33><B>".$this->lang['maxget'];
			die($dlhtml);
		}

		if(stristr($url,'magnet:?xt=') || stristr($url,'.torrent')) {
			if(preg_match('%(http|https)\:\/\/torcache.net\/torrent\/(.*)\.torrent\?title\=(.*?)%U', $url, $matches)) {
				$hash = strtolower(trim($matches[2]));
				$name = strtolower(trim($matches[3]));
				$name = str_replace('[kat.cr]','',$name);
				$url = 'magnet:?xt=urn:btih:'.$hash.'&dn='.urlencode($name);
			}
			elseif(stristr($url,'.torrent') && stristr($url,'magnet:?xt=')==false) {
				$data = @file_get_contents($this->infomagnet.'convert.php?url='.urlencode($url));
				$info = json_decode($data, true);
				if (is_array($info)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$info = json_decode($data, true);
				}
				if(!is_array($info)) die('error 1: Sorry, there was an error uploading your file.');
				if(isset($info['error']) && $info['error'] != 'no') die($info['error']);
				$url = $info['magnet'];
				$hash = $info['hash'];
			}
			elseif (preg_match('%magnet\:\?xt\=urn\:btih\:(.*)(\&dn\=)?%U', $url,$value)) $hash = strtolower(substr($url,20,40));
			elseif (preg_match('#^magnet\:\?xt\=urn\:btih\:(.*)#', $url,$value)) $hash = trim($value[1]);
			else die("can't get this file");
			$data = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash);
			$torrent = json_decode($data, true);
			if (is_array($torrent)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$torrent = json_decode($data, true);
			}
			if(is_array($torrent) == true && isset($torrent['gate']) && isset($torrent['status'])) {
				 if(isset($torrent['link']) && stristr($torrent['link'],'http') &&  $torrent['status'] == 'ok') {
					$url = $torrent['link'];
					$host = $this->domain_name($url);
				 }
				 elseif($torrent['status'] == 'leeching') {
					$gateto = $torrent['gate'];
					$url = $torrent['magnet'];
					$host = "torrent";
				 }
				 else $host = "torrent";
			}
			else $host = "torrent";

		}
		else {
			$msize = $this->size($url);
			if($msize > 10*1024) {
				$host = 'dlink';
				$filesize = $this->convertmb($msize);
			}
			else {
				$host = $this->domain_name($url);
				if($host == "oron.com" || $host == "rapidshare.com" || $host == "uploading.com" || $host == "letitbit.net" || $host == "vip-file.com" || $host == "shareflare.net" || $host == "ryushare.com" || $host == "filehaste.com" || $host == "hotfile.com" || $host == "filestay.com" || $host == "filemates.com" || $host == "shragle.com" || $host == "filehost.ws" || $host == "filerose.com" || $host == "cloudnator.com" || $host == "filereactor.com" || $host == "filejungle.com" || $host == "uploadstation.com" || $host == "fileserve.com" || $host == "wupload.com" || $host == "filesonic.com" || $host == "sharingmatrix.com" || $host == "megaupload.com" || $host == "megavideo.com" || $host == "megaporn.com" || $host == "uploadbox.com" || $host == "uploed1.com" || $host == "l1.to") {
					printf($this->lang['siteoff'],$host);
					exit;
				}
				if($host == "upstore.com1" || $host == "upstore.net1" || $host == "upstore1.com")
				{	printf($this->lang['baotri'],$host);
					exit;
				}
				if($host == "extabit.com" || $host == "extabit1.com"){
					printf($this->lang['extabit_1'],$host);
					exit;
				}
				if($host == "ryushare1.com" || $host == "oteupload1.com") {
					printf($this->lang['down_site'],$host);
					exit;
				}
				if($host == "oteupload.com" || $host == "oteupload1.com"){
					printf($this->lang['oteupload_1'],$host);
					exit;
				}
				if($host == "downloadprovider.me" || $host == "usenet.nl" || $host == "usenet.net" || $host == "firstclass-download.com"){
					printf($this->lang['notsp_site'],$host);
					exit;
				}

				$msize = 0;
				$filesize = '0 MB';
				$filename = substr(strrchr($url, '/'), 1);
				$data = $this->curl($this->checklink.urlencode($url),"","");
				if($test) echo 'checklink1 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
				$check = @json_decode($data, true);
				if (is_array($check)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$check = json_decode($data, true);
				}
				if($check['status'] == 0 ){
					$filesize = $check['filesize'];
					$msize = $this->convert($filesize);
					$filename = $check['filename'];
					$urlid = $check['url'];
					//echo $urlid;
				}
				else $urlid = $url;
			}
		}


		if (isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
		else  $limit_host = $this->hosts['other'];
		//tổng băng thông cho nhóm host riêng  = limit1 +limit2
		if(isset($this->hosts2[$host]['bandwidth'])) $totalbw_host = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
		else  $totalbw_host = ($limit_host['bandwidth'])*1024*1024;
		//set max_daily_bw
		if(isset($limit_host['daily_bw']) && isset($limit_host['overlimit_bw'])) $max_daily_bw = $limit_host['overlimit_bw']*1024*1024;
		elseif(isset($limit_host['daily_bw'])) $max_daily_bw = $limit_host['daily_bw']*1024*1024;
		else $max_daily_bw = 0;
		if(isset($limit_host['daily_bw'])) $daily_bw = $limit_host['daily_bw']*1024*1024;
		else $daily_bw = 0;

		//limit for reget
		$lefttime_reget = 0;
		if(isset($this->jobs['get'][$hash]['mtime'])) $lefttime_reget = $this->jobs['get'][$hash]['mtime'] + 60*60 - time();
		if(isset($this->jobs['get'][$hash])==true && $lefttime_reget>0 && $this->jobs['get'][$hash]['speed']>2){
			echo '<center><b><i><font color=red>'.sprintf($this->lang['limit_reget'], $this->jobs['get'][$hash]['speed'], $this->convert_time($lefttime_reget)).'</font></i></b></center>';
			return;
		}
		//limit for reget

		//chặn các link releech mà status !== 1
		if($this->total_bw_day($host) > $max_daily_bw && isset($this->jobs['leech'][$hash])==false) {
			printf($this->lang['max_bw_host_leech'],$this->convertmb($this->total_bw_day($host)),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
			return;
		}

		//check limit account bw
		if($this->total_acc_unless() <= 0 && isset($this->jobs['leech'][$hash])==false) {
			printf($this->lang['outbw_leech'],$this->convertmb($this->total_acc_unless()));
		}

		//check limit jobs
		if (isset($limit_host['max_link']) == true && $this->Checkjobs($host) >= $limit_host['max_link']){
			echo '<center><b><i><font color=red>'.sprintf($this->lang['limit_host'],$host, $limit_host['max_link']).'</font></i></b></center>';
			return;
		}

		//GET ISP
		$data = $this->curl($this->checkisp.$this->myip,"","");
		$this->isp_data = $data;

		//thay đổi link manager theo hosting - 2023/05/29 -23:04 (GMT+7)
		if(isset($this->leechrieng) && $this->leechrieng == true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
		elseif(isset($this->leechrieng_on) && in_array($host, $this->leechrieng_on)==true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
		else if(isset($this->mng_normal[$host])) $this->leechmng = $this->mng_normal[$host];

		//limit hết băng thông account status=5
		if ($this->total_acc_unless() <= 0 or $this->total_acc_unless() < $msize){
			if(isset($this->jobs['leech'][$hash]['status']) AND $this->jobs['leech'][$hash]['status'] <3) goto releech;
			if($test) echo 'bw1<BR>';
			$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
			$post['user'] = $linklogin;
			$post['email'] = $this->email;
			$post['mobile'] = $this->mobile;
			$post['acc_type'] = $this->acc_type['fullname'];
			$post['url'] = $urlid;
			$post['status'] = 5;
			$post['md5'] = $hash;
			$post['filesize'] = $msize;
			$post['filename'] = $filename;
			$post['host'] = $host;
			$post['ip'] = $this->myip;
			$post['isp'] = $this->isp_data;
			$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
			if($test) echo 'leechmng status5 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
			$json = @json_decode($data, true);
			if (is_array($json)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$json = json_decode($data, true);
			}
			if($json['status'] == '1') {
				if($test) echo 'goto leechlink<BR>';
				goto leechlink;
			}
			if($json['status'] == '2' && isset($this->jobs['leech'][$hash])==true) {
				$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['dangleech']."</b></div>";
				return $dlhtml;

			}

			$job = array(
				'status'	=> 5,
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> $filename,
				'size'	=> '0 MB',
				'msize'	=> 0,
				'bwtam'	=> 0,
				'mtime'	=> $time,
				'speed'	=> 1,
				'url'	=> $url,
				'host'	=> $host,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'network'	=> $_COOKIE['network'],
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> '',
						'cookies'=> '',
					),
			);

			$this->jobs['leech'][$hash] = $job;
			$this->save_jobs();
			printf($this->lang['outbw_leech'],$this->convertmb($this->total_acc_unless()));
			return;
		}

/*	
		if($this->acc_type['reset_bw'] == false) {
			$support_pre = @file_get_contents('http://getlink.vn/supportpre.txt');
			$list_pre = explode("\n", $support_pre);
			if(is_array($list_pre) && count($list_pre)>0) {
				foreach($list_pre as $sp_pre) {
					if(empty($sp_pre)) continue;
					if (stristr($sp_pre,$host)) {
						printf($this->lang['sitepre'],$host);
						exit;
					}
				}
			}
		}
*/

		# limit hết băng thông host status=6
		if (($this->total_bw_day($host)<$daily_bw && $this->total_bw_day($host)+$msize >= $max_daily_bw) OR $this->total_bw_day($host)>$daily_bw){
			if(isset($this->jobs['leech'][$hash]['status']) AND $this->jobs['leech'][$hash]['status'] <3) goto releech;
			if($test) echo 'bw2';
			if($_POST['download']=='leech') {
				if($test) echo 'bw3';
				$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
				$post['user'] = $linklogin;
				$post['email'] = $this->email;
				$post['mobile'] = $this->mobile;
				$post['acc_type'] = $this->acc_type['fullname'];
				$post['url'] = $urlid;
				$post['status'] = 6;
				$post['md5'] = $hash;
				$post['filesize'] = $msize;
				$post['filename'] = $filename;
				$post['host'] = $host;
				$post['ip'] = $this->myip;
				$post['isp'] = $this->isp_data;
				$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
				if($test) echo 'leechmng status6 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
				$json = @json_decode($data, true);
				if (is_array($json)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$json = json_decode($data, true);
				}
				if(!isset($json['status'])) die('error json data');
				if($json['status'] == '1') {
					if($test) echo 'goto leechlink<BR>';
					goto leechlink;
				}
				if($json['status'] == '2' && isset($this->jobs['leech'][$hash])==true) {
					if($test) echo 'dangleech1<BR>';
					$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['dangleech']."</b></div>";
					return $dlhtml;

				}
				elseif($json['status'] == '3' && isset($this->jobs['leech'][$hash])==true) {
					if($test) echo 'linkerror1<BR>';
					$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['linkerror']."</b></div>";
					return $dlhtml;

				}
				elseif($json['status'] == '4' && isset($this->jobs['leech'][$hash])==true) {
					if($test) echo 'linkdead1<BR>';
					$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='red'>".$url."</font> ".$this->lang['linkdead']."</b></div>";
					return $dlhtml;
				}
				$job = array(
					'status'	=> 6,
					'hash'	=> substr(md5($hash), 0, 10),
					'path'	=> substr(md5(rand()), 0, 5),
					'filename'	=> $filename,
					'size'	=> $filesize,
					'msize'	=> $msize,
					'bwtam'	=> 0,
					'mtime'	=> $time,
					'speed'	=> 1,
					'url'	=> $url,
					'host'	=> $host,
					'owner'	=> $this->owner,
					'ip'	=> $this->myip,
					'network'	=> $_COOKIE['network'],
					'type'	=> 'direct',
					'directlink'	=> array(
						'url'	=> '',
							'cookies'=> '',
						),
				);

				$this->jobs['leech'][$hash] = $job;
				$this->save_jobs();
			}
			printf($this->lang['max_bw_host_leech'],$this->convertmb($this->total_bw_day($host)),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
			return;
		}
		# limit hết băng thông host status=6
		releech:
		# 2021/09/12 - leech link
		if(isset($this->jobs['leech'][$hash]['mtime'])) $lefttime = time() - $this->jobs['leech'][$hash]['mtime'];
		else $lefttime = 0;
		$releech = false;
		//nếu đã leech thành công mà leech lại thì coi như file mới
		//if(!isset($this->jobs['leech'][$hash]['releech']) && isset($this->jobs['leech'][$hash]) && $this->jobs['leech'][$hash]['status'] == 1) {
		if(isset($this->jobs['leech'][$hash])) {
			$releech = true;
			if(!isset($this->jobs['leech'][$hash]['releech'])) {
				$this->jobs['leech'][$hash]['releech'] = 1;
				$this->jobs['leech'][$hash]['showfile'] = false;
			}
			else {
				$this->jobs['leech'][$hash.$this->jobs['leech'][$hash]['releech']]['showfile'] = false;
				$this->jobs['leech'][$hash]['releech'] = $this->jobs['leech'][$hash]['releech'] + 1;

			}
			$this->save_jobs();
			$newhash = $hash.$this->jobs['leech'][$hash]['releech'];
			$hash = $newhash;
		}
		/*
		//nếu đã releech thành công mà leech lại thì lấy lại data releech để trả
		elseif(isset($this->jobs['leech'][$hash]['releech']) && $this->jobs['leech'][$this->jobs['leech'][$hash]['releech']]['status'] == 1 && stristr($this->jobs['leech'][$this->jobs['leech'][$hash]['releech']]['directlink']['url'],'http') && $lefttime  < 3*24*60*60) {
			$job = $this->jobs['leech'][$rehash];
			$URL = $job['directlink']['url'];
			$filename = urldecode($job['filename']);
			$filesize = $job['size'];
			$mtime = $job['mtime'];
			if( $this->size($URL)>0 ) {
				$array_keys = array_keys($this->server);
				$sv_multi = array_shift($array_keys); //get the first key
				$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
				$dlhtml .= 'link-multi-server';
				$dlhtml .="<div><b><a title='click here to download' href='".str_replace('://us','://'.$sv_multi,$URL)."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$sv_multi."' style='color:#ffff00'>(".$this->server[$sv_multi].")</span></a>";
				$dlhtml .=  "</b></div>";
				return $dlhtml;
			}
		}
		*/


		$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
		$post['user'] = $linklogin;
		$post['email'] = $this->email;
		$post['mobile'] = $this->mobile;
		$post['acc_type'] = $this->acc_type['fullname'];
		$post['url'] = $url;
		$post['md5'] = $hash;
		$post['host'] = $host;
		$post['ip'] = $this->myip;
		$post['isp'] = $this->isp_data;


		$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
		if($test) echo $this->leechmng;
		if($test) echo 'leechmng status <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
		$json = json_decode($data, true);
		if (is_array($json)==false) {
			$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
			$json = json_decode($data, true);
		}
		if($json['status'] == '1') {
			leechlink:
			if(!isset($this->jobs['leech'][$hash]['directlink']['url']) OR !stristr($this->jobs['leech'][$hash]['directlink']['url'],'http')) {
				$filesize = $this->convertmb($json['filesize']);
				$this->leech = true;
				$_POST['download'] = 'down';
				$newlink = $this->get($json['directlink']);
				if(isset($newlink['dlink']) && stristr($newlink['dlink'],'http')==true) $directlink = $newlink['dlink'];
				else $directlink  = '';
				if($test) echo $directlink;
				$job = array(
					'status'	=> 1,
					'hash'	=> substr(md5($hash), 0, 10),
					'path'	=> substr(md5(rand()), 0, 5),
					'filename'	=> $json['filename'],
					'size'	=> $filesize,
					'msize'	=> $json['filesize'],
					'bwtam'	=> $json['filesize'],
					'mtime'	=> $time,
					'speed'	=> 1,
					'host'	=> $host,
					'url'	=> $url,
					'owner'	=> $this->owner,
					'ip'	=> $this->myip,
					'type'	=> 'direct',
					'directlink'	=> array(
						'url'	=> $directlink,
							'cookies'=> '',
						),
				);
				
				$this->jobs['leech'][$hash] = $job;
				//if($releech) $this->jobs['leech'][$hash]['releech'] = $hash;
				unset($job);
				$this->save_jobs();
			}
			if(!isset($newlink['dlink'])) {
				$job = $this->jobs['leech'][$hash];
				$URL = $job['directlink']['url'];
				$filename = urldecode($job['filename']);
				$filesize = $job['size'];
				$mtime = $job['mtime'];
	
				$array_keys = array_keys($this->server);
				$sv_multi = array_shift($array_keys); //get the first key

				if(isset($_POST['svleech'])) {
					$svleech = $this->convert_svtab($_POST['svleech']);
					if(stristr($svleech,'.')) $newURL = str_replace(parse_url($URL, PHP_URL_HOST),$svleech, $URL);
					else $newURL = str_replace('://us','://'.$svleech,$URL);

					$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
				}
				else {
					$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
				}

				$dlhtml .=  "</b></div>";
				
				return $dlhtml;
			}
			else {
				$array_keys = array_keys($this->server);
				$sv_multi = array_shift($array_keys); //get the first key

				if(isset($_POST['svleech'])) {
					$svleech = $this->convert_svtab($_POST['svleech']);
					if(stristr($svleech,'.')) $newURL = str_replace(parse_url($directlink, PHP_URL_HOST),$svleech, $directlink);
					else $newURL = str_replace('://us','://'.$svleech,$directlink);

					$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
				}
				else {
					$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$directlink' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
				}

				$dlhtml .=  "</b></div>";
			}
			
			return $dlhtml;
		}
		elseif($this->total_acc_unless() <= 0 && ($json['status'] == '5' or $json['status'] == '6')) {
			if ($json['status'] == '5'){
				if($_POST['download']=='leech') printf($this->lang['outbw_leech'],$this->convertmb($this->total_acc_unless()));
				else  printf($this->lang['outbw'],$this->convertmb($this->total_acc_unless()));
				return;
			}
			if (isset($limit_host['daily_bw']) && $limit_host['daily_bw'] == true && $this->total_bw_day($host) >= $limit_host['daily_bw']*1024*1024){
				printf($this->lang['max_bw_host_leech'],$this->convertmb($this->total_bw_day($host)),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				return;
			}

		}
		/*
		elseif($json['status'] == '2') {
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['dangleech']."</b></div>";
			return $dlhtml;

		}
		elseif($json['status'] == '3') {
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['linkerror']."</b></div>";
			return $dlhtml;

		}
		elseif($json['status'] == '4') {
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='red'>".$url."</font> ".$this->lang['linkdead']."</b></div>";
			return $dlhtml;
		}
		*/
		//status = 2, 3, 4
		else { 
		//if($json['status'] == '0') {
			//status = 0: đang leech; 1: thành công; 2: lỗi
			if(isset($torrent['size']) && isset($torrent['name']) && empty($torrent['name']) == false && $torrent['size']>0) {
					$filesize = $torrent['size'];
					$msize = $this->convert($filesize);
					$filename = $torrent['name'];

			}
			else {
				/*
				link báo lỗi sẽ check khi download
				elseif($check['status'] == 1){
					printf($this->lang['deadlink'],$url);
					return;
				}
				elseif($check['status'] == 3){
					printf($this->lang['link_error'],$url, $check["report"]);
					return;
				}
				*/
			}
			$job = array(
				'status'	=> 0,
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> $filename,
				'size'	=> $filesize,
				'msize'	=> $msize,
				'bwtam'	=> $msize,
				'mtime'	=> $time,
				'speed'	=> 1,
				'url'	=> $url,
				'host'	=> $host,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'network'	=> $_COOKIE['network'],
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> '',
						'cookies'=> '',
					),
			);
			if(isset($this->jobs['leech'][$hash]) && $test==true) print_r($this->jobs['leech'][$hash]);
/*
			if(isset($this->jobs['leech'][$hash]) && $this->jobs['leech'][$hash]['status'] == 1 && stristr($job['directlink']['url'],'http') && $lefttime  < 3*24*60*60) {
				if( $this->size($job['directlink']['url'])>0 ) {
					$dlhtml =  "<div class='download_main'><b><a title='click here to download' href='".$this->jobs['leech'][$hash]['directlink']."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$this->jobs['leech'][$hash]['filename']."</font> <font color='#FF66FF'>(".$this->jobs['leech'][$hash]['size'].")</font></a></b></div>";
				}
			}
			else {
*/
			if($test) echo 'nhaplink1<BR>';
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['nhaplink']."</b></div>";
			
			$post = array();
			$post['md5'] = $hash;
			$post['msize'] = $msize;
			$post['filename'] = $filename;
			$post['url'] = $urlid;
			$post['host'] = $host;
			$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
			if($test) echo 'leechmng 1 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
			# limit bandwidth for host
			//if limit daily_bw
			if($this->total_bw_day($host)+$msize > $max_daily_bw && $releech==false && isset($this->jobs['get'][$hash])==false) {
				$dlhtml = sprintf($this->lang['max_bw_host_leech'],$this->convertmb($this->total_bw_day($host)+$msize),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				$job['status'] = 6;
			}

			# end limit bandwidth for host

			$this->jobs['leech'][$hash] = $job;
			//if($releech) $this->jobs['leech'][$hash]['releech'] = $hash;
			$this->save_jobs();
			if($test) echo 'saved!<BR>';
			unset($job);

			$dlhtml .=  "</b></div>";
			
			return $dlhtml;
		}
		# 2021/09/12

	

		if(!isset($_COOKIE['network'])) {
			if(isset($this->jobs['leech'][$hash]['ip'])) $this->checkip($this->jobs['leech'][$hash]['ip']);
			$this->group[] = $this->network;
		}
		else $this->group[] = $_COOKIE['network'];
		$fields = array(
				'type' => $type,
				'host' => $host,
				'download' => $_POST['download'],
				'group' => json_encode($this->group),
		);
		if(isset($this->leech) && $this->leech == true) {
			$fields['host'] = 'dlink';
			$data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields), 15);
		}
		
		else $data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields));
		//echo '<pre>';print_r($fields);echo $data;exit;
		
		if (stristr($data,'|') && $host == "torrent" && !isset($gateto)) {
			//save gate to Maget links manager
			$data2 = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash.'&gate='.$data);

		}
		$this->datamega['user']['linkacc'] = $this->self;
		$this->datamega['user']['email'] = $this->email;
		$this->datamega['user']['mobile'] = $this->mobile;
		$this->datamega['user']['type'] = $this->acc_type['type'];
		$this->datamega['user']['created'] = $this->created;
		$this->datamega['user']['expired'] = $this->expired;
		$this->datamega['link']['url'] = $url;
		$this->datamega['link']['host'] = $host;

		if (stristr($data,'|')) {
			list($linkhost, $passhost, $server2) = explode('|', $data);
			$this->datamega['link']['gate'] = $linkhost;
			$this->datamega['link']['server2'] = $server2;
		}
		elseif (stristr($data,'not support mirror')) {
			$this->datamega['link']['error'] = 'không hỗ trợ mirror';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '1<pre>';
					print_r($this->datamega);
				}
			die("not support mirror for ".$host);
		}
		else {
			$contents = "link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>type=".json_encode($type)."&host=".$host."&download=".$_POST['download'];
			$this->mailreport("Không tìm thấy host phù hợp cho link $url !",$contents);
			$this->datamega['link']['error'] = 'không có gate hỗ trợ !';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
			if($test) {
				echo '2<pre>';
				print_r($this->datamega);
			}
			printf($this->lang['notsv'],$this->site_hash($url),$this->lang['mail_hotro']);
			return;
		}
		
		if(isset($linkhost)){
			$linklog = str_replace('index.php',"login.php",$this->self);
			foreach($this->firewall as $newfw=>$keyft){
				foreach($keyft as $valueft) $linklog = str_replace($valueft,$newfw,$linklog);
			}
			//echo $linklog;
		
			
			if(stristr($linklog, ':8081')) $linklog = str_replace('https://', 'http://',$linklog);
			$data = $this->curl($linkhost,'secureid='.md5($passhost),'urllist='.urlencode($url).'&server2='.$server2.'&log='.urlencode($linklog).'&mail='.$this->email.'&mobile='.$this->mobile.'&myip='.$this->myip, 120);
			
			if($test) echo "data gate <textarea>".$linkhost."\r\n".$passhost."\r\n".$url."\r\n".str_replace("textarea","",$data).'</textarea><BR>';
			if(stristr($data, 'hoster_unsupported')) echo 'hoster_unsupported';

			if(empty($data)==true) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '3<pre>';
					print_r($this->datamega);
				}

				$this->mailreport("Không load được $server2 !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			elseif(stristr($data,'Please enter Security ID')) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '4<pre>';
					print_r($this->datamega);
				}
				$this->mailreport("Sai mật khẩu login server !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			if(preg_match("/href='(.*?)' style='TEXT-DECORATION\: none' target='(.*?)'\> \<font color='#00CC00'\>(.*?)\<\/font\> \<font color='#FF66FF'\>\((.*?)\)\<\/font\>/i", $data, $content)){
				$mtime = time().rand(0,999);
				$URL = $content[1];
				$URL = str_replace('http://https','https',$URL);
				$URL = str_replace('http://http','http',$URL);
				$this->datamega['link']['premium'] = $URL;
				if(isset($this->leech) && $this->leech == true) {
					$dataleech['dlink'] = $URL;
					return $dataleech;

				}
				/* - 16:58:15 - Sunday, 07 August 2016 [GMT+7]
				$type1 = json_encode($type);
				$type2 = $type;
				if(stristr($type1,'syd') && stristr($type1,'mel')) {
					$input = array("syd", "mel");
					$sv_key = array_rand($input, 1);
					$sv_main = $input[$sv_key];
					foreach($type2 as $key=>$val) if($val ==$sv_main) unset($type2[$key]);
					$URL =  str_replace('://us','://'.$sv_main,$URL);
				}
				elseif(stristr($type1,'syd')) {
					foreach($type2 as $key=>$val) if($val =='syd') unset($type2[$key]);
					$URL =  str_replace('://us','://syd',$URL);
				}
				elseif(stristr($type1,'mel')) {
					foreach($type2 as $key=>$val) if($val =='mel') unset($type2[$key]);
					$URL =  str_replace('://us','://mel',$URL);
				}
				*/
				//$target = $content[2];
				$filename = $content[3];
				$filesize = $content[4];
				$this->datamega['link']['filename'] = $filename;
				$this->datamega['link']['filesize'] = $this->convert($filesize);
				if($test) {
					echo '5<pre>';
					print_r($this->datamega);
				}

				$data = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				//echo $data;
				if($_POST['download'] == "mirror" ) $dlhtml .=  "<b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font></a></b><BR>";
				else {
					if(isset($_POST['svleech'])) {

						if(stristr($svleech,'.')) $newURL = str_replace(parse_url($URL, PHP_URL_HOST),$svleech, $URL);
						else $newURL = str_replace('://us','://'.$svleech,$URL);

						$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
					}
					else {
						$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
					}

					$dlhtml .=  "</b></div>";
				}
				/*
			$svie = false;
			$seng = false;
			$sub = str_replace(substr($file[1],-4),'',$file[1]);
			if($this->size($sub.'.srt') >0 ) $svie = true;
			if($this->size($sub.'_VIE.srt') >0 ) $svie = true;
			if($this->size($sub.'_ENG.srt') >0 ) $svie = true;
				*/
			}
			else {
				$dlhtml .= $data;
				if(!stristr($data,'<font color=#ffcc33 face=Arial size=2>')) $this->datamega['link']['error'] = $data;
				else $this->datamega['link']['error'] = $this->cut_str($data, "<font color=#ffcc33 face=Arial size=2>", "</font>");;
				$megadata = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '5<pre>'.$megadata;
					print_r($this->datamega);
				}
				return $dlhtml;
			}
		}
		savedata:
		$msize = $this->convert($filesize);
		//account hết băng thônng khi leech
		if ($msize > ($this->total_acc_unless()+100*1024*1024) && isset($this->jobs['get'][$hash])==false){
			if(!isset($limit_host['total']) or $limit_host['total'] == true) {
				if($_POST['download']=='leech') printf($this->lang['outbw_leech'],$this->convertmb($this->total_acc_unless()));
				else printf($this->lang['outbw'],$this->convertmb($this->total_acc_unless()));
				if($test) echo 'bw2';
				if($_POST['download']=='leech') {
					$data = $this->curl($this->checkisp.$this->myip,"","");
					$this->isp_data = $data;

					$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
					$post['user'] = $linklogin;
					$post['email'] = $this->email;
					$post['mobile'] = $this->mobile;
					$post['acc_type'] = $this->acc_type['fullname'];
					$post['url'] = $url;
					$post['status'] = 5;
					$post['md5'] = $hash;
					$post['host'] = $host;
					$post['ip'] = $this->myip;
					$post['isp'] = $this->isp_data;
					$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
					$json = @json_decode($data, true);
					if (is_array($json)==false) {
						$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
						$json = json_decode($data, true);
					}
					if($json['status'] != '1') {
						$job = array(
							'status'	=> 5,
							'hash'	=> substr(md5($hash), 0, 10),
							'path'	=> substr(md5(rand()), 0, 5),
							'filename'	=> '',
							'size'	=> '0 MB',
							'msize'	=> 0,
							'bwtam'	=> 0,
							'mtime'	=> $time,
							'speed'	=> 1,
							'url'	=> $url,
							'host'	=> $host,
							'owner'	=> $this->owner,
							'ip'	=> $this->myip,
							'network'	=> $_COOKIE['network'],
							'type'	=> 'direct',
							'directlink'	=> array(
								'url'	=> '',
									'cookies'=> '',
								),
						);

						$this->jobs['leech'][$hash] = $job;
						$this->save_jobs();
						return;
					}
				}
			}

		}

		# limit bandwidth for host

		//if limit daily_bw
		if(isset($limit_host['daily_bw']) && $limit_host['daily_bw']==true) {
			if($this->total_bw_day($host)+$msize > $max_daily_bw && isset($this->jobs['get'][$hash])==false) {
				printf($this->lang['max_bw_host'],$this->convertmb($this->bw[$host]['day']),$this->convertmb($limit_host['daily_bw']*1024*1024),$host);
				return;
			}
		}

		# end limit bandwidth for host


		if(isset($URL)){
			if ($hash == false) {
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return $dlhtml;
			}
			if(isset($this->jobs['get'][$hash])==false || (isset($this->jobs['get'][$hash])==true && time() > $this->jobs['get'][$hash]['mtime']+24*60*60)){
				$speed = 1;
			}
			elseif((isset($this->jobs['get'][$hash])==true && $lefttime_reget < 0)) $speed = $this->jobs['get'][$hash]['speed'] - 1;
			else $speed = $this->jobs['get'][$hash]['speed']+1;
			$job = array(
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> isset($hashphim)?$namemovies:$filename,
				'size'	=> $filesize,
				'msize'	=> $msize,
				'mtime'	=> time(),
				'speed'	=> $speed,
				'url'	=> isset($hashphim)?$hashphim:$url,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> $URL,
						'cookies'=> $this->cookie,
					),
			);
			
			$this->jobs['get'][$hash] = $job;
			$this->save_jobs();
			unset($job);
			if($_POST['download'] == 'phim') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:#339900; font-size:16px;" title="'.$this->lang['downfilm'].'">'.$filename.' <font color = "red">('.$filesize.')</font></a>';
				if(isset($this->phim[$hashphim]['count'])) $this->phim[$hashphim]['count'] = $this->phim[$hashphim]['count'] + 1;
				else $this->phim[$hashphim]['count'] = 1;
				$file = $this->pathphim;
				$fh = fopen($file, 'w') 
				or die('<CENTER><font color=red size=3>Could not open file ! Try to chmod the file "<B>'.$file.'</B>" to 666</font></CENTER>');
				if(!is_writable($file)) { chmod($file, 0666); }
				fwrite($fh, json_encode($this->phim));
				fclose($fh);
				@chmod($file, 0666);

				return $dhtml;
			}
			elseif($_POST['download']=='subviet') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.$this->lang['subviet'].'</a>';
				return $dhtml;
			}
			elseif($_POST['download']=='subeng') {
				$dhtml = '<a href="'.$URL.'" style="font-weight: bold;color:blue; font-size:14px;" title="'.$this->lang['downsub'].'">'.$this->lang['subeng'].'</a>';
				return $dhtml;
			}
		}
		
		return $dlhtml;
	}


	function leecherror($url){
		$test = false;
		$dlhtml = "";
		$url = trim($url);
		$time = time();
		if (empty($url)) return;
		if(!isset($_POST['download'])) return;
		$hash = md5($url.$this->self.'error');
		$type = array_keys($this->server); //list server --> đã bỏ không sử dụng
		// PHP8 guard: array_rand() on empty array throws ValueError
		$sv_root = 'us';
		if (is_array($this->sv_root) && count($this->sv_root) > 0) {
			$sv_root = array_rand($this->sv_root, 1);
		}
		$type[] = $sv_root;
		$this->leechmng = $this->mng_error;

		if(stristr($url,'magnet:?xt=') || stristr($url,'.torrent')) {
			if(preg_match('%(http|https)\:\/\/torcache.net\/torrent\/(.*)\.torrent\?title\=(.*?)%U', $url, $matches)) {
				$hash = strtolower(trim($matches[2]));
				$name = strtolower(trim($matches[3]));
				$name = str_replace('[kat.cr]','',$name);
				$url = 'magnet:?xt=urn:btih:'.$hash.'&dn='.urlencode($name);
			}
			elseif(stristr($url,'.torrent') && stristr($url,'magnet:?xt=')==false) {
				$data = @file_get_contents($this->infomagnet.'convert.php?url='.urlencode($url));
				$info = @json_decode($data, true);
				if (is_array($info)==false) {
					$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
					$info = json_decode($data, true);
				}
				if(!is_array($info)) die('error 1: Sorry, there was an error uploading your file.');
				if(isset($info['error']) && $info['error'] != 'no') die($info['error']);
				$url = $info['magnet'];
				$hash = $info['hash'];
			}
			elseif (preg_match('%magnet\:\?xt\=urn\:btih\:(.*)(\&dn\=)?%U', $url,$value)) $hash = strtolower(substr($url,20,40));
			elseif (preg_match('#^magnet\:\?xt\=urn\:btih\:(.*)#', $url,$value)) $hash = trim($value[1]);
			else die("can't get this file");
			$data = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash);
			$torrent = @json_decode($data, true);
			if (is_array($torrent)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$torrent = json_decode($data, true);
			}

			if(is_array($torrent) == true && isset($torrent['gate']) && isset($torrent['status'])) {
				 if(isset($torrent['link']) && stristr($torrent['link'],'http') &&  $torrent['status'] == 'ok') {
					$url = $torrent['link'];
					$host = $this->domain_name($url);
				 }
				 elseif($torrent['status'] == 'leeching') {
					$gateto = $torrent['gate'];
					$url = $torrent['magnet'];
					$host = "torrent";
				 }
				 else $host = "torrent";
			}
			else $host = "torrent";

		}
		else {
			$filesize = $this->size($url);
			if($filesize > 10*1024) $host = 'dlink';
			else $host = $this->domain_name($url);
		}

		if($host == "oron.com" || $host == "rapidshare.com" || $host == "uploading.com" || $host == "letitbit.net" || $host == "vip-file.com" || $host == "shareflare.net" || $host == "ryushare.com" || $host == "filehaste.com" || $host == "hotfile.com" || $host == "filestay.com" || $host == "filemates.com" || $host == "shragle.com" || $host == "filehost.ws" || $host == "filerose.com" || $host == "cloudnator.com" || $host == "filereactor.com" || $host == "filejungle.com" || $host == "uploadstation.com" || $host == "fileserve.com" || $host == "wupload.com" || $host == "filesonic.com" || $host == "sharingmatrix.com" || $host == "megaupload.com" || $host == "megavideo.com" || $host == "megaporn.com" || $host == "uploadbox.com" || $host == "uploed1.com" || $host == "l1.to") {
			printf($this->lang['siteoff'],$host);
			exit;
		}
		if($host == "upstore.com1" || $host == "upstore.net1" || $host == "upstore1.com")
		{	printf($this->lang['baotri'],$host);
			exit;
		}
		if($host == "extabit.com" || $host == "extabit1.com"){
			printf($this->lang['extabit_1'],$host);
			exit;
		}
		if($host == "ryushare1.com" || $host == "oteupload1.com") {
			printf($this->lang['down_site'],$host);
			exit;
		}
		if($host == "oteupload.com" || $host == "oteupload1.com"){
			printf($this->lang['oteupload_1'],$host);
			exit;
		}
		if($host == "downloadprovider.me" || $host == "usenet.nl" || $host == "usenet.net" || $host == "firstclass-download.com"){
			printf($this->lang['notsp_site'],$host);
			exit;
		}
		$max_link_error_leech = $this->max_link_error_leech['otherhost'];
		if(isset($this->max_link_error_leech[$host])) $max_link_error_leech = $this->max_link_error_leech[$host];
		if($this->Checkjobs($host, 'error') >= $max_link_error_leech){
			printf($this->lang['manyjob'],$this->Checkjobs($host, 'error'),$max_link_error_leech);
			exit;
		}

/*
		if($this->acc_type['reset_bw'] == false) {
			$support_pre = @file_get_contents('http://getlink.vn/supportpre.txt');
			$list_pre = explode("\n", $support_pre);
			if(is_array($list_pre) && count($list_pre)>0) {
				foreach($list_pre as $sp_pre) {
					if(empty($sp_pre)) continue;
					if (stristr($sp_pre,$host)) {
						printf($this->lang['sitepre'],$host);
						exit;
					}
				}
			}
		}
*/
		# 2021/09/12 - leech link
		if(isset($this->jobs['leech'][$hash]['mtime'])) $lefttime = time() - $this->jobs['leech'][$hash]['mtime'];
		else $lefttime = 0;
		
		$data = $this->curl($this->checkisp.$this->myip,"","");
		$this->isp_data = $data;

		$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
		$post['user'] = $linklogin;
		$post['email'] = $this->email;
		$post['mobile'] = $this->mobile;
		$post['acc_type'] = $this->acc_type['fullname'];
		$post['url'] = $url;
		$post['md5'] = $hash;
		$post['host'] = $host;
		$post['ip'] = $this->myip;
		$post['isp'] = $this->isp_data;


		$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
		if($test) echo $this->leechmng;
		if($test) echo 'leechmng status <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
		$json = @json_decode($data, true);
		if (is_array($json)==false) {
			$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
			$json = json_decode($data, true);
		}
		if($json['status'] == '1') {
			leechlink:
			$filesize = $this->convertmb($json['filesize']);
			$this->leech = true;
			$_POST['download'] = 'down';
			$newlink = $this->get($json['directlink']);
			if(isset($newlink['dlink']) && stristr($newlink['dlink'],'http')==true) {
				
				$directlink = $newlink['dlink'];
				if($test) echo $directlink;
				$job = array(
					'status'	=> 1,
					'hash'	=> substr(md5($hash), 0, 10),
					'path'	=> substr(md5(rand()), 0, 5),
					'filename'	=> $json['filename'],
					'size'	=> $filesize,
					'msize'	=> $json['filesize'],
					'bwtam'	=> $json['filesize'],
					'mtime'	=> $time,
					'speed'	=> 1,
					'leecherror' => 1,
					'host'	=> $host,
					'url'	=> $url,
					'owner'	=> $this->owner,
					'ip'	=> $this->myip,
					'type'	=> 'direct',
					'directlink'	=> array(
						'url'	=> $directlink,
							'cookies'=> '',
						),
				);
				
				$this->jobs['leech'][$hash] = $job;
				unset($job);
				$this->save_jobs();

				$array_keys = array_keys($this->server);
				$sv_multi = array_shift($array_keys); //get the first key


				if(isset($_POST['svleech'])) {
					$svleech = $this->convert_svtab($_POST['svleech']);
					if(stristr($svleech,'.')) $newURL = str_replace(parse_url($directlink, PHP_URL_HOST),$svleech, $directlink);
					else $newURL = str_replace('://us','://'.$svleech,$directlink);

					$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
				}
				else {
					$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$directlink' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
				}

				$dlhtml .=  "</b></div>";
				return $dlhtml;
			}
		}
		//status = 0: đang leech; 1: thành công; 2: lỗi
		$msize = 0;
		$filesize = '0 MB';
		$filename = substr(strrchr($url, '/'), 1);
		if(isset($torrent['size']) && isset($torrent['name']) && empty($torrent['name']) == false && $torrent['size']>0) {
				$filesize = $torrent['size'];
				$msize = $this->convert($filesize);
				$filename = $torrent['name'];

		}
		else {
			$data = $this->curl($this->checklink.urlencode($url),"","");
			if($test) echo 'checklink3b <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
			$check = @json_decode($data, true);
			if (is_array($check)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$check = json_decode($data, true);
			}
			if($check['status'] == 0 ){
				$filesize = $check['filesize'];
				$msize = $this->convert($filesize);
				$filename = $check['filename'];
				$urlid = $check['url'];
				//echo $urlid;
			}
			else $urlid = $url;
		}
		$job = array(
			'status'	=> 0,
			'hash'	=> substr(md5($hash), 0, 10),
			'path'	=> substr(md5(rand()), 0, 5),
			'filename'	=> $filename,
			'size'	=> $filesize,
			'msize'	=> $msize,
			'bwtam'	=> $msize,
			'mtime'	=> $time,
			'speed'	=> 1,
			'leecherror' => 1,
			'url'	=> $url,
			'host'	=> $host,
			'owner'	=> $this->owner,
			'ip'	=> $this->myip,
			'network'	=> $_COOKIE['network'],
			'type'	=> 'direct',
			'directlink'	=> array(
				'url'	=> '',
					'cookies'=> '',
				),
		);
		if(isset($this->jobs['leech'][$hash]) && $test==true) print_r($this->jobs['leech'][$hash]);
		else {
			if($test) echo 'nhaplink2<BR>';
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['nhaplink']."</b></div>";
			
			$post = array();
			$post['md5'] = $hash;
			$post['msize'] = $msize;
			$post['filename'] = $filename;
			$post['url'] = $urlid;
			$post['host'] = $host;
			$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
			if($test) echo 'leechmng 2 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';

			$this->jobs['leech'][$hash] = $job;
			$this->save_jobs();
			if($test) echo 'saved!<BR>';
		}
		unset($job);

		$dlhtml .=  "</b></div>";
		
		return $dlhtml;
	
		# 2021/09/12

	

		if(!isset($_COOKIE['network'])) {
			if(isset($this->jobs['leech'][$hash]['ip'])) $this->checkip($this->jobs['leech'][$hash]['ip']);
			$this->group[] = $this->network;
		}
		else $this->group[] = $_COOKIE['network'];
		$fields = array(
				'type' => $type,
				'host' => $host,
				'download' => $_POST['download'],
				'group' => json_encode($this->group),
		);
		if(isset($this->leech) && $this->leech == true) {
			$fields['host'] = 'dlink';
			$data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields), 15);
		}
		
		else $data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields));
		//echo '<pre>';print_r($fields);echo $data;exit;
		
		if (stristr($data,'|') && $host == "torrent" && !isset($gateto)) {
			//save gate to Maget links manager
			$data2 = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash.'&gate='.$data);

		}
		$this->datamega['user']['linkacc'] = $this->self;
		$this->datamega['user']['email'] = $this->email;
		$this->datamega['user']['mobile'] = $this->mobile;
		$this->datamega['user']['type'] = $this->acc_type['type'];
		$this->datamega['user']['created'] = $this->created;
		$this->datamega['user']['expired'] = $this->expired;
		$this->datamega['link']['url'] = $url;
		$this->datamega['link']['host'] = $host;

		if (stristr($data,'|')) {
			list($linkhost, $passhost, $server2) = explode('|', $data);
			$this->datamega['link']['gate'] = $linkhost;
			$this->datamega['link']['server2'] = $server2;
		}
		elseif (stristr($data,'not support mirror')) {
			$this->datamega['link']['error'] = 'không hỗ trợ mirror';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '1<pre>';
					print_r($this->datamega);
				}
			die("not support mirror for ".$host);
		}
		else {
			$contents = "link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>type=".json_encode($type)."&host=".$host."&download=".$_POST['download'];
			$this->mailreport("Không tìm thấy host phù hợp cho link $url !",$contents);
			$this->datamega['link']['error'] = 'không có gate hỗ trợ !';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
			if($test) {
				echo '2<pre>';
				print_r($this->datamega);
			}
			printf($this->lang['notsv'],$this->site_hash($url),$this->lang['mail_hotro']);
			return;
		}
		
		if(isset($linkhost)){
			$linklog = str_replace('index.php',"login.php",$this->self);
			foreach($this->firewall as $newfw=>$keyft){
				foreach($keyft as $valueft) $linklog = str_replace($valueft,$newfw,$linklog);
			}
			//echo $linklog;
		
			
			if(stristr($linklog, ':8081')) $linklog = str_replace('https://', 'http://',$linklog);
			$data = $this->curl($linkhost,'secureid='.md5($passhost),'urllist='.urlencode($url).'&server2='.$server2.'&log='.urlencode($linklog).'&mail='.$this->email.'&mobile='.$this->mobile.'&myip='.$this->myip, 120);
			
			if($test) echo "data gate <textarea>".$linkhost."\r\n".$passhost."\r\n".$url."\r\n".str_replace("textarea","",$data).'</textarea><BR>';
			if(stristr($data, 'hoster_unsupported')) echo 'hoster_unsupported';

			if(empty($data)==true) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '3<pre>';
					print_r($this->datamega);
				}

				$this->mailreport("Không load được $server2 !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			elseif(stristr($data,'Please enter Security ID')) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '4<pre>';
					print_r($this->datamega);
				}
				$this->mailreport("Sai mật khẩu login server !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			if(preg_match("/href='(.*?)' style='TEXT-DECORATION\: none' target='(.*?)'\> \<font color='#00CC00'\>(.*?)\<\/font\> \<font color='#FF66FF'\>\((.*?)\)\<\/font\>/i", $data, $content)){
				$mtime = time().rand(0,999);
				$URL = $content[1];
				$URL = str_replace('http://https','https',$URL);
				$URL = str_replace('http://http','http',$URL);
				$this->datamega['link']['premium'] = $URL;
				if(isset($this->leech) && $this->leech == true) {
					$dataleech['dlink'] = $URL;
					return $dataleech;

				}
				/* - 16:58:15 - Sunday, 07 August 2016 [GMT+7]
				$type1 = json_encode($type);
				$type2 = $type;
				if(stristr($type1,'syd') && stristr($type1,'mel')) {
					$input = array("syd", "mel");
					$sv_key = array_rand($input, 1);
					$sv_main = $input[$sv_key];
					foreach($type2 as $key=>$val) if($val ==$sv_main) unset($type2[$key]);
					$URL =  str_replace('://us','://'.$sv_main,$URL);
				}
				elseif(stristr($type1,'syd')) {
					foreach($type2 as $key=>$val) if($val =='syd') unset($type2[$key]);
					$URL =  str_replace('://us','://syd',$URL);
				}
				elseif(stristr($type1,'mel')) {
					foreach($type2 as $key=>$val) if($val =='mel') unset($type2[$key]);
					$URL =  str_replace('://us','://mel',$URL);
				}
				*/
				//$target = $content[2];
				$filename = $content[3];
				$filesize = $content[4];
				$this->datamega['link']['filename'] = $filename;
				$this->datamega['link']['filesize'] = $this->convert($filesize);
				if($test) {
					echo '5<pre>';
					print_r($this->datamega);
				}

				$data = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				//echo $data;
				if($_POST['download'] == "mirror" ) $dlhtml .=  "<b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font></a></b><BR>";
				else {
					if(isset($_POST['svleech'])) {
						$svleech = $this->convert_svtab($_POST['svleech']);
						if(stristr($svleech,'.')) $newURL = str_replace(parse_url($URL, PHP_URL_HOST),$svleech, $URL);
						else $newURL = str_replace('://us','://'.$svleech,$URL);

						$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
					}
					else {
						$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
					}

					$dlhtml .=  "</b></div>";
				}

				/*
			$svie = false;
			$seng = false;
			$sub = str_replace(substr($file[1],-4),'',$file[1]);
			if($this->size($sub.'.srt') >0 ) $svie = true;
			if($this->size($sub.'_VIE.srt') >0 ) $svie = true;
			if($this->size($sub.'_ENG.srt') >0 ) $svie = true;
				*/
			}
			else {
				$dlhtml .= $data;
				if(!stristr($data,'<font color=#ffcc33 face=Arial size=2>')) $this->datamega['link']['error'] = $data;
				else $this->datamega['link']['error'] = $this->cut_str($data, "<font color=#ffcc33 face=Arial size=2>", "</font>");;
				$megadata = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '5<pre>'.$megadata;
					print_r($this->datamega);
				}
				return $dlhtml;
			}
		}
		savedata:
		$msize = $this->convert($filesize);
		if(isset($URL)){
			if ($hash == false) {
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return $dlhtml;
			}

			elseif((isset($this->jobs['get'][$hash])==true && $lefttime_reget < 0)) $speed = $this->jobs['get'][$hash]['speed'] - 1;
			else $speed = $this->jobs['get'][$hash]['speed']+1;
			$job = array(
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> isset($hashphim)?$namemovies:$filename,
				'size'	=> $filesize,
				'msize'	=> $msize,
				'mtime'	=> time(),
				'speed'	=> $speed,
				'leecherror' => 1,
				'url'	=> isset($hashphim)?$hashphim:$url,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> $URL,
						'cookies'=> $this->cookie,
					),
			);
			
			$this->jobs['get'][$hash] = $job;
			$this->save_jobs();
			unset($job);

		}
		
		return $dlhtml;
	}


	function leechfshare($url){
		$test = false;
		$dlhtml = "";
		$url = trim($url);
		$time = time();
		if (empty($url)) return;
		if(!isset($_POST['download'])) return;
		$hash = md5($url.$this->self.'fshare');
		$type = array_keys($this->server); //list server --> đã bỏ không sử dụng
		// PHP8 guard: array_rand() on empty array throws ValueError
		$sv_root = 'us';
		if (is_array($this->sv_root) && count($this->sv_root) > 0) {
			$sv_root = array_rand($this->sv_root, 1);
		}
		$type[] = $sv_root;
		$this->leechmng = $this->mng_fshare;

		if(!stristr($url,'fshare.vn') || !stristr($url,'http')) {
			printf($this->lang['onlyfshare']);
			exit;
		}
		$host = $this->domain_name($url);

		if($this->Checkjobs($host, 'fshare') >= $this->maxlink_fshare){
			printf($this->lang['manyjob'],$this->Checkjobs($host, 'fshare'), $this->maxlink_fshare);
			exit;
		}

/*
		if($this->acc_type['reset_bw'] == false) {
			$support_pre = @file_get_contents('http://getlink.vn/supportpre.txt');
			$list_pre = explode("\n", $support_pre);
			if(is_array($list_pre) && count($list_pre)>0) {
				foreach($list_pre as $sp_pre) {
					if(empty($sp_pre)) continue;
					if (stristr($sp_pre,$host)) {
						printf($this->lang['sitepre'],$host);
						exit;
					}
				}
			}
		}
*/
		# 2021/09/12 - leech link
		if(isset($this->jobs['leech'][$hash]['mtime'])) $lefttime = time() - $this->jobs['leech'][$hash]['mtime'];
		else $lefttime = 0;
		
		$data = $this->curl($this->checkisp.$this->myip,"","");
		$this->isp_data = $data;

		$linklogin = str_replace(substr(strrchr($this->self, '/'), 1),"",$this->self);
		$post['user'] = $linklogin;
		$post['email'] = $this->email;
		$post['mobile'] = $this->mobile;
		$post['acc_type'] = $this->acc_type['fullname'];
		$post['url'] = $url;
		$post['md5'] = $hash;
		$post['host'] = $host;
		$post['ip'] = $this->myip;
		$post['isp'] = $this->isp_data;


		$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
		if($test) echo $this->leechmng.'<BR>';
		if($test) echo 'leechmng status <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
		$json = @json_decode($data, true);
		if (is_array($json)==false) {
			$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
			$json = json_decode($data, true);
		}
		if($json['status'] == '1') {
			leechlink:
			$filesize = $this->convertmb($json['filesize']);
			$this->leech = true;
			$_POST['download'] = 'down';
			$newlink = $this->get($json['directlink']);
			if(isset($newlink['dlink']) && stristr($newlink['dlink'],'http')==true) {
				
				$directlink = $newlink['dlink'];
				if($test) echo $directlink;
				$job = array(
					'status'	=> 1,
					'hash'	=> substr(md5($hash), 0, 10),
					'path'	=> substr(md5(rand()), 0, 5),
					'filename'	=> $json['filename'],
					'size'	=> $filesize,
					'msize'	=> $json['filesize'],
					'bwtam'	=> $json['filesize'],
					'mtime'	=> $time,
					'speed'	=> 1,
					'fshare' => 1,
					'host'	=> $host,
					'url'	=> $url,
					'owner'	=> $this->owner,
					'ip'	=> $this->myip,
					'type'	=> 'direct',
					'directlink'	=> array(
						'url'	=> $directlink,
							'cookies'=> '',
						),
				);
				
				$this->jobs['leech'][$hash] = $job;
				unset($job);
				$this->save_jobs();

				if(isset($_POST['svleech'])) {
					$svleech = $this->convert_svtab($_POST['svleech']);
					if(stristr($svleech,'.')) $newURL = str_replace(parse_url($directlink, PHP_URL_HOST),$svleech, $directlink);
					else $newURL = str_replace('://us','://'.$svleech,$directlink);

					$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$time'> <font color='#00CC00'>".$json['filename']."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a></b></div>";
				}
				else {
					$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$directlink' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
				}
				$dlhtml .=  "</b></div>";
				return $dlhtml;
			}
		}
		//status = 0: đang leech; 1: thành công; 2: lỗi
		$msize = 0;
		$filesize = '0 MB';
		$filename = substr(strrchr($url, '/'), 1);
		if(isset($torrent['size']) && isset($torrent['name']) && empty($torrent['name']) == false && $torrent['size']>0) {
				$filesize = $torrent['size'];
				$msize = $this->convert($filesize);
				$filename = $torrent['name'];

		}
		else {
			$data = $this->curl($this->checklink.urlencode($url),"","");
			if($test) echo 'checklink3c <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';
			$check = @json_decode($data, true);
			if (is_array($check)==false) {
				$data = trim($data, "\xEF\xBB\xBF"); //remove hidden characters
				$check = json_decode($data, true);
			}
			if($check['status'] == 0 ){
				$filesize = $check['filesize'];
				$msize = $this->convert($filesize);
				$filename = $check['filename'];
				$urlid = $check['url'];
				//echo $urlid;
			}
			else $urlid = $url;
		}
		$job = array(
			'status'	=> 0,
			'hash'	=> substr(md5($hash), 0, 10),
			'path'	=> substr(md5(rand()), 0, 5),
			'filename'	=> $filename,
			'size'	=> $filesize,
			'msize'	=> $msize,
			'bwtam'	=> $msize,
			'mtime'	=> $time,
			'speed'	=> 1,
			'fshare' => 1,
			'url'	=> $url,
			'host'	=> $host,
			'owner'	=> $this->owner,
			'ip'	=> $this->myip,
			'network'	=> $_COOKIE['network'],
			'type'	=> 'direct',
			'directlink'	=> array(
				'url'	=> '',
					'cookies'=> '',
				),
		);
		if(isset($this->jobs['leech'][$hash]) && $test==true) print_r($this->jobs['leech'][$hash]);
		else {
			if($test) echo 'nhaplink2<BR>';
			$dlhtml =  "<div class='download_main'><b><a href='".$url."' style='TEXT-DECORATION: none' target='".$time."'> <font color='#00CC00'>".$url."</font> ".$this->lang['nhaplink']."</b></div>";
			
			$post = array();
			$post['md5'] = $hash;
			$post['msize'] = $msize;
			$post['filename'] = $filename;
			$post['url'] = $urlid;
			$post['host'] = $host;
			$data = $this->curl($this->leechmng,"auth=".md5($this->passleech),http_build_query($post));
			if($test) echo 'leechmng 2 <textarea>'.str_replace("textarea","",$data).'</textarea><BR>';

			$this->jobs['leech'][$hash] = $job;
			$this->save_jobs();
			if($test) echo 'saved!<BR>';
		}
		unset($job);

		$dlhtml .=  "</b></div>";
		
		return $dlhtml;
	
		# 2021/09/12

	

		if(!isset($_COOKIE['network'])) {
			if(isset($this->jobs['leech'][$hash]['ip'])) $this->checkip($this->jobs['leech'][$hash]['ip']);
			$this->group[] = $this->network;
		}
		else $this->group[] = $_COOKIE['network'];
		$fields = array(
				'type' => $type,
				'host' => $host,
				'download' => $_POST['download'],
				'group' => json_encode($this->group),
		);
		if(isset($this->leech) && $this->leech == true) {
			$fields['host'] = 'dlink';
			$data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields), 15);
		}
		
		else $data = $this->curl($this->linkgate,"auth=".md5($this->passgate),http_build_query($fields));
		//echo '<pre>';print_r($fields);echo $data;exit;
		
		if (stristr($data,'|') && $host == "torrent" && !isset($gateto)) {
			//save gate to Maget links manager
			$data2 = $this->curl($this->linkmagnet,"auth=".md5($this->passmagnet),'hash='.$hash.'&gate='.$data);

		}
		$this->datamega['user']['linkacc'] = $this->self;
		$this->datamega['user']['email'] = $this->email;
		$this->datamega['user']['mobile'] = $this->mobile;
		$this->datamega['user']['type'] = $this->acc_type['type'];
		$this->datamega['user']['created'] = $this->created;
		$this->datamega['user']['expired'] = $this->expired;
		$this->datamega['link']['url'] = $url;
		$this->datamega['link']['host'] = $host;

		if (stristr($data,'|')) {
			list($linkhost, $passhost, $server2) = explode('|', $data);
			$this->datamega['link']['gate'] = $linkhost;
			$this->datamega['link']['server2'] = $server2;
		}
		elseif (stristr($data,'not support mirror')) {
			$this->datamega['link']['error'] = 'không hỗ trợ mirror';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '1<pre>';
					print_r($this->datamega);
				}
			die("not support mirror for ".$host);
		}
		else {
			$contents = "link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>type=".json_encode($type)."&host=".$host."&download=".$_POST['download'];
			$this->mailreport("Không tìm thấy host phù hợp cho link $url !",$contents);
			$this->datamega['link']['error'] = 'không có gate hỗ trợ !';
			$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
			if($test) {
				echo '2<pre>';
				print_r($this->datamega);
			}
			printf($this->lang['notsv'],$this->site_hash($url),$this->lang['mail_hotro']);
			return;
		}
		
		if(isset($linkhost)){
			$linklog = str_replace('index.php',"login.php",$this->self);
			foreach($this->firewall as $newfw=>$keyft){
				foreach($keyft as $valueft) $linklog = str_replace($valueft,$newfw,$linklog);
			}
			//echo $linklog;
		
			
			if(stristr($linklog, ':8081')) $linklog = str_replace('https://', 'http://',$linklog);
			$data = $this->curl($linkhost,'secureid='.md5($passhost),'urllist='.urlencode($url).'&server2='.$server2.'&log='.urlencode($linklog).'&mail='.$this->email.'&mobile='.$this->mobile.'&myip='.$this->myip, 120);
			
			if($test) echo "data gate <textarea>".$linkhost."\r\n".$passhost."\r\n".$url."\r\n".str_replace("textarea","",$data).'</textarea><BR>';
			if(stristr($data, 'hoster_unsupported')) echo 'hoster_unsupported';

			if(empty($data)==true) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '3<pre>';
					print_r($this->datamega);
				}

				$this->mailreport("Không load được $server2 !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			elseif(stristr($data,'Please enter Security ID')) {
				$contents = "hostget: $linkhost <BR> server2=$server2 <BR> link get: $url <BR>Type: ".json_encode($type)."<BR>Host: $host<BR>download: ".$_POST['download']."<BR>urllist=$url&server2=$server2&log=".$linklog;
				$this->datamega['link']['error'] = 'không load được gate!';
				$this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '4<pre>';
					print_r($this->datamega);
				}
				$this->mailreport("Sai mật khẩu login server !",$contents);
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return;
			}
			if(preg_match("/href='(.*?)' style='TEXT-DECORATION\: none' target='(.*?)'\> \<font color='#00CC00'\>(.*?)\<\/font\> \<font color='#FF66FF'\>\((.*?)\)\<\/font\>/i", $data, $content)){
				$mtime = time().rand(0,999);
				$URL = $content[1];
				$URL = str_replace('http://https','https',$URL);
				$URL = str_replace('http://http','http',$URL);
				$this->datamega['link']['premium'] = $URL;
				if(isset($this->leech) && $this->leech == true) {
					$dataleech['dlink'] = $URL;
					return $dataleech;

				}
				/* - 16:58:15 - Sunday, 07 August 2016 [GMT+7]
				$type1 = json_encode($type);
				$type2 = $type;
				if(stristr($type1,'syd') && stristr($type1,'mel')) {
					$input = array("syd", "mel");
					$sv_key = array_rand($input, 1);
					$sv_main = $input[$sv_key];
					foreach($type2 as $key=>$val) if($val ==$sv_main) unset($type2[$key]);
					$URL =  str_replace('://us','://'.$sv_main,$URL);
				}
				elseif(stristr($type1,'syd')) {
					foreach($type2 as $key=>$val) if($val =='syd') unset($type2[$key]);
					$URL =  str_replace('://us','://syd',$URL);
				}
				elseif(stristr($type1,'mel')) {
					foreach($type2 as $key=>$val) if($val =='mel') unset($type2[$key]);
					$URL =  str_replace('://us','://mel',$URL);
				}
				*/
				//$target = $content[2];
				$filename = $content[3];
				$filesize = $content[4];
				$this->datamega['link']['filename'] = $filename;
				$this->datamega['link']['filesize'] = $this->convert($filesize);
				if($test) {
					echo '5<pre>';
					print_r($this->datamega);
				}

				$data = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				//echo $data;
				if($_POST['download'] == "mirror" ) $dlhtml .=  "<b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font></a></b><BR>";
				else {
					if(isset($_POST['svleech'])) {
						$svleech = $this->convert_svtab($_POST['svleech']);
						if(stristr($svleech,'.')) $newURL = str_replace(parse_url($URL, PHP_URL_HOST),$svleech, $URL);
						else $newURL = str_replace('://us','://'.$svleech,$URL);

						$dlhtml .="<div><b><a title='click here to download' href='".$newURL."' style='TEXT-DECORATION: none' target='$mtime'><font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='".$svleech."' style='color:#ffff00'>(server ".$svleech.")</span></a>";
					}
					else {
						$dlhtml .=  "<div class='download_main'><b><a title='click here to download' href='$URL' style='TEXT-DECORATION: none' target='$mtime'> <font color='#00CC00'>".$filename."</font> <font color='#FF66FF'>($filesize)</font> | <span id='us' style='color:#ffff00'>(server SG)</span></a></b></div>";
					}

					$dlhtml .=  "</b></div>";
				}

				/*
			$svie = false;
			$seng = false;
			$sub = str_replace(substr($file[1],-4),'',$file[1]);
			if($this->size($sub.'.srt') >0 ) $svie = true;
			if($this->size($sub.'_VIE.srt') >0 ) $svie = true;
			if($this->size($sub.'_ENG.srt') >0 ) $svie = true;
				*/
			}
			else {
				$dlhtml .= $data;
				if(!stristr($data,'<font color=#ffcc33 face=Arial size=2>')) $this->datamega['link']['error'] = $data;
				else $this->datamega['link']['error'] = $this->cut_str($data, "<font color=#ffcc33 face=Arial size=2>", "</font>");;
				$megadata = $this->curl($this->megalink,"auth=".md5($this->passmega),'megalink='.json_encode($this->datamega));
				if($test) {
					echo '5<pre>'.$megadata;
					print_r($this->datamega);
				}
				return $dlhtml;
			}
		}
		savedata:
		$msize = $this->convert($filesize);
		if(isset($URL)){
			if ($hash == false) {
				printf($this->lang['cantjob'],$this->lang['mail_hotro']);
				return $dlhtml;
			}
			if(isset($this->jobs['get'][$hash])==false || (isset($this->jobs['get'][$hash])==true && time() > $this->jobs['get'][$hash]['mtime']+24*60*60)){
				$speed = 1;
			}
			elseif((isset($this->jobs['get'][$hash])==true && $lefttime_reget < 0)) $speed = $this->jobs['get'][$hash]['speed'] - 1;
			else $speed = $this->jobs['get'][$hash]['speed']+1;
			$job = array(
				'hash'	=> substr(md5($hash), 0, 10),
				'path'	=> substr(md5(rand()), 0, 5),
				'filename'	=> isset($hashphim)?$namemovies:$filename,
				'size'	=> $filesize,
				'msize'	=> $msize,
				'mtime'	=> time(),
				'speed'	=> $speed,
				'fshare' => 1,
				'url'	=> isset($hashphim)?$hashphim:$url,
				'owner'	=> $this->owner,
				'ip'	=> $this->myip,
				'type'	=> 'direct',
				'directlink'	=> array(
					'url'	=> $URL,
						'cookies'=> $this->cookie,
					),
			);
			
			$this->jobs['get'][$hash] = $job;
			$this->save_jobs();
			unset($job);

		}
		
		return $dlhtml;
	}



	function updateleech() {
		if(isset($_POST['test']) && $_POST['test']==true) print_r($_POST);
		if(isset($_POST['status']) && isset($_POST['veri']) && isset($_POST['host']) && isset($_POST['hash']) && $_POST['veri'] == $this->pw_verified) {
			$hash = $_POST['hash'];
			$host = $_POST['host'];
			if(isset($_POST['status']) && isset($_POST['hash']) && $_POST['status'] != '1') {
				if(isset($this->jobs['leech'][$hash])) {
					$this->jobs['leech'][$hash]['status'] = $_POST['status'];
					$this->save_jobs();
					if(isset($_POST['status'])) echo 'user update status='.$_POST['status'].'<BR>';
				}

			}
			elseif(isset($_POST['dlink']) && isset($_POST['filesize']) && isset($_POST['filename']) && isset($_POST['hash']) && $_POST['status'] == '1') {
				$filesize = $this->convertmb($_POST['filesize']);
				if(isset($this->jobs['leech'][$hash]['status'])) {
					$this->leech = true;
					$_POST['download'] = 'down';
					//if(isset($_POST['test']) && $_POST['test']==true) echo "dlink: ".$_POST['dlink']."\r\n";
					$dlink_size = $this->size($_POST['dlink']);
					//if($dlink_size > 50*1024) $newlink = $this->get($_POST['dlink'], $this->jobs['leech'][$hash]);
					//else die('Error: Size dlink < 0');
					$newlink = $this->get($_POST['dlink'], $this->jobs['leech'][$hash]);
					if(isset($newlink['dlink'])) {
						$directlink = $newlink['dlink'];
						$this->jobs['leech'][$hash]['status'] = 1;
						$this->jobs['leech'][$hash]['filename'] = $_POST['filename'];
						$this->jobs['leech'][$hash]['msize'] = $_POST['filesize'];
						$this->jobs['leech'][$hash]['size'] = $filesize;
						$this->jobs['leech'][$hash]['directlink']['url'] = $directlink;
						$this->save_jobs();
						
						if(isset($_POST['status'])) echo 'user update status='.$_POST['status'].'<BR>';
						echo $_POST['dlink'].' user saved!<BR>';
					}
					else die('Error not get dlink');
				}
				else {
					die('not found hash: '.$hash.'<BR>');
				}
					
				//print_r($this->jobs['leech'][$hash]);
			}
			else {
				die('error download link');
			}

		}

	} 

	function authcmp($field) {
		return function($a, $b) use ($field) {
			$av = isset($a[$field]) ? $a[$field] : '';
			$bv = isset($b[$field]) ? $b[$field] : '';
			return strcasecmp((string)$av, (string)$bv);
		};
	}
	function datecmp($field) {
		return function($a, $b) use ($field) {
			$av = isset($a[$field]) ? $a[$field] : 0;
			$bv = isset($b[$field]) ? $b[$field] : 0;
			if ($av == $bv) return 0;
			return ($av < $bv) ? 1 : -1; // desc
		};
	}
	function date_az($field) {
		return function($a, $b) use ($field) {
			$av = isset($a[$field]) ? $a[$field] : 0;
			$bv = isset($b[$field]) ? $b[$field] : 0;
			if ($av == $bv) return 0;
			return ($av > $bv) ? 1 : -1; // asc
		};
	}
	function fulllist() {
		if (isset($_POST['clearfile'])) {
			$this->jobs['get']['clearfile'] = time();
			$this->save_jobs();
		}
		if(!isset($this->jobs['get']['clearfile'])) $this->jobs['get']['clearfile'] = 0;
		$files = array();	
		$hdsize = 0; //tổng dung lượng đã ẩn
		$hdfile = 0; //tổng số file đã ẩn
		foreach ($this->jobs['get'] as $key=>$job) {
			if(!isset($job['mtime']) || $job['mtime'] < $this->jobs['get']['clearfile']) {
				if(isset($job['msize'])) {
					$hdsize = $hdsize + $job['msize'];
					$hdfile = $hdfile + 1;
				}
				continue;
			}
			if ($job['owner']!=$this->owner  && $this->privatef==true) continue;
			if (isset($_GET['listfile']) && $_GET['listfile']=='get' && empty($job['directlink']['url'])==true) continue;
			//if (isset($_GET['listfile']) && $_GET['listfile']=='leech' && empty($job['directlink']['url'])==false) continue;
			$files[$key] = $job;
			$files[$key]['hash'] = $key;
		}
		$compare = $this->datecmp('mtime'); 
		if (count($files)==0 && $hdfile>0) {
			echo '<Center>'.sprintf($this->lang['report_hd_file'], $hdfile, $this->convertmb($hdsize), date('H:i:s- d.m.Y', $this->jobs['get']['clearfile'])).'</center>'; return;
		}
		elseif (count($files)==0) {
			echo "<Center>".$this->lang['notfile']."<br/><a href='$this->self'> [".$this->lang['main']."] </a></center>"; return;
		}


		$data = '<div>';
		echo $this->lang['chon_sv_get'].'<BR>';
		foreach($this->server as $keysv=>$nsv) {
			$data .= '<a onclick="return chon_sv(\''.$keysv.'\');" href="javascript:void(0)" style="TEXT-DECORATION: none"><span style="color:#00ccff">'.$nsv.'</span></a>&nbsp;&nbsp;|
			';
		}

		$data .='</div><div style="overflow: auto; height: auto; max-height: 1200px; width: 1000px;"><table id="table_filelist" class="filelist" align="left" cellpadding="3" cellspacing="1" width="100%"><thead><tr class="flisttblhdr" valign="bottom"><td class="sorttable_alpha"><b>'.$this->lang['name'].'</b></td><td><b>'.$this->lang['Original'].'</b></td><td><b>'.$this->lang['Size'].'</b></td><td><b>'.$this->lang['Date'].'</b></td><td><B>IP</B></td></tr></thead><tbody>
		';


		usort($files, $compare);
		$i = 0;
		foreach ($files as $file){
			$i++;
			$timeago = $this->convert_time(time() - $file['mtime']). " ".$this->lang['ago'];
			if(time() - $file['mtime'] > 86400*8) $timeago = date('d/m/Y',$file['mtime']);

			if (strlen($file['filename']) > 100) $file['filename']= substr($file['filename'],0,90);
			if(stristr($file['url'],'http')) {
				$url = $file['url'];
				$hosting = substr($this->site_hash($file['url']),0,15);
			}
			elseif(stristr($file['url'],'magnet') || stristr($file['url'],'.torrent')) {
				$url = $file['url'];
				$hosting = 'torrent';
			}
			elseif(substr(strrchr($file['directlink']['url'], '.'), 1)=='srt') {
				$url = '?id=phim';
				$hosting = 'phụ đề';

			}
			else {
				$url = '?id=phim';
				$hosting = 'phim';
			}
			
			if (strlen($file['ip']) > 16) {
				$ip = substr($file['ip'],0,15).'***';
			}
			else $ip = substr($file['ip'], 0, -3).'***';



			$data .= "
			<tr class='flistmouseoff' align='center'>
			<td id='linkdl".$i."'><a href='".$file['directlink']['url']."' style='font-weight: bold; color: rgb(0, 0, 0);' target='".$file['hash']."'>".$file['filename']."  | <span id='us' style='color:#000099'>(US)</span></a></td>
			<td><a href='$url' style='color: rgb(0, 0, 0);'>".$hosting."</a></td>
			<td>".$this->convertmb($file['msize'])."</td>
			<td><font color=#000000>$timeago</font></center></td>
			<td><font color=#000000>".$ip."</font></td></tr>";

		}
		echo $data;
		$totalall = $this->convertmb($this->totalMB);
		$thislimitMBIP =	round($this->limitMBIP/1024,0);
		
		echo '</tbody><tbody><tr class="flisttblftr"><td>&nbsp;</td><td>'.$this->lang['Total'].':</td><td>'.$totalall.'</td><td></td><td>&nbsp;</td></tr></tbody></table>
		</div></form>';
		printf($this->lang['autodel'],$this->convert_time($this->ttl*60));

		//Clear list files
		if($hdfile>0) echo '<Center>'.sprintf($this->lang['report_hd_file'], $hdfile, $this->convertmb($hdsize), date('H:i:s- d.m.Y', $this->jobs['get']['clearfile'])).'</center><BR>';
		echo '	<form action="./?listfile=get" method="POST">
					<input input type="hidden" name="clearfile" value="1"/>
					<input type="submit" value="'.$this->lang['clear_list'].'"><BR>'.$this->lang['note_clear'].'
				</form><br>
				';
		//end clear

	}

	function listleech($type=false, $tableech = false){
		$svleech = false;
		if($tableech) $svleech = $this->convert_svtab($tableech);
		if (!isset($this->jobs['leech']) || !is_array($this->jobs['leech']) || count($this->jobs['leech'])==0) {
			return;
		}
		$data = '';

		if(isset($_GET['leecherror'])) $type='error';
		elseif(isset($_GET['fshare'])) $type='fshare';
		if($type == 'error') echo $this->lang['chon_sv_error'];
		elseif($type == 'fshare') echo $this->lang['chon_sv_fshare'];
		else echo $this->lang['chon_sv_leech'];

	
		foreach($this->server as $keysv=>$nsv) {
			$data .= '<a onclick="return chon_sv(\''.$keysv.'\');" href="javascript:void(0)" style="TEXT-DECORATION: none"><span style="color:#00ccff">'.$nsv.'</span></a>&nbsp;&nbsp;|
			';
		}
		if(isset($_GET['listfile'])) $style = "overflow: auto; height: auto; max-height: 1200px; width: 90%;";
		else $style = "overflow: auto; height: auto; max-height: 450px; width: 90%;";
		$data .='<div style="'.$style.'"><table id="table_filelist" class="filelist" align="left" cellpadding="3" cellspacing="1" width="100%"><thead><tr class="flisttblhdr" valign="bottom"><td class="sorttable_alpha"><b>'.$this->lang['Original'].'</b></td><td><b>'.$this->lang['status'].'</b></td><td><b>'.$this->lang['name'].'</b></td><td><b>'.$this->lang['Size'].'</b></td><td><b>'.$this->lang['Date'].'</b></td><td><B>IP</B></td></tr></thead><tbody>
		';

		$files = array();
		foreach ($this->jobs['leech'] as $key=>$job) {
			if (!is_array($job)) continue;
			//check update status
			$hash = $key;
			if(!isset($job['leecherror']) && $type=='error') continue;
			elseif(!isset($job['fshare']) && $type=='fshare') continue;
			if($type==false && isset($job['leecherror'])==true) continue;
			elseif($type==false && isset($job['fshare'])==true) continue;

			//if(isset($_GET['listfile']) AND isset($this->jobs['leech'][$hash]['showfile']) AND $this->jobs['leech'][$hash]['showfile'] == false) continue; //an file releech trung nhau
			//ẩn file releech trùng nhau
			if(isset($this->jobs['leech'][$hash]['showfile']) AND $this->jobs['leech'][$hash]['showfile'] == false) continue;
			if(isset($job['host'])) $host = $job['host'];
			else {
				$url = $job['url'];
				if(stristr($url,'magnet:?xt=') || stristr($url,'.torrent')) $host = "torrent";
				else $host = $this->domain_name($url);
			}
			
			if (isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
			else  $limit_host = $this->hosts['other'];
			#tổng băng thông cho nhóm host riêng  = limit1 +limit2
			if(isset($this->hosts2[$host]['bandwidth']) && isset($limit_host['bandwidth'])) $totalbw_host = $limit_host['bandwidth'] + $this->hosts2[$host]['bandwidth'];
			else if(isset($limit_host['bandwidth'])) $totalbw_host = $limit_host['bandwidth'];

			//link sau 3 ngày chuyển sang error
			$lefttime = time() - $job['mtime'];
			if(6*24*60*60 > $lefttime && $lefttime  > 3*24*60*60) {
				if(($job['status'] == 0 or $job['status'] == 2)) {
					$this->jobs['leech'][$key]['status'] = 3;
				}

			}

			$files[$key] = $job;
			$files[$key]['hash'] = $key;
			$this->save_jobs();
		}
		$compare = $this->datecmp('mtime'); 
		usort($files, $compare);
		$total = 0;
		$i = 0;
		$listhash = array();
		foreach ($files as $file){
			//ẩn file releech trùng nhau
			$hash = substr(md5($file['url']),0,10);
			if(isset($listhash[$hash])) continue;
			else $listhash[$hash] = $file['filename'];

			$i++;
			if($i>$this->max_list_file && !isset($_GET['listfile'])) break;
			$timeago = $this->convert_time(time() - $file['mtime']). " ".$this->lang['ago'];
			if(time() - $file['mtime'] > 86400*8) $timeago = date('d/m/Y',$file['mtime']);
			//$filesize = $this->lang['unknown'];
			$url = $file['url'];
			$host = $file['host'];
			//thay đổi link manager theo hosting - 2023/05/29 -23:04 (GMT+7)
			if(isset($this->leechrieng) && $this->leechrieng == true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
			elseif(isset($this->leechrieng_on) && in_array($host, $this->leechrieng_on)==true && isset($this->mng_rieng[$host])) $this->leechmng = $this->mng_rieng[$host];
			else if(isset($this->mng_normal[$host])) $this->leechmng = $this->mng_normal[$host];

			if(isset($_GET['testgl'])) echo $this->leechmng.'<BR>';

			if($file['status'] == 2 or $file['status'] == 0) {
				$datacheck = $this->curl($this->leechmng,"auth=".md5($this->passleech),'hash='.$file['hash'].'&status='.$file['status'], 15);
				
				if(isset($_GET['testgl'])) echo 'hash='.$file['hash'].'&status='.$file['status'].' <textarea>'.str_replace("textarea","",$datacheck).'</textarea><BR>';
				$json = @json_decode($datacheck, true);
				if (is_array($json)==false) {
					$datacheck = trim($datacheck, "\xEF\xBB\xBF"); //remove hidden characters
					$json = json_decode($datacheck, true);
				}
				if(isset($json['status']) && $json['status'] == '1' && empty($json['directlink'])== false) {
					$this->leech = true;
					$hash = $file['hash'];
					$host = $json['host'];
					$_POST['download'] = 'down';
					$newlink = $this->get($json['directlink'], $this->jobs['leech'][$hash]);

					if(isset($newlink['dlink'])) {
						$directlink = $newlink['dlink'];
						$filesize = $this->convertmb($json['filesize']);
						$this->jobs['leech'][$hash]['status'] = 1;
						$this->jobs['leech'][$hash]['filename'] = $json['filename'];
						$this->jobs['leech'][$hash]['msize'] = $json['filesize'];
						$this->jobs['leech'][$hash]['size'] = $filesize;
						$this->jobs['leech'][$hash]['directlink']['url'] = $directlink;
						$file = $this->jobs['leech'][$hash];
					}

				}
			}


			$filesize = $file['size'];
			$dlink = $file['directlink']['url'];
			if($svleech) {
				if(stristr($svleech,'.')) $dlink = str_replace(parse_url($dlink, PHP_URL_HOST),$svleech, $dlink);
				else $dlink = str_replace('://us','://'.$svleech,$dlink);
			}

			if($file['msize']>0 AND $file['status'] <3) $total = $file['msize'] + $total;
			if($file['msize'] == 0) $filesize = 'Updating';
			//if ($file['status'] == 0) $filestatus = $this->lang['leeching'].' &nbsp;<a href="javascript:void(0)" style="TEXT-DECORATION: none"><span id="huyleech_'.$file['hash'].'" class="'.$url.'" style="font-weight: bold; color:red">'.$this->lang['huyleech'].'</span></a>';
			for ($x = 0; $x <= $this->lang['max_status']; $x++) {
				if ($file['status'] == $x) {
					$filestatus = $this->lang['status'.$x];
				}
			} 

			if ($file['status'] == 1) {
				if(!stristr($dlink,'http')) {
					$file['status'] = 2;
					$filestatus = $this->lang['status2'];
					$this->jobs['leech'][$file['hash']]['status'] = 2;
					$this->save_jobs();
				}
				if (strlen(urldecode($file['filename'])) > 80) $file['filename']= substr(urldecode($file['filename']),0,70);
				$filesize = $this->convertmb($file['msize']);
			}

			$renewdomain = 'https://giahan.getlink.vn/buy/gia-han-get-link.php?url='.str_replace("index.php","", $this->self);


			$filename = urldecode($file['filename']);
			if($file['status'] == 5) {
				if($this->acc_type['reset_bw']) $filename = sprintf($this->lang['filename5'],$renewdomain);
				else $filename = sprintf($this->lang['filenamespro5'],$renewdomain);
			}
			if($file['status'] == 6) {
				$filename = sprintf($this->lang['filename6'],$renewdomain);
			}
			if(stristr($url,'http')) {
				$hosting = substr($this->site_hash($file['url']),0,15);
			}
			if($file['status']>2) $filesize = 'Updating';
			elseif(stristr($url,'magnet')) $hosting = 'magnet';
			elseif(stristr($url,'torrent')) $hosting = 'torrent';
			if(empty($filename)) {
				//$filename = $this->lang['unknown'];
				$filename = '<i>Loading....</i> '.$url;
				if (strlen(urldecode($filename)) > 100) $filename = substr(urldecode($filename),0,90);
			}

			if (strlen($file['ip']) > 16) {
				$ip = substr($file['ip'],0,15).'***';
			}
			else $ip = substr($file['ip'], 0, -3).'***';
			if(stristr($svleech,'.')) $svleech = $tableech;
			$data .= "
			<tr class='flistmouseoff' align='center'>
			<td><a href='$url' style='color: rgb(0, 0, 0);' target='".$file['hash']."'>".$hosting."</a></td>
			<td>".$filestatus."</td>
			".(($dlink AND $file['status']==1)?"<td id='linkdl".$i."'><a href='".$dlink."' style='font-weight: bold; color: #372bc0;'>".$filename."  | <span id='".($svleech==true? $svleech:'us')."' style='color:#990000'>(server ".($svleech==true? $svleech:'US').")</span></a></td>":"<td>".$filename."</td>")."
			<td>".$filesize."</td>
			<td><font color=#000000>$timeago</font></center></td>
			<td><font color=#000000>".$ip."</font></td></tr>";

		}
		if(count($files) > 0) {
			echo $data;
			$totalall = $this->convertmb($total);
		
			echo '</tbody><tbody><tr class="flisttblftr"><td>&nbsp;</td><td>&nbsp;</td><td>'.$this->lang['Total'].':</td><td>'.$totalall.'</td><td></td><td>&nbsp;</td></tr></tbody></table>';
			if(isset($_GET['id']) && $_GET['id']=='leecherror') echo $this->lang['show_file_error'];
			elseif(isset($_GET['id']) && $_GET['id']=='fshare') echo $this->lang['show_file_fshare'];
			else echo $this->lang['show_file_leech'];
			echo '</div></form>';
		}
	}

	function limit_hosting(){
		$time  = time();
		$daynow = date('d.m.Y', $time);
		echo '<table>';
		if(isset($this->hosts) && is_array($this->hosts) && count($this->hosts) > 0) {
			$json = $this->bw_api();
			if(!isset($json[$daynow])) $json[$daynow] = array();
			$i = 0;
			$day = date('d.m.Y', time());
			foreach($json[$daynow] as $host=>$value) {
				$used = $this->total_bw_day($host);
				if($used == 0) continue;
				$used = $this->convertmb($used);
				if(isset($this->hosts[$host])) $limit_host = $this->hosts[$host];
				else $limit_host = $this->hosts['other'];
				if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
				else {
					if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
					else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
				}

				echo '
				<tr style="color:#ccc;">
					<td width="50%">'.$host.'</td>
					<td align="center" width="50%">'.$used.' / '.$this->convertmb($totalbw).'</td>
				</tr>
				';
				$i++;
				if($i==6) break;
			}

			foreach($this->hosts as $host=>$value) {
				if($i==6) break;
				$used = $this->total_bw_day($host);
				if($used > 0) continue;
				$used = $this->convertmb($used);
				$limit_host = $this->hosts[$host];

				if(isset($limit_host['daily_bw']) == true && $limit_host['daily_bw'] == true) $totalbw = $limit_host['daily_bw']*1024*1024;
				else {
					if(isset($this->hosts2[$host]['bandwidth'])) $totalbw = ($limit_host['bandwidth']+$this->hosts2[$host]['bandwidth'])*1024*1024;
					else  $totalbw = ($limit_host['bandwidth'])*1024*1024;
				}

				echo '
				<tr style="color:#ccc;">
					<td width="50%">'.$host.'</td>
					<td align="center" width="50%">'.$used.' / '.$this->convertmb($totalbw).'</td>
				</tr>
				';
				$i++;
				if($i==6) break;
			}

			echo '</table>
				<div align="left"><a href="./?id=profile">'.$this->lang['more'].' >>></a> &nbsp; &nbsp; &nbsp;<a href="./?id=addbw">Mua băng thông >>></a></div>';
		}
		echo '<BR><BR>';
		exit;

	}


	function showimg($hash){
		header("Content-type: image/jpeg");
		$path = $this->phim[$hash]['poster'];

		//$fname = $this->phim[$hash]['name'];
		if(isset($this->phim[$hash]['saveimg']) && $this->phim[$hash]['saveimg'] != false) {
			readfile($this->folderimg.$this->phim[$hash]['saveimg']);
			/*
			if(file_exists($this->folderimg.$this->phim[$hash]['saveimg'])) {
				echo $this->folderimg.$this->phim[$hash]['saveimg'];
				echo '<BR>';
				$image = imagecreatefromjpeg($this->folderimg.$this->phim[$hash]['saveimg']); 
				$color = imagecolorallocate($image, 68, 68, 68);
				imagestring($image, 4, 5, 2, "getlink.vn", $color); 
				imagejpeg($image);
			}
			else {
				$im = imagecreate(600, 30);
				$bg = imagecolorallocate($im, 255, 255, 255);
				$textcolor = imagecolorallocate($im, 0, 0, 255);
				imagestring($im, 5, 100, 0, 'Not found file '.$this->folderimg.$this->phim[$hash]['saveimg'], $textcolor);
				imagejpeg($im);
				imagedestroy($im);
			}
			*/

		}
		elseif(file_exists($this->folderimg.$hash.'.jpg')) {
			$image = imagecreatefromjpeg($this->folderimg.$hash.'.jpg'); 
			$color = imagecolorallocate($image, 68, 68, 68);
			imagestring($image, 4, 5, 2, "http://getlink.vn", $color); 
			imagejpeg($image);
		}
		else {
			$this->copyfile($path,$this->folderimg.$hash.'.jpg');
			echo $this->curl($path,'','');	
		}


		exit;

	}

	function showinfo($i,$files){
		$name = substr(strrchr($files['movie'], '/'), 1);
		$name = str_replace('_',' ',$name);
		$name = str_replace('%20',' ',$name);
		$name = str_replace('%28',' ',$name);
		$name = str_replace('%29',' ',$name);
		$gen = '';
		foreach($files['listgenre'] as $val) {
			$gen .= '<a href="./?id=phim&gen='.$val.'"><strong>'.(isset($this->gens[$val])?$this->gens[$val]:$val).'</strong></a>, ';
		}
		$info = '
		<div id="sticky'.$i.'" class="atip" style="width:'.(empty($i)? '700px':'450px').'">
			'.$this->lang['name_film'].': <b>'.$files['name'].'</b></br>
			'.((isset($files['timephim']))?$this->lang['Date'].': '.$files['timephim'].'<BR>':'').'
			'.$this->lang['name'].': <b>'.$name.'</b><br>
			'.$this->lang['Size'].': <b>'.$this->convertmb($files['size']).'</b><br>
			'.$this->lang['rate_imdb'].': <b>'.$files['vote'].'</b><br>
			'.$this->lang['count_dl'].': <b>'.(isset($files['count'])?$files['count']:0).'</b><br>
			'.((isset($files['quality']) && empty($files['quality'])==false)?$this->lang['quality'].': <a href="./?id=phim&quality='.$files['quality'].'"><b>'.$files['quality'].'</b></a><br>':'').'
			'.$this->lang['release'].': <a href="./?id=phim&year='.date("Y",strtotime($files['year'])).'"><b>'.$files['year'].'</b></a><br>
			IMDB: <b><a href="'.$files['imdb'].'" target="'.$files['time'].'">'.$files['imdb'].'</b></a><br>
			'.$this->lang['type_f'].': <b>'.substr($gen,0,-2).'</b><br>
			<p align=justify>'.$files['note'].'</p><br><Br>
		</div>
		';
		return $info;
	}

	function listphim($type) {
		if(isset($_GET['phim'])) {
			$hash = trim($_GET['phim']);

			echo '<div class="al-pl">';
			if(isset($this->phim[$hash])) {
				echo '<div class="imgdl"><img src="http://img.getlinkvn.com/'.$hash.'.jpg"/></div>';
				echo $this->showinfo('',$this->phim[$hash]);
				if(isset($this->jobs['get']['phim_'.$hash]))  {
					$data = '';
					$filename = substr(strrchr($this->jobs['get']['phim_'.$hash]['directlink']['url'], '/'), 1);
					$data .= '<div id="phim'.$hash.'"><a href="'.$this->jobs['get']['phim_'.$hash]['directlink']['url'].'" title="'.$this->lang['downfilm'].'" style="font-weight: bold;font-size:16px;color:green">'.$filename.' <font color = "red">('.$this->jobs['get']['phim_'.$hash]['size'].')</font></a><br>
					<a href="javascript:void(0)" onclick="getphim(\''.$hash.'\');" title="'.$this->lang['f_reget1'].'" style="text-decoration: underline;">'.$this->lang['f_reget2'].'</a><br>
					</div>';
					if(isset($this->jobs['get']['subviet_'.$hash]) && isset($this->jobs['get']['subeng_'.$hash]))  {
						$data .= '<td><span id="subeng'.$hash.'"><a href="'.$this->jobs['get']['subeng_'.$hash]['directlink']['url'].'" style="font-weight: bold;font-size:14px;color:blue">'.$this->lang['subeng'].'</a></span>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span id="subviet'.$hash.'"><a href="'.$this->jobs['get']['subviet_'.$hash]['directlink']['url'].'" style="font-weight: bold; font-size:14px;color:blue">'.$this->lang['subviet'].'</a></span></td>';
					}
					elseif(isset($this->jobs['get']['subeng_'.$hash]))  {
						$data .= '<td><span id="subeng'.$hash.'"><a href="'.$this->jobs['get']['subeng_'.$hash]['directlink']['url'].'" style="font-weight: bold; font-size:14px;color:blue">'.$this->lang['subeng'].'</a></span><span id="subviet'.$hash.'></span></td>';
					}
					elseif(isset($this->jobs['get']['subviet_'.$hash]))  {
						$data .= '<td><span id="subeng'.$hash.'"></span><span id="subviet'.$hash.'><a href="'.$this->jobs['get']['subviet_'.$hash]['directlink']['url'].'" style="font-weight: bold; font-size:14px;color:blue">'.$this->lang['subviet'].'</a></span></td>';
					}
					else {
						$data .= '<td><span id="subeng'.$hash.'"></span>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span id="subviet'.$hash.'"></span></td>';

					}
					echo $data;

				}
				else {
					echo '<div id="phim'.$hash.'"><a href="javascript:void(0)" onclick="getphim(\''.$hash.'\');" title="'.$this->lang['downfilm'].'" style="font-weight: bold;font-size:16px;">'.$this->lang['downfilm'].' '.$this->phim[$hash]['name'].'</a></div>';
					echo '<div><span id="subeng'.$hash.'"></span>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span id="subviet'.$hash.'"><span></div>';
				}
				echo '<BR><BR>';


			}
			else {
				echo '<br><br>'.$this->lang['not_f'].' <br><a href="javascript:history.back(1)">« '.$this->lang['back'].'</a><br><br></div>';
				return;
			}
			echo '</div>';
			
			$files = array();
			foreach ($this->phim as $key=>$job) {
				$files[$key] = $job;
				$files[$key]['hash'] = $key;
				if(!isset($files[$key]['count'])) $files[$key]['count'] = 0;

				if(!stristr($files[$key]['name'],trim($this->phim[$hash]['name']))) unset($files[$key]);
			}
			if(empty($files)) return;
			echo '
			<!-- List new -->
			<div class="al-pl">
				<div class="title-main">
					<label class="ico-playlist"></label>
				</div>';
				echo '<ul class="list-al-pl">';
			$j = 0;
			$info = '';
			//echo '<pre>';
			//print_r($files);
			foreach($files as $i=>$file){
				$j++;
				echo '
				<li>
					<div class="poster" data-tooltip="stickynew'.$i.'">
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'"><img src="http://img.getlinkvn.com/'.$hash.'.jpg" style="max-height:180px; width:110px"/></a>
					</div>
					<h3>
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'">'.$files[$i]['name'].'</a><p>'.$this->lang['quality'].': '.$files[$i]['quality'].'<BR>'.$this->lang['Size'].': '.$this->convertmb($files[$i]['size']).'<BR>'.$this->lang['count_dl'].': '.$files[$i]['count'].'<BR>Rate: '.$files[$i]['vote'].'</p>
					</h3>
				</li>';
				if($j == 6)  {
					echo '<br class="clr">';
					$j = 0;
				}
				$info .= $this->showinfo('new'.$i,$files[$i]);
			}
			echo '
					<br class="clr">
				</ul>
			</div>
			<!-- End List new -->';
			if(isset($info)) echo '
				<!--HTML for the tooltips-->
				<div id="mystickytooltip" class="stickytooltip">
					<div style="padding:5px">
						'.$info.'
					</div>
					<div class="stickystatus"></div>
				</div>
				<!--HTML for the tooltips-->';
			return;
		}
		if(isset($_GET['view']) && $_GET['view'] == 'request') { 
			include($this->fileinfo_dir."/info.php");
			
			echo '<div class="al-pl">
					<div class="title-main">
						<label class="ico-playlist">'.$this->lang['f_request'].'</label>
					</div>';
			echo '<div id="wait" style="width: 600px; padding:10px 0px 10px 20px;font-size:14px" align="center"><p align="justify">'.$this->lang['requestphim'].'</p></div>
				<div style="overflow: auto; height: auto; width: 500px;" id="contact">
				<form action="javascript:contact(document.getElementById(\'form_contact\'));" name="form_contact" id="form_contact">
				<table cellpadding="3" cellspacing="1" border="0" align="center">
					<tr>
						<td align="right">T&#7921; x&#432;ng :</td>
						<td>
							<select name="tuxung">
								<option value="anh">'.$this->lang['anh'].'</option>
								<option value="ch&#7883;">'.$this->lang['chi'].'</option>
								<option value="b&#225;c">'.$this->lang['bac'].'</option>
							</select>
						</td>
					</tr>
					<tr>
						<td align="right">'.$this->lang['fullname'].' *:</td>
						<td><input type="text" class="text" name="hovaten" size="30" value="'.$username.'"/></td>
					</tr>
					<tr>
						<td align="right">'.$this->lang['address'].'</td>
						<td><input type="text"  class="text" name="diachi" size="30" value="'.$address.'"/></td>
					</tr>
					<tr>
						<td align="right">'.$this->lang['mobile_sp'].'</td>
						<td><input type="text"  class="text" name="sodienthoai" size="30" value="'.$mobile.'"/></td>
					</tr>
					<tr>
						<td align="right">Email *:</td>
						<td>'.$email.'</td>
					</tr>
					<tr><td height="5px"></td></tr>
					<tr>
						<td align="right">'.$this->lang['sub'].' *:</td>
						<td><input type="text" class="text" name="tieude" size="60" value="yêu cầu phim"/></td>
					</tr>
					<tr>
						<td align="right" valign="top">'.$this->lang['content'].' *:</td>
						<td><textarea name="noidung" style="width:99%;height:100px;"></textarea></td>
					</tr>
					<tr>
						<td></td>
						<td align="left"><input type="submit" value="G&#7917;i" id="submit123"/></td>
					</tr>

				</table>
				</form><br><br></div>
			</div>';
			return;
		}
		$self = 'http://'.$_SERVER['HTTP_HOST'].isset($_SERVER['REQUEST_URI'])? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];
		$files = array();	
		$newfile = array();
		$title  = $this->lang['f_update'];
		foreach ($this->phim as $key=>$job) {
			$files[$key] = $job;
			$files[$key]['hash'] = $key;
			//if(strlen($files[$key]['year'])==4) $files[$key]['yearsec'] = strtotime('1-1-'.$files[$key]['year']);
			//else $files[$key]['yearsec'] = strtotime($files[$key]['year']);
			if(!isset($files[$key]['count'])) $files[$key]['count'] = 0;
			if(isset($_GET['search'])) {
				if(!stristr($files[$key]['name'],trim($_GET['search']))) unset($files[$key]);
			}
			elseif(isset($_GET['view']) && $type == 'down') {
				if(!isset($this->jobs['get']['phim_'.$key])) unset($files[$key]);
				$title  = $this->lang['f_dl'];
			}
		}
		
		if(isset($_GET['view']) && $type == 'new') {
			$compare = $this->datecmp('year'); 
			usort($files, $compare);
			$title  = $this->lang['f_new'];
		}
		
		elseif(isset($_GET['view']) && $type == 'hot') {
			$compare = $this->datecmp('vote'); 
			usort($files, $compare);
			$title  = $this->lang['f_hot'];
		}
		elseif(isset($_GET['view']) && $type == 'dl') {
			$compare = $this->datecmp('count'); 
			usort($files, $compare);
			$title  = $this->lang['f_dlhot'];
		}
		else {
			$compare = $this->datecmp('time'); 
			usort($files, $compare);
		}
		if(isset($_GET['search'])) $title  = $this->lang['f_results'];
		elseif(isset($_GET['gen'])) {
			$gen = strtolower(trim($_GET['gen']));
			foreach($files as $key=>$phim) {
				if (in_array($gen, $phim['listgenre'])==true && $phim["status"] == 1) {
					$newfile[] = $phim;
				}
			}
			$files = $newfile;
			$title  = $this->lang['f_type'].': '.(isset($this->gens[$gen])?$this->gens[$gen]:$gen);
		}
		elseif(isset($_GET['quality'])) {
			$quality = trim($_GET['quality']);
			$title  = $this->lang['f_quality'].': '. $quality;
			foreach($files as $key=>$phim) {
				if (isset($phim['quality']) && empty($phim['quality'])==false && stristr($quality,$phim['quality']) && $phim["status"] == 1) {
					$newfile[] = $phim;
				}
			}
			$files = $newfile;
			$title  = $this->lang['f_quality'].': '. $quality;
		}
		elseif(isset($_GET['year'])) {
			$year = trim($_GET['year']);
			foreach($files as $key=>$phim) {
				if ($year == $phim['year'] && $phim["status"] == 1) {
					$newfile[] = $phim;
				}
			}
			$files = $newfile;
			$title  = $this->lang['f_year']. $year;
		}

		if(isset($_GET['page'])) {
			if (!is_numeric($_GET['page'])) $page = 0;
			else $page = trim($_GET['page']) - 1;
		}
		else $page = 0;
		$phim_per_page = 18;
		$totalphim = count($files);
		$totalpage = round($totalphim/$phim_per_page, 0);
		if ($totalpage*$phim_per_page < $totalphim) $totalpage = $totalpage+1;

		$trang = 'Trang: ';
		$end = 0;
		for ($h = 1 ; $h < $totalpage+1; $h++) {
			$end++;
			if(isset($_GET['page']) && $h == $_GET['page']) $pages = "<B><font color='red'>".$_GET['page']."</font></b>";
			elseif(isset($_GET['page'])==false && $h == 1)  $pages = "<B><font color='red'>1</font></b>";
			else $pages = $h;
			if(isset($_GET['year'])) $trang .= '&nbsp;<a href="./?id=phim&year='.$_GET['year'].'&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif(isset($_GET['quality'])) $trang .= '&nbsp;<a href="./?id=phim&quality='.$_GET['quality'].'&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif(isset($_GET['gen'])) $trang .= '&nbsp;<a href="./?id=phim&gen='.$_GET['gen'].'&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif($type == 'hot')  $trang .= '&nbsp;<a href="./?id=phim&view=hot&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif($type == 'new')   $trang .= '&nbsp;<a href="./?id=phim&view=new&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif($type == 'update')   $trang .= '&nbsp;<a href="./?id=phim&view=update&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif($type == 'dl')   $trang .= '&nbsp;<a href="./?id=phim&view=dl&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif($type == 'down')   $trang .= '&nbsp;<a href="./?id=phim&view=down&page='.$h.'">['.$pages.']</a>&nbsp;';
			elseif(isset($_GET['search']))   $trang .= '&nbsp;<a href="./?id=phim&search='.$_GET['search'].'&page='.$h.'">['.$pages.']</a>&nbsp;';
			if($end == "30") {
				$trang .=  "<BR>";
				$end = 0;
			}
		}
		if($totalphim == 0) {
			if(isset($_GET['search'])) echo $this->lang['f_notkey'];

			else echo '
			<div class="al-pl">
				<center><br><br>'.$this->lang['soon_up'].'<br><br></center>
			</div>
			';

			return;
		}
		if($type == 'main') {
			echo '
			<!-- List new -->
			<div class="al-pl">
				<div class="title-main">
					<label class="ico-playlist">'.$this->lang['f_update'].'</label>
					<a href="./?id=phim&view=update" class="more">'.$this->lang['f_list'].' »</a>
				</div>
				<ul class="list-al-pl">';
			if(count($files) < 12) $max = count($files);
			elseif(isset($_GET['phim'])) $max = 6;
			else $max = 12;
			$j = 0;
			$info = '';
			for($i = 0; $i <$max;$i++) {
				$j++;
				echo '
				<li>
					<div class="poster" data-tooltip="stickynew'.$i.'">
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'"><img src="http://img.getlinkvn.com/'.$files[$i]['hash'].'.jpg" style="max-height:180px; width:110px"/></a>
					</div>
					<h3>
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'">'.$files[$i]['name'].'</a><p>Lượt down: '.$files[$i]['count'].'<BR>Rate: '.$files[$i]['vote'].'</p>
					</h3>
				</li>';
				if($j == 6)  {
					echo '<br class="clr">';
					$j = 0;
				}
				$info .= $this->showinfo('new'.$i,$files[$i]);
			}
			echo '
					<br class="clr">
				</ul>
				<div class="title-main" align="right">
					<a href="./?id=phim&view=update" class="more">'.$this->lang['more'].' »</a>
				</div>	
				
			</div>
			<!-- End List new -->';

	
			$compare = $this->datecmp('count'); 
			usort($files, $compare);

			echo '
			<!-- List hot -->
			<div class="al-pl">
				<div class="title-main">
					<label class="ico-playlist">'.$this->lang['f_hot'].'</label>
					<a href="./?id=phim&view=dl&page=1" class="more">'.$this->lang['more'].' »</a>
				</div>
				<ul class="list-al-pl">';

			$j = 0;
			$h = 0;
			$year = date('Y') - 1;
			$max = count($files);
			for($i = 0; $i <$max;$i++) {
				if($files[$i]['count'] < $this->count_dl && $files[$i]['year'] < $year) continue;
				$j++;
				$h++;
				echo '
				<li>
					<div class="poster" data-tooltip="stickyhot'.$i.'">
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'"><img src="http://img.getlinkvn.com/'.$files[$i]['hash'].'.jpg" style="max-height:180px; width:110px"/></a>
					</div>
					<h3 id="phim'.$files[$i]['hash'].'">
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'">'.$files[$i]['name'].'</a><p>Lượt down: '.$files[$i]['count'].'<BR>Rate: '.$files[$i]['vote'].'</p>
					</h3>
				</li>';
				if($j == 6)  {
					echo '<br class="clr">';
					$j = 0;
				}
				$info .= $this->showinfo('hot'.$i,$files[$i]);
				if($h==18)break;
			}
			echo '
					<br class="clr">
				</ul>
				<div class="title-main" align="right">
					<a href="./?id=phim&view=dl&page=1" class="more">'.$this->lang['more'].' »</a>
				</div>	
			</div>
			<!-- End List hot -->';
		}
		else {
			echo '
			<!-- List new -->
			<div class="al-pl">
				<div class="title-main">
					<label class="ico-playlist">'.$title.'</label>
				</div>';
				echo $trang;
				echo '<ul class="list-al-pl">';
			$j = 0;
			$info = '';
			for ($i=$page*$phim_per_page; $i < $page*$phim_per_page + $phim_per_page; $i++){
				$j++;
				if(!isset($files[$i])) break;
				echo '
				<li>
					<div class="poster" data-tooltip="stickynew'.$i.'">
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'"><img src="http://img.getlinkvn.com/'.$files[$i]['hash'].'.jpg" style="max-height:180px; width:110px"/></a>
					</div>
					<h3>
						<a href="./?id=phim&phim='.$files[$i]['hash'].'" title="'.$this->lang['downfilm'].'">'.$files[$i]['name'].'</a><p>Lượt down: '.$files[$i]['count'].'<BR>Rate: '.$files[$i]['vote'].'</p>
					</h3>
				</li>';
				if($j == 6)  {
					echo '<br class="clr">';
					$j = 0;
				}
				$info .= $this->showinfo('new'.$i,$files[$i]);
			}
			echo '
					<br class="clr">
				</ul>
				<br>'.$trang.'<br><br>
			</div>
			<!-- End List new -->';
			
		}

		if(isset($info)) echo '
			<!--HTML for the tooltips-->
			<div id="mystickytooltip" class="stickytooltip">
				<div style="padding:5px">
					'.$info.'
				</div>
				<div class="stickystatus"></div>
			</div>
			<!--HTML for the tooltips-->';
	}
}
##################################### End class stream_get ###################################


?>