<?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): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Settings class
* @package TenderSystem
* @subpackage settings
* @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 settings {
	// user paramaters
	var $settings;
	var $error;
	
	/**
	 * Constructor that sets the valid types  
	 */
	function settings ($settings_type) {
		// determine which display types to include
		if ($settings_type == "general") {
			$this->settings = array(
				'theme'				=> "['theme']",
				'language'			=> "['language']",
				'header'			=> "['header']",
				'localprecurrency'	=> "['local']['precurrency']",
				'localpostcurrency'	=> "['local']['postcurrency']"
			);
		} elseif ($settings_type == "pop") {
			$this->settings = array(
				'popstatus'			=> "['pop']['status']",
				'popserver'			=> "['pop']['server']",
				'popport'			=> "['pop']['port']",
				'poptenderusername'	=> "['pop']['tender']['username']",
				'poptenderpassword'	=> "['pop']['tender']['password']",
				'popnotype'			=> "['pop']['notype']"
			);
		} elseif ($settings_type == "security") {
			$this->settings = array(
				'errorfile'			=> "['error']['file']",
				'erroremail'		=> "['error']['email']",
				'logstatus'			=> "['log']['status']",
				'logfile'			=> "['log']['file']",
				'securityip_track'	=> "['security']['ip_track']",
				'securitycall'		=> "['security']['call']",
				'securityip0'		=> "['security']['ip']['0']",
				'securityip1'		=> "['security']['ip']['1']",
				'securityip2'		=> "['security']['ip']['2']",
				'apiauthenticate'	=> "['api']['authenticate']",
				'apiusername0'		=> "['api']['username']['0']",
				'apipassword0'		=> "['api']['password']['0']",
				'apiusername1'		=> "['api']['username']['1']",
				'apipassword1'		=> "['api']['password']['1']",
				'apiusername2'		=> "['api']['username']['2']",
				'apipassword2'		=> "['api']['password']['2']",
				'apiusername3'		=> "['api']['username']['3']",
				'apipassword3'		=> "['api']['password']['3']",
				'apiusername4'		=> "['api']['username']['4']",
				'apipassword4'		=> "['api']['password']['4']",
				'displaylogin'		=> "['display']['login']",
				'displaylogs'		=> "['display']['logs']",
				'displaylimit'		=> "['display']['limit']",
				'logphp'			=> "['log']['php']"
			);
		} elseif ($settings_type == "sms") {
			$this->settings = array(
				'smsstatus'			=> "['sms']['status']",
				'smscode'			=> "['sms']['code']",
				'smsapi_id'			=> "['sms']['api_id']",
				'smsuser'			=> "['sms']['user']",
				'smspassword'		=> "['sms']['password']",
				'smsreceipt'		=> "['sms']['receipt']",
				'smsurlsend'		=> "['sms']['urlsend']"
			);
		} elseif ($settings_type == "smtp") {
			$this->settings = array(
				'smtpstatus'			=> "['smtp']['status']",
				'smtpserver'			=> "['smtp']['server']",
				'smtpport'				=> "['smtp']['port']",
				'smtphelo'				=> "['smtp']['helo']",
				'smtpauth'				=> "['smtp']['auth']",
				'smtpuser'				=> "['smtp']['user']",
				'smtppassword'			=> "['smtp']['password']",
				'smtpencoding'			=> "['smtp']['encoding']",
				'smtpblob'				=> "['smtp']['blob']",
				'smtpfrom'				=> "['smtp']['from']",
				'smtptenderemail'		=> "['smtp']['tender']['email']",
				'smtpmessage'			=> "['smtp']['message']",
				'smtpdisclaimer'		=> "['smtp']['disclaimer']",
				'smtpsourceforge'		=> "['smtp']['sourceforge']",
				'smtpsupportemail'		=> "['smtp']['support']['email']",
				'smtpbackupstatus'		=> "['smtp']['backup']['status']",
				'smtpbackupemail'		=> "['smtp']['backup']['email']",
				'smtpkeyword0'			=> "['smtp']['keyword']['0']",
				'smtpkeyword1'			=> "['smtp']['keyword']['1']",
				'smtpkeyword2'			=> "['smtp']['keyword']['2']",
				'smtpreceiptimgenable'	=> "['smtp']['receipt']['img']['enable']",
				'smtpsupportpriority'	=> "['smtp']['support']['emailpriority']",
				'smtptenderpriority'	=> "['smtp']['tender']['emailpriority']"
			);
		} elseif ($settings_type == "time") {
			$this->settings = array(
				'timeformat'			=> "['time']['format']",
				'dateformat'			=> "['date']['format']",
				'timeopen0'				=> "['time']['open']['0']",
				'timeclose0'			=> "['time']['close']['0']", 
				'timeopen1'				=> "['time']['open']['1']",
				'timeclose1'			=> "['time']['close']['1']",
				'timeopen2'				=> "['time']['open']['2']",
				'timeclose2'			=> "['time']['close']['2']",
				'timeopen3'				=> "['time']['open']['3']",
				'timeclose3'			=> "['time']['close']['3']", 
				'timeopen4'				=> "['time']['open']['4']",
				'timeclose4'			=> "['time']['close']['4']",
				'timeopen5'				=> "['time']['open']['5']",
				'timeclose5'			=> "['time']['close']['5']",
				'timeopen6'				=> "['time']['open']['6']",
				'timeclose6'			=> "['time']['close']['6']", 
				'timelunchstarthour'	=> "['time']['lunch']['start']['hour']",
				'timelunchstartmin'		=> "['time']['lunch']['start']['min']",
				'timelunchendhour'		=> "['time']['lunch']['end']['hour']", 
				'timelunchendmin'		=> "['time']['lunch']['end']['min']", 
				'loginagent'			=> "['login']['agent']",
				'loginsubscriber'		=> "['login']['subscriber']",
				'loginadmin'			=> "['login']['admin']",
				'loginagent'			=> "['login']['agent']",
				'loginsubscriber'		=> "['login']['subscriber']",
				'loginadmin'			=> "['login']['admin']",
				'localduration'			=> "['local']['duration']",
				'localdisplay'			=> "['local']['display']"
			);
		} elseif ($settings_type == "message") {
			$this->settings = array(
				'messageschedulestatus'		=> "['message']['schedule']['status']",
				'messagescheduleattempts'	=> "['message']['schedule']['attempts']",
				'messagescheduletime'		=> "['message']['schedule']['time']",
				'messageschedulego'			=> "['message']['schedule']['go']"
			);
		} elseif ($settings_type == "holiday") {
			for($i = 0; $i < 30; $i++) {
				$this->settings['holiday'.$i.'date'] = "['holiday']['".$i."']['date']"; 
				$this->settings['holiday'.$i.'name'] = "['holiday']['".$i."']['name']";
			}
		} else {
			// set error
			$this->error[] = "258";
			$this->error[] = "106";
			// return
			return FALSE;
		}
		// return valid settings
		return $this->settings;	
	}
	
	/**
	 * Get settings from a settings file
	 * 
	 * @param string file name of settings file
	 * @param mixed cfg The Config settings of tendersystem
	 *
	 * @param mixed the settings on success Or FALSE on error  
	 */
	function get_settings($file,$cfg) {
		// instantiate file class
		$new_file = new file;
		// check if file exists
		if(!$new_file->file_check($file,FALSE,$cfg)){
			// No type
			$this->error = $new_file->error;
			// Error in settings class
			$this->error[] = "106";
			// response
			return FALSE;
		}
		// open file for reading
		$fp = fopen($file,"r");
		// check if file open okay
		if (!$fp) {
			// instantiate the error class and log
			$new_error = new error;
			$error_text = "Error: Can not open ".$file." in ".__file__." on line ".__line__;
			$new_error->log("FILE","serious",$error_text,$cfg);
			// Cannot open file
			$this->error[] = "77";
			// Error in settings class 
			$this->error[] = "106";
			// response
			return FALSE;
		}
		// initial values for all the_settings
		foreach($this->settings as $key => $value) {
			$response[$key] = FALSE;
		}
		// get settings from file
		while(!feof($fp)) {
			// get line from file
			$line = fgets($fp,1024); 
			$is_setting = strpos($line,"="); 
			if($is_setting) {
				// for double quotes
				$start = strpos($line,'"',$is_setting);
				$end = strpos($line,'"',$start+1);
				// if not double quotes
				if(!$start) {
					// for single quotes
					$start = strpos($line,"'",$is_setting);
					$end = strpos($line,"'",$start+1); 
				}
				// if not single quotes
				if(!$start) {
					$start = $is_setting;
 					$end = strpos($line,";",$start+1);
				}
				// get each setting using valid_settings
				foreach($this->settings as $key => $value) {
					// get the setting
					if(strpos($line,"cfg".$value)){
						$response[$key] = trim(substr($line,$start + 1,$end - $start - 1));
						break;
					} 
				}							
			}
		}
		// close file 
		fclose($fp);
		// return the settings
		return $response;
	}

	/**
	 * Write settings to a file
	 * 
	 * @param string file name of settings file
	 * @param array settings the settings to write
	 * @param mixed cfg The Config settings of tendersystem
	 *
	 * @param mixed TRUE on success Or FALSE on error  
	 */
	function set_settings ($file,$settings,$cfg) {
		// Validate $settings parameter
		foreach ($settings as $key => $value) {
			// check if key exists in valid_settings
			if (!$this->settings[$key]) {
				// Invalid Setting	
				$this->error[] = "122";
				// Error in settings class
				$this->error[] = "106";
				// response
				return FALSE;			
			}
		}
		
		// instantiate the file class
		$new_file = new file;
		// check if file exists
		if (!$new_file->file_check($file,TRUE,$cfg)){
			// Error code for the specfic type 
			$this->error = $new_file->error;
			// Error in settings class
			$this->error[] = "106";
			// response	
			return FALSE;
		}
		// open file for reading
		$fp = fopen($file,"r");
		// check if file open okay
		if (!$fp) {
			// Cannot open File 
			$this->error[] = "77";
			// Error in settings class
			$this->error[] = "106";
			return FALSE;
		}
		// read file into array and replace needed sections
		$line = 0;
		while(!feof($fp)) {
			// get line from file
			$config_array[$line++] = fgets($fp,1048576); 
			// replace needed location section
			foreach($settings as $key => $value) {
				// if a setting match 
				if(strpos($config_array[$line - 1],$this->settings[$key]) !== FALSE) {
					// replace setting
					$config_array[$line - 1] = "\$cfg".$this->settings[$key]." = ";
					// if a boolean type
					if(trim($value) === "TRUE" || trim($value) === "FALSE") {
						// leave out inverted commas
						$config_array[$line - 1].= $value.";\n";
					} else {
						// else insert inverted commas
						$config_array[$line - 1].= "'".str_replace("'","\\'",$value)."';\n"; 
					}
				}
			}
		}
		// close file
		fclose($fp);
		
		// on some platforms (happens on FREBSD 4) a wierd error happens when trying to write to
		// a file that was opened for reading instead, to writing to a different file is done and
		// then renamed
		if($cfg['settings']['rename']) {
			$real_file = $file;
			$file.=".tmp";	
		}
		// open file for writing
		$fp = fopen($file,"w+"); 
		// check if file open okay
		if (!$fp) {
			// Can't open file 
			$this->error[] = "77";
			// Error in settings class
			$this->error[] = "106";
			return FALSE;
		}
		// write new data back into file
		foreach($config_array as $line) {
			if($line) {
				if(!fwrite($fp,$line,strlen($line))) {
					// Could not write to file 
					$this->error[] = "111";
					// Error in settings class
					$this->error[] = "106";
					return FALSE;
				}
			}
		}
		// close file
		fclose($fp);
		// rename file
		if($cfg['settings']['rename']) {
			if(!rename($file,$real_file)) {
				// Could not write to file 
				trigger_error(sprintf('Could not rename file : %s', $file), E_USER_WARNING);
				return FALSE;
			}
		}
		// return changed settings
		return TRUE;
	}
}
?>