<?php
class config
{
	var $cfg;
	function read_config($file)
		{
			//create a file handler to the specified configuration file to read
				$hwnd = @fopen($file,"r");
				//if the file handler could not create return a null value
				if (!$hwnd)
					{
						return NULL;
					}
					else
					{
						//if it could then read the contents
						$data = fread($hwnd,filesize($file));
						//split by new lines
						$settings = explode("\n",$data);
						//for all the settings
						for ($d=0;$d<sizeof($settings);$d++)
						{
						if (substr($settings[$d],0,1) != "#")
							{
								if ($settings[$d] != "" && $settings[$d] != NULL && $settings[$d] != "=")
								{
							//if its not a comment
								$bits = explode("=",$settings[$d]);
								//save the value to the setting in a 2D array
								$CFG[$bits[0]] = $bits[1];
								}
							}
							else
							{
							continue;
							}
						}
						//return the array
						return $CFG;
					}
		}
	function is_setting($setting, $file)
		{
			//see if the setting exsists
			//load all the settings
			$cfg = $this->read_config($file);
			//loop through the array to see if it matches
			foreach($cfg as $set => $value)
				{
					// match $setting against $set
					if ($set == $setting)
						{
							return true;
							break;
						}
						else
						{
							continue;
						}
				}
		}
		
	function update_setting($setting, $newvalue, $file)
		{
			if ($this->is_setting($setting, $file) == true)
				{
					$this->cfg = $this->read_config($file);
					$this->cfg[$setting] = $newvalue;
					$this->update_file($file);
					return true;
				}
			else
				{
					return $this->add_setting($setting, $newvalue, $file);
				}
		}
		
	function delete_setting($setting, $file)
		{
			if ($this->is_setting($setting, $file) == true)
			{
				$this->cfg = $this->read_config($file);
				unset($this->cfg["$setting"]);
				$this->update_file($file);
					return true;
				
			}
			else
			{
			return NULL;
			}
		}
	
	function add_setting($setting, $value, $file)
		{
			if ($this->is_setting($setting, $file) == true)
				{
					return $this->update_setting($setting, $value, $file);
				}
				else
				{
				$this->cfg = $this->read_config($file);
				$this->cfg[$setting] = $value;
				return $this->update_file($file);
				}
		}
	function update_file($file)
		{
			$hwnd = @fopen($file,"w");
			//if the file handler could not create return a null value
			if (!$hwnd)
				{
					return NULL;
				}
				else
				{
					foreach($this->cfg as $set => $value)
					{
						fputs($hwnd,$set."=".$value."\n");
					}
					$this->cfg = $this->read_config($file);
				fclose($hwnd);
				}
		}
}
?>