<?php
/**
 * 紫斑马软件
 * @author afan
 * @link http://www.zibanma.com
 */
class ZibanmaFile{
	public $max_size = -1;
	public $allow_extends = array('gif','jpg','jpeg','bmp');
	public $save_path;					//存储路径，例/upload/date
	public $error = array();
	public $same_replace = true;		//同名替换
	private $_files;						//$_FILES属性
	private $_files_access_path = array();
	private $file_name;
	private $file_size;
	private $file_type;
	private $file_error;
	private $file_tmp_name;
	private $file_extends;
	
	public function __construct($_files='', $dir='upload', $max_size=-1){
		$this->set_files($_files);
		$this->set_save_path($dir);
		$this->set_max_size($max_size);
	}
	
	private function is_size(){
		if($this->max_size != -1 && $this->file_size > $this->max_size){
			$this->error[] = '文件大小超出限制';
			return false;
		}
		return true;
	}
	
	private function is_directory(){
		if($this->save_path){
			$arr = explode('/', $this->save_path);
			$dir = array('/');
			foreach ($arr as $ak){
				$dir[] = $ak;
				if(!is_dir(($path=ZIBANMA_SYS_APP_ROOT.implode('/', $dir)))){
					if(!mkdir($path)){
						$this->error[] = $path.' 目录创建失败';
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
	
	public function is_extends(){
		if(!in_array($this->file_extends, $this->allow_extends)){
			$this->error[] = '上传文件扩展名不被支持';
			return false;
		}
		return true;
	}
	
	public function set_max_size($max_size){
		$this->max_size = $max_size;
	}
	
	public function set_files($_files){
		$this->_files = $_files;
	}
	
	public function set_save_path($dir){
		$this->save_path = $dir.date('/Y/m/d/');
	}
	
	public function is_term(){
		if($this->max_size && is_array($this->allow_extends) && $this->save_path && $this->_files){
			return true;
		}else{
			$this->error[] = '上传条件不满足';
			return false;
		}
	}
	
	public function upload(){
		if($this->is_term()){
			for($i=0; $i<count($this->_files['file']['name']); $i++){
				$extends = pathinfo($this->_files['file']['name'][$i]);
				$this->file_extends = $extends['extension'];
				if($this->is_extends() && $this->is_size() && $this->is_directory()){
					$filepath = $this->save_path.$this->get_random_number(10).'.'.$this->file_extends;
					if(move_uploaded_file($this->_files['file']['tmp_name'][$i], ZIBANMA_SYS_APP_ROOT.$filepath)){
						$this->_files_access_path[] = $filepath;
					}else{
						$this->error[] = '上传文件失败';
					}
				}
			}
		}
	}
	
	/**
	 * @return array
	 */
	public function get_access_path(){
		return $this->_files_access_path;
	}
	
	public function get_error(){
		if($this->error){
			return implode(',', $this->error);
		}
		return null;
	}
	
	/**
	 * @param int $size 位数
	 * @return int
	 */
	public function get_random_number($size){
		$digit = array();
		if($size > 0){
			for($i=0; $i<$size; $i++){
				if($i == 0){
					$digit[] = rand(1, 9);
				}else{
					$digit[] = rand(0, 9);
				}
			}
			return implode('', $digit);
		}
		return 0;
	}
}
?>