<?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                   //
// ======================================================================== //
ob_start();
if (!is_object($tmpl)) {
	require_once ("../class/tpl/Koobi.class.php");
	require_once ("../class/db.php");
	require_once ("../inc/functions.php");
	
	$tmpl = new Koobi("templates/" . $_GET['theme']);
}

$tmpl->register_function("get_post_icon", "getPostIcon");

$stitle = $lang["forumtitle"];
$sname = simpletitle($stitle);

$tmpl->assign("lang", $lang);

switch ($_GET['action']) {
	
	
	
	
	// ================================================================================
	//  <<-- Im Forum suchen -->>
	// ================================================================================
	case "search":

	$pattern = ($_POST['pattern'] != "") ? addslashes($_POST['pattern']) : addslashes($_GET['pattern']);
	$f_id = ($_POST['f_id'] != "") ? $_POST['f_id'] : $_GET['f_id'];
	$t_id = ($_POST['t_id'] != "") ? $_POST['t_id'] : $_GET['t_id'];
	
	$permissions = getForumPermissions($f_id, UGROUP);
	
	if ($pattern == "") {
		// es wurde kein suchbegriff eingegeben
		if ($f_id == 0 && $f_id != "") {
			$EOUT = msg("f_forum", "f_err_search_pattern_missing", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
		} elseif ($f_id != "") {
			$EOUT = msg("f_forum", "f_err_search_pattern_missing", str_replace("__URL__", "index.php?p=showforum&amp;fid=" . $f_id, $lang['redirect']) ."&amp;area=$area", "index.php?p=showforum&amp;fid=" . $f_id . "&amp;area=$area");
		} elseif ($t_id != "") {
			$EOUT = msg("f_forum", "f_err_search_pattern_missing", str_replace("__URL__", "index.php?p=showtopic&amp;toid=" . $t_id, $lang['redirect']) ."&amp;area=$area", "index.php?p=showtopic&amp;toid=" . $t_id ."&amp;area=$area");
		}
		$NOOUT = 1;
	} else {
		$matches = array();
		
		// passende topics finden
		$q_topic = "
			SELECT
				t.id,
				t.forum_id,
				t.title,
				t.status,
				t.type,
				t.datum,
				t.views,
				t.posticon,
				t.uid,
				t.replies,
				u.uname,
				r.rating,
				f.title AS f_title
			FROM
				" . PREFIX . "_f_topic AS t,
				" . PREFIX . "_user AS u,
				" . PREFIX . "_f_rating AS r,
				" . PREFIX . "_f_forum AS f
			WHERE
				t.title LIKE '%$pattern%' AND
				u.uid = t.uid AND
				r.topic_id = t.id AND
				f.id = t.forum_id
		";
		
		$r_topic = new dbc($q_topic);
		
		while ($topic = $r_topic->fetchrow()) {
			$topic->link = "index.php?p=showtopic&amp;toid=" . $topic->id . "&amp;high=$_GET[pattern]";
			$topic->closelink = "index.php?p=closetopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
			$topic->openlink = "index.php?p=opentopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
			$topic->dellink = "index.php?p=deltopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
			$topic->movelink = "index.php?p=move&amp;item=t&amp;id=$topic->id&amp;area=$area";
			$topic->autorlink = "index.php?p=user&amp;id=$topic->uid&amp;area=$area";
			$topic->autor = $topic->uname;
			
			$rating = @explode(",", $topic->rating);
			
			$topic->rating = (int) (array_sum($rating) / count($rating));
			
			$q_forum = "SELECT id, status FROM " . PREFIX . "_f_forum WHERE id = " . $topic->forum_id;
			$r_forum = new dbc($q_forum);
			$forum = $r_forum->fetchrow();
			
			if ($topic->status == FORUM_STATUS_MOVED) {
				$topic->statusicon = getIcon("thread_moved.gif", "moved");
			} else {
				if ($islogged == 0 || ($forum->status == FORUM_STATUS_CLOSED) ) {
					// nicht eingeloggt oder forum geschlossen
					$topic->statusicon = getIcon("thread_lock.gif", "lock");
				} else {
					setTopicIconObj($topic, $forum);
				}
			}
			
			array_push($matches, $topic);
		}
		
		$q_post = "
			SELECT
				p.id,
				p.title,
				p.topic_id,
				p.datum,
				p.uid,
				p.message,
				u.name,
				u.uname
			FROM
				" . PREFIX . "_f_post AS p,
				" . PREFIX . "_user AS u
			WHERE
				(p.title LIKE '%$pattern%' OR p.message LIKE '%$pattern%') AND
				u.uid = p.uid
		";
		
		$r_post = new dbc($q_post);
		
		while ($post = $r_post->fetchrow()) {
			$q_topic = "
				SELECT
					t.id,
					t.title,
					t.status,
					t.type,
					t.datum,
					t.views,
					r.rating,
					t.posticon,
					t.uid,
					t.replies,
					u.uname
				FROM
					" . PREFIX . "_f_topic AS t,
					" . PREFIX . "_user AS u,
					" . PREFIX . "_f_rating AS r
				WHERE
					id = " . $post->topic_id . " AND 
					u.uid = t.uid AND 
					r.topic_id = t.id
				";
			
			$r_topic = new dbc($q_topic);
			
			while ($topic = $r_topic->fetchrow()) {
				$topic->link = "index.php?p=showtopic&amp;toid=" . $topic->id;
				$topic->closelink = "index.php?p=closetopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
				$topic->openlink = "index.php?p=opentopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
				$topic->dellink = "index.php?p=deltopic&amp;fid=$_GET[f_id]&amp;toid=$topic->id&amp;area=$area";
				$topic->movelink = "index.php?p=move&amp;item=t&amp;id=$topic->id&amp;area=$area";
				$topic->autorlink = "index.php?p=user&amp;id=$topic->uid&amp;area=$area";
				$topic->autor = $topic->uname;
				
				$rating = @explode(",", $topic->rating);
				
				$topic->rating = (int) (array_sum($rating) / count($rating));
				
				array_push($matches, $topic);
			}
		}
		
		if ($f_id != "") {
			$navi_id = $f_id;
			$type = "forum";
		} else {
			$navi_id = $t_id;
			$type = "topic";
		}
		
		// =============================================================
		//  seitennavigation
		// =============================================================
		$order_by = ($_GET["sortby"] != "") ? $_GET["sortby"] : "datum";
		$order = ($order != "") ? $order : "DESC";
		$num = count($matches);
		
		if( (isset($_REQUEST['pp'])) && ($_REQUEST['pp']!="") && (is_numeric($_REQUEST['pp'])) ){
			$limit = $_REQUEST['pp'];
		} else {
			$limit = 15;
		}
		
		$limit = ($_REQUEST['pp']=="") ? 15 : $_REQUEST['pp'];
		
		if(!isset($page)){
			$page = 1;
		}
		
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		if ($limit < $num) {
			$tmpl->assign('pages', pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?p=forum&amp;action=search&amp;pattern=$pattern&amp;f_id=$f_id&amp;t_id=$t_id&amp;pp=$limit&amp;page={s}&amp;area=$area\">{t}</a> "));
		}
		
		// =============================================================
		$navigation = getNavigation($navi_id, $type);
		
		$stitle = $lang["forumtitle"];
		$sname = simpletitle(str_replace($lang['f_navi_separator'], " - ", strip_tags($navigation)) . " - " . $lang['f_link_search']);
		
		$tmpl->assign("navigation", $navigation);
		$tmpl->assign("matches", array_slice($matches, $a, $limit));
		$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/result.tpl")));
	}
#}
break;




// ================================================================================
//  <<-- Suchmaske -->>
// ================================================================================
case "search_mask":
$forums_dropdown = array();
getForums(0, $forums_dropdown, "");

$tmpl->assign("navigation", "<a class='f_link_navi' href='index.php?p=showforums&amp;area=$area'>" . $lang['f_link_forums'] . "</a>");
$tmpl->assign("forums_dropdown", $forums_dropdown);
$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/search_mask.tpl")));
break;





// ================================================================================
//  <<-- Suchergebnisse zur Suchmaske -->>
// ================================================================================
case "xsearch":

if ($_GET['pattern'] == "" && $_GET['user_name'] == "") {
	// es wurde kein suchbegriff eingegeben
	$EOUT = msg("f_forum", "f_err_search_pattern_missing", str_replace("__URL__", "index.php?p=forum&amp;action=search_mask&amp;area=$area", $lang['redirect']), "index.php?p=forum&amp;action=search_mask&amp;area=$area");
	$NOOUT = 1;
}

// typ des topics
$type = "1";
switch ($_GET['type']) {
	case 1:
	$type = "t.type = " . TOPIC_TYPE_STICKY;
	break;
	case 2:
	$type = "t.type = " . TOPIC_TYPE_ANNOUNCE;
	break;
	case 3:
	$type = "t.status = " . FORUM_STATUS_MOVED;
	default:
	break;
}

// art der suche
$search_type = 'REGEXP';
$search_prefix = '';

$search_type = ($_GET['regexp'] == 1) ? 'REGEXP' : 'LIKE';
$search_prefix = ($_GET['regexp'] == 1) ? '' : '%';

// schluesselwort
$pattern_or = @explode('or', strtolower($_GET['pattern']));
$pattern_tmp = "";
$p_and_array = array();

foreach ($pattern_or as $part) {
	$pattern_and = @explode('and', strtolower($part));
	$sub_pattern = array();
	
	foreach ($pattern_and as $sub_part) {
		$sub_part = trim($sub_part);
		
		// die gesamten beitraege durchsuchen
		if ($_GET['search_post'] == 1) {
			$sub_pattern[] = "
			(
			p.title $search_type '" . $search_prefix . $sub_part . $search_prefix . "' OR 
			p.message $search_type '" . $search_prefix . $sub_part . $search_prefix . "' OR 
			t.title $search_type '" . $search_prefix . $sub_part . $search_prefix . "'
			)";
			// nur den beitrag durchsuchen
		} else {
			$sub_pattern[] = "
			(
			p.title $search_type '" . $search_prefix . $sub_part . $search_prefix . "' OR 
			t.title $search_type '" . $search_prefix . $sub_part . $search_prefix . "'
			)";
		}
	}
	$pattern_tmp = @implode(' AND ', $sub_pattern);
	$p_and_array[] = $pattern_tmp;
}

$pattern = @implode(' OR ', $p_and_array);

// sortieren nach
$order_by = "t.title";

switch ($_GET['search_sort']) {
	case 1:
	$order_by = "t.title";
	break;
	case 2:
	$order_by = "t.replies";
	break;
	case 3:
	$order_by = "author";
	break;
	case 4:
	$order_by = "forum";
	break;
	case 5:
	$order_by = "views";
	break;
	case 6:
	$order_by = "datum";
	break;
}

// sortieren
$order = $_GET['ascdesc'];

// nach benutzer suchen
$search_by_user = "(1)";

if ($_GET['user_name'] != "") {
	// exakte suche
	if ($_GET['user_opt'] == 1) {
		$search_by_user = "(u.uname LIKE '" . $_GET['user_name'] . "')";
	} elseif ($_GET['user_opt'] == 0) {
		$search_by_user = "(u.uname LIKE '%" . $_GET['user_name'] . "%')";
	}
}

// suche in foren
$search_in_forums = "(1)";

// Dummy-Array
if ($_GET['search_in_forums'] == '' || $_GET['search_in_forums'] == 'Array') { $_GET['search_in_forums'] = array('0','') ; }


if ($_GET['search_in_forums'] != "") {
	// foren die zu durchsuchen sind durchgehen
	// und die foren rausfiltern die die gruppe
	// nicht durchsuchen kann
	$allowed_forums = array();
	
	// wenn alle foren durchsucht werden sollen,
	// muessen zunaechst die foren ins array geschoben
	// werden, die auch durchsucht werden duerfen
	if (in_array(0, $_GET['search_in_forums'])) {
		$q_all_forums = "SELECT id FROM " . PREFIX . "_f_forum";
		$r_all_forums = new dbc($q_all_forums);
		
		while ($one_forum = $r_all_forums->fetchrow()) {
			$f_perms = getForumPermissions($one_forum->id, UGROUP);
			if ( ($f_perms[FORUM_PERMISSION_CAN_SEARCH_FORUM] == 1) && ($f_perms[FORUM_PERMISSION_CAN_SEE] == 1) ) {
				$allowed_forums[] = $one_forum->id;
				
			}
			$f_perms = "";
		}
		// ansonsten gehe alle ausgewaehlten foren durch und
		// ueberpruefe die berechtigung
	} else { 
		foreach ($_GET['search_in_forums'] as $forum) {
		
			$f_perms = getForumPermissions($forum, UGROUP);
			#if ($f_perms[FORUM_PERMISSION_CAN_SEARCH_FORUM] == 1) {
			if ( ($f_perms[FORUM_PERMISSION_CAN_SEARCH_FORUM] == 1) && ($f_perms[FORUM_PERMISSION_CAN_SEE] == 1) ) {
				$allowed_forums[] = $forum;
			}
		}
	}
	
	$search_in_forums = "(f.id = " . @implode(' OR f.id = ', $allowed_forums) . ")";
	
	
}

// suche nach dem datum
$search_by_date = "(1)";
$date_comparator = ($_GET['b4after'] == 0) ? ' <= ' : ' >= ';
// Tage
$divisor = 60 * 60 * 24;
$search_by_date = ($_GET['date'] == 0) ? "(1)" : "((UNIX_TIMESTAMP(NOW()) / $divisor - (UNIX_TIMESTAMP(t.datum) / $divisor)) $date_comparator " . $_GET['date'] . ")";


$query = "
	SELECT DISTINCT
		t.id,
		t.forum_id,
		t.title,
		t.replies,
		t.views,
		t.type,
		t.datum,
		t.status,
		t.posticon,
		t.uid,
		r.rating,
		f.status AS f_status,
		f.title AS f_title,
		u.uname AS autor,
		f.title AS forum,
		t.opened,
		p.opened
	FROM
		" . PREFIX . "_f_topic AS t,
		" . PREFIX . "_f_post AS p,
		" . PREFIX . "_f_forum AS f,
		" . PREFIX . "_user AS u,
		" . PREFIX . "_f_rating AS r
	WHERE
		(" . $pattern . ") AND
		(" . $type . ") AND
		(t.id = p.topic_id AND t.forum_id = f.id AND u.uid = t.uid AND r.topic_id = t.id) AND 
		f.active = 1 AND
		$search_by_user AND
		$search_in_forums AND
		$search_by_date
	ORDER BY
		t.type DESC,
		" . $order_by . " " . $order;

$result = new dbc($query);
$matches = array();

while ($hit = $result->fetchrow()) {
	
	// freizuschaltende beitrage nicht beruecksichtigen!
	if(is_mod($hit->forum_id) || ($hit->opened == 1) ) {
		
		$q_forum = "SELECT id, status FROM " . PREFIX . "_f_forum WHERE id = " . $hit->forum_id;
		$r_forum = new dbc($q_forum);
		$forum = $r_forum->fetchrow();
		
		$rating_array = @explode(",", $hit->rating);
		$hit->rating = (int) ( array_sum($rating_array) / count($rating_array) );
		
		$hit->link = "index.php?p=showtopic&amp;toid=$hit->id&amp;area=$area";
		
		if ($hit->status == FORUM_STATUS_MOVED) {
			$hit->statusicon = getIcon("thread_moved.gif", "moved");
		} else {
			if ($islogged == 0 || ($hit->f_status == FORUM_STATUS_CLOSED) ) {
				// nicht eingeloggt oder forum geschlossen
				$hit->statusicon = getIcon("thread_lock.gif", "lock");
			} else {
				setTopicIconObj($hit, $forum);
			}
		}
		
		$hit->autorlink = "index.php?p=user&amp;id=$hit->uid&amp;area=$area";
		
		$matches[] = $hit;
	}
}

// wenn keinen ergebnisse gefunden wurden...
if(!$matches){
	$EOUT = msg('searchmask_no_matches_title', 'searchmask_no_matches_body', str_replace("__URL__", "index.php?p=forum&amp;action=search_mask&amp;area=$area", $lang['redirect']), "index.php?p=forum&amp;action=search_mask&amp;area=$area");
	$NOOUT = 1;
}

// seitennavigation
$page_order_by = ($_GET["sortby"] != "") ? $_GET["sortby"] : "datum";
$page_order = ($order != "") ? $order : "DESC";
$num = count($matches);

$limit = ($_REQUEST['pp']=="") ? 15 : $_REQUEST['pp'];

if(!isset($page)){
	$page = 1;
}

$seiten = ceil($num / $limit);
$a = prepage() * $limit - $limit;


if ($limit < $num) {
	$tmpl->assign('pages', pagenav($seiten, $lang['aktpos'], 
	" <a class=\"page_navigation\" href=\"index.php?p=forum&amp;action=xsearch&amp;area=$area" . 
	"&amp;type=" . $_GET['type'] . 
	"&amp;pattern=" . $_GET['pattern'] . 
	"&amp;user_name=" . $_GET['user_name'] . 
	"&amp;search_in_forums=" . $_GET['search_in_forums'] . 
	"&amp;user_opt=" . $_GET['user_opt'] . 
	"&amp;search_post=" . $_GET['search_post'] . 
	"&amp;date=" . $_GET['date'] . 
	"&amp;b4after=" . $_GET['b4after'] . 
	"&amp;search_sort=" . $_GET['search_sort'] . 
	"&amp;ascdesc=" . $_GET['ascdesc'] . 
	"&amp;pp=" . $limit . 
	"&amp;page={s}\">{t}</a> "));
}

$tmpl->assign("matches", array_slice($matches, $a, $limit));
$tmpl->assign("navigation", "<a class='f_link_navi' href='index.php?p=showforums&amp;area=$area'>" . $lang['f_link_forums'] . "</a>");
$tmpl->assign("matches_count", $result->numrows());
$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/result.tpl")));

break;





// ================================================================================
//  <<-- Den Typ des Themas aendern -->>
// ================================================================================
case "change_type":
	$f_id = ($_POST['fid'] != "") ? $_POST['fid'] : $_GET['fid'];
	$permissions = getForumPermissionsByUser($f_id, UID);
	
	if ($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 0) {
		//if ($islogged == 0 || !permission("changetopictype")) {
		$EOUT = msg("nopermission", "nopermission_t", 
		str_replace("__URL__", "index.php?p=showforums", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
		$NOOUT = 1;
	} else {
		$q_topic = "SELECT id, title, type FROM " . PREFIX . "_f_topic WHERE id =" . $_GET["id"];
		$r_topic = new dbc($q_topic);
		$topic = $r_topic->fetchrow();
		
		$tmpl->assign("topic", $topic);
		$tmpl->assign("navigation", getNavigation($_GET["id"], "topic"));
		$tmpl->assign("content", parsetrue("container/" . container("forum"), $stitle, $tmpl->fetch("forums/change_type.tpl")));
	}
	
	break;
	
	
	
	
	// ================================================================================
	//  <<-- Den Typ des Themas uebernehmen -->>
	// ================================================================================
	case "save_type":
	
	$f_id = ($_POST['f_id'] != "") ? $_POST['f_id'] : $_GET['f_id'];
	$permissions = getForumPermissionsByUser($f_id, UID);
	
	if ( ($islogged == 0 ) ||  ($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 0) ) {
		$EOUT = msg("nopermission", "nopermission_t", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
		$NOOUT = 1;
	} else {
		$q_topic_type = "
		UPDATE
		" . PREFIX . "_f_topic
		SET
		type = " . $_POST["type"] . "
		WHERE
		id = " . $_POST["t_id"];
		
		$r_topic_type = new dbc($q_topic_type);
		
		$EOUT = msg("select_typechange_topic", "typ_change_successfully", str_replace("__URL__", "index.php?p=showforum&amp;fid=$_POST[f_id]&amp;area=$area", $lang['redirect']),  "index.php?p=showforum&amp;fid=$_POST[f_id]&amp;area=$area");
		$NOOUT = 1;
	}
	
	break;
	
	
	
	
	// ================================================================================
	//  <<-- Abstimmen -->>
	// ================================================================================
	case "rating":
	
	$q_forum = "
	SELECT
	f.id
	FROM
	" . PREFIX . "_f_forum AS f,
	" . PREFIX . "_f_topic AS t
	WHERE
	t.id = " . $_POST['t_id'] . " AND
	t.forum_id = f.id";
	
	$r_forum = new dbc($q_forum);
	$forum = $r_forum->fetchrow();
//	$permissions = getForumPermissions($forum->id, UGROUP);
	$permissions = getForumPermissionsByUser($forum->id, UID);
	
	if ($permissions[FORUM_PERMISSION_CAN_RATE_TOPIC] == 0) {
		$EOUT = msg("nopermission", "nopermission_t", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
		$NOOUT = 1;
	} else {		
		$q_sel_rating = "SELECT uid, rating, ip FROM " . PREFIX . "_f_rating WHERE topic_id = " . $_POST['t_id'];
		$r_sel_rating = new dbc($q_sel_rating);
		
		$rating = $r_sel_rating->fetchrow();
		$r_uid = @explode(",", $rating->uid);
		$ip = @explode(",", $rating->ip);
		
		if(@is_numeric(UID)){
			$v_uid = UID;
		} else {
			$v_uid = "";
		}
		
		if(UID != 0 || UID != "UID" || UID != ""){
			// wenn user eingeloggt ist und kein gast abstimmen darf
			if (!in_array(UID, $r_uid)) {
				
				// wenn noch niemand bewertet hat
				if ($rating->rating == "") {
					
					$q_rating = "
						UPDATE
							" . PREFIX . "_f_rating
						SET
							rating = '" . $_POST['rating'] . "',
							ip = '" . $_SERVER['REMOTE_ADDR'] . "',
							uid = '" . $v_uid . "'
						WHERE
							topic_id = " . $_POST['t_id'];
				} else {
					$q_rating = "
						UPDATE
							" . PREFIX . "_f_rating
						SET
							rating = CONCAT(rating, ',', '" . $_POST['rating'] . "'),
							uid = CONCAT(uid, ',', '" . $v_uid . "'),
							ip = CONCAT(ip, ',', '" . $_SERVER['REMOTE_ADDR'] . "')
						WHERE
							topic_id = " . $_POST['t_id'];
				}
				
				$r_rating = new dbc($q_rating);
			}
			// ansonstenn nicht angemeldete benutzer
		} else {
			
			// wenn keine uid gloabl ist (gast)
			if (!in_array($_SERVER['REMOTE_ADDR'], $ip)) {
				if ($rating->rating == "") {
					$q_rating = "
					UPDATE
						" . PREFIX . "_f_rating
					SET
						rating = '" . $_POST['rating'] . "',
						ip = '" . $_SERVER['REMOTE_ADDR'] . "',
						uid = '" . $v_uid . "'
					WHERE
						topic_id = " . $_POST['t_id'];
				} else {
					$q_rating = "
					UPDATE
						" . PREFIX . "_f_rating
					SET
						rating = CONCAT(rating, ',', '" . $_POST['rating'] . "'),
						ip = CONCAT(ip, ',', '" . $_SERVER['REMOTE_ADDR'] . "'),
						uid = CONCAT(uid, ',', '" . $v_uid . "'),
					WHERE
						topic_id = " . $_POST['t_id'];
				}
				
				$r_rating = new dbc($q_rating);
			}
		} // ende wenn gast abstimmen darf
		$EOUT = msg("rating_thread_message", "f_msg_type_changed", str_replace("__URL__", "index.php?p=showtopic&amp;toid=$_POST[t_id]&amp;area=$area", $lang['redirect']),  "index.php?p=showtopic&amp;toid=$_POST[t_id]&amp;area=$area");
		$NOOUT = 1;
	}
	
	break;
	
	
	
	
	// ================================================================================
	//  <<-- Thema abonnieren / Abo abbestellen -->>
	// ================================================================================
	case "addsubscription":
	$r_subscriptions = new dbc("SELECT notification FROM " . PREFIX . "_f_topic WHERE id = '" . escs($_GET['t_id']) . "'");
	$subscriptions = $r_subscriptions->fetchrow();
	$user_id = split(",", $subscriptions->notification);
	
	if (!in_array($UID, $user_id)) {
		$r_subscribe = new dbc("UPDATE " . PREFIX . "_f_topic SET notification = CONCAT(notification, ';', '$UID') WHERE id = '" . escs($_GET['t_id']) . "'");
	}
	
	$EOUT = msg("thread_abo_message", "f_msg_user_subscription", str_replace("__URL__", "index.php?p=showtopic&amp;toid=$_GET[t_id]&amp;area=$area", $lang['redirect']),  "index.php?p=showtopic&amp;toid=$_GET[t_id]&amp;area=$area");
	$NOOUT = 1;
	
	break;
	
	
	
	
	case "unsubscription" :
	$sql = new dbc("SELECT notification FROM " . PREFIX . "_f_topic WHERE id = '" . escs($_GET['t_id']) . "'");
	$row = $sql->fetchrow();
	
	$new_insert = str_replace(";" . UID, "", $row->notification);
	$sql = new dbc("UPDATE " . PREFIX . "_f_topic set notification='$new_insert' WHERE id = '" . escs($_GET['t_id']) . "'");
	
	$EOUT = msg("thread_abo_message", "f_msg_user_unsubscription", str_replace("__URL__", "index.php?p=showtopic&amp;toid=$_GET[t_id]&amp;area=$area", $lang['redirect']),  "index.php?p=showtopic&amp;toid=$_GET[t_id]&amp;area=$area");
	$NOOUT = 1;
	break;
	
	
	
	// ================================================================================
	//  <<-- Aktive Themen der ausgewaehlten Zeitspanne anzeigen -->>
	// ================================================================================
	case "show":
	
	$unit = ($_GET['unit'] == "") ? $_POST['unit'] : $_GET['unit'];
	$period = ($_GET['period'] == "") ? $_POST['period'] : $_GET['period'];
	$fid = ($_GET['fid'] == "") ? $_POST['fid'] : $_GET['fid'];
	
	$forum_stat = ($fid != "") ? " AND t.forum_id = $fid" : "";
	$sort = ($_POST['sort'] != "") ? $_POST['sort'] : "ASC";
	
	switch ($unit) {
		
		// Stunden
		case 'h':
		// sekunden * 60 * 60 = stunde
		$divisor = 60 * 60;
		$where_time_stat = "((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 = "((UNIX_TIMESTAMP(NOW()) / $divisor) - (UNIX_TIMESTAMP(p.datum) / $divisor)) <= $period";
		break;
		
		// Monat
		case 'm':
		$divisor = 60 * 60 * 24 * 30;
		$where_time_stat = "((UNIX_TIMESTAMP(NOW()) / $divisor) - (UNIX_TIMESTAMP(p.datum) / $divisor)) <= $period";
		break;
		
		case 'all':
		$where_time_stat = "1";
	}
	
	$q_last_active = "
		SELECT DISTINCT
			t.id,
			t.forum_id,
			t.title,
			t.status,
			t.type,
			t.datum,
			t.views,
			t.posticon,
			t.uid,
			t.replies,
			u.uname,
			r.rating,
			f.title AS f_title	
		FROM
			" . PREFIX . "_f_topic AS t,
			" . PREFIX . "_user AS u,
			" . PREFIX . "_f_rating AS r,
			" . PREFIX . "_f_post AS p,
			" . PREFIX . "_f_forum AS f
		WHERE
			$where_time_stat AND
			u.uid = t.uid AND
			r.topic_id = t.id AND
			p.topic_id = t.id AND
			f.id = t.forum_id
			$forum_stat
		ORDER BY
			t.datum
			$sort
	";
	
	$r_last_active = new dbc($q_last_active);
	
	$matches = array();
	
	while ($topic = $r_last_active->fetchrow()) {
		$topic->autorlink = "index.php?p=user&amp;id=$topic->uid&amp;area=$area";
		$topic->autor = $topic->uname;
		$topic->link = "index.php?p=showtopic&amp;toid=$topic->id&amp;area=$area";
		
		$rating = @explode(",", $topic->rating);
		$topic->rating = (int) (array_sum($rating) / count($rating));
		
		// =================================================
		//  <<-- Anzahl der Postings ermitteln -->>
		// =================================================
		
		// als limit fuer die maximale anzahl der postings auf
		// einer seite wird 15 als standardwert genommen
		$limit = 15;
		
		$r_post = new dbc("SELECT COUNT(id) as count FROM " . PREFIX . "_f_post WHERE topic_id = ' " . $topic->id . "'");
		$post = $r_post->fetchrow();
		
		$count = (($post->count / $limit) > ((int) ($post->count / $limit))) ? ((int) ($post->count / $limit)) + 1 : ((int) ($post->count / $limit));
		
		$topic->navigation_count = ($count == 1) ? 0 : $count;
		
		// forum zum thema
		$r_forum = new dbc("SELECT id, status FROM " . PREFIX . "_f_forum WHERE id = '".$topic->forum_id."'");
		
		if ($topic->status == FORUM_STATUS_MOVED) {
			$topic->statusicon = getIcon("thread_moved.gif", "moved");
		} else {
			if ($islogged == 0 || ($forum->status == FORUM_STATUS_CLOSED) ) {
				// nicht eingeloggt oder forum geschlossen
				$topic->statusicon = getIcon("thread_lock.gif", "lock");
			} else {
				setTopicIconObj($topic, $forum);
			}
		}
		
		array_push($matches, $topic);
	}
	
	$tmpl->assign("navigation", "<a href='index.php?p=showforums&amp;area=$area'>" . $lang['f_header_forum'] . "</a>");
	$tmpl->assign("matches", $matches);
	$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/result.tpl")));
	
	break;
	
	
	
	
	
	case "print":
	switch ($_GET['what']) {
		case 'subscription':
		if (is_numeric(UID)) {
			
			$f_id = ($_GET['id'] == "") ? "t.forum_id" : "'" . $_GET['id'] . "'";
			
			$query = "
				SELECT
					t.id,
					t.title,
					t.forum_id,
					t.views,
					t.posticon,
					t.rating,
					t.uid,
					f.title AS f_title,
					t.notification,
					t.replies,
					t.status,
					u.uname
				FROM
					" . PREFIX . "_f_topic AS t,
					" . PREFIX . "_f_forum AS f,
					" . PREFIX . "_user AS u
				WHERE
					f.id = $f_id AND
					t.forum_id = f.id AND
					u.uid = t.uid";
			
			$result = new dbc($query);
			
			$matches = array();
			
			while ($topic = $result->fetchrow()) {
				$notification = @explode(';', $topic->notification);
				
				if (in_array(UID, $notification)) {
					if ($topic->status == FORUM_STATUS_MOVED) {
						$topic->statusicon = getIcon("thread_moved.gif", "moved");
					} else {
						if ($islogged == 0 || ($forum->status == FORUM_STATUS_CLOSED) ) {
							// nicht eingeloggt oder forum geschlossen
							$topic->statusicon = getIcon("thread_lock.gif", "lock");
						} else {
							setTopicIconObj($topic, $forum);
						}
					}
					
					$topic->autorlink = "index.php?p=user&amp;id=$topic->uid&amp;area=$area";
					$topic->link = "index.php?p=showtopic&amp;toid=$topic->id&amp;fid=$topic->forum_id&amp;area=$area";
					$topic->autor = $topic->uname;
					$rating = @explode(",", $topic->rating);
					$topic->rating = (int) (array_sum($rating) / count($rating));
					
					$matches[] = $topic;
				}
			}
			
			$tmpl->assign("navigation", "<a href='index.php?p=showforums&amp;area=$area'>" . $lang['f_header_forum'] . "</a>");
			$tmpl->assign("matches", $matches);
			$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/result.tpl")));
		}
		
		break;
		
		case 'posting':
		if ("" != $_GET['id']) {
			
			$limit = ($_REQUEST['pp']=="") ? 15 : (int)$_REQUEST['pp'];
			
			$query = "
				SELECT
					p.id,
					p.title,
					p.topic_id,
					p.datum,
					p.use_bbcode,
					p.use_smilies,
					p.use_sig,
					p.message,
					p.attachment,
					f.id AS forum_id,
					f.title AS forum_title,
					t.title AS topic_title,
					u.uname
				FROM
					" . PREFIX . "_f_post AS p,
					" . PREFIX . "_f_topic AS t,
					" . PREFIX . "_f_forum AS f,
					" . PREFIX . "_user AS u
				WHERE
					p.uid = " . $_GET['id'] . " AND
					u.uid = p.uid AND
					t.id = p.topic_id AND
					t.forum_id = f.id AND
					f.active = 1
				ORDER BY datum DESC
			";
			
			$result = new dbc($query);
			$num = $result->numrows();
			
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
			
			$query2 = "
				SELECT
					p.id,
					p.title,
					p.topic_id,
					p.datum,
					p.use_bbcode,
					p.use_smilies,
					p.use_sig,
					p.message,
					p.attachment,
					f.id AS forum_id,
					f.title AS forum_title,
					t.title AS topic_title,
					u.uname
				FROM
					" . PREFIX . "_f_post AS p,
					" . PREFIX . "_f_topic AS t,
					" . PREFIX . "_f_forum AS f,
					" . PREFIX . "_user AS u
				WHERE
					p.uid = " . $_GET['id'] . " AND
					u.uid = p.uid AND
					t.id = p.topic_id AND
					t.forum_id = f.id AND
					f.active = 1
				ORDER BY
					datum DESC
					LIMIT $a,$limit
			";//LIMIT $a,$limit
			$result = new dbc($query2);
			$matches = array();
			
			while ($post = $result->fetchrow()) {
				$post->datum = datumtomytime($post->datum);
				
				$permissions = getForumPermissionsByUser($post->forum_id, UID);
				if ($permissions[FORUM_PERMISSION_CAN_SEE] == 1) {
					// soll bbcode verwendet werden
					if ($post->use_bbcode == 1) {
						$post->message = kcodes($post->message);
					} else {
						$post->message = nl2br($post->message);
					}
					$matches[] = $post;
				} else {
					$post->message = "denied";
					$matches[] = $post;
				}
				
			}
			
			$stitle = $lang['show_posts'];
			$sname = simpletitle($stitle);
			
			if ($limit < $num) {
				$id = (!is_numeric($_REQUEST['id'])) ? 1 : $_REQUEST['id'];
				$tmpl->assign('pages', pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?p=forum&amp;action=print&amp;what=posting&amp;id=$id&amp;page={s}&amp;area=$area&amp;pp=$limit\">{t}</a> "));
			}
			$tmpl->assign("navigation", "<a href='index.php?p=showforums&amp;area=$area'>" . $lang['f_header_forum'] . "</a>");
			$tmpl->assign("post_count", $num);
			$tmpl->assign("matches", $matches);
			$tmpl->assign("lang", $lang);
			$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/showpost.tpl")));
		}
		break;
	}
	
	break;
	
	
	
	
	// ================================================================================
	//  <<-- Passwort geschuetztes Forum -->>
	// ================================================================================	
	case "login":
	$r_pass = new dbc("SELECT password, title FROM " . PREFIX . "_f_forum WHERE id = '" . escs($_POST['fid']) . "'");
	$pass = $r_pass->fetchrow();
	
	if (md5($_POST['pass']) == $pass->password) {
		// cookie setzen
		@setcookie("f_pass_id_" . $_REQUEST['fid'] , md5($_POST['pass']) , 0);
		
		
		header("Location: index.php?p=showforum&fid=$_POST[fid]&area=$area");
	} else {
		$stitle = $lang["f_title_forum_login"];
		$sname = simpletitle($stitle);
		
		$tmpl->assign("navigation", getNavigation($fid, "forum") . $lang["forum_navi_separator"] . $pass->title);
		$tmpl->assign("fid", $_POST['fid']);
		$tmpl->assign("error", $lang['f_err_wrong_password']);
		$tmpl->assign("lang", $lang);
		$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/forumlogin.tpl")));
	}
	
	break;
	
	
	
	
	
	// ================================================================================
	//  <<-- Download Anhang -->>
	// ================================================================================	
	case 'getfile':
	// berechtigung ueberpruefen
	$permissions = getForumPermissionsByUser($_GET['f_id'], UID);
	
	if (($permissions[FORUM_PERMISSION_CAN_DOWNLOAD_ATTACHMENT] == 0) && (UGROUP != 1)) {
		$EOUT = msg("nopermission", "nopermission_t", str_replace("__URL__", "index.php?p=showtopic&amp;toid=$_GET[toid]&amp;area=$area", $lang['redirect']), "index.php?p=showtopic&amp;toid=$_GET[toid]&amp;area=$area");
		$NOOUT = 1;
	} else {
		$result = new dbc("SELECT filename, orig_name FROM " . PREFIX . "_f_attachment WHERE id = '".escs($_GET['id'])."'");
		$file = $result->fetchrow();
		
		$update = new dbc("UPDATE " . PREFIX . "_f_attachment set hits=hits+1 WHERE id='$_GET[id]'");
		ob_end_flush();
		ob_end_clean();
		header("Cache-control: private");
		header("Content-type: application/octet-stream"); 
		header("Content-disposition:attachment; filename=" . str_replace(' ','',$file->orig_name));
		header("Content-Length: " . filesize("uploads/attachment/" . $file->filename));
		readfile("uploads/attachment/" . $file->filename);
		exit();
	}
	
	
	break;
	
	case 'markread':
	
	switch ($_GET['what']) {
		case 'forum':
		if ($_GET['id'] != "") {
			setForumAsRead(escs($_GET['id']));
			header("Location:index.php?p=showforum&fid=$_GET[id]&area=$area");
		}
		break;
	}
	
	break;
	
}
?>