<?php

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

class File {
	public $fid;
	public $name;
	public $mimetype;

	public function link()
	{
		return "?mode=file&amp;fid=" . $this->fid;
	}

	public function show()
	{
		global $PERMSTORE;
		echo "<div class=\"file\">\n";
		echo "  <a class=\"delete\" href=\"?mode=filehandler&amp;task=delete&amp;fid=" . $this->fid . "\">Delete</a>\n";
		echo "  <div class=\"filename\">Filename: <a href=\"" . $this->link() . "\">" . $this->name  . "</a>(" . $this->mimetype. ")</div>\n";
		echo "  <div class=\"filesize\">Size: " . ceil(filesize($PERMSTORE . "/" . $this->fid) / 1024) . "kb</div>\n";
		echo "</div>\n";
	}

	public function File($fid, $name, $mimetype)
	{
		$this->fid = $fid;
		$this->name = $name;
		$this->mimetype = $mimetype;
	}
}

class Files {

	private $file;
	public $files = array();
	
	public function add($file) {
		$key = $file->fid;
		$this->files[$key] = $file;
	}
	
	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, "<files>\n");
 		foreach($this->files as $file) {
			fwrite($fp, "  <file fid=\"" .
						 htmlspecialchars($file->fid, ENT_QUOTES, "UTF-8") . "\"\n");
			fwrite($fp, "        name=\"" . 
						 htmlspecialchars($file->name, ENT_QUOTES, "UTF-8") . "\"\n");
			fwrite($fp, "        mimetype=\"" . 
						 htmlspecialchars($file->mimetype, ENT_QUOTES, "UTF-8") . "\">\n");
			fwrite($fp, "  </file>\n");
		}
		fwrite($fp, "</files>\n");

		fclose($fp);
	}

	public function show()
	{
 		foreach($this->files as $file) {
			$file->show();
		}
	}

	public function getFile($fid)
	{
		$file = $this->files[$fid]; 
		return $file;
	}

	public function newFile($tempfile, $name)
	{
		global $PERMSTORE;
		$fid = time();

		// move tempfile to permstore and put it in db.
		move_uploaded_file($tempfile, $PERMSTORE . "/" . $fid);

		$f = new File($fid, $name, getMimeType($name)->name);
		$this->add($f);

		// We cannot wait to write the db, otherwise we'll get inconsistency!
		$this->write();

		// Return new file id.
		return $fid;
	}

	public function deleteFile($fid)
	{
		global $PERMSTORE;
		unlink($PERMSTORE . "/" . $fid);
		unset($this->files[$fid]);

		// We cannot wait to write the db, otherwise we'll get inconsitency!
		$this->write();
	}

	private function read()
	{
		$dom = new DomDocument;
		$dom->preserveWhiteSpace = FALSE;
		$dom->load($this->file);
		$files = $dom->getElementsByTagName('file');

		foreach ($files as $f) {
			$file = new File($f->getAttribute('fid'),
											 $f->getAttribute('name'),
											 $f->getAttribute('mimetype'));

			$this->add($file);
		}

	}

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

}
?>