<?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();
}

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

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

//=================================================================
// alle postings für einen thread anzeigen
//=================================================================
if ( isset($_REQUEST['toid']) && $_REQUEST['toid'] != "" ) 
{
	//=================================================================
	// gibt es den topic und das posting ueberhaupt schon
	//=================================================================
	if (!topicExists((int)$_REQUEST['toid'])) 
	{
		koobi_message('Forums_Title', 'Forums_ErrorNoPermission', HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
	} 
	
	//=================================================================
	// Wer liest hier?
	//=================================================================
	$expire = time() + (300);
	$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_f_topic_viewing WHERE Expire <= '" . time() . "'");
	$sql = $GLOBALS['db']->Query("SELECT Ip FROM " . PREFIX . "_f_topic_viewing WHERE Ip='" . $_SERVER['REMOTE_ADDR'] . "' AND Topic = '" . $_REQUEST['toid'] . "' limit 1");
	$num = $sql->numrows();
	
	if ($num < 1) 
    	$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_f_topic_viewing (Ip,Topic,Expire) VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', '" . $_REQUEST['toid'] . "', '$expire')");
	else 
		$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic_viewing SET Expire = '$expire'  WHERE Topic = '" . $_REQUEST['toid'] . "' AND Ip = '" . $_SERVER['REMOTE_ADDR'] . "' ");
	

	$navigation = getNavigation((int)$_REQUEST['toid'], "topic");
	
	//================================================================
	// ueberpruefen ob das forum passwortgeschuetzt ist
	// und ob der benutzer sich schon angemeldet hat
	//================================================================
	$pass = $GLOBALS['db']->RowQuery("
	SELECT 
		f.id,
		f.password 
	FROM 
		" . PREFIX . "_f_forum AS f,
		" . PREFIX . "_f_topic AS t
	WHERE 
		t.id = '" . $_REQUEST['toid'] . "' AND
		t.forum_id = f.id");
	
	$pass_b = false;
	
	if (is_object($pass) && $pass->password != "") 
	{
		$p1 = (isset($_COOKIE['f_pass_id_' . $pass->id])) ? $_COOKIE['f_pass_id_' . $pass->id] : '';
		$p2 = $pass->password;
		if( $p1 == $p2 ){
			$pass_b = true;
			
		} else {
			$stitle = $GLOBALS["config_vars"]["Forums_ForumTitle_login"];
			$sname = $stitle;
			$GLOBALS['tmpl']->assign('fid', $pass->id);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/forumlogin.tpl')); 
		}
	} else {
		$pass_b = true;
	}
	
	if ($pass_b)
	{
		//================================================================
		// zugriffsrechte
		//================================================================
		$group_id = array();
		
		if (!@is_numeric(UID))
		{
			$group_id[] = UGROUP;
		} else {
			$query = "SELECT GruppeMisc as group_id_misc FROM " . PREFIX . "_benutzer WHERE Id = '" . UID . "'";
			$result = $GLOBALS['db']->Query($query);
			$user = $result->fetchrow();
			
			if(is_object($user) && $user->group_id_misc != "")
			{
				$group_id_ = UGROUP . ";" . $user->group_id_misc;
				$group_id = @explode(";", $group_id_);
			} else {
				$group_id[] = UGROUP;
			}
		}
			
		$category = $GLOBALS['db']->RowQuery("
			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");
		
		$category->group_id = @explode(",", $category->group_id);
		
		if (!array_intersect($group_id, $category->group_id))
		{
			koobi_message('Forums_Title', 'Forums_PermissionDenied', HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
		} 
		
		$permissions = getForumPermissionsByUser($pass->id, UID);
		if (@$permissions[FORUM_PERMISSION_CAN_SEE] != 1 || (!@$permissions[FORUM_PERMISSION_CAN_SEE_TOPIC] || @$permissions[FORUM_PERMISSION_CAN_SEE_TOPIC]==0))
		{
			koobi_message('Forums_Title','Forums_PermissionDenied',HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
		} 
		
		//================================================================
		//================================================================
		$post_count_extra = (isset($_REQUEST['fid']) && !is_mod($_REQUEST['fid'])) ? " AND opened = 1 " : "";
		
		//================================================================
		// freischalten
		//================================================================
		if(isset($_REQUEST['open']) && $_REQUEST['open'] == 1)
		{
			if(isset($_REQUEST['fid']) && is_mod($_REQUEST['fid']))
			{ 
				if(isset($_REQUEST['ispost']) && $_REQUEST['ispost'] == 1)
				{
					$sql_p = "UPDATE " . PREFIX . "_f_post SET opened = '1' WHERE id='$_REQUEST[id]'";
					$res_p = $GLOBALS['db']->Query($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";
					$sql = $GLOBALS['db']->Query("SELECT uid FROM ".PREFIX."_f_post WHERE id = '$_REQUEST[id]'");
					$row = $sql->fetchrow();
					
					$sql_2 = $GLOBALS['db']->Query("SELECT Benutzername as uname, Email as email FROM ".PREFIX."_benutzer WHERE Id = '$row->uid'");
					$row_2 = $sql_2->fetchrow();
					
					$body = str_replace("__USER__", $row_2->uname, $GLOBALS['config_vars']['body_to_postautor_moderated']);
					$body = str_replace("__LINK__", $link, $body);
					
					$Koobi = new Koobi;
					$Koobi->koobi_mail($row_2->email, stripslashes($body), $GLOBALS['config_vars']['subject_to_postautor_moderated'], STANDARDMAIL, STANDARDMAIL, "text", "");
					
				} else {
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET opened = '1' WHERE id='$_REQUEST[toid]'");
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_post SET opened = '1' WHERE topic_id='$_REQUEST[toid]'");
					
					//================================================================
					// 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]";
					$sql = $GLOBALS['db']->Query("SELECT uid FROM ".PREFIX."_f_topic WHERE id = '$_REQUEST[toid]'");
					$row = $sql->fetchrow();
					
					$sql_2 = $GLOBALS['db']->Query("SELECT Benutzername as uname, Email as email FROM ".PREFIX."_benutzer WHERE Id = '$row->uid'");
					$row_2 = $sql_2->fetchrow();
					
					$body = str_replace("__USER__", $row_2->uname, $GLOBALS['config_vars']['Forums_body_to_autor_moderated']);
					$body = str_replace("__LINK__", $link, $body);
					
					$Koobi = new Koobi;
					$Koobi->koobi_mail($row_2->email, stripslashes($body), $GLOBALS['config_vars']['Forums_subject_to_autor_moderated'], STANDARDMAIL, STANDARDMAIL, "text", "");
				}
			}
		}
			
		//================================================================
		// Alle Beitraege holen
		//================================================================
		$only_postid = (isset($_REQUEST['print_post']) && $_REQUEST['print_post'] != '') ? " AND id = '" . escs($_REQUEST['print_post']) . "'" : "";
		
		$post_count_result = $GLOBALS['db']->Query("SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = '" . $_REQUEST['toid'] . "' $only_postid $post_count_extra ORDER BY id DESC");
		$num = $post_count_result->numrows();
		
		if($num < 1)
		{
			koobi_message('Forums_Title','Forums_ErrorNoPermission',HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
		} 
		
		//================================================================
		// Thema als gelesen ablegen
		//================================================================
		Koobi_Board_SetTopicRead(escs($_REQUEST['toid']));
		
		//================================================================
		//================================================================
		$l_my = MySettings('Forum_Beitraege_Limit');
		$l_my = (!$l_my) ? 15 : $l_my;
		$limit = ($l_my >= 1) ? $l_my : $_REQUEST['pp'];
	
		if(!isset($page)) $page = 1;
		$seiten = getPageNum($num, $limit);
		$a = prepage() * $limit - $limit;
		
		$post_query_extra = (!is_mod($_REQUEST['fid'])) ? " AND opened = 1 " : "";
	
		$post_result = $GLOBALS['db']->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($_REQUEST['toid']) . "' $only_postid 
			$post_query_extra 
		ORDER BY 
			datum ASC
		LIMIT $a, $limit");
		
		$post_array = array();
		
		$current_user = null;
		
		if ((ISLOGGED != 0)) 
		{
			$current_user = $GLOBALS['db']->RowQuery("SELECT Id as uid, Emailempfang as user_viewemail, Pnempfang as user_canpn FROM " . PREFIX . "_benutzer WHERE Id = '".UID."'");;
		}
	
		while ($post = $post_result->fetchrow()) 
		{
			$post->anchorId = $post->id;
			//================================================================
			// der beitragverfasser
			//================================================================
			$q_user = "
			SELECT 
				u.Gruppe as ugroup,
				u.Avatar_Default as usedefault_avatar, 
				u.Id as uid, 
				u.Vorname as name, 
				u.Geloescht,
				u.Benutzername as uname, 
				u.Email as email, 
				u.Webseite as url, 
				u.Avatar as user_avatar, 
				u.Regdatum as user_regdate, 
				u.Signatur as user_sig, 
				u.Unsichtbar as invisible, 
				u.Team,
				ug.Name as groupname_single 
			FROM
				" . PREFIX . "_benutzer AS u,
				" . PREFIX . "_benutzer_gruppen AS ug 
			WHERE u.Id = '" . $post->uid . "' AND ug.Id = u.Gruppe";
			
			$r_user = $GLOBALS['db']->Query($q_user);
			$poster = $r_user->fetchRow();
			
			if(is_object($poster))
			{
				$postings = $GLOBALS['db']->RowQuery("SELECT COUNT(id) AS count FROM " . PREFIX . "_f_post WHERE uid = '" . $poster->uid . "'");
				$poster->user_posts = $postings->count;
			
				//================================================================
				// Ranking
				//================================================================
				$rank = $GLOBALS['db']->RowQuery("SELECT title, count FROM " . PREFIX . "_f_rank WHERE count <= '" . $poster->user_posts . "' ORDER BY count DESC LIMIT 1");
				
				//================================================================
				// Beitrag zusammensetzen
				//================================================================
				$poster->avatar = getAvatar($poster->ugroup,$poster->user_avatar,$poster->usedefault_avatar);
				$poster->regdate = stime($poster->user_regdate);
				
				//================================================================
				// Signatur?
				//================================================================
				if(perm_byid($poster->uid,'Signatur_Erlaubt')==1)
				{
					$poster->user_sig_length = perm_byid($poster->uid,'Signatur_Laenge');
					$poster->user_sig = (!badwordreplace($poster->user_sig)) ? $poster->user_sig : badwordreplace($poster->user_sig);
					$poster->user_sig = (perm_byid($poster->uid,'KoobiCode_Signatur')==1) ? kcodes(substr($poster->user_sig,0,$poster->user_sig_length)) : nl2br(substr($poster->user_sig,0,$poster->user_sig_length));
				} else {
					$poster->user_sig = '';
				}
				
				
				$poster->rank = @$rank->title;
				$poster->UserPop = userDropDownPop($poster->uid,base64_encode($poster->uname));
				if(SMILIES==1) $poster->user_sig = dosmilies($poster->user_sig);
				
				//================================================================
				// der verfasser
				//================================================================
				$post->poster = $poster;
			} else {
				$poster->DeletedUser = 1;
				$post->poster = $poster;
			}
			
			//================================================================
			// soll bbcode verwendet werden
			//================================================================
			if ($post->use_bbcode == 1) 
			{
				$post->message = ($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 : badwordreplace($post->message);
			$post->message = high($post->message);
			
			//================================================================
			// Anlagen
			//================================================================
			$post->files = array();	
			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 = $GLOBALS['db']->Query($q_file);
				
				while ($file = $r_file->fetchrow()) {
					$post->files[] = $file;
				}
			}
			
			array_push($post_array, $post);
			
		}
		$GLOBALS['tmpl']->register_function('get_attachment_size','get_attachment_size');
		
		//================================================================
		// Anzahl der Hits erhoehen
		//================================================================
		$increment_query = $GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET views = views + 1 WHERE id = '" . escs($_REQUEST['toid']). "'");

		//================================================================
		// Daten des aktuellen Themas holen
		//================================================================
		$topic = $GLOBALS['db']->RowQuery("SELECT  notification, id, title, status, forum_id, uid FROM " . PREFIX . "_f_topic WHERE id = '" . escs($_REQUEST['toid']) . "'");
		
		//================================================================
		// Hat der Benutzer das Thema abonniert?
		//================================================================
		$user_id = split(";", $topic->notification);
		$GLOBALS['tmpl']->assign('canabo', ((@in_array(UID, $user_id)) ? 0 : 1));
		
		//================================================================
		// Hat der Benutzer schon abgestimmt?
		//================================================================
		$row_ip = $GLOBALS['db']->RowQuery("SELECT uid,ip FROM " . PREFIX . "_f_rating WHERE  topic_id = '".(int)$_REQUEST['toid']."' ");
		$v_uid = @explode(",", $row_ip->uid);
		$ip = @explode(",", $row_ip->ip);
		
		if ( (!@in_array(UID, $v_uid)) && (!@in_array($_SERVER['REMOTE_ADDR'], $ip)) )
		{
			$GLOBALS['tmpl']->assign('display_rating', 1);
		}
		
		//================================================================
		// Naechstes Thema holen
		//================================================================
		$next_topic = $GLOBALS['db']->RowQuery("SELECT title,id FROM " . PREFIX . "_f_topic WHERE id < '" . $_REQUEST['toid'] . "' AND forum_id = '" . $pass->id . "' ORDER BY id DESC LIMIT 1");

		//================================================================
		// Vorheriges Thema holen
		//================================================================
		$prev_topic = $GLOBALS['db']->RowQuery("SELECT title,id FROM " . PREFIX . "_f_topic WHERE id > '" . $_REQUEST['toid'] . "' AND forum_id = '" . $pass->id . "' ORDER BY id ASC LIMIT 1");
		
		$topic->next_topic = @$next_topic;
		$topic->prev_topic = @$prev_topic;
		
		$stitle = $GLOBALS['config_vars']['Forums_Title'];
		$sname = str_replace(array('|||',$GLOBALS['config_vars']['Forums_Splitter']), $GLOBALS['config_vars']['Forums_Splitter'], strip_tags($navigation)) . " - " . stripslashes(koobispecialchars($topic->title));
		
		//================================================================
		// navigation erzeugen
		//================================================================
		$navigation = getNavigation((int)$_REQUEST['toid'], 'topic');
		$topic->title = str_replace($GLOBALS['config_vars']['Forums_Splitter'],'|||',$topic->title);
		$tmp_navi = $navigation . $GLOBALS['config_vars']['Forums_Splitter'] . '<span class="forum_topictile">' . koobispecialchars($topic->title) . '</span>';
		
		$GLOBALS['tmpl']->assign("navigation", $tmp_navi);
		$GLOBALS['tmpl']->assign("treeview", @explode($GLOBALS['config_vars']['Forums_Splitter'], $tmp_navi));
		//================================================================
		// ende navigation
		//================================================================
		
		if ($limit < $num)
		{
			$GLOBALS['tmpl']->assign('pages', pagenav($seiten, $GLOBALS['config_vars']['aktpos'], " <a class=\"page_navigation\" href=\"index.php?" . ((isset($_REQUEST['high']) && $_REQUEST['high'] != '') ? 'high=' . koobispecialchars($_REQUEST['high']) . '&amp;' : '') . "p=showtopic&amp;toid=$_REQUEST[toid]&amp;fid=1&amp;page={s}&amp;t=$_REQUEST[t]\">{t}</a> "));
		}
		
		if (UID == 1) array_fill(0, sizeof($permissions), 1);
		if(is_mod($_REQUEST['fid'])) $GLOBALS['tmpl']->assign('ismod', 1); 
		
		$categories = array();
		getCategories(0, $categories, '');
		
		$GLOBALS['tmpl']->register_function('getonlinestatus', 'getonlinestatus');
		$GLOBALS['tmpl']->assign('permissions', $permissions);
		$GLOBALS['tmpl']->assign('categories_dropdown', $categories);
		$GLOBALS['tmpl']->assign('navigation', $navigation);
		$GLOBALS['tmpl']->assign('next_site', $seiten);
		$GLOBALS['tmpl']->assign('currUser', $current_user);
		$GLOBALS['tmpl']->assign('printlink', $printlink);
		$GLOBALS['tmpl']->assign('topic', $topic);
		$GLOBALS['tmpl']->assign('postings', $post_array);
		$GLOBALS['tmpl']->assign('pagetitle_html', $sname);
		$GLOBALS['tmpl']->assign('keywords', '');
		$GLOBALS['tmpl']->assign('keywords', $sname);
		$GLOBALS['tmpl']->assign('description', $sname);
		$GLOBALS['tmpl']->assign('SearchPop', popSearch());
		$GLOBALS['tmpl']->assign('printlink', 'index.php?p=showtopic&amp;print=1&amp;toid='.$_REQUEST['toid'].'&amp;fid='.$pass->id.'&amp;page='.@$_REQUEST['page'].'&amp;t=' . seotitle(koobispecialchars($topic->title)));
		$GLOBALS['tmpl']->assign('origlink', @$_SERVER['HTTP_REFERER']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . ((isset($_REQUEST['print']) && $_REQUEST['print']==1) ? '/forums/showtopic_print.tpl' : '/forums/showtopic.tpl')  )); 
	}
} else {
	koobi_message('Global_NoPermission', 'Forums_ErrorNoPermission',HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
}
?>