<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
// 
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
// 
// 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, or (at your option) 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 program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

class File {
		
	var $max_width        = false;
	var $max_height       = false;
	var $save_name        = false;
	var $md5_name         = false;
	var $mime_type        = false;
	var $file             = false;
	var $db               = false;
	var $core_config_file = false;
	var $red              = 255;
	var $blue             = 255;
	var $green            = 255;
	var $user_id          = 0;

	// File --------------------------------------------------------------
	// the constructor
	// Sebastian Oblom 22th September 2006
	// 	
	function File($db, $core_config_file) {
		$this->db = $db;
		$this->core_config_file = $core_config_file;
	}//EO File
	
	
		
	// setFile -----------------------------------------------------------
	// sets the file
	// Sebastian Oblom 22th September 2006
	//
	function setFile($file) {
		$this->file = $file;
	}//EO setFile



	// getFile -----------------------------------------------------------
	// returns the file
	// Sebastian Oblom 22th September 2006
	//
	function getFile() {
		return $this->file;
	}//EO getFile



	// setSaveName -------------------------------------------------------
	// sets save-name to file
	// Sebastian Oblom 22th September 2006
	//
	function setSaveName($save_name) {
		$this->save_name = $save_name;
	}//EO setSaveName



	// getSaveName -------------------------------------------------------
	// returns the save-name
	// Sebastian Oblom 22th September 2006
	//
	function getSaveName() {
		return $this->save_name;
	}//EO getSaveName
	
	
	
	// scale -------------------------------------------------------------
	// scales an image to new maximum dimensions during upload
	// Sebastian Oblom 22th September 2006
	//	
	function scale($max_x = null, $max_y = null) {
		$this->max_width = $max_x;
		$this->max_height = $max_y;
	}//EO scale
	
	
	
	// setBgColor --------------------------------------------------------
	// sets background-color to image
	// Sebastian Oblom 22th September 2006
	//
	function setBgColor($red, $green, $blue) {
		$this->red   = $red;
		$this->green = $green;
		$this->blue  = $blue;
	}//EO setBgColor


	
	// uploadFile --------------------------------------------------------
	// moves the file physical and inserts a record in the database
	// Sebastian Oblom 22th September 2006
	//
	function uploadFile() {
		$this->moveFile();
		
		if (empty($GLOBALS['am_error_log'])) {
			$this->insertRecord();
		}
	}//EO uploadFile
	
	
	
	// insertRecord ------------------------------------------------------
	// inserts a record in the database
	// Sebastian Oblom 22th September 2006, edited 26th November 2006
	//
	function insertRecord() {
		$rec                         = array();
		$rec                         = $this->file;
		$rec['file_type']            = $this->mime_type;
		$rec['file_size']            = $this->file['size'];
		$rec['file_save_name']       = $this->save_name;
		$rec['file_md5_name']        = $this->md5_name;
		$rec['file_stamp']           = $this->stamp;
		$rec['module_id']            = $this->module_id;
		$rec['file_user_id']         = $this->user_id;
		$rec['file_create_datetime'] = time();
		
		if (isset($this->item_id) && !empty($this->item_id)) {
			$rec['item_id'] = $this->item_id;
		}
		else {
			$rec['item_id'] = 'null';
		}
			
		$table = $this->db->prefix . "_file";
			
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
			$this->file_id = $this->db->Insert_ID();
		}
		else {
			$error_info = "function=insertRecord class=File.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}						
	}//EO insertRecord
	
	
	// updateRecord ------------------------------------------------------------
	// updates a record in the database
	// Sebastian Oblom, 22th September 2006
	//
	function updateRecord($md5_name) {
		
		$query = "
			SELECT file_id, module_id, file_type, file_size, file_save_name, 
			file_md5_name, file_stamp, file_user_id, file_create_datetime
			FROM " . $this->db->prefix . "_file 
			WHERE file_md5_name LIKE '" . $md5_name . "'"
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
	
			$rec = array();
			
			$rec['file_type']            = $result->fields['file_type'];
			$rec['file_save_name']       = $this->save_name;
			$rec['file_md5_name']        = $result->fields['file_md5_name'];
			$rec['file_stamp']           = $result->fields['file_stamp'];
			$rec['module_id']            = $result->fields['module_id'];
			$rec['file_user_id']         = $result->fields['file_user_id'];
			$rec['file_create_datetime'] = $result->fields['file_create_datetime'];
			
			$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			if (isset($result->fields)) {
				$this->file_id = $this->db->Insert_ID();
			}
			else {
				$error_info = "function=updateRecord class=File.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array('db_error', $error_info);
			}
		}
		else {
			$error_info = "function=updateRecord class=File.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO updateRecord


	
	// deleteFile ---------------------------------------------------------
	// deletes the record in the database and removes the physical file
	// Sebastian Oblom 22th September 2006, edited 26th November 2006
	//
	function deleteFile($md5_name) {
		
		$directory = $this->core_config_file['dir'];
		if (isset($this->core_config_module[$this->module_id])) {
			$directory .= $this->core_config_module[$this->module_id]['prefix'] . "/";
		}
		else {
			$directory .= "core/";
		}
		
		if (!is_file($directory . $md5_name)) {
			$GLOBALS['am_error_log'][] = array('file_fail_remove');
		}
			
		if (!@unlink($directory . $md5_name)) {
			$GLOBALS['am_error_log'][] = array('file_fail_remove');
		}
		
		foreach($this->core_config_file['image']['thumb'] as $t) {
			if (is_file($directory . "/thumbs/" . $md5_name . $t['suffix'])) {
				unlink($directory . "/thumbs/" . $md5_name . $t['suffix']);
			}
		}
		
		if (empty($GLOBALS['am_error_log'])) {
			$query = "
				DELETE from " . $this->db->prefix . "_file
				WHERE file_md5_name=" . $this->db->qstr($md5_name, get_magic_quotes_gpc()) . " AND "
			;
		
			if (isset($this->module_id, $this->item_id)) {
				$query .= "module_id=" . $this->module_id . " AND item_id=" . $this->item_id . " AND ";
			}
			else {
				$query .= "file_user_id=" . $this->user_id . " AND ";
			}
		
			$query .= "1=1";

			$result = $this->db->Execute($query);

			if (empty($result)) {
				$error_info = "function=deleteFile class=File.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array('db_error', $error_info);
			}
		}
	}//EO deleteFile


	
	// moveFile -----------------------------------------------------------
	// moves the physical file to the directory
	// Sebastian Oblom 22th September 2006, edited 26th November 2006
	//
	function moveFile($destination = null) {
		if (!isset($destination)) {
			$destination = $this->core_config_file['dir'];
			if (isset($this->core_config_module[$this->module_id])) {
				$destination .= $this->core_config_module[$this->module_id]['prefix'] . "/";
			}
			else {
				$destination .= "core/";
			}
		}
		
		if (empty($this->save_name)) {
			$this->save_name = $this->file['name'];
		}
		
		$stamp          = microtime();
		$this->stamp    = $stamp;
		$this->md5_name = md5($stamp . $this->save_name);
		
		if (!is_dir($destination)) {
			mkdir($destination);
		}
		
		if (!is_dir($destination . "thumbs/")) {
			mkdir($destination . "thumbs/");
		}
		
		if (@move_uploaded_file($this->file['tmp_name'], $destination . $this->md5_name)) {
			if ($this->mime_type == "image/gif" || $this->mime_type == "image/jpeg" || $this->mime_type == "image/png") {
				if ($this->max_width || $this->max_height) {
					
					$size       = getimagesize($destination . $this->md5_name);
					$width      = $size[0];
					$height     = $size[1];
					
					if ($height >= $this->max_height && $this->max_height != 0) {
						$new_height = $this->max_height;
						$new_width  = $width * ($new_height / $height);
					}
					
					if ($width >= $this->max_width && $this->max_width  != 0) {
						$new_width  = $this->max_width;
						$new_height = $height * ($new_width / $width);
		  			}
			  		
			  		if (isset($new_width)) {
						$type            = explode('/', $this->mime_type);
				  		$imagecreatefrom = 'imagecreatefrom' . $type[1];
				  		$image           = 'image' . $type[1];
				  		
				  		$new_image   = $imagecreatefrom($destination . $this->md5_name);
						$blank_image = ImageCreateTrueColor($new_width, $new_height);
						$col         = imagecolorallocate($blank_image, $this->red, $this->green, $this->blue);
						imagefilledrectangle($blank_image, 0, 0, $new_width, $new_height, $col);
						$newimage    = ImageCopyResampled($blank_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						$image($blank_image, $destination . $this->md5_name);
					}
				}
			}
		}
		else {
			$GLOBALS['am_error_log'][] = array('file_no_write_error');
		}
	}//EO moveFile
	
	
	// createThumbNails ---------------------------------------------------------------
	// creates a set of thumbnails defined in $this->thumbs
	// Sebastian Oblom, 29th September 2006
	//
	function createThumbNails() {

		$destination = $this->core_config_file['dir'];
		if (isset($this->core_config_module[$this->module_id])) {
			$destination .= $this->core_config_module[$this->module_id]['prefix'] . "/";
		}
		else {
			$destination .= "core/";
		}
		
		if ($this->mime_type == "image/gif" || $this->mime_type == "image/jpeg" || $this->mime_type == "image/png") {
			
			if (!empty($this->core_config_file['image']['thumb'])) {
					
				$size   = getimagesize($destination . $this->md5_name);
				$width  = $size[0];
				$height = $size[1];
				
				foreach($this->core_config_file['image']['thumb'] as $t) {
					
					$new_height = $height;
	  				$new_width  = $width;
	  				
					if ($height >= $t['height']) {
						$new_height = $t['height'];
						$new_width  = $width * ($new_height / $height);
					}	
					
					if ($width >= $t['width']) {
						$new_width  = $t['width'];
						$new_height = $height * ($new_width / $width);
	  				}
	  				
					if ($this->mime_type == 'image/png' || $this->mime_type == 'image/gif' || $this->mime_type == 'image/jpeg') {
						$type             = explode('/', $this->mime_type);
			  			$_imagecreatefrom = 'imagecreatefrom' . $type[1];
			  			$_image           = 'image' . $type[1];
			  		
			  			$new_image   = $_imagecreatefrom($destination . $this->md5_name);
						$blank_image = ImageCreateTrueColor($new_width, $new_height);
						$col         = imagecolorallocate($blank_image, $this->red, $this->green, $this->blue);
						imagefilledrectangle($blank_image, 0, 0, $new_width, $new_height, $col);
						$newimage    = ImageCopyResampled($blank_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						$_image($blank_image, $destination . "thumbs/" . $this->md5_name . $t['suffix']);
					}
				}
			}
		}
	}//EO createThumbNails
	
	
	
	// checkMimeType -------------------------------------------------------
	// checks if mime-type is ok
	// Sebastian Oblom 22th September 2006
	//
	function checkMimeType() {
	
		if (function_exists('finfo_open')) { // not tested but should work fine
			$resource = finfo_open(FILEINFO_MIME);
			$this->mime_type = finfo_file($resource, $this->file['tmp_name']);
			finfo_colse($resource);
		}
		elseif(function_exists('mime_content_type')) {
			$this->mime_type = mime_content_type($this->file['tmp_name']);
		}
		else {
			$this->mime_type = $this->file['type'];
		}
		
		if (!empty($this->core_config_file['browser_path'])) {
		    foreach($this->core_config_file['browser_path'] as $i):
				if ($i['from'] == $this->mime_type) {
				    $this->mime_type= $i['to'];
				}
			endforeach;
		}
		
		foreach($this->core_config_file['mime'] as $mime) {
			if ($mime['mime'] == $this->mime_type) {
				return true;
			}
		}
		return false;
	}//EO checkMimeType
		

	// selFiles ------------------------------------------------------------
	// returns all files from a user, or a specific file
	// Sebastian Oblom, 22th September 2006, edited 26th November 2006
	//
	function selFiles($images = null, $thumb_extension = null, $md5_name = null, $id = null) {
		$files = array();
		
		$query = "
			SELECT f.file_id, f.file_type, f.file_size, f.file_save_name, f.file_md5_name,
			f.file_stamp, f.file_user_id, f.file_create_datetime, f.item_id
			FROM " . $this->db->prefix . "_file f
			WHERE "
		;
	
		if (isset($images)) {
			$query .= "(f.file_type='image/gif' OR f.file_type='image/jpeg' OR f.file_type='image/png') AND ";
		}
		else {
			$query .= "(f.file_type!='image/gif' AND f.file_type!='image/jpeg' AND f.file_type!='image/png') AND ";
		}
	
		if (isset($md5_name)) {
			$query .= "f.file_md5_name LIKE '" . $md5_name . "' AND ";
		}
		
		if (isset($id)) {
			$query .= "f.file_id=" . $id . " AND ";
		}
		
		if (isset($this->module_id)) {
			$query .= "f.module_id= " . $this->module_id . " AND ";
		}
		
		if (isset($this->item_id)) {
			$query .= "f.item_id=" . $this->item_id . " AND ";
		}
		else {
			$query .= "f.file_user_id = ".$this->user_id." AND ";
		}
			
		$query .= "1=1";
		$query .= " ORDER BY f.file_create_datetime DESC";
 			//echo $query; exit;
		$result = $this->db->Execute($query);
			
		if (isset($result->fields)) {
			while(!$result->EOF) {
				
				$temp = $result->fields;
// 				$temp['directory'] = $this->directory . "/";
				$this->setThumbnails($temp['file_md5_name']); //...
				
				if (isset($thumb_extension)) {
					
					if (true/* check it if is a file here */) {
						$temp['file_md5_name_view'] = $this->module_id . '-' . $temp['file_md5_name'] . '-' . $thumb_extension;
					}
					else {
						$temp['file_md5_name_view'] = $this->module_id . '-' . $this->no_image;
					}
					$files[] = $temp;
				}
				else {
					$temp['file_md5_name_view'] = $this->module_id . '-' . $temp['file_md5_name'] . '-~-' . $temp['file_type'];
					$files[] = $temp;
				}
				$result->moveNext();
			}
			$result->Close();
		}
		return $files;
	}//EO selFiles
	
	
	function setThumbnails($md5_name) {

		$this->thumbnails = array();

/*		foreach($this->core_config_file['image']['thumb'] as $i) {
			if (is_file($this->core_config_file['dir'] . $this->directory . "/thumbs/" . $md5_name . $i['suffix']))
				$this->thumbnails[] = $i;	
		}*/
	}
		

	// selFile ------------------------------------------------------------
	// returns a file from a user, or a specific file
	// Tom Calthrop 29th September 2006
	//
	function selFile($file_id, $thumb_extension = null) {
		
		$query = "
			SELECT f.file_id, f.file_type, f.file_size, f.file_save_name, f.file_md5_name,
			f.file_stamp, f.file_user_id, f.file_create_datetime, f.item_id
			FROM " . $this->db->prefix . "_file f
			WHERE f.file_id=" . $file_id
		;		
		
		$result = $this->db->Execute($query);
			
		if (!empty($result->fields)) {
			$temp = $result->fields;

			$directory = $this->core_config_file['dir'];
			if (isset($this->core_config_module[$this->module_id])) {
				$directory .= $this->core_config_module[$this->module_id]['prefix'] . "/";
			}
			else {
				$directory .= "core/";
			}

			if (isset($thumb_extension)) {
				$directory .= "thumbs/"; 
				$file_name = $temp['file_md5_name'] . $thumb_extension;
				
				if (is_file($directory . $file_name)) {
					$temp['file_md5_name_view'] = $this->module_id . '-' . $temp['file_md5_name'] . '-' . $thumb_extension;
				}
				else {
					$temp['file_md5_name_view'] = $this->module_id . '-' . $this->no_image;
				}
			}
			else {
				$temp['file_md5_name_view'] = $this->module_id . '-' . $temp['file_md5_name'];
				
			}
			
			$temp['file_md5_name_view'] .= "-" . $temp['file_type'];
			
			return $temp;	
		}
		else {
			return array('file_md5_name_view' => $this->module_id . '-' . $this->no_image);
		}
	}//EO selFile
	
	
	// getAllocation -------------------------------------------------------
	// return the allocation from the allocation-table
	// Sebastian Öblom, November 2006
	//
	function getAllocation() {
	
		$allocation = array();
		$allocation['allocation'] = 0;
		$allocation['allocation_used'] = 0;

		$query = "
			SELECT f.file_allocation
			FROM " . $this->db->prefix . "_file_allocation f
			WHERE "
		;
		
		if (isset($this->item_id, $this->module_id)) {
			$query .= "module_id=" . $this->module_id . " AND item_id=" . $this->item_id . " AND ";
		}
		else if (isset($this->user_id)) {
			$query .= "item_id=" . $this->user_id . " AND ";
		}
		
		if (isset($this->item_type)) {
			$query .= "item_type=" . $this->item_type . " AND ";
		}
		
		
		$query .= "1=1";

		$result = $this->db->Execute($query);
			
		if (isset($result->fields)) {
			$allocation['allocation'] = $result->fields['file_allocation'];
			$result->Close();
		}
		
		$query = "
			SELECT SUM(f.file_size) AS allocation_used
			FROM " . $this->db->prefix . "_file f
			WHERE "
		;
		
		if (isset($this->item_id, $this->module_id)) {
			$query .= "f.module_id=" . $this->module_id . " AND f.item_id=" . $this->item_id . " AND ";
		}
		
		if (isset($this->user_id)) {
			$query .= "f.file_user_id=" . $this->user_id . " AND ";
		}
		
		$query .= "1=1";
		
		$result = $this->db->Execute($query);
			
		if (isset($result->fields)) {
			$allocation['allocation_used'] = $result->fields['allocation_used'];
			$result->Close();
		}
		
		return $allocation;

	}//EO getAllocation
	
	
	// checkAllocation ------------------------------------------------------
	// returns the amount of avilable allocated disk space for a user
	// when we do setup.php we allow an upload of a identity picture
	// we check this file size against the standard file allocation
	//
	function checkAllocation() {
		if (isset($this->file_allocation)) { // we are setting up the user
			$this->allocation_available = $this->file_allocation;
			
			return $this->file['size'] <= $this->file_allocation;
		
		}
		else {
			$allocation = $this->getAllocation();
		
			$this->allocation_available = $allocation['allocation'] - $allocation['allocation_used'];
		
			return $this->file['size'] + $allocation['allocation_used'] <= $allocation['allocation'];
		}

	} //EO checkAllocation

	
	
	
	
	// isOk ------------------------------------------------------------------
	// checks if the file is ok to upload
	// Sebastian Oblom 22th September 2006
	//
	function isOk() {
		if (isset($this->file['error'])) {
			if ($this->file['error'] == UPLOAD_ERR_INI_SIZE) {
				$GLOBALS['am_error_log'][] = array('file_ini_error');
			}
			elseif ($this->file['error'] == UPLOAD_ERR_FORM_SIZE) {
				$GLOBALS['am_error_log'][] = array('file_form_error');
			}
			elseif ($this->file['error'] == UPLOAD_ERR_PARTIAL) {
				$GLOBALS['am_error_log'][] = array('file_partial_error');
			}
			elseif ($this->file['error'] == UPLOAD_ERR_NO_FILE) {
				$GLOBALS['am_error_log'][] = array('file_no_image_error');
			}
			elseif ($this->file['error'] == UPLOAD_ERR_CANT_WRITE) {
				$GLOBALS['am_error_log'][] = array('file_no_write_error');
			}
		}
		
		if (!$this->checkAllocation()) {
			$GLOBALS['am_error_log'][] = array('file_allocation_error', ($this->allocation_available/1000) . "KB");
		}
		
		if (!$this->checkMimeType()) {
			$GLOBALS['am_error_log'][] = array('file_mime_error');
		}
		return empty($GLOBALS['am_error_log']);
	}//EO isOk
}

?>