<?php
class logger
{
	private $file;
	private $filename;
	private $newline="\r\n";
	private $tab="\011";
	private $fields=array();
	public $log_dir=array();
	public $dont_log_dir=array();
	private $file_exist;		// bool
	
	
	/**
	 * Enter description here...
	 *
	 * @param String $filename
	 * @param String $mode: 1 - write to file, 2 - write to sql, 3 - write to file and sql
	 * 						
	 */
	public function __construct($filename, $mode=1)
	{
		if($mode==1)	// write to file
		{
			//echo $filename;
			$this->filename=$filename;
			$this->file_exist=file_exists($this->filename);
			$this->prepare_default_data();
		}
		else if($mode==2)	// write to sql
		{
			return NULL;
		}
		else if($mode==3)	// write to file and sql
		{
			return NULL;
		}
				
	}
	
	/**
	 * When you create a new log file you can unset whatever columns you like
	 *
	 * @param onedimensional array $disable_columns
	 */
	public function unset_columns_and_values($disable_columns)
	{
		if(is_array($disable_columns))
		{
			foreach ($disable_columns as $value)
			{
				if(!$this->file_exist)
				{
					if(array_key_exists($value, $this->fields))
					unset($this->fields["{$value}"]);
				}
			}
		}
	}
	
	/**
	 * When you create a new log file you can set whatever columns you like
	 *
	 * @param onedimensional array $enable_columns
	 */
	public function set_columns_and_values($enable_columns)
	{
		if(is_array($enable_columns))
		{
			foreach ($enable_columns as $key => $value)
			{
				if($this->file_exist)
				{
					if(array_key_exists($key, $this->fields))
					{
						$this->fields["{$key}"]=$value;
					}							
				}
				else 
					$this->fields["{$key}"]=$value;
			}
		}
	}
	
	/**
	 * this method checks if the given file already exists. If the file exist it sets the default set of columns, otherwise it gets the first row from the file (which is a header)
	 *
	 * @return bool
	 */
	private function prepare_default_data()
	{
		if($this->file_exist)
		{
			if(!$this->file = fopen($this->filename, "r"))
				return false;
			else
			{
				$line=fgets($this->file);
				$att=explode($this->newline, $line);
				$att=explode($this->tab, $att[0]);
				
				foreach($att as $value)
				{
					if($value=="TIME")
						$this->fields["TIME"]=date("d-m-Y H:i:s");
					else if($value=="IP")
						$this->fields["IP"]=$_SERVER['REMOTE_ADDR'];
					//else if($value=="REFERER")
						//$this->fields["REFERER"]="klobasa debela";
					else if($value=="SKRIPTA_ABS_POT")
						$this->fields["SKRIPTA_ABS_POT"]=$_SERVER['PHP_SELF'];
					else if($value=="USER_ID")
					{
						if(isset($_SESSION["UserInfo"]["id"]))
							$this->fields["USER_ID"]=$_SESSION["UserInfo"]["id"];
						else
							$this->fields["USER_ID"]="???";
					}
					else if($value=="POST")
					{
						if(isset($_POST))
							$this->fields["POST"]=$_POST;
						else
							$this->fields["POST"]="-----";
					}
					else if($value=="GET")
					{
						if(isset($_GET))
							$this->fields["GET"]=$_GET;
						else
							$this->fields["GET"]="-----";
					}
					else if($value=="SESSION")
					{
						if(isset($_SESSION))
							$this->fields["SESSION"]=$_SESSION;
						else
							$this->fields["SESSION"]="-----";
					}
					else 
						$this->fields["{$value}"]="";
				}
				
				$this->close_file();
				return true;
			}
		}
		
		/*$nekaj=array();
		$nekaj["ena"]="ena";
		$nekaj["dva"]="dva";
		$nekaj["tri"]="tri";
		
		$post=array();
		
		$post["id"]=34;
		$post["action"]="update";
		$post["db_table"]="warpit.nekaj_pac";
		$post["nekaj"]=$nekaj;*/
				
		$this->fields["TIME"]=date("d-m-Y H:i:s");
		$this->fields["IP"]=$_SERVER['REMOTE_ADDR'];
		//$this->fields["REFERER"]="klobasa debela";
		$this->fields["SKRIPTA_ABS_POT"]=$_SERVER['PHP_SELF'];
		$this->fields["USER_ID"]=$_SESSION["UserInfo"]["id"];
		$this->fields["POST"]=$_POST;
		$this->fields["GET"]=$_GET;
		$this->fields["SESSION"]=$_SESSION;
		
		return true;			
	}
	
	
	/**
	 * If the file doesnt exist it writes the headers to thew file and therefor prepares the file to be written to
	 *
	 * @return bool
	 */
	public function prepare_file()
	{		
		if(!$this->file_exist)
		{
			if(!$this->file = fopen($this->filename, "w"))
				return false;
			else
			{
				$fields=array_keys($this->fields);
				$fields=join($this->tab, $fields);
				$fields.=$this->newline;
				
				
				if(fwrite($this->file, $fields)===FALSE)
					return false;
				
				$this->close_file();
			}
			return true;	
		}
		
		return true;
	}

	
	/**
	 * This method checks if a script should be logged or not
	 *
	 * @return bool
	 */
	private function check_to_log_script()
	{
		if(count($this->log_dir)==0)
		{
			if(count($this->dont_log_dir)==0)
				return true;
			else 
			{
				foreach($this->dont_log_dir as $value)
				{
					if(strpos($value, $_SERVER['PHP_SELF'])!==FALSE)
						$search2=FALSE;
				}

				if($search2===FALSE)
					return true;
				else
					return false;
			}
			
		}
		else if(count($this->dont_log_dir)==0)
		{
			foreach($this->log_dir as $value)
			{
				if(strpos($value, $_SERVER['PHP_SELF'])!==FALSE)
					$search2=TRUE;
			}

			if($search2===TRUE)
				return true;
			else
				return false;
		}
		else 
		{
			foreach($this->dont_log_dir as $value)
			{
				if(strpos($value, $_SERVER['PHP_SELF'])!==FALSE)
					$search2=FALSE;
			}
			
			foreach($this->log_dir as $value)
			{
				if(strpos($value, $_SERVER['PHP_SELF'])!==FALSE)
					$search1=TRUE;
			}
			
			if(($search1===TRUE && $search2===FALSE) || ($search1===TRUE && $search2!==FALSE))
				return true;
			else
				return false;
		}
		
	}
	
	/**
	 * The method gets the columns and their values and parses the whole variable "fields" into a string and then writes this string to the file
	 *
	 * @return bool
	 */
	public function write_to_file()
	{		
		if($this->check_to_log_script())
		{
			$string=array();
			foreach($this->fields as $key => $value)
			{
				if(is_array($this->fields["{$key}"]))
				{
					$arr_to_str="";
					$arr_to_str=json_encode($this->fields["{$key}"]);
					$string[]=$arr_to_str;
					
				}
				else 
				{
					if($this->fields["{$key}"]=="")
						$string[]="-----";
					else
						$string[]=$this->fields["{$key}"];
				}				
			}
			$string=join($this->tab, $string) . $this->newline;
			
			if($this->file = fopen($this->filename, "a"))
			{
				if (!fwrite($this->file, $string)) 
		        {
		        	$this->close_file();
		            return false; // failed.
		        }
		        else 
		        {
		        	$this->close_file();
		            return true; //success.
		        }
			}
			return true;
		}
	}
	
	/**
	 * Closes the link to the file
	 *
	 */
	private function close_file()
	{
		fclose($this->file);
	}
	
	/**
	 * This method sets what scripts or directories should be logged
	 *
	 * @param onedimensional array $log_dir
	 */
	public function set_dir_to_log($log_dir)
	{
		if(is_array($log_dir))
		{
			foreach ($log_dir as $value)
			{
				if(!array_search($value, $this->log_dir) && !array_search($value, $this->dont_log_dir))
				{
					$this->log_dir[]=$value;					
				}
			}
		}
	}
	
	
	
	/**
	 * This method sets what scripts or directories should NOT be logged
	 *
	 * @param onedimensional array $dont_log_dir
	 */
	public function unset_dir_to_log($dont_log_dir)
	{
		if(is_array($dont_log_dir))
		{
			foreach ($dont_log_dir as $value)
			{
				if(!array_search($value, $this->log_dir) && !array_search($value, $this->dont_log_dir))
				{
					$this->dont_log_dir[]=$value;					
				}
			}
		}
	}
}


/*
$write= new logger(PATH_TO_ROOT."/_log/test.log", 1);

$enable=array();
$enable["ERIK"]="EEEEEEEEE";
$enable["CERPNJAK"]="CCCCCCCCCC";
$enable["HASH"]=md5(date("s"));
//$write->set_columns_and_values($enable);		// if you want to set extra columns uncomment this line (if file exists then only the existing columns will store values)


$disable=array();
$disable[]="TIME";
$disable[]="REFERER";
$disable[]="POST";
//$write->unset_columns_and_values($disable);	// if you want to unset columns uncomment this line (you can do that only if the file doesnt exist allready)

$log_dir=array();
$log_dir[]='/logger/warpit/webcati/_classes/lejko.php';
$log_dir[]='/logger/warpit/webcati/_classes/da_vidimo.php';
//$write->set_dir_to_log($log_dir);

$dont_log_dir=array();
$dont_log_dir[]='/logger/warpit/webcati/_classes';
//$write->unset_dir_to_log($dont_log_dir);

echo "<pre>";
print_r($write->log_dir);
echo "</pre>";

echo "<pre>";
print_r($write->dont_log_dir);
echo "</pre>";

$write->prepare_file();		// checks if the file already exists and if not it creates one and inserts columns stored in the objects variable called "fields" 

if($write->write_to_file())
	echo "TRUE";
else
	echo "FALSE";

	*/
?>