<?php /* -*- Mode: php; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */

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

/**
 * <?xml version="1.0" encoding="UTF-8"?>
 * <thread tid="1" name="Thread1">
 *   .
 *   .
 *   .
 * </thread>
 */

class Thread {
	public $tid;
	public $name;
	public $lastseen = array();
	public $lastpost;

  public $first_pid;
  public $first_title; 
  public $first_user;
  public $first_date;

  public $last_pid;
  public $last_title; 
  public $last_user;
  public $last_date;

  public $numposts;
  public $numunread;

	public function show()
	{
		global $fid, $current_user;
    global $users;

    $str = "";

		$jumptonew = "";
    $newcls = " thread_nonew";
		if($this->lastseen[$current_user->uid] < $this->lastpost) {
      $newcls = " thread_new";
			$jumptonew = "#firstunread";
    }

		$str .=  "    <div class=\"thread\">\n";
    $str .=  "      <span class=\"thread_icon".$newcls."\">&nbsp;</span>\n";
		$str .=  "      <span class=\"thread_title\"><a href=\"?fid=" . $fid .
      "&amp;tid=" .	$this->tid . $jumptonew."\">" . $this->name . "</a></span>\n";
    $str .=  "      <span class=\"thread_numposts\">".$this->numposts." posts";
    if($this->numunread != 0) {
      $str .=  " <strong>(".$this->numunread." unread)</strong>";
    }
    $str .=  "</span>\n";
    $str .=  "      <span class=\"thread_lastpost\">Last post: ".
      date("j. M Y - G:i", $this->lastpost)."</span>\n";
		$user = $users->getUser($this->first_user);
    $str .=  "      <span class=\"thread_createdby\">By ".$user->name;
    $str .=  " at ". date("j. M Y - G:i", $this->first_date)."</span>\n";
		$str .=  "    </div>\n";

    return $str;
	}

  public function processPost($pid, $title, $user, $date)
  {
    global $current_user;

    $this->numposts++;

    if($this->lastseen[$current_user->uid] < $date) {
      $this->numunread++;
    }

    if($date < $this->first_date || $this->first_date == -1) {
      $this->first_pid = $pid;
      $this->first_title = $title; 
      $this->first_user = $user;
      $this->first_date = $date;
    }

    if($date > $this->last_date || $this->last_date == -1) {
      $this->last_pid = $pid;
      $this->last_title = $title; 
      $this->last_user = $user;
      $this->last_date = $date;
    }
  }

	private function loadLastSeen($lastseen)
	{
		if($lastseen == "") return;
		$list = explode(",", $lastseen);
		foreach($list as $l) {
			$pair = explode("=", $l);
			if($pair[0] != "" && $pair[1] != "") {
				$this->lastseen[$pair[0]] = $pair[1];
			} 
		}
	}

	public function Thread($tid, $name, $lastpost, $lastseen)
	{
      $this->numunread = 0;
    $this->numposts = 0;
    $this->first_date = -1;
    $this->last_date = -1;
		$this->tid = $tid;
		$this->name = $name;
		$this->lastpost = $lastpost;
    if($this->lastpost == "") $this->lastpost = 0;
		$this->loadLastSeen($lastseen);
	}
}

class Threads {

	private $dir;
	public $threads = array();
	
	public function add($thread) {
		//		$key = $thread->name;
		//		$key = sprintf("%d-%d", $thread->lastpost, $thread->tid);
		//		$key = sprintf("%d", $thread->lastpost);
		$key = $thread->lastpost . "-" . $thread->tid;//name;
		//		echo "[" . $key . "]";
		$this->threads[$key] = $thread;
	}
	
	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 getThread($tid)
	{
		$thread = $this->threads[$tid]; 
		return $thread;
	}

  public function getLatestThread()
  {
    $tid = -1;
    $last = -1;
		foreach($this->threads as $thread) {
      if($thread->lastpost > $last) {
        $last = $thread->lastpost;
        $tid = $thread->tid;
      }
    }
    if($tid != -1) return $this->getThread($tid);
    return NULL;
  }

	public function show()
	{
    $str = "";
    
		foreach($this->threads as $thread) {
			$str .= $thread->show();
		}
    
    return $str;
	}

	public function newStuff()
	{
		global $current_user;

		foreach($this->threads as $thread) {
			if($thread->lastseen[$current_user->uid] < $thread->lastpost) return true;
		}

		return false;
	}

	private function recurser($parentpost, $element, $thread)
	{
		if($element->tagName != "post") return;

    $thread->processPost($element->getAttribute('pid'),
                         $element->getAttribute('title'),
                         $element->getAttribute('user'),
                         $element->getAttribute('date'));

		foreach($element->childNodes as $child) {
			if($child->tagName == "post")
				$this->recurser($post, $child, $thread);
		}
	}

	private function read()
	{
		$dh = opendir($this->dir);
		while($file = readdir($dh)) {
			if($file == "." || $file == "..") continue;
			$dom = new DomDocument;
			$dom->preserveWhiteSpace = FALSE;
			$dom->load($this->dir . "/" . $file);
			$threads = $dom->getElementsByTagName('thread');
			
			foreach($threads as $f) {
				$thread = new Thread($f->getAttribute('tid'),
														 $f->getAttribute('name'),
														 $f->getAttribute('lastpost'),
														 $f->getAttribute('lastseen'));

        foreach($f->childNodes as $child) {
          $this->recurser(false, $child, $thread);
        }

				$this->add($thread);
			}
		}
	}

	public function Threads($dir)
	{
		$this->dir = $dir;
		$this->read();
		krsort($this->threads);
	}

}
?>