<?php

include_once($UTIL_DIR . "/convert.php");
include_once($UTIL_DIR . "/threads.php");


class Forum {
	public $fid;
	public $readlist;
	public $writelist;
	public $name;
	private $newStuff;

	public function setNewStuff($newStuff)
	{
		$this->newStuff = $newStuff;
	}

	public function show()
	{
		echo "<div class=\"forum\">";
		if($this->newStuff) echo "<div class=\"new\"></div>";
		else echo "<div class=\"nonew\"></div>";
		echo "<a href=\"?fid=" . $this->fid . "\">" . $this->name . "</a>";
		echo "</div>";
	}

	public function Forum($fid, $readlist, $writelist, $name)
	{
		$this->fid = $fid;
		$this->readlist = $readlist;
		$this->writelist = $writelist;
		$this->name = $name;
	}
}

class Forums {

	private $file;
	public $forums = array();
	
	public function add($forum) {
		$key = $forum->fid;
		$this->forums[$key] = $forum;
	}
	
	public function write()
	{
		/*
		$fp = fopen($this->file, "w");

		$block = TRUE;
		flock($fp, LOCK_EX, $block); // do an exclusive lock

		fwrite($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

		fwrite($fp, "<members>\n");
		foreach($this->members as $member) {
			fwrite($fp, "  <member id=\"" .
						 htmlspecialchars($member->id, ENT_QUOTES, "UTF-8") . "\"\n");
			fwrite($fp, "          name=\"" . 
						 htmlspecialchars($member->name, ENT_QUOTES, "UTF-8") . "\"\n");
			fwrite($fp, "          description=\"" . 
						 htmlspecialchars($member->description, ENT_QUOTES, "UTF-8") . "\"\n");
			fwrite($fp, "          image=\"" . 
						 htmlspecialchars($member->image, ENT_QUOTES, "UTF-8") . "\">\n");


			fwrite($fp, "  </member>\n");
		}
		fwrite($fp, "</members>\n");

		fclose($fp);
		*/
	}

	/*
	public function deleteForumUser($id)
	{
		if($this->members[$id]) {
			unset($this->members[$id]); 
			//			$this->write();
		} else {
			echo "<p>ERROR: User! <em>".$id."</em> does not exist!</p>\n";
			return false;
		}
		return true;
	}
	*/

	public function getForum($fid)
	{
		$forum = $this->forums[$fid]; 
		return $forum;
	}

	public function show()
	{
		foreach($this->forums as $forum) {
			$forum->show();
		}
	}

	private function read()
	{
		global $FORUMS_DIR;

		$dom = new DomDocument;
		$dom->preserveWhiteSpace = FALSE;
		$dom->load($this->file);
		$forums = $dom->getElementsByTagName('forum');

		foreach($forums as $f) {
			$forum = new Forum($f->getAttribute('fid'),
												 $f->getAttribute('readlist'),
												 $f->getAttribute('writelist'),
												 $f->getAttribute('name'));

			$this->add($forum);

			$threads = new Threads($FORUMS_DIR . "/" . $f->getAttribute('fid'));
			$forum->setNewStuff($threads->newStuff());
		}
	}

	public function Forums($file)
	{
		$this->file = $file;
		$this->read();
	}

}
?>