<?php

/*************************************************

applicationobject.php - a pseudo-implementation of ASPs application object

home page: www.samscripts.com/scripts/application_object
support: support.samscripts.com/index.php

licence: freeware / optionally giftware ( www.samscripts.com/donate.php )
author: Sam Yapp
date: 8th September 2002

documentation and examples at www.samscripts.com

*************************************************/


class _appdata{
	function _appdata(){}
}

class application{

	function application($appfilepath = "", $win98 = false){
		$this->_win98 = $win98;
		$this->_filepath = $appfilepath;
		$this->_fp = 0;
		$this->_mode = "";
		$this->_fplock = 0;
	}


	function getdata(&$data){
		foreach($data as $k=>$v){
			$this->$k = $v;
		}
	}

	function flock(&$fp, $mode){
		if( $this->_win98 ) return true;
		return flock($fp, $mode);
	}

	function open($mode = "r"){
		if( $this->_mode == "" ){
			switch( $mode ){
				case "w":
					$this->_fplock = @fopen($this->_filepath.".lock", "r");
					if( !$this->_fplock ){
						$this->_fplock = @fopen($this->_filepath.".lock", "w");
					}
					if( $this->_fplock ){
						if( $this->flock($this->_fplock, LOCK_EX) ){
							$this->_fp = @fopen($this->_filepath, "rb");
							if( $this->_fp){
								$data = unserialize(fread($this->_fp, filesize($this->_filepath)));
								fclose($this->_fp);
							$this->getdata(&$data);
							}
							$this->_mode = "w";
						}else{
							fclose($this->_fplock);
						}
					}
					break;
				default:
					$this->_fp = @fopen($this->_filepath, "rb");
					if( $this->_fp ){
						if( $this->flock($this->_fp, LOCK_SH) ){
							$data = unserialize(fread($this->_fp, filesize($this->_filepath)));
							$this->flock($this->_fp, LOCK_UN);
							$this->getdata(&$data);
						}
						fclose($this->_fp);
						$this->_fp = 0;
					}
					break;
			}
		}
	}

	function close(){
		if( $this->_mode == "w" && $this->_fplock != 0 ){
			$data = new _appdata;
			foreach( $this as $k=>$v){
				if( !in_array($k, array("_fplock", "_mode", "_fp", "_filepath", "_win98")) )
					$data->$k = $v;
			}
			$this->_fp = @fopen($this->_filepath, "wb");
			if( $this->_fp ){
				if( $this->flock($this->_fp, LOCK_EX) ){
					fwrite($this->_fp, serialize($data));
					$this->flock($this->_fp, LOCK_UN);
				}
				fclose($this->_fp);
			}
			$this->flock($this->_fplock, LOCK_UN);
			fclose($this->_fplock);
			$this->_mode = "";
			$this->_fp = 0;
			$this->_fplock = 0;
		}
	}

}
?>