<?
class glo_upload
{
	function get_upload_dir($file_arr,$type)
	{
		if(!$file_arr['name']){
			return false;
		}
		$upload_dir	=	UPLOAD_DIR.$type;	
		if(!is_dir($upload_dir)){
				mkdir($upload_dir);
				chmod($upload_dir,0777);
		}	
		$top_n	=	strtolower(substr(base64_encode($file_arr['name']),0,1));
		
		$upload_dir	=	$upload_dir.'/'.$top_n;	
		if(!is_dir($upload_dir)){
			mkdir($upload_dir);
			chmod($upload_dir,0777);
		}	
			return 	$upload_dir;
	}

	function upload_file($file_arr,$type,$name='')
	{
		if(!$file_arr['name']){
			return false;
		}
		if($file_arr['error']){
				return false;	
		}
		if(!$name){
				$name			=	get_basename($file_arr['name']);
		}	
		
		$upload_dir		=	$this->get_upload_dir($file_arr,$type);

		$upload_dir		.=	'/'.$name;	
		if($this->copy_upload_file($file_arr,$upload_dir)){
				$upload_dir	=	preg_replace('|^'.preg_filtrate(UPLOAD_DIR).'|si','',$upload_dir);
				return $upload_dir;
		}else{
			return false;
		}
	}

	function copy_upload_file($file_arr,$upload_dir)
	{
		 	if(copy($file_arr['tmp_name'],$upload_dir)){
				@unlink($file_arr['tmp_name']);
				return true;
			}else{
				return false;
			}
	}

	function copy_distance_link($url,$type,$name='')
	{
		if(!$name){
			$url_arr		=	explode('/',$url);		
			$count		=	count($url_arr);
			$name			=	rawurldecode($url_arr[$count-1]);
		}
		$upload_dir		=	$this->get_upload_dir(array('name'=>$name),$type);
		if(file_exists($upload_dir.'/'.get_basename($name))){
			$upload_dir	.=	get_basename($name.'_'.time());
		}else{
			$upload_dir	.=	'/'.get_basename($name);
		}
		if(@copy($url,$upload_dir)){
			return  preg_replace('|^'.preg_filtrate(UPLOAD_DIR).'|si','',$upload_dir);
		}else{
			return false;
		}

	}

}	
