<?php
// ======================================================================== //
//   KOOBI - CMS                                                            //
//   SCRiPTMAFiA 2005 - THE DiRTY HANDS ON YOUR SCRiPTS                     //
//                                                                          //
//   DREAM4 - AM MICHELSGRUND 7 - 69469 WEINHEIM - GERMANY                  //    
//   TEL. +49(0) 6201 - 980442 / FAX. +49(0) 6201 - 64809                   //
// ======================================================================== //
if(!checkactive('forums')) include(dirname(__FILE__)."/lib/notactive.php" );
$sname = simpletitle($lang['forums']);

$fid = ($_GET['fid'] == "") ? $_POST['fid'] : $_GET['fid'];

if ($fid == "") {
	$EOUT = stderror("nopermission", $lang['f_err_permited'], str_replace("__URL__", "index.php", $lang['redirect']), "index.php", 1);
	$error = 1;
	$NOOUT = 1;
}

$forum_result = new dbc("SELECT  id, status, title, password, category_id FROM " . PREFIX . "_f_forum WHERE id = '" . $fid . "'");

// link: neue kategorie
$newcatlink = "index.php?p=newcategory&amp;pid=" . $fid;

// es wurde eine falsche fid übergeben
if ($forum_result->numrows() < 1) {
	$EOUT = msg("f_forum", "f_noid", str_replace("__URL__", "index.php?p=showforums", $lang['redirect']), "index.php?p=showforums");
	$NOOUT = 1;
}

$forum_obj = $forum_result->fetchrow();

// navigation erzeugen
$navigation = getNavigation($fid, "forum", null);

$tmp_navi = $navigation . $lang["f_navi_separator"] . $forum_obj->title;

$tmpl->assign("navigation", $tmp_navi);
$tmpl->assign("treeview", @explode($lang['f_navi_separator'], $tmp_navi));

$pass = false;

if ($forum_obj->password != "") {
	$f_pass_id = $_COOKIE['f_pass_id'];
	$pass_id = explode(";", $f_pass_id);
	
	
	$p1 = $_COOKIE["f_pass_id_" . $_REQUEST['fid']];
	$p2 = $forum_obj->password;
	if( $p1 == $p2 ){
		$pass = true;
		
	} else {
		$stitle = $lang["f_title_forum_login"];
		$sname = simpletitle($stitle);
		
		$tmpl->assign("fid", $fid);
		$tmpl->assign("lang", $lang);
		$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/forumlogin.tpl")));
	}
	} else {
	$pass = true;
}

if ($pass) {
	// ====================================================================================
	// zugriffsrechte
	// ====================================================================================
	$group_ids = array();
	define("MISCIDSINC", 1);
	$cat_query = new dbc("SELECT group_id FROM " . PREFIX . "_f_forum WHERE id = '" . $_REQUEST['fid'] . "'");
	while ($category = $cat_query->fetchrow_assoc()) {
		
		// miscrechte
		
		if (@is_numeric(UID)) {
			$queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = '" . UID . "'";
			$result = new dbc($queryfirst);
			$user = $result->fetchrow();
			
			if($user->group_id_misc != ""){
				$group_ids_pre = UGROUP . ";" . $user->group_id_misc;
				$group_ids     = @explode(";", $group_ids_pre);
				
			} else {
				$group_ids[] = UGROUP; 
			}
		} else {
			$group_ids[] = 2;
		}
		
		$forum_obj->permissions = getForumPermissionsByUser($forum_obj->id, UID);
		$forum_obj->permissions[FORUM_PERMISSION_CAN_SEE] = 0;
		$groups = explode(",", $category['group_id']);
		$can_see = 0; 
		if (array_intersect($group_ids, $groups)) {
			
			$can_see = 1;
		}
		
		
		if ($can_see != 1){ 
			$EOUT = msg("f_forum", "f_noid", str_replace("__URL__", "index.php?p=showforums", $lang['redirect']), "index.php?p=showforums");
			$NOOUT = 1;
		}			
	}
	
	// ============================================
	//  <<-- Falls der User eine Sortierung und
	//  eine Filterung angefordert hat -->>
	// ============================================
	$unit = ($_POST['unit'] != "") ? mysql_escape_string($_POST['unit']) : mysql_escape_string($_GET['unit']);
	$period = ($_POST['period'] != "") ? mysql_escape_string($_POST['period']) : mysql_escape_string($_GET['period']);
	$order = ($_POST['sort'] != "") ? mysql_escape_string($_POST['sort']) : mysql_escape_string($_GET['sort']);
	
	$order_orig = $order;
	
	switch ($unit) {
		// Stunden
		case 'h':
		// sekunden * 60 * 60 = stunde
		$divisor = 60 * 60;
		$where_time_stat = " AND ((UNIX_TIMESTAMP(NOW()) / $divisor) - (UNIX_TIMESTAMP(p.datum) / $divisor)) <= $period";
		break;
		
		// Tage
		case 'd':
		// sekunden * 60 * 60 * 24 = tag
		$divisor = 60 * 60 * 24;
		$where_time_stat = " AND ((UNIX_TIMESTAMP(NOW()) / $divisor) - (UNIX_TIMESTAMP(p.datum) / $divisor)) <= $period";
		break;
		
		// Monat
		case 'm':
		$divisor = 60 * 60 * 24 * 30;
		$where_time_stat = " AND ((UNIX_TIMESTAMP(NOW()) / $divisor) - (UNIX_TIMESTAMP(p.datum) / $divisor)) <= $period";
		break;
		
		case 'all':
		$where_time_stat = " AND 1";
	}
	
	$order_by = ($_GET["sortby"] != "") ? mysql_escape_string($_GET["sortby"]) : "last_post_int";
	$order = ($order != "") ? $order : "DESC";
	
	// wenn user nicht mod dieses forum ist und kein admin ist, nicht freigeschaltete themen verbergen
	if(!is_mod($fid)) { 
		$q_topic_count_extra .= " AND t.opened = 1 ";
	}
	
	$q_topic_count = "
	SELECT DISTINCT
		t.id, 
		t.title, 
		t.status,
		t.datum, 
		t.type,
		t.views, 
		t.posticon, 
		t.uid, 
		u.uname,
		t.replies,
		t.last_post
	FROM 
		" . PREFIX . "_f_topic AS t,
		" . PREFIX . "_user AS u,
		" . PREFIX . "_f_post AS p
	WHERE 
		(t.forum_id = '" . $fid . "' AND u.uid = t.uid)
	AND 
		p.topic_id = t.id 
		$q_topic_count_extra 
		$where_time_stat
	";
	
	
	// der user darf nur eigene topics sehen
	if ($forum_obj->permissions[FORUM_PERMISSION_CAN_SEE_TOPIC] == 0) {
		$only_own_topics = " AND t.uid = '" . UID . "'";
	}
	
	$q_topic_count .= $only_own_topics;
	$q_topic_count .= " AND t.opened = '1'";
	$r_topic_count = new dbc($q_topic_count);
	$num = $r_topic_count->numrows();
	
	
	
	$limit = ($_REQUEST['pp']=="") ? 15 : $_REQUEST['pp'];
	
	if(!isset($page)){
		$page = 1;
	}
	
	$seiten = ceil($num / $limit);
	$a = prepage() * $limit - $limit;
	
	if(!is_mod($fid)) { 
		$topic_query_extra .= " AND t.opened = 1 ";
	}
	
	$topic_query = "
	SELECT DISTINCT
		t.id, 
		t.title, 
		t.status,
		t.datum, 
		t.type,
		t.views, 
		t.posticon, 
		t.uid, 
		u.uname,
		u.user_regdate,
		t.last_post,
		r.rating,
		t.opened
	FROM 
		" . PREFIX . "_f_topic AS t,
		" . PREFIX . "_user AS u,
		" . PREFIX . "_f_rating AS r,
		" . PREFIX . "_f_post AS p
	WHERE 
		(t.forum_id = '" . $fid . "' AND u.uid = t.uid  AND r.topic_id = t.id)
	AND 
		p.topic_id = t.id 
		$topic_query_extra
		$where_time_stat
		$only_own_topics
	ORDER BY
		type DESC, $order_by $order 
	LIMIT $a, $limit
	";
	
	$order = ($order == "DESC") ? "ASC" : "DESC";
	$topic_result = new dbc($topic_query);
	#echo "<pre>$topic_query";
	$topic_array = array();
	
	// topic liste durchgehen.
	// fuer jeden topic einen link zusammenstellen, damit im template der user
	// keine fehler machen kann.
	// fuer jeden topic den autor ermitteln und als einen link
	// zum userprofil im topic ablegen.
	
	while ($topic = $topic_result->fetchrow_assoc()) {
		$topic['link'] = "index.php?p=showtopic&amp;toid=" . $topic["id"] . "&amp;fid=$_REQUEST[fid]";
		$topic['closelink'] = "index.php?p=closetopic&amp;fid=" . $fid . "&amp;toid=" . $topic["id"];
		$topic['openlink'] = "index.php?p=opentopic&amp;fid=" . $fid . "&amp;toid=" . $topic["id"];
		$topic['dellink'] = "index.php?p=deltopic&amp;fid=" . $fid . "&amp;toid=" . $topic["id"];
		$topic['movelink'] = "index.php?p=move&amp;item=t&amp;id=" . $topic["id"];
		$topic['typelink'] = "index.php?p=forum&amp;action=change_type&amp;id=" . $topic["id"] . "&amp;fid=" . $fid;
		$topic['title'] = stripslashes($topic['title']);
		$topic['opened'] = $topic['opened'];
		
		$rating = @explode(",", $topic['rating']);
		$topic['rating'] = (int) (array_sum($rating) / count($rating));
		
		if ($topic["status"] == FORUM_STATUS_MOVED) {
			$topic["statusicon"] = getIcon("thread_moved.gif", "moved");
		} else {
			if ($islogged == 0 || ($forum_obj->status == FORUM_STATUS_CLOSED) ) {
				// nicht eingeloggt oder forum geschlossen
				$topic["statusicon"] = getIcon("thread_lock.gif", "lock");
			} else {
				setTopicIcon($topic, $forum_obj);
			}
		}
		
		$user_query = "SELECT uid, uname,  user_regdate FROM " . PREFIX . "_user WHERE uid = '" . $topic['uid'] . "'";
		
		$user_result = new dbc($user_query);
		$user_row = $user_result->fetchrow();
		
		$topic["autorlink"] = "index.php?p=user&amp;id=$topic[uid]&amp;area=$area";
		$topic["autor"] = $topic["uname"];
		
		// letzten beitrag ermitteln
		$last_post_query = "
		SELECT 
			p.id,
			datum,
			p.topic_id,
			p.uid,
			u.uname,
			u.user_regdate
		FROM 
			" . PREFIX . "_f_post AS p, 
			" . PREFIX . "_user AS u 
		WHERE
			p.topic_id = " . $topic["id"] . " AND 
			u.uid = p.uid 
		GROUP BY
			p.id 
		ORDER BY
			datum DESC
		LIMIT 1
		";
		
		$last_post_result = new dbc($last_post_query);
		
		$topic_post_count = $last_post_result->numrows();
		
		$last_post_row = $last_post_result->fetchRow();
		// ALT // $last_post_row->link = "<a class='forum_links' href='index.php?p=user&amp;id=$last_post_row->uid&amp;area=$area'>" . $lpname . "</a>";
		$last_post_row->link = ($last_post_row->user_regdate < 2) ? $lang['gguest'] : "<a class='forum_links' href='index.php?p=user&amp;id=$last_post_row->uid&amp;area=$area'>$last_post_row->uname</a>";
		
		$topic["lastposter"] = $last_post_row;
		
		// =================================================
		//  <<-- Anzahl der Postings ermitteln -->>
		// =================================================
		
		// als limit fuer die maximale anzahl der postings auf
		// einer seite wird 15 als standardwert genommen
		$limit = 15;
		
		$q_post = "SELECT COUNT(id) as count FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic['id'];
		$r_post = new dbc($q_post);
		$post = $r_post->fetchrow();
		
		$numPages = getPageNum($post->count, $limit);
		$topic['navigation_page'] = ($numPages == 1) ? 0 : $numPages;
		$topic['next_page'] = $numPages;
		$topic['replies'] = $post->count;
		
		array_push($topic_array, $topic);
	}
	
	$subcat_query = "SELECT id, title, position, comment, parent_id, group_id FROM " . PREFIX . "_f_category WHERE parent_id = " . $fid . " ORDER BY position";
	$subcat_result = new dbc($subcat_query);
	$subcat_array = array();
	
	while ($subcategory = $subcat_result->fetchrow_assoc()) {
		// gruppen, die zugriff auf die kategorie haben
		$groups = @explode(",", $subcategory['group_id']);
		
		if (array_intersect($group_ids, $groups)) {
			// den status der anzeige aus dem cookie holen
			$position = strpos($_COOKIE["categories"], "id" . $subcategory["id"]);
			if ( is_numeric($position) ) {
				$subcategory["display"] = "none";
				$subcategory["image"] = "plus.gif";
			}
			
			$subcategory["link"] = "index.php?p=showforums&amp;cid=" . $subcategory["id"] . "&amp;pid=" . $fid;
			
			array_push($subcat_array, $subcategory);
			
			$subforum_query = "
			SELECT 
			group_id,
			id, 
			title, 
			comment, 
			status
			FROM 
			" . PREFIX . "_f_forum 
			WHERE 
			category_id = " . $subcategory["id"] . " AND 
			active = 1
			ORDER BY
			position";
			
			$subforum_result = new dbc($subforum_query);
			$subforum_array[$subcategory["title"]] = array();
			
			while ($subforum = $subforum_result->fetchrow_assoc()) {
				
				if ($subforum['group_found'] != "no") {	
					$pcount = 0;
					$q_tcount = "SELECT id FROM " . PREFIX . "_f_topic WHERE forum_id = " . $subforum["id"];
					$r_tcount = new dbc($q_tcount);
					$subforum["tcount"] = $r_tcount->numrows();
					
					$ids = "";
					
					while ($tid = $r_tcount->fetchRow()) {
						if ($ids == "") {
							$ids .= $tid->id;
						} else {
							$ids .= " OR topic_id = " . $tid->id;
						} 
					}
					
					if ($ids != "") {
						$q_pcount = "
						SELECT 
						id
						FROM 
						" . PREFIX . "_f_post 
						WHERE 
						topic_id = $ids 
						";
						
						$r_pcount = new dbc($q_pcount);
						$pcount = $r_pcount->numrows();
						
						// ====================
						// letzter beitrag
						$q_last_post = "
						SELECT
							p.datum,
							p.topic_id,
							p.uid,
							p.id
						FROM
							" . PREFIX . "_f_post AS p,
							" . PREFIX . "_f_topic AS t
						WHERE
							p.topic_id = $ids AND
							t.id = p.topic_id
						ORDER BY
							p.datum DESC
						LIMIT 1
						";
						
						$r_last_post = new dbc($q_last_post);
						$last_post = $r_last_post->fetchrow();
						
						$q_replies = "SELECT COUNT(id) AS replies FROM " . PREFIX . "_f_post WHERE topic_id = " . $last_post->topic_id;
						$r_replies = new dbc($q_replies);
						$replies = $r_replies->fetchrow();
						
						$last_post->replies = $replies->replies;
						
						$q_last_user = "SELECT uname, user_regdate FROM " . PREFIX . "_user WHERE uid = " . $last_post->uid;
						$r_last_user = new dbc($q_last_user);
						$last_user = $r_last_user->fetchrow();
						
						$last_post->regdate = $last_user->user_regdate;
						$last_post->uname = $last_user->uname;
						
						$q_topic_title = "SELECT title FROM " . PREFIX . "_f_topic WHERE id = " . $last_post->topic_id;
						$r_topic_title = new dbc($q_topic_title);
						$topic_title = $r_topic_title->fetchrow();
						
						$last_post->title = $topic_title->title;

						$last_post->page = getPageNum($last_post->replies, 15);
						$subforum['lastpost'] = $last_post;
						
					}
					
					// Forumicon
					if ($islogged == 0) {
						$subforum["statusicon"] = getIcon("forum_old_lock.gif", "forum");
					} else {
						setForumIcon($subforum);
					}
					
					$subforum["pcount"] = $pcount;
					// ==============================================================
					//  <<-- Unterkategorien und Unterforen -->>
					// ==============================================================
					$q_subcat = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = " . $subforum['id'];
					$r_subcat = new dbc($q_subcat);
					
					$subfors = array();
					
					while ($subcat = $r_subcat->fetchrow()) {
						$q_subfor = "SELECT id, title FROM " . PREFIX . "_f_forum WHERE category_id = " . $subcat->id;
						$r_subfor = new dbc($q_subfor);
						
						while ($subfor = $r_subfor->fetchrow()) {
							$subfors[] = $subfor;
						}
					}
					
					
					$subforum["link"] = "index.php?p=showforum&amp;fid=$subforum[id]";
					$subforum['subforums'] = $subfors;
					array_push($subforum_array[$subcategory["title"]], $subforum);
				} 
			} 
		} 
	}
	
	$stitle = $lang["forumtitle"];
	$sname = simpletitle(str_replace($lang['f_navi_separator'], " - ", strip_tags($navigation)) . ' - ' . $forum_obj->title);
	
	$tmpl->register_function("get_post_icon", "getPostIcon");
	$tmpl->register_function("get_status_icon", "getStatusIcon");
	
	$tmpl->assign("sort_by_theme_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=title&amp;sort=$order");
	$tmpl->assign("sort_by_reply_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=replies&amp;sort=$order&");
	$tmpl->assign("sort_by_author_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=uname&amp;sort=$order");
	$tmpl->assign("sort_by_hits_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=views&amp;sort=$order");
	$tmpl->assign("sort_by_rating_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=rating&amp;sort=$order");
	$tmpl->assign("sort_by_lastpost_link", "index.php?p=showforum&amp;fid=" . $fid . "&amp;sortby=last_post_int&amp;sort=$order");
	
	if ($limit < $num) {
		$tmpl->assign('pages', pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?p=showforum&amp;fid=$fid&amp;area=$area&amp;unit=$unit&amp;period=$period&amp;sortby=$order_by&amp;sort=$order_orig&amp;pp=$limit&amp;page={s}\">{t}</a> "));
	}
	
	// foren fuer das dropdown feld
	$forums_dropdown = array();
	getForums(0, $forums_dropdown, "", $fid);
	
	$categories = array();
	getCategories(0, $categories, "");
	
	$tmpl->assign("subnavi", $subnavi);
	$tmpl->assign("theme", $THEME);
	$tmpl->assign("rsslink", "index.php?rss=forums&amp;fid=$fid");
	$tmpl->assign("categories_dropdown", $categories);
	$tmpl->assign("forum", $forum_obj);
	$tmpl->assign("f_id", $forum_obj->id);
	$tmpl->assign("newcatlink", $newcatlink);
	$tmpl->assign("lang", $lang);
	$tmpl->assign("categories", $subcat_array);
	$tmpl->assign("forums", $subforum_array);
	$tmpl->assign("topics", $topic_array);
	$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/showforum.tpl")));
} // if pass
?>