<?php
/**
* 文件上传类
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id upload.class.php 1 2008-02-25 14:34 $
*/
!defined('IN_MUDDER') && exit('Access Denied');

class Upload_class {

    var $error;
    var $folder;
    var $userSubdir;
    var $subdir;
    var $max_size;

    // only read
    var $path;
    var $size;
    var $limit_ext;
    var $filename;

    var $upsubdir;

    //private
    var $upfile;

    function __construct($upfile) { //PHP 5
        $this->upfile = $upfile;
        if($this->upfile['error']) {
            $this->error = $this->uploaderror($this->upfile['error']);
            return;
        }
        
        $this->max_size = return_bytes(ini_get('upload_max_filesize')); 
        $this->limit_ext = $this->limit_ext ? $this->limit_ext : array('rar', 'zip', '7z', 'txt') ; 
        $this->size = $this->upfile['size'];
    }

    function Upload_class($upfile) { //PHP 4
        $this->__construct($upfile);
    }

    function setmaxsize($size) {
        $newsize = return_bytes($size.'k');
        $this->max_size = min($this->max_size, $newsize);
    }

    function upload() {

        $upfile = str_replace("\\\\", "\\", $this->upfile['name']);
        $tmpfile = str_replace("\\\\", "\\", $this->upfile['tmp_name']);

        $limit_str = implode('，', $this->limit_ext);

        if(!is_uploaded_file($tmpfile)) {
            $this->error = '无法确认或识别的文件。';
        } elseif(!$this->isUpfile($upfile, $this->limit_ext)) {
            $this->error = '文件格式不正确，只允许上传'.$limit_str;
        } elseif($size > $this->max_size) {
            $this->error = '上传的文件大小不能大于'.$this->max_size.'字节';
        }

        if($this->error) {
            @unlink($tmpfile);
            return false;
        }

        $this->path = MUDDER_ROOT.'./uploads/'.$this->folder;
        if(!@is_dir($this->path)){
            if(!@mkdir($this->path, 0777)) {
                //on linux __  access
                diex("Current picture path '/$folder' have no access!");
            }
        }

        $this->subdir = $this->userSubdir ? date('Y-m', time()) : '';

        $this->path .= $this->userSubdir ? '/'.$this->subdir : '';
        $this->upsubdir = str_replace(MUDDER_ROOT.'./uploads', '', $this->path);

        if(!@is_dir($this->path)){
            if(!@mkdir($this->path, 0777)) {
                //on linux __  access
                diex("Current picture path '/$folder' have no access!");
            }
        }

        $fileinfo = pathinfo($upfile);
        $fileext = strtolower($fileinfo["extension"]); 

        PHP_VERSION < '4.2.0' && srand();
        $rand = rand(1,100);

        $name = $rand.'_'.time().'.' . $fileext;
        unset($rand);

        $sorcuefile = $this->path.'/'.$name;

        if (@move_uploaded_file($tmpfile, $sorcuefile) || @copy($tmpfile, $sorcuefile)) {

            $this->filename = $name;
            $this->deletetmp();
            return true;

        } else {

            $this->error = '文件上传失败，请检查上传权限。';
            return false;

        }

    }

    function deletetmp() {

        return @unlink(str_replace("\\\\", "\\", $this->upfile['tmp_name']));

    }

    function deletefile() {

        return @unlink($this->path.'/'.$this->filename);

    }

}

class Upload_Image_calss extends Upload_class {

    var $userWatermark      = false;
    var $thumb              = array();

    // only read
    var $thumb_filenames    = array();
    var $width              = 0;
    var $height             = 0;
    var $type               = 0;
    var $attr               = '';

    function __construct($upfile) { //PHP 5
        parent::__construct($upfile);
        $this->limit_ext = $this->limit_ext && in_array('zip', $this->limit_ext) ? array('jpeg', 'jpg', 'gif', 'png') : $this->limit_ext;
    }

    function Up_image_calss($upfile) { //PHP 4
        $this->__construct($upfile);
    }

    function upload() {

        $result = parent::upload();

        if($result) {

            $sorcuefile = $this->path.'/'.$this->filename;
            list($this->width, $this->height, $this->type, $this->attr) = @getimagesize($sorcuefile);

            /*
            $thumb = array ( 
                array (
                    'prefix' => 's_', 
                    'width' => '124', 
                    'height' => '94',
                ),
             );
            */

            if($this->thumb) foreach($this->thumb as $key => $val) {
                $savefile = $this->path.'/'.$val['prefix'].$this->filename;
                @$this->create_thumb($sorcuefile, $savefile, $val['width'], $val['height']);

                $this->thumb_filenames[$key]['filename'] = $val['prefix'].$this->filename;
                list($this->thumb_filenames[$key]['width'], $this->thumb_filenames[$key]['height'], $this->thumb_filenames[$key]['type'], $this->thumb_filenames[$key]['attr']) = @getimagesize($savefile);

            }

            $image_size = @filesize($sorcuefile);
            // watermark
            if(($this->userWatermark) && @is_file(MUDDER_ROOT.'./images/watermark.png')) {

                @$this->watermark($sorcuefile, $sorcuefile, MUDDER_ROOT.'./images/watermark.png');

            }
            // array
            $this->filenames = array ( 
                'filename' => $this->filename,
                'width' => $this->width,
                'height' => $this->height,
                'type' => $this->type,
                'attr' => $this->attr,
            );

        }

    }

    //图片加水印
    function watermark($srcimg, $destimg, $waterimg) {
        $simg = $this->imagecreatefromimg($srcimg);
        if(!$simg) return;
        $sw = imagesx($simg); //目标图片宽
        $sh = imagesy($simg); //目标图片高
        imagealphablending($simg, true); //设定混合模式
        $wimg = $this->imagecreatefromimg($waterimg); //读取水印文件
        if(!$wimg) return;
        $ww = imagesx($wimg); //水印图片宽
        $wh = imagesy($wimg); //水印图片高
        $sx = $sw - $ww - 5; //定位
        $sy = $sh - $wh - 10;
        imagecopy($simg, $wimg, $sx, $sy, 0, 0, $ww, $wh);
        $result = imagejpeg($simg, $destimg); //生成
        ImageDestroy($simg);
        ImageDestroy($wimg);
        return $result;
    }

    /*

    创建缩略图 
    按比例，优先使用 new_width 生成，
    new_height 在 $source_img_width > $source_img_height 的情况下 使用

    */
    function create_thumb($source_img_file, $dest_img_file, $new_width, $new_height) {
        $path_parts = pathinfo($source_img_file);
        $ext_name = strtolower($path_parts['extension']);
        $img = null;
        $img = $this->imagecreatefromimg($source_img_file);
        if ($img) {
            $source_img_width = imagesx ($img);
            $source_img_height = imagesy ($img);
            if ($source_img_width > $source_img_height) {
                $new_img_width = $new_width;
                $new_img_height = (int)($source_img_height / $source_img_width * $new_width);
            } else {
                $new_img_height = $new_height;
                $new_img_width = (int)($source_img_width / $source_img_height * $new_height);
            }
            $new_img = ImageCreateTrueColor ($new_img_width , $new_img_height);
            ImageCopyResampled($new_img, $img, 0, 0, 0, 0, $new_img_width, $new_img_height, $source_img_width, $source_img_height);
            ImageJPEG( $new_img, $dest_img_file, 80);
        }
    }

    //返回有效的img资源句柄
    function imagecreatefromimg($img) {
        $path_parts = pathinfo($img);
        $ext_name = strtolower($path_parts['extension']);
        switch($ext_name) {
            case 'gif':
                return function_exists('imagecreatefromgif') ? imagecreatefromgif($img) : false;
                break;
            case 'jpg':
            case 'jpe':
            case 'jpeg':
                return function_exists('imagecreatefromjpeg') ? imagecreatefromjpeg($img) : false;
                break;
            case 'png':
                return function_exists('imagecreatefrompng') ? imagecreatefrompng($img) : false;
                break;
        default:
            return false;
        }
    }

    //判断上传文件的类型
    function isUpfile($filename, $exts) {
        $fileinfo = pathinfo($filename);
        $fileext = strtolower($fileinfo["extension"]);  //文件后缀
        if(!$filename) return false;
        foreach($exts as $ext) {
            if(strtolower($fileext) == strtolower($ext)) return true;
        }
        return false;
    }

    //返回文件上传错误代码解释
    function uploaderror($code) {

        $err_arr = array(
            '1' => '上传的文件过大，超过了文件最大上传限度。',
            '2' => '上传的文件过大，超过了表单提交的上传限度。',
            '3' => '文件上传不完整。',
            '4' => '没有文件被上传。',
            '6' => '找不到临时文件夹。',
            '7' => '文件写入失败。',
        );
        return $err_arr[$code];
    }

}
?>