<?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']);

switch ($_REQUEST['p']) {
	case "index" : 
	case "" : 
	$printlink = "?area=$area&amp;print=1"; break;
	default :
	$printlink = redir()."&amp;print=1";
}

// alle postings für einen thread anzeigen
if ( $_GET["toid"] != "" ) {
	
	// gibt es den topic und das posting ueberhaupt schon
	if (!topicExists($_GET['toid'])) {
		$EOUT = msg("f_forum", "f_err_permited", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
		$NOOUT = 1;
	}
	
	$navigation = getNavigation($_GET["toid"], "topic");
	
	// ueberpruefen ob das forum passwortgeschuetzt ist
	// und ob der benutzer sich schon angemeldet hat
	$q_pass = "
	SELECT 
	f.id,
	f.password 
	FROM 
	" . PREFIX . "_f_forum AS f,
	" . PREFIX . "_f_topic AS t
	WHERE 
	t.id = " . $_GET["toid"] . " AND
	t.forum_id = f.id
	";
	
	$r_pass = new dbc($q_pass);
	$pass = $r_pass->fetchrow();
	
	$pass_b = false;
	
	if ($pass->password != "") {
		$p1 = $_COOKIE["f_pass_id_" . $pass->id];
		$p2 = $pass->password;
		if( $p1 == $p2 ){
			$pass_b = 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_b = true;
	}
	
	if ($pass_b) {
		
		
		// ====================================================================================
		// zugriffsrechte
		// ====================================================================================
		$group_id = array();
		
		if (!@is_numeric(UID)) {
			$group_id[] = UGROUP;
		} else {
			$query = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = '" . UID . "'";
			$result = new dbc($query);
			$user = $result->fetchrow();
			
			if($user->group_id_misc != ""){
				$group_id_ = UGROUP . ";" . $user->group_id_misc;
				$group_id = @explode(";", $group_id_);
				
			} else {
				$group_id[] = UGROUP;
			}
		}
		
		$query = "
			SELECT
				c.group_id
			FROM
				" . PREFIX . "_f_category AS c,
				" . PREFIX . "_f_forum AS f
			WHERE
				f.id = " . $pass->id . " AND
				f.category_id = c.id";
		
		$result = new dbc($query);
		$category = $result->fetchrow();
		$category->group_id = @explode(",", $category->group_id);
		
		if (!array_intersect($group_id, $category->group_id)) {
			$EOUT = msg("f_forum", "f_noid", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
			$NOOUT = 1;
		}
		
		$permissions = getForumPermissionsByUser($pass->id, UID);

		if ($permissions[FORUM_PERMISSION_CAN_SEE] != 1){
			$EOUT = msg("f_forum", "f_noid", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
			$NOOUT = 1;
		}	
		
		// ====================================================================================
		
		if(!is_mod($_GET['fid'])) { 
			$post_count_extra .= " AND opened = 1 ";
		}
		
		// freischalten
		if($_REQUEST['open'] == 1){
			if(is_mod($_REQUEST['fid'])) { 
				
				if($_REQUEST['ispost'] == 1){
					$sql_p = "UPDATE " . PREFIX . "_f_post SET opened = '1' WHERE id='$_REQUEST[id]'";
					$res_p = new dbc($sql_p);
					
					// mail an autor eines beitrages
					$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$_POST[toid]&pp=15&area=$area";
					$sql = new dbc("SELECT uid FROM ".PREFIX."_f_post WHERE id = '$_REQUEST[id]'");
					$row = $sql->fetchrow();
					
					$sql_2 = new dbc("SELECT uname, email FROM ".PREFIX."_user WHERE uid = '$row->uid'");
					$row_2 = $sql_2->fetchrow();
					
					$body = str_replace("__USER__", $row_2->uname, $lang['body_to_postautor_moderated']);
					$body = str_replace("__LINK__", $link, $body);
					$body = str_replace("\n","\n\n", $body);
					
					@mail($row_2->email, $lang['subject_to_postautor_moderated'], stripslashes($body),
					"From: $pref[sendemail]\r\n"
					."Reply-To: $pref[sendemail]\r\n"
					."X-Mailer: PHP/" . phpversion());
			
				} else {
					
					$sql_t = "UPDATE " . PREFIX . "_f_topic SET opened = '1' WHERE id='$_REQUEST[toid]'";
					$sql_p = "UPDATE " . PREFIX . "_f_post SET opened = '1' WHERE topic_id='$_REQUEST[toid]'";
					$res_t = new dbc($sql_t);
					$res_p = new dbc($sql_p);
					// mail an autor eines thema
					$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$_REQUEST[toid]&fid=$_REQUEST[fid]&area=$area";
					$sql = new dbc("SELECT uid FROM ".PREFIX."_f_topic WHERE id = '$_REQUEST[toid]'");
					$row = $sql->fetchrow();
					
					$sql_2 = new dbc("SELECT uname, email FROM ".PREFIX."_user WHERE uid = '$row->uid'");
					$row_2 = $sql_2->fetchrow();
					
					$body = str_replace("__USER__", $row_2->uname, $lang['body_to_autor_moderated']);
					$body = str_replace("__LINK__", $link, $body);
					$body = str_replace("\n","\n\n", $body);
					
					@mail($row_2->email, $lang['subject_to_autor_moderated'], stripslashes($body),
					"From: $pref[sendemail]\r\n"
					."Reply-To: $pref[sendemail]\r\n"
					."X-Mailer: PHP/" . phpversion());
				}
			}
		}
		
		// ======================================================
		// alle beiträge holen
		$post_count = "
		SELECT 
		id
		FROM " . 
		PREFIX . "_f_post
		WHERE 
		topic_id = '" . escs($_GET['toid']) . "' 
		$post_count_extra 
		ORDER BY
		id DESC
		";
		
		$post_count_result = new dbc($post_count);
		$num = $post_count_result->numrows();
		
		if($num < 1){
			$EOUT = msg("f_forum", "f_err_permited", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
			$NOOUT = 1;
		}
		
		// ===========================================================================
		//  <<-- aktualisierung des cookies, fuer die darstellung des topicicons -->>
		// ===========================================================================
		// der letzte beitrag
		$last_post = $post_count_result->fetchrow();
		
		// alle bereits besuchten themen
		$visited_ids = @explode("@", $_COOKIE['koobi4_f_visited']);
		$all_ids = array();
		
		// gehe alle postings in diesem thema durch _ausser_ dem aktuellsten
		// und speichere sie in einem array
		while ($last_postings = $post_count_result->fetchrow()) {
			$all_ids[] = $last_postings->id;
		}
		
		// filtere alle postings id's aus dem cookie
		$all_ids = array_diff($visited_ids, $all_ids);
		
		// fuege die aktuellste id hinzu
		if (!in_array($last_post->id, $all_ids)) {
			$all_ids[] = $last_post->id;
		}
		
		setcookie('koobi4_f_visited', @implode('@', $all_ids), EXPIRE_YEAR);
		
		// ===================================================================
		$limit = ($_REQUEST['pp'] == "") ? 15 : $_REQUEST['pp'];
		
		if(!isset($page)){ $page = 1;}
		
		$seiten = getPageNum($num, $limit);
		$a = prepage() * $limit - $limit;
		
		if(!is_mod($_GET['fid'])) { 
			$post_query_extra .= " AND opened = 1 ";
		}
		$post_query = "
		SELECT 
			p.id, 
			p.title, 
			p.message, 
			p.datum, 
			p.use_bbcode, 
			p.use_smilies, 
			p.use_sig, 
			p.uid, 
			p.attachment,
			p.opened
		FROM 
			" . PREFIX . "_f_post AS p 
		WHERE topic_id = '" . escs($_GET['toid']) . "' 
			$post_query_extra 
		ORDER BY 
			datum ASC
		LIMIT $a, $limit";
		
		$post_result = new dbc($post_query);
		
		$post_array = array();
		
		$current_user = null;
		
		if (($islogged != 0)) {
			$q_current_user = "SELECT uid, user_viewemail, user_canpn FROM " . PREFIX . "_user WHERE uid = '".UID."'";
			$r_current_user =& new dbc($q_current_user);
			$current_user = $r_current_user->fetchRow();
		}
		
		while ($post = $post_result->fetchrow()) {
			
			// der beitragverfasser
			$q_user = "
			SELECT 
				u.user_avatar,
				u.ugroup,
				u.usedefault_avatar, 
				u.uid, u.name, 
				u.uname, 
				u.email, 
				u.url, 
				u.user_avatar, 
				u.user_regdate, 
				u.user_icq, 
				u.user_aim, 
				u.user_yim, 
				u.user_msnm, 
				u.user_sig, 
				u.invisible, 
				ug.groupname_single 
			FROM
				" . PREFIX . "_user AS u,
				" . PREFIX . "_usergroup AS ug 
			WHERE u.uid = '" . $post->uid . "' AND ug.ugroup = u.ugroup";
			
			$r_user = new dbc($q_user);
			$poster = $r_user->fetchRow();
			
			$query = "SELECT COUNT(id) AS count FROM " . PREFIX . "_f_post WHERE uid = '" . $poster->uid . "'";
			$result = new dbc($query);
			$postings = $result->fetchrow();
			
			$poster->user_posts = $postings->count;
			
			$query = "SELECT title, count FROM " . PREFIX . "_f_rank WHERE count < '" . $poster->user_posts . "' ORDER BY count DESC LIMIT 1";
			$result = new dbc($query);
			$rank = $result->fetchrow();
			
			$poster->avatar = getAvatar($poster->ugroup,$poster->user_avatar,$poster->usedefault_avatar);
			$poster->regdate = mygmt($poster->user_regdate);
			$poster->user_sig = kcodes($poster->user_sig);
			$poster->rank = $rank->title;
			
			if(SMILIES==1) $poster->user_sig = dosmilies($poster->user_sig);
			
			// der verfasser
			$post->poster = $poster;
			
			
			// soll bbcode verwendet werden
			if ($post->use_bbcode == 1) {
				$post->message = kcodes($post->message);
			} else {
				$post->message = nl2br($post->message);
			}
			
			// sollen smilies angezeigt werden
			if ( ($post->use_smilies == 1) && (SMILIES==1) ) {
				$post->message = dosmilies($post->message);
			}
			
			$post->message = autowords($post->message);
			$post->message = badwordreplace($post->message);
			$post->message = high($post->message);
			
			$post->files = array();		
			// attachments
			if ($post->attachment != "") {
				$attachments = @explode(";", $post->attachment);
				$sub_query = @implode(" OR id = ", $attachments);
				
				$q_file = "
				SELECT
				id,
				hits,
				orig_name,
				filename
				FROM
				" . PREFIX . "_f_attachment
				WHERE
				 id = $sub_query
				";
				
				$r_file = new dbc($q_file);
				
				while ($file = $r_file->fetchrow()) {
					$post->files[] = $file;
				}
			}
			
			array_push($post_array, $post);
			
		}
		$tmpl->register_function('get_attachment_size','get_attachment_size');
		
		// anzahl der besichtigungen erhöhen
		$increment_query = new dbc("UPDATE " . PREFIX . "_f_topic SET views = views + 1 WHERE id = '" . escs($_REQUEST['toid']). "'");

		// daten des aktuellen topics holen
		$topic_result = new dbc("SELECT  notification, id, title, status, forum_id, uid FROM " . PREFIX . "_f_topic WHERE id = '" . escs($_REQUEST['toid']) . "'");
		$topic = $topic_result->fetchRow();
		
		// hat der user das thema abonniert?
		$user_id = split(";", $topic->notification);
		if (@in_array(UID, $user_id)) {
			$tmpl->assign('canabo', 0);
		} else {
			$tmpl->assign('canabo', 1);
		}
		
		
		// hat der user schon abgestimmt?
		$sql = new dbc("SELECT uid,ip FROM " . PREFIX . "_f_rating WHERE  topic_id = '$_GET[toid]' ");
		$row_ip = $sql->fetchrow();
		$v_uid = @explode(",", $row_ip->uid);
		$ip = @explode(",", $row_ip->ip);
		
		if ( (!@in_array(UID, $v_uid)) && (!@in_array($_SERVER['REMOTE_ADDR'], $ip)) ) {
			$tmpl->assign('display_rating', 1);
		}
		
		// nextes thema holen
		$query = "SELECT id FROM " . PREFIX . "_f_topic WHERE id < " . $_GET['toid'] . " AND forum_id = '" . $pass->id . "' ORDER BY id DESC LIMIT 1";
		$result = new dbc($query);
		$next_topic = $result->fetchrow();
		
		// vorheriges thema holen
		$query = "SELECT id FROM " . PREFIX . "_f_topic WHERE id > " .  $_GET['toid'] . " AND forum_id = '" . $pass->id . "' ORDER BY id ASC LIMIT 1";
		$result = new dbc($query);
		$prev_topic = $result->fetchrow();
		
		$topic->next_topic = $next_topic;
		$topic->prev_topic = $prev_topic;
		
		$stitle = $lang["forumtitle"];
		$sname = simpletitle(str_replace($lang['f_navi_separator'], " - ", strip_tags($navigation)) . " - " . stripslashes(htmlspecialchars($topic->title)) );
		
		
		// navigation erzeugen
		$navigation = getNavigation($_GET["toid"], "topic");
		$tmp_navi = $navigation . $lang["f_navi_separator"] . $topic->title;
		
		$tmpl->assign("navigation", $tmp_navi);
		$tmpl->assign("treeview", @explode($lang['f_navi_separator'], $tmp_navi));
		// ende navigation
		
		if ($limit < $num) {
			$tmpl->assign('pages', pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?p=showtopic&amp;toid=" . $_GET["toid"] . "&amp;area=$area&amp;high=$_GET[high]&amp;pp=".$limit."&amp;page={s}\">{t}</a> "));
		}
		
		if (UID == 1) array_fill(0, sizeof($permissions), 1);
		
		if(is_mod($_GET['fid'])) { $tmpl->assign('ismod', 1); }
		
		$categories = array();
		
		getCategories(0, $categories, "");
		
		$tmpl->assign("permissions", $permissions);
		$tmpl->assign("categories_dropdown", $categories);
		$tmpl->assign("navigation", $navigation);
		$tmpl->assign("next_site", $seiten);
		$tmpl->assign("theme", $THEME);
		$tmpl->assign("currUser", $current_user);
		$tmpl->assign("lang", $lang);
		$tmpl->assign("area", $area);
		$tmpl->assign("printlink", $printlink);
		$tmpl->assign("topic", $topic);
		$tmpl->assign("postings", $post_array);
		$tmpl->register_function('getonlinestatus', 'getonlinestatus');
		$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/showtopic.tpl")));
		
		
	}
	} else {
	$EOUT = stderror("nopermission", $lang['f_err_permited'], str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area", 1);
	$NOOUT = 1;
}
?>