<?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, $rsp_item_type_id, $arr_file, $arr_dir){
		$this->db = $db;
		$this->rsp_item_type_id = $rsp_item_type_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 f.file_id, f.file_name, f.file_suffix, f.file_title, 
			f.file_create_datetime, f.file_size, f.user_id, f.group_id 
			FROM " . $this->db->prefix . "_file f 
			WHERE  "
		;

		if (isset($this->user_id)) {
		    $query .= "f.user_id=" . $this->user_id . " AND ";
		}
		if (isset($this->group_id) && $this->group_id==0) {
		    $query .= "f.group_id is null AND ";
		}
		elseif (!empty($this->group_id)) {
		    $query .= "f.group_id=" . $this->group_id . " AND ";
		}
		
		if (isset($this->type_ids)) {
			$query .="(";
			foreach($this->type_ids as $key => $i):
				$query .="f.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 f.file_title";
		}
		
		$result = $this->db->Execute($query);

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

			while (!$result->EOF) {
				$temp1 = $result->fields;
				
				if (!empty($temp1['file_name'])) {
					if ($temp1['group_id'] > 0) {
						$fullpath = $this->arr_file['image']['path']['group']. $path;
					}
					else {
					    $fullpath = $this->arr_file['image']['path']['user'] . $path;
					}
					
					$temp1['file'] = $fullpath . $temp1['file_name'] . $thumb. "." . $temp1['file_suffix'];
				}
				
				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 (isset($this->group_id) && $this->group_id > 0) {
		    $query = "
				SELECT group_file_allocation as allocation 
				FROM " . $this->db->prefix . "_group  
				where 
				group_id=" . $this->group_id
			;
		}
		else {
		    $query = "
				SELECT user_file_allocation as allocation 
				FROM " . $this->db->prefix . "_user 
				where 
				user_id=" . $this->user_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->user_id)) {
		    $query .= "user_id=" . $this->user_id . " AND ";
		}
		
		if (!empty($this->group_id)) {
		    $query .= "group_id=" . $this->group_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() {
		
		//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 (!empty($this->group_id)) {
		    $group_id = $this->group_id;
			$file_name_prefix = $group_id;
		}
		else {
			$group_id = "null";
			$file_name_prefix = $this->user_id;
		}
		
		$file_name = $file_name_prefix . "_" . $file_name;
		
		$rec = array();
		$rec['group_id'] = $group_id;
		$rec['file_name'] = $file_name;
		$rec['file_suffix'] = $file_suffix;
		$rec['file_create_datetime'] = time();
		$rec['file_title'] = $this->arr_file_upload['file_title'];
		$rec['file_size'] = $this->arr_file_upload['size'];
		$rec['user_id'] = $this->user_id;
		
		$table = $this->db->prefix . "_file";
			
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
			
		if (isset($result)) {
			
			$file_id = $this->db->Insert_ID();
			
			$this->arr_file_upload['file_id'] = $file_id;
			$this->arr_file_upload['file_name'] = $file_name;
			$this->arr_file_upload['file_suffix'] = $file_suffix;
		}
		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
		if (!empty($this->group_id)) {
			$directory = $this->arr_dir['asset_path'] . $this->arr_file['image']['path']['group'];
		}
		else {
			$directory = $this->arr_dir['asset_path'] . $this->arr_file['image']['path']['user'];
		}
		
		//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, group_id
			FROM " . $this->db->prefix . "_file 
			where 
			file_id=" . $this->file_id
		;
		
		$result = $this->db->Execute($query);

		//setup directory paths and thumb name suffixes
		if (isset($this->thumb)) {
			$path = $this->arr_file['image']['thumb_directory'] . "/";
		    $thumb = "_" . $this->thumb;
		}
		else {
			$path = "";
			$thumb = null;
		}
		
		if (isset($result->fields)) {
			$temp = $result->fields;
			
			if (!empty($temp['file_name'])) {
				if ($temp['group_id'] > 0) {
					$fullpath = $this->config_ids['image']['path']['group']. $path;
				}
				else {
				    $fullpath = $this->config_ids['image']['path']['user'] . $path;
				}
					
				$temp['file'] = $fullpath . $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
		if (!empty($this->group_id)) {
			$path = $this->arr_file['image']['path']['group'];
		}
		else {
		    $path = $this->arr_file['image']['path']['user'];
		}
		
		$directory = $this->arr_dir['asset_path'] . $path;
		
		$thumbdirectory = $directory . $this->arr_file['image']['thumb_directory'];
		
		//location to delete from
		 //   $directory = $this->arr_dir['asset_path'] . $this->filepath[$this->section_id] . "/";
		
		//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 = "
			SELECT * FROM " . $this->db->prefix . "_file
			WHERE 
			file_id=" . $this->file_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['file_title'] = $this->arr_file_upload['file_title'];
		
		if (isset($this->arr_file_upload['size']) && $this->arr_file_upload['size'] > 0) {
			
			$rec['file_name'] = $this->arr_file_upload['file_name'];
			$rec['file_suffix'] = $this->arr_file_upload['file_suffix'];
			$rec['file_size'] = $this->arr_file_upload['size'];
		}
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO updateFileRecord
	
	
	
	// updateDefaultFile --------------------------------------------------------------------
	// updates the DB with the default image ID
	// tom calthrop - 6th December 2004
	//
	function updateDefaultFile() {
		if (isset($this->group_id)) {
			$query = "
				SELECT * FROM " . $this->db->prefix . "_group 
				WHERE group_id=" . $this->group_id
			;
		}
		else{
			$query = "
				SELECT * FROM " . $this->db->prefix . "_user 
				user_id=" . $this->user_id
			;
		}
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['file_id'] = $this->default_file_id;
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
	}//EO updateDefaultFile
}

?>
