<?php
/*
 * Project: NodeMap2.0
 * File: FileHandler.class.php
 * Purpose: Checking and reading node files from the server
 */

class FileHandler {
	private $filename;
	private $handle;

	/*
	 * Function: __construct (constructor)
	 * Description: Handling with a node file
	 * Parameters: string $filename, string $mode
	 * Returns: true is we've succesfully opened the file, otherwise false
	 */
	public function __construct($filename, $mode) {
		$this->filename = $filename;

		try {
			trigger_log(SYSLOG_DEBUG, 'Opening the file "' . $this->filename . '"', __FILE__, __LINE__);
			$this->handle = fopen($this->filename, $mode);
		} catch (Exception $err) {
			trigger_log(SYSLOG_ERR, 'Reading from file "' . $this->filename . '" failed', __FILE__, __LINE__);
			return false;
		}

		return true;
	}

	/*
	 * Function: read
	 * Description: Try to read the file we've opened in the constructor
	 * Parameters: -
	 * Returns: The content of the file if we can read from the file, otherwise false
	 */
	public function read() {
		$file = '';

		try {
			trigger_log(SYSLOG_DEBUG, 'Reading from file "' . $this->filename . '"', __FILE__, __LINE__);
			$file = stream_get_contents($this->handle);
		} catch (Exception $err) {
			trigger_log(SYSLOG_ERR, 'Reading from file "' . $this->filename . '" failed', __FILE__, __LINE__);
			return false;
		}

		return $file;
	}

	/*
	 * Function: write
	 * Description: Try to write to the file we've opened in the constructor
	 * Parameters: string $data
	 * Returns: true if we can write to the file, otherwise false
	 */
	public function write($data) {
		trigger_log(SYSLOG_DEBUG, 'Writing file "' . $this->filename . '"', __FILE__, __LINE__);

		try {
			fwrite($this->handle, $data);
		} catch (Exception $err) {
			trigger_log(SYSLOG_ERR, 'Couldn\'t write to file "' . $this->filename . '"', __FILE__, __LINE__);
			return false;
		}

		return true;
	}

	public function __destruct() {
		trigger_log(SYSLOG_DEBUG, 'Closing file "' . $this->filename . '"', __FILE__, __LINE__);
		fclose($this->handle);
	}
}