<?php
if(!defined('R_P')) exit('Access Denied');
require_once(R_P . '/include/inc.editor.php');
class qupload{
	//允许上传的最大文件,KB
	var $max_size = 10240;
	//允许的文件类型
	var $allow_ext = array();
	//是否保持原文件名不变
	var $keep_name = false;
	//文件存放目录
	var $target_dir = '';
	function qupload($dir, $ext, $max){
		$this->target_dir = $dir;
		$this->allow_ext = $ext;
		$this->max_size = $max;
		if(!is_dir(R_P .'/'. $dir)) qbase::createdir(R_P . "/" . $dir);
	}

	function setKeepName($status = false){
		$this->keep_name = $status;
	}

	/*
		return error > 0
		1 => not-found
		2 => invalid-upload
		3 => size-too-big
		4 => type-not-match
		5 => move-error
	*/

	function move($field = 'Filedata'){
		$_FILES[$field]['tmp_name'] = str_replace("\\\\","\\",$_FILES[$field]['tmp_name']);
		if (!is_uploaded_file($_FILES[$field]['tmp_name'])){
			return array(1);
		}
		if (!isset($_FILES[$field]) || !is_uploaded_file($_FILES[$field]["tmp_name"]) || $_FILES[$field]["error"] != 0) {
			return array(2);
		} 
		if ($this->max_size < $_FILES[$field]["size"] / 1024) {
			return array(3);
		} 
		$extname = getExt($_FILES[$field]["name"]);
		if (!in_array(strtolower($extname), $this->allow_ext)) {
			return array(4);
		} 

		$val = $_FILES[$field]["name"];
		if($this->keep_name) $filename = $this->get_name($val);
		else $filename = GetRndFileName($extname);
		$save_name = $this->target_dir . $filename;
		$local_name = R_P .'/'. $save_name;
		if(is_file($local_name)){
			@unlink($local_name);
			clearstatcache();
		}

		if (!@move_uploaded_file($_FILES[$field]['tmp_name'], $local_name) && !copy($_FILES[$field]['tmp_name'], $local_name)) return array(5);
		return array(0, $save_name);
	}

	function get_name($name){
		global $_SET;
		return qbase::iconvs($name, $_SET['def_charset'], 'utf-8');
	}
}
?>