<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: class_upload.php 17215 2010-09-26 10:04:38Z monkey $
 */
class qqUploadedFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($target,$filename,$ext){ 
	   global $_G;
        $input = fopen("php://input", "r");
		
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
		if ($realSize != $this->getSize()){            
            return false;
        }
		//ÑéÖ¤ÎÄ¼þMD5
	/*$content='';
		while (!feof($input)) {
		  $content .= fread($input, 8192);
		}*/
       //$file_dir=$_G['setting']['attachdir'].$target.$filename.'.'.$ext;
			$target_attach = fopen($_G['setting']['attachdir'].$target.$filename.'.'.$ext, "w");        
			fseek($temp, 0, SEEK_SET);
			stream_copy_to_stream($temp, $target_attach);
			fclose($target_attach);
		 
		 $md5=md5_file($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
	
		if($md5 && $attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where md5='{$md5}'")){
			$attach['filename']=$this->getName();
			@unlink($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
			return $attach;
		}else{
        	$attach=array(
							'uid'=>$this->uid,
							'filesize'=>$realSize,
							'attachment'=>$target.$filename.'.'.$ext,
							'filetype'=>strtolower($ext),
							'filename' =>$this->getName(),
							'remote'=>0,
							'copys' => 0,
							'md5'=>$md5,
							'dateline' => $_G['timestamp'],
			);
			if($attach['aid']=DB::insert('dzz_attachment',daddslashes($attach),1)){
				return $attach;
			}else{
				return false;
			}
		}
    }
    function getName() {
        return diconv($_GET['qqfile'],'UTF-8');
    }
    function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }   
}

/**
 * Handle file uploads via regular form post (uses the $_FILES array)
 */
class qqUploadedFileForm {  
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($target,$filename,$ext) {
	 global $_G;
		if(!save_to_local($_FILES['qqfile']['tmp_name'], $_G['setting']['attachurl'].$target.$filename.'.'.$ext)){
            return false;
        }
		

        $md5=md5_file($_G['setting']['attachurl'].$target.$filename.'.'.$ext);
	
		if($md5 && $attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where md5='{$md5}'")){
			$attach['filename']=$this->getName();
			@unlink($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
			return $attach;
		}else{
			
        	$attach=array(
							'uid'=>$this->uid,
							'filesize'=>$this->getSize(),
							'attachment'=>$target.$filename.'.'.$ext,
							'filetype'=>strtolower($ext),
							'filename' =>$this->getName(),
							'remote'=>0,
							'copys' => 0,
							'md5'=>$md5,
							'dateline' => $_G['timestamp'],
			);
			if($attach['aid']=DB::insert('dzz_attachment',daddslashes($attach),1)){
				return $attach;
			}else{
				return false;
			}
		}
    }
    function getName() {
		global $_G;
        return $_FILES['qqfile']['name'];
    }
    function getSize() {
        return $_FILES['qqfile']['size'];
    }
}

class qqFileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 10485760;
    private $file;
    private $container;
	private $uid;
	

    function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){   
	 global $_G,$uid;
	   
        $allowedExtensions = array_map("strtolower", $allowedExtensions);
           
        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;
        
       // $this->checkServerSettings();       

        if (isset($_GET['qqfile'])) {
            $this->file = new qqUploadedFileXhr();
        } elseif (isset($_FILES['qqfile'])) {
            $this->file = new qqUploadedFileForm();
        } else {
            $this->file = false; 
        } 
		$this->container=trim($_GET['container']);
		$this->uid=$uid;
    }
    
    private function checkServerSettings(){        
       /* $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
        
        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
			 if( $this->sizeLimit>0){
            	die("{'error':' $postSize increase post_max_size and upload_max_filesize to $size'}");  
			 }
        }      */  
    }
    
    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
    function getPath(){
		global $_G;
		    $subdir = $subdir1 = $subdir2 = '';
			$subdir1 = date('Ym');
			$subdir2 = date('d');
			$subdir = $subdir1.'/'.$subdir2.'/';
			$target1='dzz/'.$subdir.'index.html';
			$target='dzz/'.$subdir;
			$target_attach=$_G['setting']['attachdir'].$target1;
			$targetpath = dirname($target_attach);
			dmkdir($targetpath);
			return $target;
	 }
	  function getFileSize(){
		 return  $this->file->getSize();
	  }
    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($target, $replaceOldFile = FALSE){
		global $_G;	
		$uploadDirectory=$_G['setting']['attachdir'].$target;
        if (!is_writable($uploadDirectory)){
            return array('error' => "Server error. Upload directory isn't writable.");
        }
        
        if (!$this->file){
            return array('error' => 'No files were uploaded.');
        }
        //return array('error'=>$this->tid);
        $size = $this->file->getSize();
        
        if ($size == 0) {
            return array('error' => 'File is empty');
        }
        
        if ($this->sizeLimit && $size > $this->sizeLimit) {
            return array('error' => 'File is too large');
        }
        
        $pathinfo = pathinfo($this->file->getName());
        $filename =date('His').''.strtolower(random(16));
        //$filename = md5(uniqid());
        $ext = $pathinfo['extension'];
        if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
        }
        
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= rand(10, 99);
            }
        }
       
        if ($attach=$this->file->save($target,$filename , $ext)){
			if($data=uploadToattachment($attach,$this->uid,0,$this->container)){
				$data['success']=true;
           		return $data;
			}else{
				 return array('error'=> 'data save error');
			}
        } else {
            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
        
    }    
}?>