<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// Copyright (C) 2003, 2005 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------
// tom calthrop - file management - tom@barnraiser.org


class File {
	// CLASS FUNCTIONS
	// File
	// checkFile
	// getFiles
	// getAllocation
	// checkAllocation
	// checkFileMime
	// getSuffix
	// insertFileRecord
	// moveFile
	// makeImageThumbnails
	// getFileRecord
	// deleteFile
	// deleteFileRecord
	// updateFileRecord
	// updateDefaultFile
	
	
	
	// File --------------------------------------------------------------------
	// the constuctor
	// tom calthrop - 6th December 2004
	//
	function File($db, $section_id, $arr_file, $arr_dir){
		$this->db = $db;
		$this->section_id = $section_id;
		$this->arr_file = $arr_file;
		$this->arr_dir = $arr_dir;
	} // EO constructor
	
	
	
	// checkFile ---------------------------------------------------------------
	// validates file using checkFileMime and checkAllocation
	// tom calthrop - 6th December 2004
	//
	function checkFile() {
		if(!$this->checkFileMime($this->arr_file_upload['type'])) {
			$GLOBALS['am_error_log'][] = array(17, null, null);
		}
		
		if(!$this->checkAllocation()) {
			$GLOBALS['am_error_log'][] = array(29, null, null);
		}
		
		if (empty($GLOBALS['am_error_log'])) {
		    return true;
		}
	}// checkFile
	
	
	
	// getFiles ---------------------------------------------------------------
	// returns files selected from DB
	// tom calthrop - 6th December 2004
	//
	function getFiles () {
		$query = "
			SELECT file_id, file_name, file_suffix, file_title, 
			file_create_datetime, file_size, user_id 
			FROM " . $this->db->prefix . "_file 
			WHERE 
			section_id=" . $this->section_id . " and "
		;

		if (isset($this->section_item_id)) {
		    $query .="section_item_id=" . $this->section_item_id . " and ";
		}
		
		if (isset($this->type_ids)) {
			$query .="(";
			foreach($this->type_ids as $key => $i):
				$query .="file_suffix='" . $i . "'";
				if (count($this->type_ids) > $key+1) {
				    $query .=" or ";
				}
			endforeach;
			$query .=") and ";
		}
		
		$query .="1=1 ";
		 
		if (isset($this->orderby)) {
			$query .="order by " . $this->orderby;
		} else {
			$query .="order by file_title";
		}
		
		$result = $this->db->Execute($query);

		//setup directory paths and thumb name suffixes
		if (isset($this->thumb)) {
			$path = $this->path . "/" . $this->arr_file['image']['thumb_directory'] . "/";
		    $thumb = "_" . $this->thumb;
		}
		else {
			$path = $this->path . "/";
			$thumb = null;
		}
		
		if (isset($result->fields)) {
		
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				$temp1['file'] = $path . $temp1['file_name'] . $thumb. "." . $temp1['file_suffix'];
				//$temp1['file_size'] = round($temp1['file_size']/1000);
	
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;

		}
		else {
			$error_info = "function=getFiles class=Files.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getFiles
	

	
	// getAllocation ------------------------------------------------------------
	// returns the disk space allocated and the amount used. 
	// values returned in bytes
	// tom calthrop - 6th December 2004
	//
	function getAllocation() {
		
		//get the <module> allocated space
		if ($this->section_id == 1) {
		    $query = "
				SELECT user_file_allocation as allocation 
				FROM " . $this->db->prefix . "_user 
				where 
				user_id=" . $this->section_item_id
			;
		}
		elseif ($this->section_id == 2) {
		    $query = "
				SELECT group_file_allocation as allocation 
				FROM " . $this->db->prefix . "_group 
				where 
				group_id=" . $this->section_item_id
			;
		}
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
		   $temp['allocation'] = $result->fields['allocation'];
		   $result->Close();
		}
		
		//get used allocation
		$query = "
			SELECT sum(file_size) as allocation_used 
			FROM " . $this->db->prefix . "_file 
			where "
		;
		
		if (isset($this->section_id)) {
			$query .= "section_id=" . $this->section_id . " AND ";
		}
		
		if (isset($this->section_item_id)) {
			$query .= "section_item_id=" . $this->section_item_id . " AND ";
		}
		
		$query .= "1=1";
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
		   $temp['allocation_used'] = $result->fields['allocation_used'];
		   $result->Close();
		}
		
		return $temp;
	}//EO getAllocation
	
	
	
	/*
	* checkAllocation
	* Check the user available storage space and the space
	* tom calthrop
	* 6th December 2004
	*/
	function checkAllocation() {
		$allocation = $this->getAllocation();
		
		if (($allocation['allocation']-$allocation['allocation_used']) >= $this->arr_file_upload['size']) {
			return true;
		}
	}//EO checkAllocation
	
	
	
	// checkFileMime -------------------------------------------------------------
	// checks against config file to see if file with X MIME type is allowed 
	// to be saved
	// tom calthrop - 6th December 2004
	//
	function checkFileMime($file_mime) {
		foreach($this->arr_file['mime'] as $i):
			if ($i['mime'] == $file_mime) {
				return true;
				break;
			}
		endforeach;
	}//EO checkFileMime
	
	
	
	// getSuffix ---------------------------------------------------------------
	// gets the suffix (jpg) from the config file.
	// tom calthrop - 6th December 2004
	//
	function getSuffix($file_mime) {
		foreach($this->arr_file['mime'] as $i):
			if ($i['mime'] == $file_mime) {
				return $i['suffix'];
				break;
			}
		endforeach;
	}//EO getSuffix
	
	
	
	// insertFileRecord ---------------------------------------------------------------
	// inserts file into DB
	// tom calthrop - 6th December 2004
	//
	function insertFileRecord() {
		
		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);
		
		
		//get suffix
		$file_suffix = $this->getSuffix($this->arr_file_upload['type']);
		
		
		//remove any suffix from filename
		$file_name = substr($this->arr_file_upload['name'], 0, strlen($this->arr_file_upload['name'])-4);
		//we will only allow file names of 10 characters for easy filing
		if (strlen($file_name) > 10) {
		    $file_name = substr($file_name, 0, 10);
		}
		//remove any spaces
		$file_name = str_replace(" ", "", $file_name);
		
		//add 3 random number to end (reduces chances of duplicate naming)
		$file_name .= rand(100,999);
		 
		
		if ($this->path == "user") {
			$group_id = "null";
			$user_id = $this->section_item_id;
			$file_name_prefix = $this->section_item_id;
		} elseif ($this->path == "group") {
			$group_id = $this->section_item_id;
			$user_id = "null";
			$file_name_prefix = $this->section_item_id;
		}	
		
		$file_name = $file_name_prefix . "_" . $file_name;
		
		
		$query = "
			INSERT INTO " . $this->db->prefix . "_file (
			section_id,
			section_item_id,
			file_name,
			file_suffix,
			file_create_datetime,
			file_title,
			file_size,
			user_id
			) VALUES (
			" . $this->section_id . ",
			" . $this->section_item_id . ",
			'" . $file_name . "',
			'" . $file_suffix . "',
			" . $datetime . ",
			'" . $this->arr_file_upload['file_title'] . "',
			" . $this->arr_file_upload['size'] . ",
			" . $this->user_id . "
			)"
		;
		
		$result = $this->db->Execute($query);

		if (isset($result)) {
			//we get the id
			$query = "
				SELECT file_id FROM " . $this->db->prefix . "_file 
				WHERE
				file_name='" . $file_name . "' and 
				user_id=" . $this->user_id . " and 
				file_create_datetime=" . $datetime
			;
			
			$result = $this->db->Execute($query);
			
			if (isset($result->fields)) {
				$this->arr_file_upload['file_id'] = $result->fields['file_id'];
				$this->arr_file_upload['file_name'] = $file_name;
				$this->arr_file_upload['file_suffix'] = $file_suffix;
		   		$result->Close();
			}
			else {
				$error_info = "function=insertFileRecord class=Files.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
			}
		}
		else {
			$error_info = "function=insertFileRecord class=Files.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}


	}//EO insertFileRecord
	
	
	
	// moveFile ---------------------------------------------------------------
	// moves the uploaded file to the correct directory
	// tom calthrop - 6th December 2004
	//
	function moveFile() {
		$file_suffix = $this->arr_file_upload['file_suffix'];
		$file_name = $this->arr_file_upload['file_name'];
		
		$new_file_name = $file_name . "." . $file_suffix;
		
		//location to move to
		$directory = $this->arr_dir['asset_path'] . $this->path . "/";
		
		//move uploaded file
		move_uploaded_file($this->arr_file_upload['tmp_name'], $directory . $new_file_name);
		
		
		//check file width, quality and if thumbnails are needed
		if ($file_suffix == "jpg" || $file_suffix == "png" || $file_suffix == "gif") {
		   
			$size = getimagesize($directory . $new_file_name);
			$width = $size[0];
			$height = $size[1];
		   
		  	if ($width > $this->arr_file['image']['max_width']) {
				$new_width = $this->arr_file['image']['max_width'];
				$new_height = $height * ($new_width / $width);
		  	
				if ($file_suffix == "jpg") {
					$new_image = imagecreatefromjpeg($directory . $new_file_name);
					$blank_image = ImageCreateTrueColor($new_width, $new_height);
					$newimage = ImageCopyResampled($blank_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
					imagejpeg($blank_image, $directory . $new_file_name);
				}
				elseif ($file_suffix == "gif") {
					$new_image = imagecreatefromgif($directory . $new_file_name);
					$blank_image = ImageCreateTrueColor($new_width, $new_height);
					$newimage = ImageCopyResampled($blank_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
					imagegif($blank_image, $directory . $new_file_name);
				}
				elseif ($file_suffix == "png") {
					$new_image = imagecreatefrompng($directory . $new_file_name);
					$blank_image = ImageCreateTrueColor($new_width, $new_height);
					$newimage = ImageCopyResampled($blank_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
					imagepng($blank_image, $directory . $new_file_name);
				}
			}
			
			$thumbdirectory = $directory . $this->arr_file['image']['thumb_directory'];
			$this->makeImageThumbnails($directory, $thumbdirectory, $file_name, $file_suffix);
		}
	}//EO moveFile
	
	
	
	// makeImageThumbnails ---------------------------------------------------------------
	// makes thumbnails. Thumbnails sizes are defined in the config file
	// tom calthrop - 6th December 2004
	//
	function makeImageThumbnails($directory, $thumbdirectory, $file_name, $file_suffix) {
		$new_file_name = $file_name . "." . $file_suffix;
		$size = getimagesize($directory . $new_file_name);
		$height = $size[1];
		$width = $size[0];
		
		foreach ($this->arr_file['image']['thumb'] as $key => $i){
		
			$newheight = intval($height*$i['width'] / $width);
			
			if (function_exists('ImageCreateTrueColor')) {
				$thumbnail = ImageCreateTrueColor($i['width'], $newheight);
			} else {
				$thumbnail=ImageCreate($i['width'], $newheight);
			}
			
			if ($file_suffix == "jpg") {
				$original = imagecreatefromjpeg($directory . $new_file_name);
			}elseif ($file_suffix == "gif") {
				$original = imagecreatefromgif($directory . $new_file_name);
			}elseif ($file_suffix == "png") {
				$original = imagecreatefrompng($directory . $new_file_name);
			}
			
			ImageCopyResized($thumbnail,$original,0,0,0,0,$i['width'],$newheight,ImageSX($original),ImageSY($original));
  			
			$new_thumb_name = $file_name . "_" . $i['name'] . "." . $file_suffix;
			
			if ($file_suffix == "jpg") {
				imagejpeg($thumbnail,$thumbdirectory . $new_thumb_name, 75);
			}elseif ($file_suffix == "gif") {
				imagepng($thumbnail,$thumbdirectory . $new_thumb_name, 75);
			}elseif ($file_suffix == "png") {
				imagepng($thumbnail,$thumbdirectory . $new_thumb_name, 75);
			}
			
		}
	}//EO makeImageThumbnails
	
	
	
	// getFileRecord --------------------------------------------------------------------
	// returns a sinle row from the DB
	// tom calthrop - 6th December 2004
	//
	function getFileRecord () {
		$query = "
			SELECT file_id, file_name, file_suffix, file_title, 
			file_create_datetime, file_size, user_id 
			FROM " . $this->db->prefix . "_file 
			where 
			file_id=" . $this->file_id
		;
		
		$result = $this->db->Execute($query);

		//setup directory paths and thumb name suffixes
		$path = $this->path;
		
		if (isset($this->thumb)) { //iuser
			$path = $path . "/" . $this->arr_file['image']['thumb_directory'];
		    $thumb = "_" . $this->thumb;
		}
		else {
			$path = $path . "/";
			$thumb = null;
		}
		
		if (isset($result->fields)) {
			$temp = $result->fields;
			$temp['file'] = $path . $temp['file_name'] . $thumb. "." . $temp['file_suffix'];
			
			return $temp;

		}
		else {
			$error_info = "function=getFileRecord class=Files.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getFileRecord
	
	
	// deleteFile --------------------------------------------------------------------
	// deletes single file and its associated thumbnails
	// tom calthrop - 6th December 2004
	//
	function deleteFile($file_name, $file_suffix) {
		//location to move to
		$directory = $this->arr_dir['asset_path'] . $this->path . "/";
		
		
		$thumbdirectory = $directory . $this->arr_file['image']['thumb_directory'];
		
		//location to delete from
		    $directory = $this->arr_dir['asset_path'] . $this->path . "/";
		
		//delete file
		if (is_file($directory . $file_name . "." . $file_suffix)) {
		   	unlink($directory . $file_name . "." . $file_suffix);
		}
		
		//delete thumbs
		foreach ($this->arr_file['image']['thumb'] as $key => $i):
			if (is_file($thumbdirectory . $file_name . "_" . $i['name'] . $file_suffix)) {
		   		unlink($thumbdirectory . $file_name . "_" . $i['name'] . $file_suffix);
			}
		endforeach;
	}//EO deleteFile


	
	// deleteFileRecord --------------------------------------------------------------------
	// deletes single file from DB
	// tom calthrop - 6th December 2004
	//
	function deleteFileRecord($file_id) {

		$query = "
			DELETE FROM " . $this->db->prefix . "_file 
			WHERE 
			file_id=" . $file_id
		;
		
		$result = $this->db->Execute($query);
	}//EO deleteFileRecord
	
	
	
	// updateFileRecord --------------------------------------------------------------------
	// updates single file in DB
	// tom calthrop - 6th December 2004
	//
	function updateFileRecord() {
		//arr_file_upload
		$query = "
			UPDATE " . $this->db->prefix . "_file SET
			file_title='" . $this->arr_file_upload['file_title'] . "' 
			WHERE file_id=" . $this->file_id
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($this->arr_file_upload['size']) && $this->arr_file_upload['size'] > 0) {
			$query = "
				UPDATE " . $this->db->prefix . "_file SET
				file_name='" . $this->arr_file_upload['file_name'] . "',
				file_suffix='" . $this->arr_file_upload['file_suffix'] . "',
				file_size=" . $this->arr_file_upload['size'] . ",
				WHERE file_id=" . $this->file_id
			;
			
			$result = $this->db->Execute($query);
		}
	}//EO updateFileRecord
	
	
	
	// updateDefaultFile --------------------------------------------------------------------
	// updates the DB with the default image ID
	// tom calthrop - 6th December 2004
	//
	function updateDefaultFile() {

		if ($this->path == "group") {
			$query = "
				UPDATE " . $this->db->prefix . "_group SET 
				file_id =" . $this->default_file_id . "
				WHERE
				group_id=" . $this->section_item_id
			;
		}
		elseif ($this->path == "user") {
			$query = "
				UPDATE " . $this->db->prefix . "_user SET 
				file_id =" . $this->default_file_id . "
				WHERE
				user_id=" . $this->section_item_id
			;
		}
		
		$result = $this->db->Execute($query);
	}//EO updateDefaultFile
}

?>
