<?php


class mfUpload_TmpFile {
	private $_file;
	public $filename;
	public $error;
	public $tmp_name;
	
	public $errormessage;



	public function __construct($_file) {
		if(count($_FILES[$_file])) {
			$this->_file=$_FILES[$_file];
		} else {
			$this->errormessage="Upload not found";
			return false;
		}

		$this->filename=$this->_file['name'];
		$this->error=$this->_file['error'];
		$this->tmp_name=$this->_file['tmp_name'];
		
		if(!file_exists($this->tmp_name)) {
			$this->errormessage="An error occured during file upload. Please try again.";
			return false;
		}

		return true;
	}

	public function move_upload($path) {
		if($path && $this->tmp_name) {
			if(move_uploaded_file($this->tmp_name, $path)) {
				return true;
			} else {
				$this->errormessage="Cannot move uploaded file to $path.";
			}
		}
		return false;
	}

	public function getFileSize() {
		$stat=stat($this->tmp_name);
		if(is_array($stat) && count($stat)) {
			return $stat[7];
		}
		return 0;
	}
	
	public function getFilename() {
		$filename=$this->filename;

		// assume filename contains whole path on users machine and cut it.
		if(preg_match('#([^/\\\]+$)#',$filename,$match)) {
			$filename=$match[1];
		} else {
			$this->errormessage="No file selected.";
			return false; // if there is no filename
		}
		
		// remove potentially dangerous characters
		while(strstr($filename,'..')) {
			$filename=str_replace('..',".",$filename);
		}
		
		if(!strlen($filename)) {
			$this->errormessage="No file selected.";
			return false;
		}
		
		$filename=preg_replace('/[^a-z0-9$()+%äöüß._-]/i', '_', $filename);

		$parts=explode(".",$filename);
		$ext=strtolower(array_pop($parts));

		if(!preg_match('/^'.MFUPLOAD_ALLOWED_EXTENSIONS.'$/i',$ext)) {
			$this->errormessage="File type not allowed. Supported file types are ".ALLOWED_EXTENSIONS_STR;
			return false;
		}
		
		return $filename;
	}

}
