<?php
/*
usage:
    $options = array(
        'file_field' => 'imgfile',
        'accept_dir' => ABSPATH.'/wp-content/uploads/photo/test',
        'accept_ext' => array('gif','jpeg','jpg','png'),
        'accept_maxsize' => 2097152
    );
    $upload = new es_upload($options);
    print_r($upload->results);
*/

class QCore_Bl_Upload {

    //基本设置参数
    var $options = array();

    //返回的结果集
    /*
        $results['errors'] => 所有的错误信息 array
        $results['message'] => 所有上传成功的信息 array
        $results['newfilename'] => 上传后的文件名 array
    */
    var $results = array();

    /*构造函数*/
    /*
        $args = array(
            "file_field" => '',
            "accept_dir" => '', //最后不要有 "/"
            "accept_maxsize" => '',
            "accept_ext" => array('gif','jpg','jpeg','png')
        );
    */
    function es_upload($args) {
        $this->options = $args;
        $this->check_and_makedir($this->options['accept_dir']);
        $this->do_upload_files();
    }

    /*核心方法*/
    function do_upload_files() {
		if(empty($this->options['file_field'])) {
            $this->results['errors'][] = 'no file(s) input!';
            $this->terminate();
        }

        foreach($_FILES[$this->options['file_field']]['name'] as $key => $current_filename){
            if(empty($current_filename)) continue;
            $current_ext = $this->get_file_ext($current_filename);

            //后缀检查
            if(!in_array($current_ext, $this->options['accept_ext'])) {
                $this->results['error'][] = "Refused to accept the file type <strong>$current_ext</strong>.<em>($current_filename)</em>";
                continue;
            }

            //大小检查
            $current_size = $_FILES[$this->options['file_field']]['size'][$key];
            if($current_size > $this->options['accept_maxsize']){
                $this->results['error'][] = "File size is too large.<em>($current_filename)</em>";                continue;
            }

            //开始搬运
            $options = array('salt'=>$current_filename.$key, 'format'=>'md5', 'ext'=>$current_ext);
            $current_newfilename = $this->make_file_name($options);
            $current_absfilename = $this->options['accept_dir'].'/'.$current_newfilename;
            if(!move_uploaded_file($_FILES[$this->options['file_field']]['tmp_name'][$key], $current_absfilename)) {
                $this->results['error'][] = 'upload file '.$current_filename.' failed.';
                continue;
            }else {
                $this->results['message'][] = "file <stong>$current_filename</strong> upload successfull!";
                $this->results['newfilename'][] = $current_newfilename;
                $this->results['file_field_pos'][] = $key;  //便于文件名与其他信息对应
            }
        }
        $this->terminate();
    }

    /*检查路径安全性*/
    //不存在则创建路径，并生成一个空的index.html文件
    function check_and_makedir($absdir, $mode=0777) {
        if(!file_exists($absdir)) {
            if(!@mkdir($absdir, $mode)) {
                return false;
            }else {
                $this->make_file($absdir.'/index.html', '');
                return true;
            }
        }
        return true;
    }

    /*创建文件*/
    function make_file($absfile, $content){
        if (is_file($absfile)){
            @unlink ($absfile);
        }
        $handle = fopen ($absfile, 'w');
        if (!is_writable ($absfile)){
            return false;
        }
        if (!fwrite ($handle, $content)){
            return false;
        }
        fclose ($handle);
        return true;
    }

    /*格式化文件大小*/
	function format_file_size($size, $format='M') {
		switch($format) {
			case 'M': {
				return $size/1048576;
				break;
			}
			case 'B': {
				return $size;
				break;
			}
		}
	}

    /*获取文件扩展名*/
	function get_file_ext($filename, $dot=false){
		$ext = explode(".", $filename);
		$ext = $ext[count($ext) - 1];
        if($dot) $ext = '.'.$ext;
		return strtolower($ext);
	}

    /*产生文件名*/
    /*
        $args = array(
            format => 'md5',    //time
            salt => '',
            prefix => '',
            suffix => '',
            length => 0 //between 1 and 32
        );
    */
	function make_file_name($args) {
        $args['length'] = (int) $args['length'];
		switch($args['format']) {
			case 'md5': {
				$name_string = md5(microtime().$args['salt'].rand(1,99));
				break;
			}
			case 'time': {
                $name_string = date($args['dateformat'],time());
				break;
			}
		}
        if(!empty($args['length'])) {
            $name_string = substr($name_string,0,$length);
        }
        if(!empty($args['ext'])) {
            $newfilename = $args['prefix'].$name_string.$args['suffix'].'.'.$args['ext'];
        }else {
            $newfilename = $args['prefix'].$name_string.$args['suffix'];
        }
        return $newfilename;
	}

    /*终止执行并返回现有结果*/
    function terminate() {
        return $this->results;
    }

    //end class
}
?>