<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* File class
* @package TenderSystem
* @subpackage generic
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

Class file {
	// set the paramaters
	var $file;
	var $error;
	
	function read_folder($folder,$cfg) {
		// allowable folders that may be read
		$allowable_array = array ("language","area","category");
		// NOTE: theme is not an allowable filetype AS folder must be read from the GUI
		// and passed to the API - llok at user_profile
		// determine if allowable folders
		$allowable_file = FALSE;
		foreach ($allowable_array AS $value) {
			if (strpos($folder,$value) !== FALSE) {
				// set allowable file
				$allowable_file = TRUE;
				// break loop
				break;
			}
		}
		if (!$allowable_file) {
			// set the error
			$this->error = "52";
			// could not read the folder
			return FALSE;
		}
		// set the complete file path
		$file_path = $cfg['file'].$folder;
		// open the directory
		$dir = opendir($file_path);
		// if folder accessible
		if ($dir) {
			// loop through all the files
			while(($file=readdir($dir)) !== FALSE) {
				// determine if hidden file not included
				if($file{0} != "." && $file != "CVS" && $file != "stylesheet.php") {
					// set files in an array
					$response[] = $file;
				}
			}
			// close the directory
			closedir($dir);
			// return the file array
			return $response;
		} else {
			// set the error
			$this->error = "76";
			// could not read the folder
			return FALSE;
		}
	}
	
	function read_file($folder,$file,$cfg) {
		// allowable folders that may be read
		$allowable_array = array ("language","area","category");
		// determine if allowable folders
		foreach ($allowable_array AS $value) {
			if ($folder == $value) {
				// set allowable file
				$allowable_file = TRUE;
				// break loop
				break;
			}
		}
		if (!$allowable_file) {
			// set the error
			$this->error = "52";
			// could not read the folder
			return FALSE;
		}
		// security determine if filename has . infront
		if ($file{0} == ".") {
			// set the error
			$this->error = "52";
			// could not read the folder
			return FALSE;
		}
		// set the complete file path
		$file_path = $cfg['file'].$folder."/".$file;
		$file_check = $this->file_check($file_path,"",$cfg);
		if (!$file_check) {
			// response	
			return FALSE;
		}
		// open file for reading
		$fp = fopen($file_path,"r");
		// check if file open okay
		if (!$fp) {
			// Cannot open File 
			$this->error[] = "77";
			return FALSE;
		}
		// read file into array
		while(!feof($fp)) {
			// read into variable
			$data.= fgets($fp,1024);
		}
		if ($data) {
			// restrun the data
			return $data;
		} else {
			// file is empry
			$this->error[] = "287";
		}
	}
	
	function file_check($file,$writable,$cfg) {
		if(!file_exists($file)) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "Error: ".$file." does not exist. Error in ".__file__." on line ".__line__;
			$new_error->log("FILE","serious",$error_text,$cfg);
			// The file trying to access does not exist 
			$this->error[] = "76";
			// response
			return FALSE;
		}
		// check if it is a file (not a directory)
		if(!is_file($file)) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "Error: ".$file." is a directory. Error in ".__file__." on line ".__line__;
			$new_error->log("FILE","serious",$error_text,$cfg);
			// The file trying to access is a directory 
			$this->error[] = "75";
			// response
			return FALSE;
		}
		// check wif file is reable
		if(!is_readable($file)) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "Error: ".$file." is not readable. Error in ".__file__." on line ".__line__;
			$new_error->log("FILE","serious",$error_text,$cfg);
			// Please change the permissions of the required file
			$this->error[] = "70";
			// response
			return FALSE;
		}
		if ($writable) {
			// check if readable and writable
			if(!is_writable($file)) {
				// instantiate the error class and log
				$new_error = new error;
				$error_text = "Error: ".$file." is not writable. Error in ".__file__." on line ".__line__;
				$new_error->log("FILE","serious",$error_text,$cfg);
				// Please change the permissions of the required file
				$this->error[] = "70";
				// response
				return FALSE;
			}
		}
		// response
		return TRUE;	
	}
	
	function file_upload($file,$user,$cfg,$conn) {
		// set required resposne fields
		$this->response['name'] = $file['name'];
		// generate an authentication string
		$auth_string = md5(uniqid(rand()));
		$this->response['authentication'] = strtolower($auth_string);
		// get the next id 
		$new_database = new database;
		$table_name = "~attachment";
		$this->response['id'] = $new_database->get_next_id($table_name,$cfg,$conn);
		if (!$this->response['id']) {
			// set the errors
			$this->error = $new_database->error;
			// response
			return FALSE;
		}
		$new_database->parse_sql($table_name,$cfg);
		// insert the items in the database
		$insert = array(
			'id'				=> $this->response['id'],
			'name'				=> $file['name'],
			'authentication'	=> $this->response['authentication'],
			'status'			=> "1",
			'created_by'		=> $user
		);
		// insert created time
		$new_database->setTime("created",$insert,"",$cfg);
		// execute the query
 		$conn->AutoExecute($table_name,$insert,"INSERT");
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
       	}
       	// add the content (some database the blob must be done separately)
		$where = " id = '".$this->response['id']."'";
		// execute the update
		$conn->UpdateBlob($table_name,"content",$file['content'],$where);
		if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$this->error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$this->error_text,$cfg);
			// Error occurred while updating into Database
			$this->error[] = "1066";
			// response
			return FALSE;
		}
		// return item id
		return $this->response['id'];	
	}
	
	function file_display($file,$cfg,$conn) {
		// determine if present
		$sqlstr = "SELECT ~attachment.id, ~attachment.name AS name, ~attachment.content AS content, ";
		$sqlstr.= "~attachment.authentication, ~attachment.status ";
		$sqlstr.= "FROM ~attachment ";
		$sqlstr.= "WHERE ~attachment.id = '".$file['id']."' ";
		$sqlstr.= "AND ~attachment.authentication = '".$file['authentication']."' ";
		$sqlstr.= "AND ~attachment.status = '1' ";
		$new_database = new database;
		$new_database->parse_sql($sqlstr,$cfg);
		// execute the query
 		$row = $conn->GetRow($sqlstr);
       	if ($conn->ErrorMsg()) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// set the response error
			$this->error[] = "1065";
			// response
			return FALSE;
       	}
		// set repsonse
		$response['filename'] = $row['name'];
		// remove all apostrophes
		$response['filecontent'] = $row['content'];
		// set the array
		$file_array = array (
			// images - gif default value
			"jpeg"		=> "image/jpeg",
			"jpg"		=> "image/jpeg",
			"png"		=> "image/png",
			"tiff"		=> "image/tiff",
			"tif"		=> "image/tiff",
			"bmp"		=> "image/bmp",
			// documents
			"doc"		=> "application/msword",
			"xsw"		=> "application/vnd.sun.xml.writer",
			"pdf"		=> "application/pdf",
			"xml"		=> "text/xml",
			"txt"		=> "text",
			// spreadsheets
			"xsl"		=> "application/excel",
			"sxc"		=> "application/vnd.sun.xml.calc",
			// archives
			"gzip"		=> "application/x-gzip",
			"rar"		=> "application/x-compressed",
			"tar"		=> "application/x-tar",
			"bzip2"		=> "application/x-bzip2"
		);
		// set extension
		$extension = substr(strrchr($row['name'],"."),1);
		// determine the type
		$response['filetype'] = $file_array[$extension];
		// try with a default
		if (!$response['filetype']) {
			$response['filetype'] = "text/html";
		}
		// return sub category name
		return $response;
	}
	
	// find link items
	function link_api_find($link,$sub_link,&$xml_params,$user,$cfg,$conn) {
		// set the complete file path
		$file_path = $cfg['file']."modules";
		// open the directory
		$dir = opendir($file_path);
		// if folder accessible
		if ($dir) {
			// loop through all the files (modules)
			while(($file=readdir($dir)) !== FALSE) {
				// determine if hidden file not included
				if($file{0} != "." && $file != "CVS" && is_dir($file_path."/".$file) && file_exists($file_path."/".$file."/api_link.php")) {
					// set files in an array
					$files[] = $file_path."/".$file."/api_link.php";
				}
			}
			// close the directory
			closedir($dir);
		} else {
			return FALSE;
		}
		$menu_item = array();
		if(is_array($files)) {
			foreach($files as $value) {
				// set menu item
				include($value);
			}
		}
		return $menu_item;
	}
}
?>