<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE (c) 2002-2007 DREAM4
// 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
//=================================================================

//============================================================
//============================================================
function forumsHelp($categ='')
{
	$faq_categ = array(); 
	$faq_categ_db = ($categ != '' && is_numeric($categ)) ? " AND Id = '$categ'" : "";
	$sql = $GLOBALS['db']->Query("SELECT *,Name_" . $_SESSION['Langcode'] . " AS Name FROM " . PREFIX . "_f_hilfe WHERE Aktiv = 1 {$faq_categ_db} ORDER BY Position ASC");
	while($row = $sql->fetchrow())
	{
		$faq = array();
		$sql_faq = $GLOBALS['db']->Query("SELECT *,Name_" . $_SESSION['Langcode'] . " AS FaqName FROM " . PREFIX . "_f_hilfetext WHERE Kategorie = '" . $row->Id . "' AND Aktiv='1' ORDER BY Position ASC");
		while($row_faq = $sql_faq->fetchrow())
		{
			array_push($faq, $row_faq);
		}
		$row->Items = $faq;
		array_push($faq_categ, $row);
	}
	$GLOBALS['tmpl']->assign('faq_categ', $faq_categ);
	
	if($categ == '')
	{
		$GLOBALS['tmpl']->assign('pagetitle_html', koobispecialchars($GLOBALS['config_vars']['Help_General_Forums']));
		$GLOBALS['tmpl']->assign('keywords', koobispecialchars($GLOBALS['config_vars']['Help_General_ForumsInf']));
		$GLOBALS['tmpl']->assign('description', koobispecialchars($GLOBALS['config_vars']['Help_General_ForumsInf']));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/forums_help.tpl')); //forums_help_detail.tpl
	}
}

//============================================================
//============================================================
function forumsHelpDetail($id=1)
{
	$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_hilfetext SET Klicks = Klicks+1 WHERE Id = '" . $id . "'");
	
	$row_faq = $GLOBALS['db']->RowQuery("SELECT *,Name_" . $_SESSION['Langcode'] . " AS FaqName, Text_" . $_SESSION['Langcode'] . " AS FaqText FROM " . PREFIX . "_f_hilfetext WHERE Id = '" . $id . "' AND Aktiv='1'");
	
	if(is_object($row_faq)) 
	{
		forumsHelp($row_faq->Kategorie);
	
		$GLOBALS['tmpl']->assign('keywords', koobispecialchars($row_faq->FaqName . $row_faq->FaqText));
		$GLOBALS['tmpl']->assign('description', koobispecialchars($row_faq->FaqName . $row_faq->FaqText));
		$GLOBALS['tmpl']->assign('pagetitle_html', koobispecialchars($GLOBALS['config_vars']['Help_General_Forums'] . $GLOBALS['config_vars']['Forums_Splitter'] .$row_faq->FaqName));
	}
	$GLOBALS['tmpl']->assign('row_faq', $row_faq);
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/forums_help_detail.tpl'));
}

function attachmentDel($id,$file)
{
	$id = cleanString($id);
	$file = cleanString($file,1);
	
	$res = $GLOBALS['db']->RowQuery("SELECT * FROM  " . PREFIX . "_f_attachment WHERE id = '$id' AND filename = '$file'");
	if(is_object($res))
	{
		$GLOBALS['db']->Query("DELETE FROM  " . PREFIX . "_f_attachment WHERE id = '$id' AND filename = '$file'");
		@unlink(BASE_DIR . '/uploads/attachment/' . $file);
	}
}

function attachmentImg($name,$file='')
{
	$endg = strtolower(substr($name,-3));
	switch($endg)
	{
		case 'jpg':
		case 'gif':
		case 'png':
		case 'zip':
		case 'rar':
		case 'tar':
		case 'php':
		case 'rtf':
		case 'jpe':
		case 'doc':
		case 'pdf':
		case 'bmp':
		case 'psd':
		case 'txt':
			$file = IMG_PATH . '/attachment/' . $endg . '.gif'; 
		break;
		
		default:
			$file = IMG_PATH . '/attachment/attach.gif'; 
		break;
	}
	
	if($file)
	{
		return '<img class="absmiddle" src="' . $file . '" alt="" border="" />';
	} else {
		return '';
	}
}

//============================================================
// Anlagen-Upload
//============================================================
function attachmentUpload()
{
	if(isset($_REQUEST['toid']) && $_REQUEST['toid']!="")
	{
		$q_closed = "SELECT
			f.id,
			f.status AS fstatus, 
			t.status AS tstatus,
			t.uid
		FROM
			" . PREFIX . "_f_forum AS f, 
			" . PREFIX . "_f_topic AS t
		WHERE
		t.id = '" . $_REQUEST["toid"]  . "' AND f.id = t.forum_id";
		
		$r_closed = $GLOBALS['db']->Query($q_closed);
		$closed = $r_closed->fetchrow();
		$permissions = getForumPermissionsByUser($closed->id, UID);
	} else {
		$permissions = getForumPermissionsByUser($_REQUEST['fid'], UID);
	}
	if (@$permissions[FORUM_PERMISSION_CAN_UPLOAD_ATTACHMENT] == 0){
		echo "<pre>permission denied</pre>";
		exit;
	}
	
	if (!isset($_REQUEST['action']))
	{
		$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_f_allowed_files");
		$allowed = explode('|', $res->Typen);
		$allowed_size = $res->Max_Groesse;
		
		asort($allowed);
		
		$GLOBALS['tmpl']->assign("allowed", $allowed);
		$GLOBALS['tmpl']->assign("res", $res);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/attachment.tpl')); 
	} else {
		if (isset($_REQUEST['action']) && $_REQUEST['action'] == "upload")
		{
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_f_allowed_files");
			$allowed = explode('|', $res->Typen);
			$allowed_size = $res->Max_Groesse;
			
			$upload_dir = BASE_DIR . "/uploads/attachment/";
			$prefix = '';
			$UpError = '';
			$imgtest = '';
			$file_names = $_FILES['attachment']['name'];
			$tmp_file_names = $_FILES['attachment']['tmp_name'];
			$file_types = $_FILES['attachment']['type'];
			$file_sizes = $_FILES['attachment']['size'];
			
			$files = array();
			
			
			// alle hochgeschickten dateien durchgehen
			for($i = 0; $i < count($file_names); $i++)
			{
				if ($file_names[$i]	!= "")
				{
					$endung_1 = strtolower(substr($file_names[$i],-4));
					$endung_2 = strtolower(substr($file_names[$i],-3));
					$endung_3 = strtolower(substr($file_names[$i],-5));
					
					switch($endung_1)
					{
						case '':
							$imgtest = '';
						break;
						
						case '.jpg':
							$imgtest = 'imagecreatefromjpeg';
						break;
						
						case '.gif':
							$imgtest = 'imagecreatefromgif';
						break;
						
						case '.png':
							$imgtest = 'imagecreatefrompng';
						break;
					}
					
					$orig_name = $file_names[$i];
					
					// Fehler, wenn Datei nicht erlaubt ist
					if (!in_array($endung_1, $allowed) && !in_array($endung_2, $allowed) && !in_array($endung_3, $allowed))  
					{
						$UpError[] = $GLOBALS['config_vars']['Forums_ErrorFileNotSupported'] . ' (' . $file_names[$i] . ')';
					}
					
					// Fehler, wenn Datei zu gross ist
					if($UpError=='' && ($file_sizes[$i] / 1024) > $allowed_size) $UpError[] = $GLOBALS['config_vars']['Forums_ErrorWrongSize'];
					
					// Wenn datei ein Bild ist, Bild pruefen ob beschaedigt
					if($UpError=='')
					{
						if($imgtest)
						{
							if(!@$imgtest($tmp_file_names[$i])) $UpError[] = $GLOBALS['config_vars']['Forums_ErrorImgError'];
						}
					}
					
					// Datei hochladen und in cache legen
					if($UpError=='')
					{
						$file_names[$i] = createFilename(BASE_DIR . "/uploads/attachment/");
						if (move_uploaded_file($tmp_file_names[$i], $upload_dir . "/" . $file_names[$i])) 
						{
							@chmod($upload_dir . "/" . $file_names[$i],0777);
							$db_filename = preg_replace('/([^.A-Za-zÀ-ÖØ-öø-ÿ0-9_-]*)/', '', $orig_name);
							
							$q_attach = "INSERT INTO " . PREFIX . "_f_attachment (id,orig_name,filename) VALUES ('','$db_filename','" . $file_names[$i] . "')";
							
							$r_attach = $GLOBALS['db']->Query($q_attach);
							$file['id'] = $GLOBALS['db']->InsertId();
							$file['orig_name'] = $orig_name;
							$file['file_name'] = $prefix . $file_names[$i];
							$file['file_size'] = $file_sizes[$i];
							$file['file_type'] = $file_types[$i];
							$file['fid'] = @$_REQUEST['fid'];
							$files[] = $file;
						} else {
							$UpError[] = $GLOBALS['config_vars']['Forums_ErrorUpload'];
						}
					} 
				} 
			} 
			
			
			$GLOBALS['tmpl']->assign("res", $res);
			$GLOBALS['tmpl']->assign("allowed", $allowed);
			$GLOBALS['tmpl']->assign("files", $files);
			$GLOBALS['tmpl']->assign("UpError", $UpError);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/attachment.tpl')); 
		} 
	}
}


function popSearch()
{
	$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/search_small.tpl');
	$out = str_replace('<','&lt;',$out);
	$out = str_replace('>','&gt;',$out);
	$out = str_replace('"','\'',$out);
	return $out;
}

function forumsDropdown()
{
	$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/forums_onclick_options.tpl');
	$out = str_replace('<','&lt;',$out);
	$out = str_replace('>','&gt;',$out);
	$out = str_replace('"','\'',$out);
	return $out;
}
	
	
function userDropDownPop($uid,$name='')
{
	$GLOBALS['tmpl']->assign('is_ignore',0);
	$GLOBALS['tmpl']->assign('ignore_options',0);
	
	if(UGROUP != 2 && ($uid != UID))
	{
		$ignore = $GLOBALS['db']->RowQuery("SELECT IgnorierId FROM " . PREFIX . "_ignorierliste WHERE BenutzerId = '" . UID . "'");
		if(is_object($ignore) && $uid == $ignore->IgnorierId)
		{
			$GLOBALS['tmpl']->assign('is_ignore',1);
		} else {
			$GLOBALS['tmpl']->assign('is_ignore',0);
		}
		$GLOBALS['tmpl']->assign('ignore_options',1);
	}
	
	$GLOBALS['tmpl']->assign('theuid',$uid);
	$GLOBALS['tmpl']->assign('theuname',$name);
	$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/user_onclick_options.tpl'); 
	$out = str_replace('<','&lt;',$out);
	$out = str_replace('>','&gt;',$out);
	$out = str_replace('"','\'',$out);
	return $out;
}

function userOnlineLinks()
{
	$online = array();
	$sql_online = $GLOBALS['db']->Query("SELECT Uid,Benutzername,Unsichtbar FROM " . PREFIX . "_benutzer_online WHERE Benutzername != 'UNAME'");
	while($row_online = $sql_online->fetchrow())
	{
		if(UGROUP != 1 && $row_online->Unsichtbar == 1)
		{
			// Nothing
		} else {
			array_push($online,$row_online);
		}
	}
	$UserOnline = $GLOBALS['db']->RowQuery("SELECT COUNT(Ip) AS Online FROM " . PREFIX . "_benutzer_online WHERE Benutzername != 'UNAME'");
	$GuestOnline = $GLOBALS['db']->RowQuery("SELECT COUNT(Ip) AS Online FROM " . PREFIX . "_benutzer_online WHERE Benutzername = 'UNAME'");
	$GLOBALS['tmpl']->assign('UserOnline', $UserOnline->Online);
	$GLOBALS['tmpl']->assign('GuestsOnline', $GuestOnline->Online);
	
	$GLOBALS['tmpl']->assign('userOnlineLinks', $online);
	echo $GLOBALS['tmpl']->fetch(BASE_DIR . "/theme/" . $GLOBALS['theme'] . "/forums/user_online_links.tpl");
}

function stats_user_forums()
{
    $tmpl = new Koobi("templates/");
    $row_threads = $GLOBALS['db']->RowQuery("SELECT COUNT(id) AS Topics FROM " . PREFIX . "_f_topic");
    $num_threads = $row_threads->Topics;

    $row_posts = $GLOBALS['db']->RowQuery("SELECT COUNT(id) AS Posts FROM " . PREFIX . "_f_post");
    $num_posts = $row_posts->Posts;

    $row_members = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Benutzer FROM " . PREFIX . "_benutzer WHERE Aktiv = '1'  AND Gruppe!=2 AND Profil_public=1 ");
    $num_members = $row_members->Benutzer;

    $sql_newest_member = $GLOBALS['db']->Query("SELECT Id as uid, Benutzername as uname FROM " . PREFIX . "_benutzer WHERE Aktiv='1' AND Gruppe!=2 AND Profil_public=1 ORDER BY Id DESC");
    $row_newest_member = $sql_newest_member->fetchrow();
	
	$GLOBALS['tmpl']->assign('newestmember', $row_newest_member->uname);
	$GLOBALS['tmpl']->assign('uid', $row_newest_member->uid);
	$GLOBALS['tmpl']->assign('num_members', $num_members);
	$GLOBALS['tmpl']->assign('num_posts', $num_posts);
	$GLOBALS['tmpl']->assign('num_threads', $num_threads);
	$GLOBALS['tmpl']->assign('lang', $lang);
	echo $GLOBALS['tmpl']->fetch(BASE_DIR . "/theme/" . $GLOBALS['theme'] . "/forums/stats_user.tpl");
} 

function miscIds()
{
	if (@is_numeric(UID)) 
	{
		$queryfirst = "SELECT GruppeMisc FROM " . PREFIX . "_benutzer WHERE Id = '" . UID . "'";
		$result = $GLOBALS['db']->Query($queryfirst);
		$user = $result->fetchrow();
		
		if(is_object($user) && $user->GruppeMisc != "")
		{
			$group_ids_pre = UGROUP . ";" . $user->GruppeMisc;
			$group_ids     = @explode(";", $group_ids_pre);
			
		} else {
			$group_ids[] = UGROUP;
		}
	} else {
		$group_ids[] = 2;
	}
	return $group_ids;
}

function createFilename($dir)
{
    $fn = time() . mt_rand(900000000, 9999999999);
    if (file_exists($dir . $fn)) {
        return createFilename($dir);
    } else {
        return md5($fn);
    } 
} 

function getNavigation($id, $type, $result = null)
{
	if ($type == "category") $parent_id = "parent_id";
    if ($type == "forum") $parent_id = "category_id";
    if ($type == "topic") $parent_id = "forum_id";
    if ($type == "post") $parent_id = "topic_id"; 
    // daten des aktuellen bereichs
    $q_navi = "SELECT id, title, $parent_id AS pid FROM " . PREFIX . "_f_" . $type . " WHERE id = $id";
    $r_navi = $GLOBALS['db']->Query($q_navi);
    $navi = $r_navi->fetchRow(); 
    // rekursion abgeschlossen
    if (!is_object($navi) || $navi->pid == 0) {
        return  '<a class="forum_links_navi"  href="index.php?p=showforums">'.$GLOBALS['config_vars']['Forums_Title'].'</a>' . $result;
    } 
    // typ des darueberliegenden bereiches bestimmen
    if ($type == "post") $type = "topic";
    else if ($type == "topic") $type = "forum";
    else if ($type == "forum") $type = "category";
    else if ($type == "category") $type = "forum"; 
    // daten des darueberliegenden bereiches
    $q_parent = "SELECT id, title FROM " . PREFIX . "_f_$type WHERE id = " . $navi->pid;
    $r_parent = $GLOBALS['db']->Query($q_parent);
    $parent = $r_parent->fetchRow();

    if ($type == "topic") $result = $GLOBALS["config_vars"]["Forums_Splitter"] . "<a title='" . koobispecialchars($parent->title) . "' class='forum_links_navi' href='index.php?p=showtopic&amp;tid=" . $parent->id . "&amp;t=" . seotitle(koobispecialchars($parent->title)) . "'>" . str_replace($GLOBALS['config_vars']['Forums_Splitter'],'|||',koobispecialchars($parent->title)) . "</a>" . $result;
    else if ($type == "forum") $result = $GLOBALS["config_vars"]["Forums_Splitter"] . "<a title='" . koobispecialchars($parent->title) . "' class='forum_links_navi' href='index.php?p=showforum&amp;fid=" . $parent->id . "&amp;t=" . seotitle(koobispecialchars($parent->title)) . "'>" . str_replace($GLOBALS['config_vars']['Forums_Splitter'],'|||',koobispecialchars($parent->title)) . "</a>" . $result;
    else if ($type == "category") $result = $GLOBALS["config_vars"]["Forums_Splitter"] . "<a title='" . koobispecialchars($parent->title) . "' class='forum_links_navi' href='index.php?p=showforums&amp;cid=" . $parent->id . "&amp;t=" . seotitle(koobispecialchars($parent->title)) . "'>" . str_replace($GLOBALS['config_vars']['Forums_Splitter'],'|||',koobispecialchars($parent->title)) . "</a>" . $result;

    return getNavigation($navi->pid, $type, $result);
} 


//============================================================
// topicExists eueberprueft, ob thema existiert
//============================================================
function topicExists($t_id)
{
	$query = "SELECT id FROM " . PREFIX . "_f_topic WHERE id = $t_id";
	$result = $GLOBALS['db']->Query($query);
	if ($result->numrows() > 0) return 1;
	return 0;
} 


//============================================================
// getForums listet alle foren auf 
//============================================================
function getForums($id, &$forums, $prefix, $f_id = "0")
{ 
	$r_sub_cat = '';
    // kategorien holen
    $q_cat = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = $id";
    $r_cat = $GLOBALS['db']->Query($q_cat); 
   
    //============================================================
	// berechtigung holen
    //============================================================
	$group_ids_misc = array(); 
    //============================================================
	// 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(); 
        // ========================================================
		// wenn misc nicht leer ist...
        // ========================================================
		if (is_object($user) && $user->group_id_misc != "") {
            $group_ids_pre = UGROUP . ";" . $user->group_id_misc;
            $group_ids_misc = @explode(";", $group_ids_pre); 
            // ========================================================
			// wennn misc leer ist und user eingeloggt ist
        	// ========================================================
		} else {
		    $group_ids_misc[] = UGROUP;
        } 
        // ========================================================
		// wenn user nicht eingeloggt ist
		// ========================================================
    } else {
        $group_ids_misc[] = 2;
    } 

	// ========================================================
    // kategorien durchgehen
	// ========================================================
    while ($cat = $r_cat->fetchrow())
	{
		// foren zur kategorie holen
        $q_forum = "
			SELECT 
			f.id, 
			f.category_id, 
			f.title,
			f.group_id
			FROM 
			" . PREFIX . "_f_forum AS f
			WHERE 
			f.category_id = '" . $cat->id . "' AND 
			f.active = 1"; 
        $result = $GLOBALS['db']->Query($q_forum); 
		
        // alle foren durchgehen
        while ($forum = $result->fetchrow())
		{
			// forumname
			$sql_ftitle = $GLOBALS['db']->Query("SELECT title FROM " . PREFIX . "_f_category WHERE id='$forum->category_id'");
            $row_ftitle = $sql_ftitle->fetchrow();

            $group_ids = explode(",", $forum->group_id);
			
            if (array_intersect($group_ids_misc, $group_ids))
			{
                foreach($group_ids_misc as $gids_misc)
				{
					if(in_array($gids_misc, $group_ids))
					{
						$permissions = getForumPermissions($forum->id, $gids_misc);
						 
						if ($permissions[FORUM_PERMISSION_CAN_SEE] == 1)
						{
							$forum->visible_title = $prefix . $forum->title;
               				$forum->fname = $row_ftitle->title;
							
							$q_sub_cat = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = " . $forum->id;
							$r_sub_cat = $GLOBALS['db']->Query($q_sub_cat);
							$forums[] = $forum;
						}
					}
				}

				if(isset($r_sub_cat) && !empty($r_sub_cat))
				{
					while ($sub_cat = $r_sub_cat->fetchrow())
					{
						getForums($forum->id, $forums, $prefix . "- ", $f_id);
					} 
				}
            } 
        } 
    } 
} 

function getCategories($id, &$categories, $prefix)
{ 
    global $db;
	// kategorien holen
    $q_cat = "
		SELECT 
		id, 
		title, 
		group_id,
		position
		FROM 
		" . PREFIX . "_f_category 
		WHERE 
		parent_id = $id
		ORDER BY
		position";

    $r_cat = $GLOBALS['db']->Query($q_cat); 
    // berechtigung holen
    $group_ids_misc = array(); 
    // =====================================================================================
    // miscrechte
    // =====================================================================================
    if (@is_numeric(UID))
	{
       # $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = " . UID;
		$queryfirst = "SELECT GruppeMisc as group_id_misc FROM " . PREFIX . "_benutzer WHERE Id = " . UID;
        $result = $GLOBALS['db']->Query($queryfirst);
        $user = $result->fetchrow(); 
        // wenn misc nicht leer ist...
        if (is_object($user) && $user->group_id_misc != "") {
            $group_ids_pre = UGROUP . ";" . $user->group_id_misc;
            $group_ids_misc = @explode(";", $group_ids_pre); 
            // wennn misc leer ist und user eingeloggt ist
        } else {
            $group_ids_misc[] = UGROUP;
        } 
        // wenn user nicht eingeloggt ist
    } else {
        $group_ids_misc[] = 2;
    } 
    // =====================================================================================
    // kategorien durchgehen
    while ($cat = $r_cat->fetchrow()) {
        $cat->group_id = @explode(",", $cat->group_id);
        if (array_intersect($cat->group_id, $group_ids_misc)) {
            // foren zur kategorie holen
            $q_forum = "
				SELECT 
				f.id, 
				f.category_id, 
				f.title,
				f.group_id,
				f.position
				FROM 
				" . PREFIX . "_f_forum AS f
				WHERE 
				f.category_id = '" . $cat->id . "' AND 
				f.active = 1
				ORDER BY
				position";

            $result = $GLOBALS['db']->Query($q_forum); 
            // alle foren durchgehen
            while ($forum = $result->fetchrow()) {
                // forumname
                $sql_ftitle = $GLOBALS['db']->Query("SELECT title FROM " . PREFIX . "_f_category WHERE id='$forum->category_id'");
                $row_ftitle = $sql_ftitle->fetchrow();

                $group_ids = explode(",", $forum->group_id);

                if (array_intersect($group_ids_misc, $group_ids)) {
                    $forum->visible_title = $prefix . $forum->title;
                    $forum->fname = $row_ftitle->title;

                    $q_sub_cat = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = " . $forum->id;
                    $r_sub_cat = $GLOBALS['db']->Query($q_sub_cat);

                    $cat->forums[] = $forum;

                    while ($sub_cat = $r_sub_cat->fetchrow()) {
                        getCategories($forum->id, $categories, $prefix . "- ");
                    } 
                } // if array
            } // while forum
            $categories[] = $cat;
        } // if array_intersect			
    } 
} 


// ========================================================
// ONLINE- STATUS ICON
// gibt das betreffende User- Statisicon aus
// ========================================================
function getRank($posts)
{
	$posts = ($posts < 1) ? 1 : $posts;
	$rank = $GLOBALS['db']->RowQuery("SELECT title FROM " . PREFIX . "_f_rank WHERE count <= '" . $posts . "' ORDER BY count DESC LIMIT 1");
	if(is_object($rank)) return stripslashes($rank->title);
	return false;
}

function getonlinestatus($param)
{
	$sql = $GLOBALS['db']->Query("SELECT Benutzername as uname, Unsichtbar as invisible FROM " . PREFIX . "_benutzer_online WHERE Benutzername='$param[uname]' limit 1");
	$num = $sql->numrows();
    $row = $sql->fetchrow();
    if ($num >= 1) 
	{
		if ((UGROUP == 1) && ($row->invisible == "INVISIBLE")) {
            $img = "user_invisible.png" ;
            $alt = $GLOBALS['config_vars']['Forums_userisinvisible'];
        } 
        if ($row->invisible != "INVISIBLE") {
            $img = "user_online.png" ;
            $alt = $GLOBALS['config_vars']['Forums_userisonline'];
        } 
        if ((UGROUP != 1) && ($row->invisible == "INVISIBLE")) {
            $img = "user_offline.png" ;
            $alt = $GLOBALS['config_vars']['Forums_userisoffline'];
        } 
    } else {
        $img = "user_offline.png" ;
        $alt = $GLOBALS['config_vars']['Forums_userisoffline'];
    } 

    $status_img = "<img title=\"$alt\" class=\"absmiddle\" src=\"theme/" . $GLOBALS['theme'] . "/images/forums/$img\" alt=\"$alt\" />";
    return $status_img;
} 


// ========================================================
// FORUM KATEGORIE- LOESCHFUNKTION
// 1. foren loeschen
// 2. kategorie loeschen
// ========================================================
function deleteCategory($id)
{ 
global $db;
    // foren loeschen
    $query = "SELECT id FROM " . PREFIX . "_f_forum WHERE category_id = $id";
    $result = $GLOBALS['db']->Query($query);

    while ($forum = $result->fetchrow()) {
        deleteForum($forum->id);
    } 
    // kategorie loeschen
    $query = "DELETE FROM " . PREFIX . "_f_category WHERE id = $id";
    $result = $GLOBALS['db']->Query($query);
} 


// ========================================================
// FORUM- LOESCHFUNKTION
// 1. themen loeschen
// 2. berechtigungen loeschen
// 3. unterkategorien loeschen
// 4. tforum loeschen 
// ========================================================
function deleteForum($id)
{
global $db;
    $query = "SELECT id FROM " . PREFIX . "_f_topic WHERE forum_id = $id";
    $result = $GLOBALS['db']->Query($query); 
    // themen loeschen
    while ($topic = $result->fetchrow()) {
        deleteTopic($topic->id);
    } 
    // berechtigungen loeschen
    $query = "DELETE FROM " . PREFIX . "_f_permissions WHERE forum_id = $id";
    $result = $GLOBALS['db']->Query($query); 
    // unterkategorien loeschen
    $query = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = $id";
    $result = $GLOBALS['db']->Query($query);

    while ($category = $result->fetchrow()) {
        deleteCategory($category->id);
    } 
    // forum loeschen
    $query = "DELETE FROM " . PREFIX . "_f_forum WHERE id = $id";
    $result = $GLOBALS['db']->Query($query);
} 


// ========================================================
// THEMEN- LOESCHFUNKTION
// 1. alle beitraege zum thema loeschen
// 2. das rating zum thema loeschen
// 3. thema loeschen
// ========================================================
function deleteTopic($id)
{
global $db;
    $query = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = $id";
    $result = $GLOBALS['db']->Query($query); 
    // Beitraege loeschen
    while ($post = $result->fetchrow()) {
        deletePost($post->id);
    } 
    // Rating loeschen
    $query = "DELETE FROM " . PREFIX . "_f_rating WHERE topic_id = $id";
    $result = $GLOBALS['db']->Query($query); 
    // Thema loeschen
    $query = "DELETE FROM " . PREFIX . "_f_topic WHERE id = $id";
    $result = $GLOBALS['db']->Query($query);
} 


// ========================================================
// BEITRAGS- LOESCHFUNKTION
// 1. alle anhaenge loeschen
// 2. anzahl der beitraege im thema reduzieren
// 3. anzahl der beitraege des benutzers reduzieren
// 4. beitrag loeschen
// ========================================================
function deletePost($id)
{
global $db;
    $query = "SELECT attachment, topic_id FROM " . PREFIX . "_f_post WHERE id = $id";
    $result = $GLOBALS['db']->Query($query);
    $post = $result->fetchrow();

    $attachments = @explode(";", $post->attachment); 
    // anhaenge loeschen
    foreach ($attachments as $attachment) {
        if ($attachment != "") {
            $query = "SELECT filename FROM " . PREFIX . "_f_attachment WHERE id = $attachment";
            $result = $GLOBALS['db']->Query($query);
            $file = $result->fetchrow(); 
            // loesche aus dem dateisystem
            //  @unlink ("../uploads/attachment" . $file);
            // loesche aus der datenbank
            $query = "DELETE FROM " . PREFIX . "_f_attachment WHERE id = $attachment";
            $result = $GLOBALS['db']->Query($query);
        } 
    } 
    // reduziere die anzahl der beitraege im thema
    $query = "UPDATE " . PREFIX . "_f_topic SET replies = replies - 1 WHERE id = " . $post->topic_id;
    $result = $GLOBALS['db']->Query($query); 
    // reduziere die anzahl der beitraege des benutzers
    $query = "UPDATE " . PREFIX . "_benutzer SET Beitraege = Beitraege - 1 WHERE Id = " . UID;
    $result = $GLOBALS['db']->Query($query); 
    // loesche beitrag
    $query = "DELETE FROM " . PREFIX . "_f_post WHERE id = $id";
    $result = $GLOBALS['db']->Query($query);
} 



function setForumAsRead($Board = '', $Usr = null, $BoardAll = '')
{
	global $db;
	if (is_null($Usr))
	$Usr = UID;
	
	$Board  = (int) $Board;
	$BoardAll = ($_REQUEST['ReadAll']==1) ? 'WHERE Topic.forum_id != 0' :   'WHERE Topic.forum_id = '.$Board.'';
	$Usr    = (int) $Usr;

	$SQL_Post48h    = ' Topic.last_post > \''.date('Y-m-d', strtotime(KOOBI_BOARD_NEWPOSTMAXAGE)).'\' ';
	$sql = 'REPLACE DELAYED INTO '.PREFIX.'_f_topic_read (Usr,Topic)
        SELECT  
			'.$Usr.', 
			Topic.id
        FROM  '.PREFIX.'_f_topic as Topic
        	'.$BoardAll.' 
        AND 
			'.$SQL_Post48h.'';
			
	$dump = $GLOBALS['db']->Query($sql);
	
}


function setForumAsRead_Old($id)
{
	global $db;
	$cookie_ids = @explode('@', $_COOKIE['koobi4_f_visited']);
	$Forums_TheLastPostings = getLastPostings($id);

	$prev_ids = array();
	$curr_ids = array();

	foreach ($Forums_TheLastPostings as $post) {
		$curr_ids[] = $post->id;

		if (!$post->prev_post == 0) {
			$prev_ids[] = $post->prev_post->id;
		}
	}

	$cookie_ids = array_diff($cookie_ids, $prev_ids);
	setcookie('koobi4_f_visited', @implode("@", array_merge($cookie_ids, $curr_ids)), EXPIRE_YEAR);
}

function getLastPost($id)
{
	global $db;
	$post = "";
    if(is_numeric($id))
	{
		$query = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = '$id' ORDER BY id DESC LIMIT 2";
		$result = $GLOBALS['db']->Query($query);
		$post = $result->fetchrow();
	
		if ($result->numrows() > 1)
		{
			$post->prev_post = $result->fetchrow();
		} 
	}
    return $post;
} 


function getLastPostings($id)
{
	global $db;
	$postings = "";
	if(is_numeric($id))
	{
		$query = "SELECT id FROM " . PREFIX . "_f_topic WHERE forum_id = '$id'";
		$result = $GLOBALS['db']->Query($query);
	
		$postings = array();
	
		while ($topic = $result->fetchrow())
		{
			$postings[] = getLastPost($topic->id);
		} 
	}
    return $postings;
} 

// ========================================================
// MIT DIESER FUNKTION WIRD AUSGELESEN, OB DER USER
// MODERATOR FUER EIN FORUM IST
// WENNN USER ADMIN IST, IST ER AUCH MOD 
// if(is_mod($forum_id)) { $opened = 1; }
// ========================================================
function is_mod($fid)
{
    $sql = $GLOBALS['db']->Query("SELECT user_id FROM " . PREFIX . "_f_mods WHERE forum_id = '$fid'");
    while ($row = $sql->fetchrow())
	{
        $mods[] = $row->user_id;
    } 
    $user_is_mod = (@in_array(UID, $mods)) ? 1 : 0;

    if ((UGROUP == 1) || ($user_is_mod == 1))
	{
		return true;
    } else {
        return false;
    } 
} 

function getPageNum($repliesCount, $limit)
{ 
    // ============================================================================
    // Berechnung
    // 1. ermitteln wieviele beitraege bereits im bereich 0 bis $limit liegen.
    // modulo (%) liefert den rest einer division
    // 2. ermitteln wieviele beitraege bis zum naechsten
    // hoechstwert ($limit*n) noch fehlen
    // 3. diesen wert zu den gesamtantworten addieren;
    // danach hat man eine durch $limit teilbare zahl
    // 4. durch die division durch $limit erhaelt man
    // nun die seite auf der der beitrag angezeigt wird -->>
    // ============================================================================
	$limit = (!$limit) ? 15 : $limit;
    if (($repliesCount % $limit) == 0) return $repliesCount / $limit;
    return ($repliesCount + ($limit - ($repliesCount % $limit))) / $limit;
}


// ========================================================
// <<-- GET AVATAR
// ermittelt die rechte fuer den aktuellen user -->>
// ========================================================
function getAvatar($group, $avatar, $usedefault)
{
    $own = 1;
    $permown = -1; 
	$avatar_raw = $avatar;
	
	// nutzt er default- avatar?
	if (($usedefault == 1) && ($avatar == ''))  $own = 0;
 	$row  = $GLOBALS['db']->RowQuery("SELECT Rechte FROM " . PREFIX . "_berechtigungen WHERE Gruppe='$group' AND Sektion = '" . $_SESSION['area'] . "'");
    
	// wenn er admin ist, fallen alle regeln weg
    if ($row->Rechte == 'all' || $group == 1)
	{
        $permown = 1;
    } else {
        $perms = explode(',', $row->Rechte); 
        // wenn seine gruppe die rechte besitzt, eigene avatar zu nutzen
        if (in_array('own_avatar', $perms))
		{
            $permown = 1;
        } 
    } 
    if ($permown != 1) $own = 0;
    
	
    // wenn eigenes avatar beutzt werden darf und es existiert
    if ($own == 1 && $usedefault != 1)
	{
       if (@is_file(BASE_DIR . "/uploads/avatars/$avatar"))
		{
			$avatar = "<img src=\"uploads/avatars/$avatar\" alt=\"\" border=\"\" />"; 
        } else {
			$avatar = "";
		}
		
    } else {
	    $row = $GLOBALS['db']->RowQuery("SELECT Avatar_Default,Avatar FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '$group'");
        if (($row->Avatar_Default == 1) && ($row->Avatar != ""))
		{
           $avatar = "<img src=\"uploads/avatars/default/$row->Avatar\" alt=\"\" border=\"\" />";
        } 
    } 
	
	if ($own == 1 && @!is_file(BASE_DIR . "/uploads/avatars/$avatar_raw")) $avatar = "";
    return $avatar;
} 

// ================================================================
// setTopicIconObj setzt das zutreffende icon fuer jeden beitrag 
// ================================================================
function setTopicIconObj(&$topic, $forum)
{
    global $db,$UID; 
    $SQL_Post48h    = ' Topic.last_post > \''.date('Y-m-d', strtotime(KOOBI_BOARD_NEWPOSTMAXAGE)).'\' ';
	
	$HOT_VIEW_COUNT = 250;
    $HOT_REPLY_COUNT = 20; 
    // post holen
    $post = $GLOBALS['db']->RowQuery("SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic->id . " ORDER BY id DESC"); 
	
    // alle uid's zum topic holen
    $r_uid = $GLOBALS['db']->Query("SELECT uid FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic->id);
    $uids = array();

    while ($uid = $r_uid->fetchrow()) 
	{
        $uids[] = $uid->uid;
    } 
	
	$sql = "
        SELECT  COUNT(*) AS NewPostCount
        
        FROM    ".PREFIX."_f_topic AS Topic
            
            LEFT JOIN ".PREFIX."_f_topic_read AS TRead
                ON  Topic.id = TRead.Topic
                AND TRead.Usr = ".UID."

        WHERE   Topic.id=".$topic->id."
            AND (   TRead.ReadOn < Topic.last_post
                OR  TRead.ReadOn IS NULL )
            AND ".$SQL_Post48h."
    ";
    $NewPost = $GLOBALS['db']->RowQuery($sql);
	
    // ==================================================
    // ==================================================
    // neu oder nicht
    $new = false; 
    // ==================================================
    $file = "thread"; 
    // eigene beitraege im thema vorhanden?
    if (in_array(UID, $uids)) $file .= "_dot"; 
    // ein "heisses" thema?
    if ($topic->replies > $HOT_REPLY_COUNT || $topic->views > $HOT_VIEW_COUNT) $file .= "_hot"; 
    // gesperrt?
    if ($topic->status == FORUM_STATUS_CLOSED || $forum->status == FORUM_STATUS_CLOSED) $file .= "_lock"; 
    // neue beitraege vorhanden?
    if (!in_array($post->id, $all_ids)) {
        $file .= "_new";
        $new = true;
    } 

    $file .= ".png";

    switch ($topic->type) {
        case TOPIC_TYPE_ANNOUNCE:
            if ($new) {
                $topic->statusicon = getIcon('announcement_new.png', $GLOBALS['config_vars']['Forums_Icons_Announcement']);
            } else {
                $topic->statusicon = getIcon('announcement_old.png', $GLOBALS['config_vars']['Forums_Icons_Announcement']);
            } 
            break;
        case TOPIC_TYPE_STICKY:
			$topic->statusicon = ($new) ? getIcon('important_new.png', $GLOBALS['config_vars']['Forums_Icons_Important']) : getIcon('important_old.png', $GLOBALS['config_vars']['Forums_Icons_Important']);
		break;
		
        default:
            $topic->statusicon = getIcon($file, '-');
		break;
    } 
} 

//============================================================
// setzt den status des forums auf $status
// auch die subforen werden beachtet
//============================================================
function switchForumStatus($id, $status)
{
global $db;
    $q_close = "UPDATE " . PREFIX . "_f_forum SET status = $status WHERE id = $id";
    $r_close = $GLOBALS['db']->Query($q_close);
    $q_child = "
		SELECT f.id FROM 
		" . PREFIX . "_f_category AS c, 
		" . PREFIX . "_f_forum AS f 
		WHERE parent_id = $id AND f.category_id = c.id";

    $r_child = $GLOBALS['db']->Query($q_child);

    if ($r_child->numrows() == 0) return;

    while ($child = $r_child->fetchrow()) {
        switchForumStatus($child->id, $status);
    } 
    return;
} 


//============================================================
// setForumIcon setzt das zutreffende icon fuer die foren 
//============================================================
function setForumIcon(&$forum)
{
    global $db;
	$SQL_Post48h    = ' Topic.last_post > \''.date('Y-m-d', strtotime(KOOBI_BOARD_NEWPOSTMAXAGE)).'\' ';
     
    $q_topic = "
        SELECT  COUNT(*) AS NewPostCount

        FROM    ".PREFIX."_f_topic AS Topic
            
            LEFT JOIN ".PREFIX."_f_topic_read AS TRead
                ON  Topic.id = TRead.Topic
                AND TRead.Usr = ".UID."

        WHERE   forum_id = ".$forum['id']."
            AND (   TRead.ReadOn < Topic.last_post
                OR  TRead.ReadOn IS NULL )
            AND ".$SQL_Post48h."";

    $r_topic = $GLOBALS['db']->Query($q_topic);

    $topic = $r_topic->fetchrow();
    $NewPostCount = $topic->NewPostCount;
    
    $icon = "forum";

    $icon .= ($NewPostCount > 0) ? "_new" : "_old";
    $icon .= ($forum['status'] == FORUM_STATUS_CLOSED) ? "_lock" : "";
    $icon .= ".png";

    $forum['statusicon'] = getIcon($icon, (($NewPostCount > 0) ? $GLOBALS['config_vars']['Forums_Icons_NewPosts'] : $GLOBALS['config_vars']['Forums_Icons_NoNewPosts']) );
} 

//============================================================
// setTopicIcon setzt das zutreffende icon fuer jedes thema 
//============================================================
function setTopicIcon(&$topic, $forum)
{
    global $db;
	$SQL_Post48h    = ' Topic.last_post > \''.date('Y-m-d', strtotime(KOOBI_BOARD_NEWPOSTMAXAGE)).'\' ';

    $HOT_VIEW_COUNT = 250;
    $HOT_REPLY_COUNT = 20; 
    // post holen
    $q_post = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic['id'] . " ORDER BY id DESC";
    $r_post = $GLOBALS['db']->Query($q_post);
    $post = $r_post->fetchrow(); 
    
    /* Counting, how often user has posted in this topic */
    $q_uid = "
        SELECT  COUNT(*) PostedInThread
        FROM    ".PREFIX."_f_post
        WHERE   topic_id=".$topic['id']."
            AND uid = ".UID."
    ";
    $r_uid = $GLOBALS['db']->Query($q_uid);
    $uid = $r_uid->fetchrow();
    
    /* New Posts in Topic */
    $sql = "
        SELECT  COUNT(*) AS NewPostCount

        FROM    ".PREFIX."_f_topic AS Topic
            
            LEFT JOIN ".PREFIX."_f_topic_read AS TRead
                ON  Topic.id = TRead.Topic
                AND TRead.Usr = ".UID."

        WHERE   Topic.id=".$topic['id']."
            AND (   TRead.ReadOn < Topic.last_post
                OR  TRead.ReadOn IS NULL )
            AND ".$SQL_Post48h."
    ";
    $res = $GLOBALS['db']->Query($sql);
    $NewPost = $res->fetchrow();
	
    // neu oder nicht
    $new = false; 
    $file = "thread"; 
    // eigene beitraege im thema vorhanden?
    if ($uid->PostedInThread > 0) $file .= "_dot"; 
    // ein "heisses" thema?
    if (@$topic['replies'] > $HOT_REPLY_COUNT || $topic['views'] > $HOT_VIEW_COUNT) $file .= "_hot"; 
    // gesperrt?
    if (@$topic['status'] == FORUM_STATUS_CLOSED || @$forum->status == FORUM_STATUS_CLOSED) $file .= "_lock"; 
    // neue beitraege vorhanden?
    if ($NewPost->NewPostCount > 0) {
        $file .= "_new";
        $new = true;
    } 

    $file .= ".png";

    switch ($topic['type']) {
        case TOPIC_TYPE_ANNOUNCE:
            $topic['statusicon'] = ($new) ? getIcon('announcement_new.png', $GLOBALS['config_vars']['Forums_Icons_Announcement']) : getIcon('announcement_old.png', $GLOBALS['config_vars']['Forums_Icons_Announcement']);
        break;
		
        case TOPIC_TYPE_STICKY:
			 $topic['statusicon'] = ($new) ? getIcon('important_new.png', $GLOBALS['config_vars']['Forums_Icons_Important']) : getIcon('important_old.png', $GLOBALS['config_vars']['Forums_Icons_Important']);
		break;
		
        default:
            $topic['statusicon'] = getIcon($file, '-');
		break;
    } 
} 


//============================================================
// FORUM PERMISSIONS
// ermittelt die rechte fuer den aktuellen benutzer 
//============================================================
function getForumPermissions($forumid, $groupid, $ext_uid = 0)
{
	global $db;
    $sql = $GLOBALS['db']->Query("SELECT permissions FROM " . PREFIX . "_f_permissions WHERE forum_id = '$forumid' AND group_id = '$groupid'");
    $row = $sql->fetchrow();
    if (UGROUP == 1) {
        return @explode(",", "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1");
    } else {
        return @explode(",", @$row->permissions);
    } 
} 

function getForumPermissionsByUser($forum_id, $user_id){

   global $db;
    if (@is_numeric(UID)) {
       # $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = '$user_id'";
		$queryfirst = "SELECT GruppeMisc as group_id_misc FROM " . PREFIX . "_benutzer WHERE Id = '$user_id'";
        $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;
    } 

    $all_permissions = array();

    foreach ($group_ids as $group_id) {
        $query = "SELECT permissions FROM " . PREFIX . "_f_permissions WHERE forum_id = '$forum_id' AND group_id = '$group_id'";
        $result = $GLOBALS['db']->Query($query);
        $permissions = $result->fetchrow();

        $permissions = @explode(",", $permissions->permissions);

        if ($permissions[0] == 1) {
            $all_permissions[0] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_SEE_TOPIC] && @$permissions[FORUM_PERMISSION_CAN_SEE_TOPIC] == 1) 
		{
            $all_permissions[FORUM_PERMISSION_CAN_SEE_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_SEE_DELETE_MESSAGE] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_SEE_DELETE_MESSAGE] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_SEARCH_FORUM] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_SEARCH_FORUM] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_DOWNLOAD_ATTACHMENT] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_DOWNLOAD_ATTACHMENT] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_CREATE_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_CREATE_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_REPLY_OWN_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_REPLY_OWN_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_REPLY_OTHER_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_REPLY_OTHER_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_UPLOAD_ATTACHMENT] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_UPLOAD_ATTACHMENT] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_RATE_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_RATE_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_EDIT_OWN_POST] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_EDIT_OWN_POST] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_DELETE_OWN_POST] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_DELETE_OWN_POST] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_MOVE_OWN_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_MOVE_OWN_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_CLOSE_OPEN_OWN_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_CLOSE_OPEN_OWN_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_DELETE_OWN_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_DELETE_OWN_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_DELETE_OTHER_POST] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_DELETE_OTHER_POST] = 1;
        } 

        if (@$permissions[FORUM_PERMISSION_CAN_EDIT_OTHER_POST] == 1) {
            $all_permissions[FORUM_PERMISSION_CAN_EDIT_OTHER_POST] = 1;
        } 

        if (@$permissions[FORUM_PERMISSIONS_CAN_OPEN_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSIONS_CAN_OPEN_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 1) {
            $all_permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] = 1;
        } 

        if (@$permissions[FORUM_PERMISSIONS_CAN_MOVE_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSIONS_CAN_MOVE_TOPIC] = 1;
        } 

        if (@$permissions[FORUM_PERMISSIONS_CAN_DELETE_TOPIC] == 1) {
            $all_permissions[FORUM_PERMISSIONS_CAN_DELETE_TOPIC] = 1;
        } 
    } 

    return $all_permissions;
}

//============================================================
// Thema als gelesen markieren
//============================================================
function Koobi_Board_SetTopicRead($Topic, $Usr = null)
{
   global $db;
    if (is_null($Usr))
        $Usr = UID;

    $Topic  = (int) $Topic;
    $Usr    = (int) $Usr;

    $sql = "
        REPLACE DELAYED INTO ".PREFIX."_f_topic_read
        (
            Usr,
            Topic
        )
        VALUES
        (
            '".$Usr."',
            '".$Topic."'
        )
    ";
    $dump = $GLOBALS['db']->Query($sql);
}

//============================================================
// Letzten Beitrag setzen
//============================================================
function Koobi_Board_SetLastPost($Board)
{
   	global $db;
    $Board = (int) $Board;
    $Sql = "
        SELECT  Post.id,
                Post.datum

        FROM    ".PREFIX."_f_topic AS Topic

            INNER JOIN ".PREFIX."_f_post AS Post
                ON  Topic.id = Post.topic_id
                AND Topic.forum_id = '".$Board."'

        ORDER
            BY  Post.datum DESC

        LIMIT 1
    ";
    $Res = $GLOBALS['db']->Query($Sql);
    if ($Res !== false) {
        $LastPost = $Res->fetchrow();
  		 $Sql = "UPDATE  ".PREFIX."_f_forum SET     
		 		last_post       = '" . @$LastPost->datum . "',
                last_post_id    = '" . @$LastPost->id . "'
           WHERE   
		   		id = ".$Board." ";
        $Res = $GLOBALS['db']->Query($Sql);
    }
}

//============================================================
//============================================================
function Koobi_Board_GetTopic_Board($Topic)
{
    global $db;
	$Topic = (int) $Topic;
    $Sql = "SELECT  Topic.forum_id FROM    ".PREFIX."_f_topic AS Topic WHERE   Topic.id = ".$Topic." LIMIT 1";
    $Res = $GLOBALS['db']->Query($Sql);
    $Row = $Res->fetchrow();
    return (int) $Row->forum_id;    
}

// ========================================================
// <<-- FUNKTION LETZE FORUM THREADS -->>
// verwendetes template: /templates/forums/latthreads.tpl
// $param sind die foren_id's getrennt durch ,
// AUSGABE durch: {lastthreads forums='1,2,3,4,5' limit='5'}
// Die Ausgabe kann auf der ganzen Seite erfolgen
// ========================================================
function getLastForumPosts($param)
{
    global $db,$THEME;
	$last_threads = array();
    $tmpl = new Koobi("templates/");
    $fids = str_replace(",", ' OR forum_id = ', $param['forums']);
    $sql = $GLOBALS['db']->Query("
	SELECT 
		title,
		id,
		last_post_int
	FROM " . PREFIX . "_f_topic WHERE  
		forum_id = $fids 
	order by id desc LIMIT " . $param['limit']);

    $i = 0;

    while ($row = $sql->fetchrow())
	{
        $last_threads[$i]['tid'] = $row->id;
        $last_threads[$i]['title'] = $row->title;
        $last_threads[$i]['time'] = mygmt($row->last_post_int);
        $i++;
    } 

    $tmpl->assign('theme', $THEME);
    $tmpl->assign('last_thread_array', $last_threads);
    $lastthreads = $tmpl->fetch("$THEME/forums/lastthreads.tpl");

    return $lastthreads;
}


// ========================================================
// <<-- MODERATOREN EINES FORUM AUSLESEN -->>
// ========================================================
function get_mods($fid)
{
    if ($fid)
	{
        $sql = $GLOBALS['db']->Query("SELECT user_id FROM " . PREFIX . "_f_mods WHERE forum_id = '$fid'");
        while ($row = $sql->fetchrow())
		{
         	$mods[] = "<a class=\"forum_links_small\" href=\"index.php?p=user&amp;id=$row->user_id\">" . fetchusername($row->user_id) . "</a>";
        } 
        return @implode(", ", $mods);
    } 
}


// ========================================================
// USER- PANEL
// gibt das betreffende user- panel im forum aus
// ========================================================
function printpanel()
{
    $tmpl = new Koobi("templates/");
    if (ISLOGGED == 1) {
        $tmpl->assign("login", 1);
        $tmpl->assign("name", $UNAME);
    } else {
        $tmpl->assign("login", 0);
        $tmpl->assign("gast", $GROUPSINGLE);
    } 
    if (permission('canpn')) {
        $tmpl->assign('pn', 1);
    } else {
        $tmpl->assign('pn', 0);
    } 
    if (permission('adminpanel')) {
        $tmpl->assign('adminlink', 1);
    } 

    $tmpl->assign('area', $area);
    $tmpl->assign('redir', redir());
    echo $tmpl->fetch("$THEME/user/user_panel_forum.tpl");
} 

// ===============================================================
// <<-- ANHANGGROESSE -->>
// ==============================================================
function get_attachment_size($param)
{
    if ($fsize = @filesize('uploads/attachment/' . $param['file'])) {
		$fsize = $fsize/1024;
        return file_size($fsize);
    } 
} 







?>