<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/
	
class uploadFile {
	//==============================
	//DEFAULT CONFIGURATION
	//==============================
	
	//Upload path
	var $path = "/";
	
	//File max. size
	var $max_size = 512000; //500Kb (in bytes)
	
	//Mime: Accepted files
	var $mime = array();
	
	//Show errors
	var $show_errors = true;
	
	//Overwrite files with same name
	var $overwrite = false;
	
	//File field
	var $field;
	
	//==============================
	//IMAGES CONFIGURATION
	//==============================
	
	//Mime: Images
	var $mime_img = array('image/gif','image/pjpeg','image/jpeg','image/png','image/tiff','image/bmp');
	
	//Max. image size
	var $max_width = 9999999;
	var $max_height = 9999999;
	
	//Resize
	var $resize = false;
	var $resize_width = 100;
	var $resize_height = 100;
	
	//Thumb
	var $createthumb = false;
	var $path_thumb = "/";
	var $thumb_suffix = "_thumb";
	var $thumb_width = 100;
	var $thumb_height = 100;
	
	//Try to fix the chmod if the file/folder is not writable
	var $fixchmod = true;
	
	//==============================
	//DO NOT EDIT
	//==============================
	var $FILES = array();
	var $error;
	var $filename;
	var $thumbname;
	var $selected = true;
	var $jump = false;
	
	//PHP5 Constructor
	function __construct() {
		$this->FILES = array();
		$this->error = "";
	}
	//PHP4 Constructor
	function uploadFile() {
		$this->FILES = array();
		$this->error = "";
	}
	
	//Check if the selected path is writable
	function isWritable() {
		if (!is_writable($this->path)) {
			if ($this->fixchmod) {
				if (!@chmod($this->path,0777)) {
					if (!mem_ftp_chmod($this->path,777)) {
						$this->error = _FOLDER_NOT_WRITABLE_;
					}
				}
			} else {
				$this->error = _FOLDER_NOT_WRITABLE_;
			}
		}
	}
	
	//Check if the file size exceed the limit
	function checkFileSize() {
		if ($this->FILES[$this->field]['size']>$this->max_size) {
			$this->error = _ERROR_TOOBIG_;
		}
	}
	
	//Executed only when the file is an image (mime_img)
	function processImage() {
		if (@in_array($this->FILES[$this->field]['type'],$this->mime_img)) {
			$imagesize = @getimagesize($this->path.$this->filename);
			if ($this->resize) {
				$this->max_width = $this->resize_width;
				$this->max_height = $this->resize_height;
			}
			if ($imagesize[0]>$this->max_width OR $imagesize[1]>$this->max_height) {
				if ($this->resize) {
					//Resize
					//--------------------
					if (extension_loaded('gd')) {
						if ($imagesize[0] > $imagesize[1]) {
							$ratio = ($this->resize_width/$imagesize[0]);
							$new_width = round($imagesize[0]*$ratio);
							$new_height = round($imagesize[1]*$ratio);
						} else {
							$ratio = ($this->resize_height/$imagesize[1]);
							$new_width = round($imagesize[0]*$ratio);
							$new_height = round($imagesize[1]*$ratio);
						}
						$image_p = @imagecreatetruecolor($new_width,$new_height);
						switch ($this->FILES[$this->field]['type']) {
							case "image/gif":
								$image = @imagecreatefromgif($this->path.$this->filename);
							break;
							case "image/png":
								$image = @imagecreatefrompng($this->path.$this->filename);
							break;
							case "image/bmp":
								$image = @imagecreatefrombmp($this->path.$this->filename);
							break;
							default:
							case "image/jpeg":
							case "image/pjpeg":
								$image = @imagecreatefromjpeg($this->path.$this->filename);
							break;
						}
						imagecopyresampled($image_p,$image,0,0,0,0,$new_width,$new_height,$imagesize[0],$imagesize[1]);
						imagejpeg($image_p,$this->path.$this->filename,100);
					} else {
						$this->error = _ERROR_GD_MISSING_.". "._CANNOT_RESIZE_IMAGE_;
						@unlink($this->path.$this->filename);
					}
					//-------------------
				} else {
					$this->error = _ERROR_IMAGE_TOO_LARGE_;
					@unlink($this->path.$this->filename);
				}
			}
			if ($this->createthumb) {
				//Thumb
				//--------------------
				if (extension_loaded('gd')) {
					if ($imagesize[0] > $imagesize[1]) {
						$ratio = ($this->thumb_width/$imagesize[0]);
						$new_width = round($imagesize[0]*$ratio);
						$new_height = round($imagesize[1]*$ratio);
					} else {
						$ratio = ($this->thumb_height/$imagesize[1]);
						$new_width = round($imagesize[0]*$ratio);
						$new_height = round($imagesize[1]*$ratio);
					}
					$image_p = @imagecreatetruecolor($new_width,$new_height);
					switch ($this->FILES[$this->field]['type']) {
						case "image/gif":
							$image = @imagecreatefromgif($this->path.$this->filename);
						break;
						case "image/png":
							$image = @imagecreatefrompng($this->path.$this->filename);
						break;
						case "image/bmp":
							$image = @imagecreatefrombmp($this->path.$this->filename);
						break;
						default:
						case "image/jpeg":
						case "image/pjpeg":
							$image = @imagecreatefromjpeg($this->path.$this->filename);
						break;
					}
					
					$temp_name = $this->file_name($this->filename);
					$temp_ext = $this->file_ext($this->filename);
					$this->thumbname = $temp_name.$this->thumb_suffix.".".$temp_ext;
					
					imagecopyresampled($image_p,$image,0,0,0,0,$new_width,$new_height,$imagesize[0],$imagesize[1]);
					imagejpeg($image_p,$this->path_thumb.$this->thumbname,100);
				} else {
					$this->error = _ERROR_GD_MISSING_.". "._CANNOT_CREATE_THUMBNAIL_;
					@unlink($this->path_thumb.$this->thumbname);
				}
				//-------------------
			}
		}
	}
	
	//Check if the file mime type is accepted
	//If the mime array is empty, accept all files
	function checkMime() {
		if (sizeof($this->mime) AND !@in_array($this->FILES[$this->field]['type'],$this->mime)) {
			$this->error = _ERROR_FILENOTPERMITTED_;
		}
	}
	
	//Return the file mime
	function getMime() {
		return $this->FILES[$this->field]['type'];
	}
	
	//Check if the file has been uploaded or not
	function isUploaded() {
		if (!is_uploaded_file($this->FILES[$this->field]['tmp_name'])) {
			$this->error = _FILE_NOT_UPLOADED_;
		}
	}
	
	//Check if there are selected files
	function fileSelected() {
		if (!isset($this->FILES[$this->field]) OR $this->filename=="") {
			$this->error = _ERROR_NOFILESELECTED_;
			$this->selected = false;
		}
	}
	
	//Generate a random string
	function random_str($length) {
		$key = "";
		$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
		for($i=0;$i<$length;$i++) {
			$key .= $pattern{rand(0,35)};
		}
		return $key;
	}
	
	//Return the file name
	function file_name($name) {
		$ext = strrchr($name, '.');
		if ($ext != false) {
			$name = substr($name, 0, -strlen($ext));
		}
		return $name;
	}
	
	//Return the file extension
	function file_ext($name) {
		return strtolower(end(explode('.',$name)));
	}
	
	//Print errors if $show_errors is set to true (default)
	function print_error() {
		@unlink($this->FILES[$this->field]['tmp_name']);
		if ($this->show_errors) {
		echo "<div style='margin: 2px; padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;'>".$this->error."</div>";
		}
		return false;
	}
	
	//Create a simple file upload form
	function print_form($field,$action) {
		echo "<form name='form_upload' method='post' action='$action' enctype='multipart/form-data'>\n";
			echo "<input type='file' name='$field' size='20'> <input type='submit' name='Submit' value='Upload'>\n";
		echo "</form>";
	}
	
	/*********************************************/
	/* Fonction: ImageCreateFromBMP              */
	/* Author:  DHKold                          */
	/* Contact:  admin@dhkold.com                */
	/* Date:    The 15th of June 2005          */
	/* Version:  2.0B                            */
	/*********************************************/
	function imagecreatefrombmp($filename) {
	   if (! $f1 = fopen($filename,"rb")) return FALSE;
	
	   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
	   if ($FILE['file_type'] != 19778) return FALSE;
	
	   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
					 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
					 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
	   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
	   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
	   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
	   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
	   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
	   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
	   $BMP['decal'] = 4-(4*$BMP['decal']);
	   if ($BMP['decal'] == 4) $BMP['decal'] = 0;
	
	   $PALETTE = array();
	   if ($BMP['colors'] < 16777216)
	   {
	   $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
	   }
	
	   $IMG = fread($f1,$BMP['size_bitmap']);
	   $VIDE = chr(0);
	
	   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
	   $P = 0;
	   $Y = $BMP['height']-1;
	   while ($Y >= 0)
	   {
	   $X=0;
	   while ($X < $BMP['width'])
	   {
		 if ($BMP['bits_per_pixel'] == 24)
		   $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
		 elseif ($BMP['bits_per_pixel'] == 16)
		 { 
		   $COLOR = unpack("n",substr($IMG,$P,2));
		   $COLOR[1] = $PALETTE[$COLOR[1]+1];
		 }
		 elseif ($BMP['bits_per_pixel'] == 8)
		 { 
		   $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
		   $COLOR[1] = $PALETTE[$COLOR[1]+1];
		 }
		 elseif ($BMP['bits_per_pixel'] == 4)
		 {
		   $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
		   if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
		   $COLOR[1] = $PALETTE[$COLOR[1]+1];
		 }
		 elseif ($BMP['bits_per_pixel'] == 1)
		 {
		   $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
		   if    (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
		   elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
		   elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
		   elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
		   elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
		   elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
		   elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
		   elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
		   $COLOR[1] = $PALETTE[$COLOR[1]+1];
		 }
		 else
		   return FALSE;
		 imagesetpixel($res,$X,$Y,$COLOR[1]);
		 $X++;
		 $P += $BMP['bytes_per_pixel'];
	   }
	   $Y--;
	   $P+=$BMP['decal'];
	   }
	
	   fclose($f1);
	
	 return $res;
	}
	
	//Upload the file :\
	function upload() {
		global $_FILES;
		$this->error = "";
		$this->FILES = $_FILES;
		$this->filename = @str_replace("%","_",@urlencode($this->FILES[$this->field]['name']));
		$this->fileSelected();
		if ($this->error=="") { $this->isWritable(); }
		if ($this->error=="") { $this->isUploaded(); }
		if ($this->error=="") { $this->checkFileSize(); }
		if ($this->error=="") { $this->checkMime(); }
		if ($this->error=="") {
			if (file_exists($this->path.$this->filename)) {
				if ($this->overwrite) {
					@unlink($this->path.$this->filename);
				} else {
					$temp_name = $this->file_name($this->filename);
					$temp_ext = $this->file_ext($this->filename);
					$this->filename = $temp_name."_".$this->random_str(5).".".$temp_ext;
				}
			}
		}
		if ($this->error=="") {
			if (@copy($this->FILES[$this->field]['tmp_name'],$this->path.$this->filename)) {
				$this->processImage();
				if ($this->error=="") {
					return $this->filename;
				} else {
					$this->print_error();
				}
			} else {
				$this->error = "File not uploaded";
				$this->print_error();
			}
		} else {
			$this->print_error();
		}
	}
}

?>