<?php
@set_time_limit(0);
//ignore_user_abort(true);
$url = $_REQUEST['url'];
$appoid = $_REQUEST['appoid'];
$appname = $_REQUEST['apkname'];
$channel = $_REQUEST['channel'];
$url = urldecode($url);

$type = $_REQUEST['update'];

if(!empty($url) && (strpos($url, "http://apkdownload.appmaker.cc") === 0))
{
	if ($type=="1"){
	
		$androidurl = updateplugin($url);
	
	}else{
		$androidurl = downloadurl($url,'./android/',$appname,$channel);
		if($androidurl)
		{
			$arr = array(
				'returncode' => '200'
			);
			echo json_encode($arr);
		}
		
		$feedbackurl = 'http://i.appmaker.cc:9090/GameServer/uptruedownurl!uptruedownurl.action?channel='.$channel.'&appoid='.$appoid;
		fgets(fopen($feedbackurl,"r"));
	}
}
else {
	$arr = array(
			'returncode' => '100'
	);
	echo json_encode($arr);
}
function mkrdirUrl($dir){
	return is_dir($dir) or (mkrdirUrl(dirname($dir)) and mkdir($dir, 0777,true));
}
function downloadurl($android,$destination_folder,$destination_name,$channel)
{
	mkrdirUrl($destination_folder);
	$arr = get_headers($android,true);	
	
	$newfname = $destination_folder . $destination_name ;
	$file = @fopen ($android, "rb");

	if ($file) {
		$newf = @fopen ($newfname, "wb");
		
		if ($newf)
			try
			{
				while(!feof($file)) {
					fwrite($newf, fread($file,$arr['Content-Length']),$arr['Content-Length']);
				};
				
			}
			catch (Exception $e)
			{
				return  false;
			}
	
	}
	if ($file) {
		fclose($file);
	}
	if ($newf) {
		fclose($newf);
	}
	
	
	
	if ($channel=="default"){
	
		if(file_exists($destination_folder."appmaker.apk")){
			unlink($destination_folder."appmaker.apk");
		}
		
		
		copy($destination_folder.$destination_name,$destination_folder."appmaker.apk");
	}
	
	return  true;
	
}

function updateplugin($android)
{
	$file = @fopen ($android, "r");
	
	if ($file) {
		try
		{
			while($filename = fgets($file)) {
			    if ((strpos($filename, "#") === 0)){
					continue;
				}
				$arrf = explode("|",$filename);
				downloadurl($arrf[0],$arrf[1],$arrf[2],"");
			};
		}
		catch (Exception $e)
		{
			return  false;
		}
	}
	if ($file) {
		fclose($file);
	}

	return  true;
	
}



?>
