<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE(c) DREAM4(r) 
// HTTP://WWW.DREAM4.DE
//=================================================================
// ACHTUNG!
// DIESER PROGRAMMCODE IST URHERRECHTLICH GESCHUETZT
// DIE URHEBERRECHTE LIEGEN BEI DEN JEWEILIGEN AUTOREN.
// AENDERUNGEN IN DIESER DATEI ERFOLGEN AUF EIGENE GEFAHR!
// ES IST NICHT GESTATTET, DEN COPYRIGHTHINWEIS ZU AENDERN ODER ZU
// ENTFERNEN. NUR WENN SIE EINE COPYRIGHTHINWEIS-ENTFERNUNG BESTELLT
// HABEN, DUERFEN SIE DIESEN ENTFERNEN.
//================================================================
// BEI FRAGEN WENDEN SIE SICH BITTE AN: KONTAKT@DREAM4.DE
//=================================================================
if(!defined('BASE_DIR')) exit;
if(!get_active('forums'))
{
	notActive();
}

$only_own_topics = '';
$q_topic_count_extra = '';
$subforum_array = '';

$sname = $GLOBALS['config_vars']['Forums_Name'];

$fid = $_REQUEST['fid'];
if ($fid == "")
{
	koobi_message('Global_NoPermission', 'Forums_ErrorNoPermission', HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
}

$forum_result = $GLOBALS['db']->Query("SELECT  id, status, title, password, category_id FROM " . PREFIX . "_f_forum WHERE id = '" . $fid . "'");
$forum_obj    = $forum_result->fetchrow();

//=================================================================
// es wurde eine falsche fid übergeben
//=================================================================
if ($forum_result->numrows() < 1)
{
	koobi_message('Forums_Title', 'Forums_ErrorNoPermission', HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
}

//=================================================================
// navigation erzeugen
//=================================================================
$navigation = getNavigation($fid, "forum", null);
$tmp_navi = $navigation . $GLOBALS["config_vars"]["Forums_Splitter"] . $forum_obj->title;

$GLOBALS['tmpl']->assign("navigation", $tmp_navi);
$GLOBALS['tmpl']->assign("treeview", @explode($GLOBALS['config_vars']['Forums_Splitter'], $tmp_navi));

$pass = false;

if ($forum_obj->password != "")
{
	$f_pass_id = (isset($_COOKIE['f_pass_id'])) ? $_COOKIE['f_pass_id'] : '';
	$pass_id = explode(";", $f_pass_id);
	
	
	$p1 = (isset($_COOKIE['f_pass_id_' . $_REQUEST['fid']])) ? $_COOKIE['f_pass_id_' . $_REQUEST['fid']] : '';
	$p2 = $forum_obj->password;
	if( $p1 == $p2 )
	{
		$pass = true;
	} else {
		$stitle = $GLOBALS["config_vars"]["Forums_ForumTitle_login"];
		$sname = $stitle;
		
		$GLOBALS['tmpl']->assign('fid', $fid);
		$GLOBALS['tmpl']->assign('pagetitle_html', $stitle);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/forumlogin.tpl')); 
	}
} else {
	$pass = true;
}

if ($pass)
{
	//=================================================================
	// zugriffsrechte
	//=================================================================
	$group_ids = array();
	define("MISCIDSINC", 1);
	$cat_query = $GLOBALS['db']->Query("SELECT group_id FROM " . PREFIX . "_f_forum WHERE id = '" . $_REQUEST['fid'] . "'");
	while ($category = $cat_query->fetchrow_assoc())
	{
		// miscrechte
		if (@is_numeric(UID)) 
		{
			$queryfirst = "SELECT GruppeMisc as group_id_misc FROM " . PREFIX . "_benutzer WHERE Id = '" . UID . "'";
			$result = $GLOBALS['db']->Query($queryfirst);
			$user = $result->fetchrow();
			
			if(is_object($user) && $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)
		{ 
			koobi_message('Forums_PermissionDenied', 'Forums_ErrorNoPermission', HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
		}			
	}
	
	//=================================================================
	// Falls der User eine Sortierung und
	// eine Filterung angefordert hat
	//=================================================================
	$unit = (isset($_REQUEST['unit']) && $_REQUEST['unit'] != "") ? $_REQUEST['unit'] : '';
	$period = (isset($_REQUEST['period']) && $_REQUEST['period'] != '') ? $_REQUEST['period'] : '';
	$order = (isset($_REQUEST['sort']) && $_REQUEST['sort'] != "" && ($_REQUEST['sort']=='ASC' || $_REQUEST['sort']=='DESC')) ? $_REQUEST['sort'] : 'DESC'; 
	$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':
		case '':
		$where_time_stat = " AND 1";
	}
	$where_time_stat = (!preg_match('/[0-9]/',$period)) ? '' : $where_time_stat; 

	//=================================================================
	// Bad Requests fuer Sortierung abfangen
	//=================================================================
	$allowed_sort = array('last_post_int','title','replies','uname','views','rating');
	
	$order_by = (isset($_REQUEST['sortby']) && $_REQUEST['sortby'] != '' && (in_array($_REQUEST['sortby'],$allowed_sort))) ? $_REQUEST['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.Benutzername as uname,
		t.replies,
		t.last_post
	FROM 
		" . PREFIX . "_f_topic AS t,
		" . PREFIX . "_benutzer AS u,
		" . PREFIX . "_f_post AS p
	WHERE 
		(t.forum_id = '" . $fid . "' AND u.Id = 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] || @$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 = $GLOBALS['db']->Query($q_topic_count);
	$num = $r_topic_count->numrows();
	
	if(!isset($page)) $page = 1;
	
	$l_my = (!MySettings('Forum_Themen_Limit')) ? 15 : MySettings('Forum_Themen_Limit');
	$limit = ($l_my >= 1) ? $l_my : $_REQUEST['pp'];
	$seiten = ceil($num / $limit);
	$a = prepage() * $limit - $limit;
	
	$topic_query_extra = (!is_mod($fid)) ? " AND t.opened = 1 " : "";
	$order_by = str_replace('last_post_int', 'last_post', $order_by);
    
	$topic_query = "
	SELECT DISTINCT
		t.id, 
		t.title, 
		t.status,
		t.datum, 
		t.type,
		t.views, 
		t.posticon, 
		t.uid, 
		u.Benutzername as uname,
		u.Regdatum as user_regdate,
		u.Geloescht,
		t.last_post,
		r.rating,
		t.opened
	FROM 
		" . PREFIX . "_f_topic AS t,
		" . PREFIX . "_benutzer AS u,
		" . PREFIX . "_f_rating AS r,
		" . PREFIX . "_f_post AS p
	WHERE 
		(t.forum_id = '" . $fid . "' AND u.Id = 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 = $GLOBALS['db']->Query($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())
	{
		$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_f_topic_viewing WHERE Expire <= '" . time() . "'");
	
		$sql_view = $GLOBALS['db']->Query("SELECT  Ip FROM " . PREFIX . "_f_topic_viewing WHERE Topic='" . $topic["id"] . "'");
		
		$topic['viewing'] = $sql_view->numrows();
		$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.png", "moved");
		} else {
			if (ISLOGGED == 0 || ($forum_obj->status == FORUM_STATUS_CLOSED) )
			{
				// nicht eingeloggt oder forum geschlossen
				$topic["statusicon"] = getIcon("thread_lock.png", $GLOBALS['config_vars']['Forums_Icons_TopicClosed']);
			} else {
				setTopicIcon($topic, $forum_obj);
			}
		}
		
		$user_query = "SELECT Id as uid, Benutzername as uname,  Regdatum as user_regdate FROM " . PREFIX . "_benutzer WHERE Id = '" . $topic['uid'] . "'";
		$user_result = $GLOBALS['db']->Query($user_query);
		$user_row = $user_result->fetchrow();
		
		$topic["autorlink"] = "index.php?p=user&amp;id=$topic[uid]";
		$topic["autor"] = $topic["uname"];
		
		//=================================================================
		// letzten beitrag ermitteln
		//=================================================================
		$last_post_query = "
		SELECT 
			p.id,
			datum,
			p.topic_id,
			p.uid,
			u.Benutzername as uname,
			u.Regdatum as user_regdate,
			u.Geloescht 
		FROM 
			" . PREFIX . "_f_post AS p, 
			" . PREFIX . "_benutzer AS u 
		WHERE
			p.topic_id = " . $topic["id"] . " AND 
			u.Id = p.uid 
		GROUP BY
			p.id 
		ORDER BY
			datum DESC
		LIMIT 1
		";
		
		$last_post_result = $GLOBALS['db']->Query($last_post_query);
		$topic_post_count = $last_post_result->numrows();
		$last_post_row = $last_post_result->fetchRow();
		$last_post_row->link = ($last_post_row->user_regdate < 2) ? $GLOBALS['config_vars']['gguest'] : "<a title='" . $GLOBALS['config_vars']['Forums_ShowUserProfile'] . "' class='forum_links_small' href='index.php?p=user&amp;id=$last_post_row->uid'>$last_post_row->uname</a>";
		$last_post_row->link = ($last_post_row->Geloescht==1) ? $last_post_row->uname : $last_post_row->link;
		$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 = $GLOBALS['db']->Query($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 = $GLOBALS['db']->Query($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.png";
			}
			
			$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 = $GLOBALS['db']->Query($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 = '" . (int)$subforum["id"] . "'";
					$r_tcount = $GLOBALS['db']->Query($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 = $GLOBALS['db']->Query($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 = $GLOBALS['db']->Query($q_last_post);
						$last_post = $r_last_post->fetchrow();
						
						$replies = $GLOBALS['db']->RowQuery("SELECT COUNT(id) AS replies FROM " . PREFIX . "_f_post WHERE topic_id = '" . $last_post->topic_id . "'");
						$last_post->replies = $replies->replies;
						
						$last_user = $GLOBALS['db']->RowQuery("SELECT Benutzername, Regdatum FROM " . PREFIX . "_benutzer WHERE Id = '" . $last_post->uid . "'");
						$last_post->regdate = $last_user->Regdatum;
						$last_post->uname = $last_user->Benutzername;
						
						$q_topic_title = "SELECT title FROM " . PREFIX . "_f_topic WHERE id = '" . $last_post->topic_id . "'";
						$r_topic_title = $GLOBALS['db']->Query($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.png", "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 = $GLOBALS['db']->Query($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 = $GLOBALS['db']->Query($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 = $GLOBALS['config_vars']['Forums_Title'];
	$sname = str_replace('|||', $GLOBALS['config_vars']['Forums_Splitter'], strip_tags($navigation)) . ' - ' . $forum_obj->title;
	
	
	$GLOBALS['tmpl']->register_function('get_post_icon', 'getPostIcon');
	$GLOBALS['tmpl']->register_function('get_status_icon', 'getStatusIcon');
	$GLOBALS['tmpl']->assign('sort_by_theme_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=title&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('sort_by_reply_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=replies&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('sort_by_author_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=uname&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('sort_by_hits_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=views&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('sort_by_rating_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=rating&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('sort_by_lastpost_link', 'index.php?p=showforum&amp;fid=' . $fid . '&amp;sortby=last_post_int&amp;sort=' . $order);
	$GLOBALS['tmpl']->assign('forums_name', $forum_obj->title);
	
	if ($limit < $num)
	{
		$unit = ($unit=='') ? 0 : $unit;
		$period = ($period=='') ? 0 : $period;
		$GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?p=showforum&amp;fid=$fid&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, '');
	
	$GLOBALS['tmpl']->assign('categories_dropdown', $categories);
	$GLOBALS['tmpl']->assign('forum', $forum_obj);
	$GLOBALS['tmpl']->assign('f_id', $forum_obj->id);
	$GLOBALS['tmpl']->assign('categories', $subcat_array);
	$GLOBALS['tmpl']->assign('forums', $subforum_array);
	$GLOBALS['tmpl']->assign('topics', $topic_array);
	$GLOBALS['tmpl']->assign('SearchPop', popSearch());
	$GLOBALS['tmpl']->assign('pagetitle_html', $sname);
	$GLOBALS['tmpl']->assign('get_mods', get_mods($fid));
	$GLOBALS['tmpl']->assign('f_down',forumsDropdown());
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/showforum.tpl')); 
}
?>