<?php 
// PHP4 MySQL Session Handler by Ying Zhang (ying@zippydesign.com)
$SESS_DBH = "";
function sess_open($save_path, $session_name)
{
    global $dbhost, $dbname, $dbuser, $dbpass, $SESS_DBCONN;
    if (!$SESS_DBCONN = @mysql_connect($dbhost, $dbuser, $dbpass)) {
        echo "<pre>Problems while connecting to the Database. Please try again later.</pre>";
        exit;
    } 
    return true;
} 

function sess_close()
{
    return true;
} 
function sess_read($key)
{
    global $SESS_DBCONN, $dbname, $SESS_LIFE;
    $SQL = "SELECT value FROM " . PREFIX . "_sessions WHERE sesskey = '$key'";
    $REF = @mysql_db_query($dbname, $SQL, $SESS_DBCONN);
    if (list($value) = @mysql_fetch_row($REF)) {
        return $value;
    } 
    return false;
} 

function sess_write($key, $val)
{
    global $dbhost, $dbname, $dbuser, $dbpass, $SESS_DBCONN, $UNAME;

    $expiry = time() + 3600;
    $value = addslashes($val);

    $qry = "INSERT INTO " . PREFIX . "_sessions VALUES ('$key', $expiry, '$value')";
    $qid = @mysql_query($qry, $SESS_DBCONN);

    if (! $qid) {
        $qry = "UPDATE " . PREFIX . "_sessions SET expiry = $expiry, value = '$value', uname='$UNAME' WHERE sesskey = '$key'";
        $qid = @mysql_query($qry, $SESS_DBCONN);
    } 

    return $qid;
} 

function sess_destroy($key)
{
    global $dbhost, $dbname, $dbuser, $dbpass, $SESS_DBCONN;
    $qry = "DELETE FROM " . PREFIX . "_sessions WHERE sesskey = '$key'";
    $qid = @mysql_query($qry, $SESS_DBCONN);
    return $qid;
} 

function sess_gc($maxlifetime)
{
    global $dbhost, $dbname, $dbuser, $dbpass, $SESS_DBCONN;
    $qry = "DELETE FROM " . PREFIX . "_sessions WHERE expiry < " . time();
    $qid = @mysql_query($qry, $SESS_DBCONN);
    return mysql_affected_rows($SESS_DBCONN);
} 

session_set_save_handler(
    "sess_open",
    "sess_close",
    "sess_read",
    "sess_write",
    "sess_destroy",
    "sess_gc");
// ===============================================================
// <<-- CHECKACTIVE
// ueberprueft, ob ein bereich aktiv oder inaktiv ist -->>
// ==============================================================
function checkactive($param)
{
    global $lang, $THEME, $area;
    $sql = new dbc("SELECT active FROM " . PREFIX . "_active WHERE val = '$param'");
    $row = $sql->fetchrow();
    if ($row->active != 1) {
        if (UGROUP == 1) {
            $tmpl = new Koobi("templates/$THEME/other/");
            $tmpl->assign('lang', $lang);
            echo $tmpl->fetch('notactive_adminmessage.tpl');
            return true;
        } else {
            return false;
        } 
    } else {
        return true;
    } 
} 
// ================================================================
// <<-- SPEEDBAR
// erzeugt eine einfache navigation -->>
// ================================================================
function speedbar($sectionid)
{
    global $THEME;
    $db = &new dbc("SELECT slink,linkname,target FROM " . PREFIX . "_speedbar WHERE section='$sectionid' AND aktiv='Y' order by posi asc");

    $speedbar_array = array();
    while ($row = $db->fetchrow()) {
        array_push($speedbar_array, array('speedbtitle' => stripslashes($row->linkname),
                'speedblink' => $row->slink,
                'target' => $row->target,
                'theme' => $THEME
                )
            );
    } 
    $speedbar = new Koobi("templates/$THEME/");
    $speedbar->assign('speedbar_array', $speedbar_array);
    $speedbar = $speedbar->fetch("navi/speed_bar.tpl");

    return $speedbar;
} 
// ================================================================
// <<-- FETCHMAINTEMPLATE
// liest das standard- template fuer den body aus -->>
// ================================================================
function fetchmaintemplate($id)
{
    global $area;
    $sql = new dbc("SELECT tpl FROM " . PREFIX . "_container WHERE typ='out' AND id='$id' and area='$area' ");
    $rowtpl = $sql->fetchrow();
    $thetpl = $rowtpl->tpl;
    if (!$thetpl) $thetpl = "main";
    $thetpl = "page/" . $thetpl . ".tpl";
    return $thetpl;
} 
// dropdownmenue fuer seitenwahl
function ppsite()
{
    $pps_array = array();
    for($a = 10; $a <= 50; $a += 10) {
        unset($pps_sel);
        if ($_REQUEST['pp'] == $a) {
            $pps_sel = "selected";
        } 
        array_push($pps_array, array('ps' => $a,
                'pps_sel' => $pps_sel
                )
            );
    } 
    return $pps_array;
} 
// ueberprueft, ob ein seitenlimit uebergeben wurde
function limit()
{
    $limit = ($_REQUEST['pp'] != '') ? $_REQUEST['pp'] : 10 ;
    return $limit;
} 
// aktualisiert den druckstatus einer news
function printupdate()
{
    if (($_REQUEST['p'] == "news") && ($_REQUEST['print'] == 1)) {
        $sql = &new dbc("UPDATE " . PREFIX . "_news SET printed=printed+1 WHERE newsid='" . $_REQUEST['newsid'] . "'");
        $sql->close();
    } 
} 
// ================================================================
// <<-- AUTOWORDS
// ersetzt woerter eines textes mit den eigetragenen woertern
// der enzyklopaedie und setzt ein link zur beschreibung -->>
// ================================================================
function autowords($text)
{
    global $THEME;
    $sql = new dbc("SELECT id,words FROM " . PREFIX . "_autowords where active='1'");
    $words = array();

    while ($arr = $sql->fetcharray()) {
        array_push($words, array($autowords = $arr['words'])
            );
        $s = explode("||", $autowords);

        while (list($key, $val) = each($s)) {
            $val = " " . $val . " ";
            $treffer = '([^\<\>]*)(' . $val . ')([^\<\>]*)';
            $ersatz = '\\1<a href="javascript:popup(\'index.php?p=misc&amp;do=autowords&amp;id=' . $arr['id'] . '\',\'name\',\'500\',\'400\',\'yes\');" class="autowords">\\2<img src="templates/' . $THEME . '/img/page/autoextern.gif" border="0" alt="" hspace="2" /></a>\\3 ';
            $text = @eregi_replace($treffer, $ersatz , $text);
        } 
    } 
    return $text;
} 
// ================================================================
// <<-- CONTAINER
// weist dem jeweiligen bereich ein template zu,
// welches im Adminbereich festgelegt wird -->>
// ================================================================
function container($tpl)
{
    global $dbprefix, $area;
    $sql = &new dbc("SELECT tpl FROM " . $dbprefix . "_container WHERE name='$tpl' and area='$area'");
    $con = $sql->fetchrow();
    $sql->close();
    $con = $con->tpl;
    return $con;
} 
// ================================================================
// <<-- PARSETRUE
// fuellt das template, welches im adminbereich fuer den bereich
// zugeteilt wurde, mit den jeweiligen werten -->>
// ================================================================
function parsetrue($template, $title, $in)
{
    global $THEME, $lang;
    $tmpl = new Koobi("templates/$THEME/");
    $tmpl->assign('maxattachment', MAXATTACHMENT);
    $tmpl->assign('title', $title);
    $tmpl->assign('content', $in);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('lang', $lang);
    $theerg = $tmpl->fetch("$template.tpl");
    return $theerg;
} 
// ================================================================
// <<-- SIMPLETITLE
// erzeugt einen einfachen seitentitel -->>
// ================================================================
function simpletitle($location)
{
    global $lang, $area;
    $sql = new dbc("SELECT area_name FROM " . PREFIX . "_areas WHERE area_id='$area'");
    $row = $sql->fetchrow();
    $sql->close();
    $ptitle = $lang['pagesep'] . $row->area_name . $lang['pagesep'] . $location;
    return $ptitle;
} 
// ================================================================
// <<-- PERMISSION
// uebergibt true oder false fuer berechtigungen bzw. true,
// wenn user admin ist -->>
// ================================================================
function permission($action)
{
    global $HTTP_SESSION_VARS, $PERMS;
    $area = ($_REQUEST['area'] != "") ? $_REQUEST['area'] : 1 ;
    if ($HTTP_SESSION_VARS[$action . $area] == 1) return true;
    if (($HTTP_SESSION_VARS['alles'] == 1) || (UGROUP == 1)) return true;
    return false;
} 
// ================================================================
// <<-- ISREADED
// setzt einen status fuer eine persoenliche nachricht -->>
// ================================================================
function isreaded($pn)
{
    global $row, $THEME;
    if ($row->is_readed == "yes") {
        $im = "readed";
    } else {
        $im = "unreaded";
    } 
    if ($row->reply == "yes") {
        $im = "reply";
    } 
    if ($row->forward == "yes") {
        $im = "forward";
    } 
    $icon = '<img aling="" hspace="1" src="templates/' . $THEME . '/img/pn/' . $im . '.gif" border="0">';
    return $icon;
} 
// ================================================================
// <<-- Ein und Ausgabe-Filter -->>
// ================================================================
function oform($text)
{
    $text = stripslashes($text);
    $text = kspecialchars($text);
    $text = wordwrap($text, "100", "\n", 1);
    return $text;
} 

function iform($text, $chars, $allowed)
{
    global $pref;
    $text = addslashes($text);
    $text = strip_tags($text, "" . $allowed . "");
    $text = substr($text, 0, $chars);
    return $text;
} 
// ================================================================----
// <<-- MySQL-ESCAPE-String -->>
// ================================================================
function escs($text)
{
    return mysql_escape_string($text);
} 
// ================================================================
// <<-- MSG
// gibt eine nachricht fuer eine aktion mit
// weiterleitung aus -->>
// ================================================================
function msg($title, $msg, $url, $meta, $opt = "0", $time = "0")
{
    global $lang, $THEME;
    $sname = $title;
    $mesg = new Koobi("templates/$THEME/");
    $mesg->assign('msgtitle', $lang["" . $title . ""]);

    $mmsg = ($opt == 1) ? $msg : $lang[$msg];
    $mesg->assign('msg', $mmsg);

    $ttime = ($time != 0) ? $time : 3;
    $mesg->assign('timerefresh', $ttime);

    $mesg->assign('url', $url);
    $mesg->assign('meta', $meta);
    $mesg = $mesg->fetch("other/msg.tpl");
    return $mesg;
} 
// ================================================================
// <<-- REDIR
// leitet den besucher nach einer aktion weiter -->>
// ================================================================
function redir()
{
    global $HTTP_GET_VARS, $HTTP_SERVER_VARS, $HTTP_HOST, $htt;
    $uri = $_SERVER['PHP_SELF'];
    if (!empty($HTTP_GET_VARS)) {
        $parmams = array();
        foreach($HTTP_GET_VARS as $paname => $value) {
            $params[] = @urlencode($paname) . '=' . @urlencode($value);
        } 
        $uri .= '?' . implode('&amp;', $params);
    } 
    $htt = "http://";
    return($htt . $_SERVER['HTTP_HOST'] . $uri);
} 
// ================================================================
// <<-- MAKEPASS
// generiert ein 6- stelliges passwort -->>
// ================================================================
function makepass()
{
    $pass = "";
    $chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
        "a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J",
        "k", "K", "l", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T",
        "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z");

    $count = count($chars) - 1;
    srand((double)microtime() * 1000000);
    for($i = 0; $i < 6; $i++) {
        $pass .= $chars[rand(0, $count)];
    } 
    return($pass);
} 
// ================================================================
// <<-- SECURECODE
// generiert einen sicherjeits- code fuer die registration -->>
// ================================================================
function securecode()
{
    $code = "";
    $chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");

    $count = count($chars) - 1;
    srand((double)microtime() * 1000000);
    for($i = 0; $i < 7; $i++) {
        $code .= $chars[rand(0, $count)];
    } 
    return($code);
} 
// ================================================================
// <<-- EMSG
// gibt einen fehlermeldung aus -->>
// ================================================================
function emsg($text)
{
    global $lang;
    $error .= "<li><span class=\"errorfont\">" . $lang[$text] . "</span></li>";
    return $error;
} 
// ================================================================
// <<-- DOWNLOADFILE
// downloadfunktion für pn und klp- dateien -->>
// ================================================================
function downloadfile($datstring, $datname, $dattype, $extra = "0")
{
    $filetype = 'application/octet-stream';
    header('Content-Type: ' . $dattype);
    header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Content-Disposition: attachment; filename="' . $datname . '"');
    if ($extra != 1) header('Content-Length: ' . strlen($datstring));
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    echo $datstring;
    exit();
} 
// ================================================================
// <<-- BANNED
// ueberprueft, ob name oder email gesperrt wurden -->>
// ================================================================
function bannedname($name_tobann)
{
    global $pref, $lang;
    $sql = new dbc("SELECT bannednames FROM " . PREFIX . "_settings");
    $row = $sql->fetchrow();

    $BANNED = "";
    $bnames = str_replace(array("\r\n", "\n"), "", $row->bannednames);
    $bnames = trim($bnames);

    $names = explode(",", $bnames);

    foreach ($names as $name) {
        if ($name == $name_tobann) {
            setcookie("kuid", "0" , time()-10000);
            setcookie("kpass", "0" , time()-10000);
            $BANNED = 1;
        } 
    } 
    return $BANNED;
} 

function bannedemail($email_tobann)
{
    global $pref, $lang;
    $sql = new dbc("SELECT bannedemails FROM " . PREFIX . "_settings");
    $row = $sql->fetchrow();

    $range = explode("@", $email_tobann);
    $isin = "*@" . $range[1];
    $BANNED = "";

    $emails = str_replace(array("\r\n", "\n"), "", $row->bannedemails);
    $emails = trim($emails);

    $emails = explode(",", $emails);

    foreach ($emails as $email) {
        if ($email == $email_tobann || $email == $isin) {
            setcookie("kuid", "0" , time()-10000);
            setcookie("kpass", "0" , time()-10000);
            $BANNED = 1;
        } 
    } 
    return $BANNED;
} 
// ================================================================
// <<-- BADWORDREPLACE
// ersetzt zu zensierende woerter durch den platzhalter -->>
// ================================================================
function badwordreplace($param)
{
    $sql = new dbc("SELECT badwords,badwords_replace FROM " . PREFIX . "_settings");
    $row = $sql->fetchrow();

    $baw = $row->badwords;
    $baw = str_replace(array("\r\n", "\n"), "", $baw);
    $baw = trim($baw);

    $bwrp = $row->badwords_replace;
    if (!$row->badwords_replace) $bwrp = "!#*$&?";

    $bwarray = explode(",", $baw);
    if ($baw) {
        while (list($key, $val) = each($bwarray)) {
            $param = @eregi_replace("$val", $bwrp, $param);
        } 
    } 
    return $param;
} 
// ================================================================
// <<-- FETCH__
// ermittelt benutzer- werte anhand der id oder des namens -->>
// ================================================================
function fetchgroupname($id)
{
    $db = &new dbc("SELECT groupname FROM " . PREFIX . "_usergroup WHERE ugroup='" . $id . "'");
    $row = $db->fetchrow();
    $group = stripslashes(kspecialchars($row->groupname));
    $db->close();
    return $group;
} 

function fetchusername($param)
{
    $where = (@is_array($param)) ? $param[userid] : $param;
    $sql = new dbc("SELECT uname FROM " . PREFIX . "_user WHERE uid='$where'");
    $row_thusername = $sql->fetchrow();
    return stripslashes(kspecialchars($row_thusername->uname));
} 

function fetchuserid($name)
{
    $sql = new dbc("SELECT uid FROM " . PREFIX . "_user WHERE uname='" . $name . "'");
    $row = $sql->fetchrow();
    $uid = $row->uid;
    $sql->close();
    return $uid;
} 
// ================================================================
// <<-- getNavigation
// erstellt rekursiv einen forum- navigations-
// bereich, indem sich der user befindet.
//  @param id $ des bereichs in dem sich der benutzer befindet
//  @param type $ typ des bereichs {kategorie, forum, ... -->> 
// ================================================================
function getNavigation($id, $type, $result = null){
    global $lang,$area;

    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 = &new dbc($q_navi);
    $navi = $r_navi->fetchRow(); 
    // rekursion abgeschlossen
    if ($navi->pid == 0) {
        return "<a class='forum_links_navi' href='index.php?p=showforums&amp;area=$area'>Forum</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 = &new dbc($q_parent);
    $parent = $r_parent->fetchRow();

    if ($type == "topic") $result = $lang['f_navi_separator'] . "<a class='forum_links_navi' href='index.php?p=showtopic&amp;tid=" . $parent->id . "&amp;area=$area'>" . $parent->title . "</a>" . $result;
    else if ($type == "forum") $result = $lang['f_navi_separator'] . "<a class='forum_links_navi' href='index.php?p=showforum&amp;fid=" . $parent->id . "&amp;area=$area'>" . $parent->title . "</a>" . $result;
    else if ($type == "category") $result = $lang['f_navi_separator'] . "<a class='forum_links_navi' href='index.php?p=showforums&amp;cid=" . $parent->id . "&amp;area=$area'>" . $parent->title . "</a>" . $result;

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

function getDocument()
{
    $document = split("/", $_SERVER['PHP_SELF']);
    return $document[count($document)-1] . "?" . $_SERVER['QUERY_STRING'];
} 
// ================================================================
// <<-- getNavigationPath
// erzeugt einen pfad zur aktuellen position
// ausgangspunkt --> ... --> aktuelle position -->>
// ================================================================
function getNavigationPath($id, $table, $link, $key, $idtype, $nametype, $result = null, $extra = 0)
{
    global $lang, $area; 
    // daten des aktuellen bereichs
    $q_item = "SELECT $idtype, $nametype, parent_id FROM " . PREFIX . "_$table WHERE $idtype = $id";
    $r_item = new dbc($q_item);
    $item = $r_item->fetchrow(); 
    // rekursion abgeschlossen
    if ($item->parent_id == 0) {
        return "<a title='" . $item->$nametype . "' class='boxnavi' href='index.php?p={$link}&amp;{$key}={$item->$idtype}&amp;area={$area}$bextra'>" . $item->$nametype . "</a>" . $result;
    } 
    // daten des darueberliegenden bereiches
    if ($extra == 1) {
        $sqlextra = ", parent_id";
    } 
    $q_parent = "SELECT $idtype, $nametype  $sqlextra FROM " . PREFIX . "_$table WHERE $idtype = " . $item->parent_id;
    $r_parent = new dbc($q_parent);
    $parent = $r_parent->fetchRow();

    if ($extra == 1) {
        $bextra = "&amp;parent=$parent->catid";
    } 
    $result = $lang['f_navi_separator'] . "<a title='" . $item->$nametype . "' class='boxnavi' href='index.php?p={$link}&amp;{$key}=" . $item->$idtype . "&amp;area={$area}$bextra'>" . $item->$nametype . "</a>" . $result;

    return getNavigationPath($item->parent_id, $table, $link, $key, $idtype, $nametype, $result, $extra);
} 
// ================================================================
// <<-- getNavigationptitle
// erzeugt einen seitentitel zur aktuellen position -->>
// ================================================================
function getNavigationptitle($id, $table, $link, $key, $idtype, $nametype, $result = null)
{
    global $lang;

    $q_item = "SELECT $idtype, $nametype, parent_id FROM " . PREFIX . "_$table WHERE $idtype = $id";
    $r_item = new dbc($q_item);
    $item = $r_item->fetchrow();

    if ($item->parent_id == 0) return $item->$nametype . $result;

    $q_parent = "SELECT $idtype, $nametype FROM " . PREFIX . "_$table WHERE $idtype = " . $item->parent_id;
    $r_parent = new dbc($q_parent);
    $parent = $r_parent->fetchRow();

    $result = $lang['f_navi_separator'] . $item->$nametype . $result;

    return getNavigationptitle($item->parent_id, $table, $link, $key, $idtype, $nametype, $result);
} 
// ================================================================
// <<-- getStaticNavigation
// erzeugt das navigationsmenue fuer die seite -->>
// ================================================================
function getStaticNavigation($document, $area_id, $group_id = -1)
{
    if ($document != -1) {
        $r_navi = new dbc("
			SELECT 
			id,
			parent_id,
			document,
			target
			FROM 
			" . PREFIX . "_navi 
			WHERE 
			document = '$document' AND 
			area = $area_id
			");

        $navi = $r_navi->fetchrow();

        if ($navi->parent_id != "") {
            $r_parent1 = new dbc("
				SELECT 
				id,
				parent_id,
				document,
				target
				FROM 
				" . PREFIX . "_navi 
				WHERE 
				id = " . $navi->parent_id);

            $parent1 = $r_parent1->fetchrow();
        } 
        // wenn parent_id nicht 0 ist, dann existiert noch eine
        // ebene darüber
        if ($parent1->parent_id != 0) {
            $r_parent2 = new dbc("
				SELECT
				id,
				parent_id,
				document,
				target
				FROM 
				" . PREFIX . "_navi 
				WHERE 
				id = " . $parent1->parent_id . " AND 
				area = $area_id
				");

            $parent2 = $r_parent2->fetchrow();
        } 
    } 

    $r_navi = new dbc("
		SELECT 
		id, 
		title, 
		document, 
		area, 
		openonclick, 
		group_id,
		posi,
		target
		FROM 
		" . PREFIX . "_navi 
		WHERE 
		parent_id = 0 AND 
		area = $area_id
		ORDER BY
		posi
		");

    $output = array(); 
    // erste ebene der navigation
    while ($navi = $r_navi->fetchrow()) {
        $navi->group_array = ($navi->group_id != "") ? explode(",", $navi->group_id) : $navi->group_id; 
        // array der parameter in der url holen
        $navi_params = explode("&", trim(str_replace("index.php?", "", $navi->document)));
        $request_params = explode("&", $_SERVER['QUERY_STRING']); 
        // uebereinstimmungen der arrays berechnen
        $intersect = array_intersect($navi_params, $request_params);

        foreach ($intersect as $inter) {
            $pair = explode("=", $inter); 
            // wenn der parameter p in den uebereinstimmungen (page=agb)
            // dabei ist, markiere den navigationspunkt
			
			// static-navi fix
			$static_nav = explode('page=', $navi->document);
			$static_req = explode('page=', $_SERVER['QUERY_STRING']);
			
			
			if($static_nav[1]!=""){
				$navi->active = false;
			} else {
            if ($pair[0] == "p") {
                $navi->active = true;
            } 
		  }
        } 
        // die navi nur dann anzeigen, wenn die gruppe die berechtigung hat
        if (in_array($group_id, $navi->group_array) || $group_id == -1) {
            // der navigationspunkt wird expandiert angezeigt falls ...
            if (!$navi->openonclick || $navi->document == $document || $parent1->document == $navi->document || $parent2->document == $navi->document || $document == -1) {
                // um den pfad später verfolgen zu können
                // wird ein flag gesetzt
                if ($parent1->document == $navi->document || $parent2->document == $navi->document) {
                    $navi->active = true;
                } 
                $r_sub_navi = new dbc("SELECT id, title, document, area, openonclick, group_id, posi,target  FROM " . PREFIX . "_navi WHERE parent_id = " . $navi->id . " AND area = $area_id ORDER BY posi");
                $navi->sub_navi = array(); 
                // zweite ebene der navigation
                while ($sub_navi = $r_sub_navi->fetchrow()) {
                    $sub_navi->group_array = ($sub_navi->group_id != "") ? explode(",", $sub_navi->group_id) : $sub_navi->group_id;
                    if (in_array($group_id, $sub_navi->group_array) || $group_id == -1) {
                        // ...
                        if (!$sub_navi->openonclick || $sub_navi->document == $document || $parent1->document == $sub_navi->document || $parent2->document == $sub_navi->document || $document == -1) {
                            if ($parent1->document == $sub_navi->document || $parent2->document == $sub_navi->document) {
                                $sub_navi->active = true;
                            } 
                            $r_last_navi = new dbc("SELECT id, title, document, area, openonclick, group_id, posi,target FROM " . PREFIX . "_navi WHERE parent_id = " . $sub_navi->id . " AND area = $area_id ORDER BY posi");
                            $sub_navi->sub_navi = array(); 
                            // letzte ebene der navigation
                            while ($last_navi = $r_last_navi->fetchrow()) {
                                $last_navi->group_array = ($last_navi->group_id != "") ? explode(",", $last_navi->group_id) : $last_navi->group_id;
                                if (in_array($group_id, $last_navi->group_array) || $group_id == -1) {
                                    array_push($sub_navi->sub_navi, $last_navi);
                                } 
                            } 
                        } 
                        array_push($navi->sub_navi, $sub_navi);
                    } 
                } 
            } 
            array_push($output, $navi);
        } 
    } 

    return $output;
} 
// ================================================================
// <<-- topicExists
// eueberprueft, ob thema existiert -->>
// ================================================================
function topicExists($t_id)
{
    $query = "SELECT id FROM " . PREFIX . "_f_topic WHERE id = $t_id";
    $result = new dbc($query);
    if ($result->numrows() > 0) return 1;
    return 0;
} 
// ================================================================
// <<-- getForums
// listet alle foren auf -->>
// ================================================================
function getForums($id, &$forums, $prefix, $f_id = "0")
{ 
    // kategorien holen
    $q_cat = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = $id";
    $r_cat = new dbc($q_cat); 
    // berechtigung holen
    $group_ids_misc = array(); 
    // =====================================================================================
    // miscrechte
    // =====================================================================================
    if (@is_numeric(UID)) {
        $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = " . UID;
        $result = new dbc($queryfirst);
        $user = $result->fetchrow(); 
        // wenn misc nicht leer ist...
        if ($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"; 
        // c.title
        // c.id = '" . $cat->id . "' AND
        $result = new dbc($q_forum); 
        // alle foren durchgehen
        while ($forum = $result->fetchrow()) {
            // forumname
            $sql_ftitle = new dbc("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 = new dbc($q_sub_cat);

                $forums[] = $forum;

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

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

    $r_cat = new dbc($q_cat); 
    // berechtigung holen
    $group_ids_misc = array(); 
    // =====================================================================================
    // miscrechte
    // =====================================================================================
    if (@is_numeric(UID)) {
        $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = " . UID;
        $result = new dbc($queryfirst);
        $user = $result->fetchrow(); 
        // wenn misc nicht leer ist...
        if ($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 = new dbc($q_forum); 
            // alle foren durchgehen
            while ($forum = $result->fetchrow()) {
                // forumname
                $sql_ftitle = new dbc("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 = new dbc($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			
    } 
} 

function getNavigationByGroup($navi, $group)
{
    foreach ($navi as $item) {
        if (!in_array($group, $item->group_array)) {
            $gotcha = array_search($item, $navi);
            unset($navi[$gotcha]);
        } else {
        } 
    } 

    return $navi;
} 
// ================================================================
// <<-- getForums
// setzt den status des forums auf $status
// auch die subforen werden beachtet -->>
// ================================================================
function switchForumStatus($id, $status)
{
    $q_close = "UPDATE " . PREFIX . "_f_forum SET status = $status WHERE id = $id";
    $r_close = new dbc($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 = new dbc($q_child);

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

    while ($child = $r_child->fetchrow()) {
        switchForumStatus($child->id, $status);
    } 
    return;
} 
// ================================================================
// <<-- createFilename
// erzeugt einen dateinamen fuer attachments -->>
// ================================================================
function createFilename($dir)
{
    $fn = time() . mt_rand(0, 1000000000);
    if (file_exists($dir . $fn)) {
        return createFilename($dir);
    } else {
        return $fn;
    } 
} 
// ================================================================
// <<-- setForumIcon
// setzt das zutreffende icon fuer die foren -->>
// ================================================================
function setForumIcon(&$forum)
{
    $visited_ids = @explode("@", $_COOKIE['koobi4_f_visited']); 
    // alle posting ids zum forum holen
    $q_topic = "
		SELECT
		id
		FROM
		" . PREFIX . "_f_topic AS t
		WHERE
		forum_id = " . $forum['id'];

    $r_topic = new dbc($q_topic);

    $all_ids = array();
    $all_dates = array();

    while ($topic = $r_topic->fetchrow()) {
        $q_post = "
			SELECT
			id,
			UNIX_TIMESTAMP(datum) AS datum
			FROM
			" . PREFIX . "_f_post
			WHERE
			topic_id = " . $topic->id . "
			ORDER BY
			id DESC
			";

        $r_post = new dbc($q_post);
        $post = $r_post->fetchrow();

        if ($post) {
            $all_ids[] = $post->id;
            $all_dates[] = $post->datum;
        } 
    } 

    $icon = "forum";

    $icon .= (count(array_diff($all_ids, $visited_ids)) > 0) ? "_new" : "_old";
    $icon .= ($forum['status'] == FORUM_STATUS_CLOSED) ? "_lock" : "";
    $icon .= ".gif";

    $forum['statusicon'] = getIcon($icon, "forum");
    /*
		foreach ($all_dates as $date) {
			if ($date > $visited_ids[0]) {
				$forum['statusicon'] = getIcon("forum_new.gif", "forum");
				return;
			}
		}
		*/
} 
// ================================================================
// <<-- setTopicIcon
// setzt das zutreffende icon fuer jedes thema -->>
// ================================================================
function setTopicIcon(&$topic, $forum)
{
    global $UID; 
    // cookie auslesen
    $all_ids = @explode('@', $_COOKIE['koobi4_f_visited']);

    $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 = new dbc($q_post);
    $post = $r_post->fetchrow(); 
    // ==================================================
    // alle uid's zum topic holen
    $q_uid = "SELECT uid FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic['id'];
    $r_uid = new dbc($q_uid);
    $uids = array();

    while ($uid = $r_uid->fetchrow()) {
        $uids[] = $uid->uid;
    } 
    // ==================================================
    // ==================================================
    // 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 .= ".gif";

    switch ($topic['type']) {
        case TOPIC_TYPE_ANNOUNCE:
            if ($new) {
                $topic['statusicon'] = getIcon("announcement_new.gif", "announcement");
            } else {
                $topic['statusicon'] = getIcon("announcement_old.gif", "announcement");
            } 
            break;
        case TOPIC_TYPE_STICKY:
        default:
            $topic['statusicon'] = getIcon($file, $file);
    } 
} 
// ================================================================
// <<-- setTopicIconObj
// setzt das zutreffende icon fuer jeden beitrag -->>
// ================================================================
function setTopicIconObj(&$topic, $forum)
{
    global $UID; 
    // cookie auslesen
    $all_ids = @explode('@', $_COOKIE['koobi4_f_visited']);

    $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 = new dbc($q_post);
    $post = $r_post->fetchrow(); 
    // ==================================================
    // alle uid's zum topic holen
    $q_uid = "SELECT uid FROM " . PREFIX . "_f_post WHERE topic_id = " . $topic->id;
    $r_uid = new dbc($q_uid);
    $uids = array();

    while ($uid = $r_uid->fetchrow()) {
        $uids[] = $uid->uid;
    } 
    // ==================================================
    // ==================================================
    // 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 .= ".gif";

    switch ($topic->type) {
        case TOPIC_TYPE_ANNOUNCE:
            if ($new) {
                $topic->statusicon = getIcon("announcement_new.gif", "announcement");
            } else {
                $topic->statusicon = getIcon("announcement_old.gif", "announcement");
            } 
            break;
        case TOPIC_TYPE_STICKY:
        default:
            $topic->statusicon = getIcon($file, $file);
    } 
} 
// ==============================================
// <<-- Galeriefunktionen -->>
// ==============================================
function getGallery($id, $prefix, &$gallery, &$area, $active, $orderby, $ascdesc, $sorting = "0")
{
    global $TFORMAT, $THEME, $lang, $_COOKIE;

    switch ($_REQUEST['orderby']) {
        case "date" : $orderby = "ctime";
            break;
        case "author" : $orderby = "uid";
            break;
        case "title" : $orderby = "title";
            break;
        default : $orderby = "posi";
            break;
    } 

    switch ($_REQUEST['ascdesc']) {
        case "asc": $ascdesc = "ASC";
            break;
        case "desc": $ascdesc = "DESC";
            break;
        default : $ascdesc = "DESC";
            break;
    } 
    // auswahl nach alpha
    if ($sorting == 1) {
        switch ($_REQUEST['charakter']) {
            case "1" :
                for($i = 1;$i < 10;$i++) {
                    $loop .= " OR title  LIKE '" . $i . "%'";
                } 
                $c_sort = " AND(title like '0%' $loop)";
                break;

            case "" :
            case "all" :
                $c_sort = "";
                break;

            default :
                $c_sort = " AND(title LIKE '" . $_REQUEST['charakter'] . "%')";
                break;
        } 

        $limit = limit();
        if ($active == 1) $zusatz = " AND active=1";

        $query = new dbc("
			SELECT id
			FROM " . PREFIX . "_gallery WHERE parent_id = $id AND area = $area $c_sort 
			");

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

        $query = new dbc("
			SELECT *
			FROM " . PREFIX . "_gallery WHERE parent_id = $id AND area = $area $c_sort $zusatz 
			ORDER BY $orderby $ascdesc limit $a,$limit
			");

        if ($num > $limit) {
            define("GALNAVI" , pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?do=sort&amp;p=gallery&amp;area=$_REQUEST[area]&amp;charakter=$_REQUEST[charakter]&amp;orderby=$_REQUEST[orderby]&amp;ascdesc=$_REQUEST[ascdesc]&amp;page={s}\">{t}</a> "));
        } else {
            define("GALNAVI" , "");
        } 
        // wenn admin
    } else {
        $query = new dbc("
			SELECT *
			FROM " . PREFIX . "_gallery WHERE parent_id = $id AND area = $area  $zusatz 
			ORDER BY $orderby $ascdesc");
    } 
    if (!$query->numrows()) return;
    $posi = "";

    while ($item = $query->fetchrow()) {
        $posi = strpos($_COOKIE["galshow"], "gtoggle_" . $item->id . "");
        if ((!is_numeric($posi))) {
            $disp_gal = "";
            $plusminus = "minus.gif";
        } else {
            $plusminus = "plus.gif";
            $disp_gal = "none";
        } 

        $toggleimage_gal = "<img class=\"absmiddle\" border=\"0\" id=\"gimg_toggle_" . $item->id . "\" 
			src=\"templates/" . $THEME . "/img/page/" . $plusminus . "\" 
			onmouseover=\"this.style.cursor = 'pointer'\" 
			onclick=\"MWJ_changeDisplay('gtoggle_" . $item->id . "', MWJ_getStyle( 'gtoggle_" . $item->id . "', 'display' ) ? '' : 'none'); 
			koobi4_toggleImage('gimg_toggle_" . $item->id . "', this.src); 
			koobi4_setCookie('galshow', 'gtoggle_" . $item->id . "');\" alt=\"" . $lang['shortinfo'] . "\" />"; 
        // todo next: default- image
        $sql = new dbc("SELECT id,path FROM " . PREFIX . "_gallery_items WHERE  gal_id='" . $item->id . "' limit 1");
        $row_g = $sql->fetchrow();

        if (is_file("uploads/galerie/" . $row_g->path)) {
            $item->galthumb = $row_g->id;
        } else {
            $item->galthumb = 987654321;
        } 

        $item->ulink = "index.php?area=" . $area . "&amp;p=user&amp;id=" . $item->uid . "";
        $item->glink = "index.php?area=$area&amp;p=gallery&amp;action=showimages&amp;galid=" . $item->id . "";
        $item->visible_title = $prefix . " " . $item->title;
        $item->created = mygmt($item->ctime);
        $item->user = fetchusername($item->uid);
        $item->toggleimage = $toggleimage_gal;
        $item->toggleimage_td = $toggleimage_td;
        $item->dispgal = $disp_gal;

        $sql = new dbc("SELECT distinct id FROM " . PREFIX . "_gallery_items WHERE gal_id=$item->id ");
        $item->pics = $sql->numrows();

        array_push($gallery, $item);
        getGallery($item->id, $prefix . "- - ", $gallery, $area, $active, $orderby, $ascdesc, $sorting);
    } 

    return;
} 
// ==============================================
// <<-- Galeriedropdown -->>
// ==============================================
function galdropdown($kat_id, $i, $url)
{
    global $parent_id, $area;

    $sql = new dbc("SELECT * FROM " . PREFIX . "_gallery WHERE parent_id='$kat_id' AND area='$area' order by title asc");
    while ($row = $sql->fetcharray()) {
        $gdrop .= '<option  value="' . $row['id'] . '" ';
        if ($row['active'] == 1) {
            $gdrop .= 'class="active" ' ;
        } else {
            $gdrop .= 'class="notactive" ' ;
        } 

        if ($row['parent_id'] == 0) {
            $gdrop .= ' style="font-weight:bold;" ';
        } ;
        if ($row['id'] != $_REQUEST['id'] && $row['parent_id'] != $_REQUEST['id']) {
            if ($_GET['galid'] == $row['id']) {
                $gdrop .= "selected";
            } ;
            $gdrop .= '>';
        } 
        for($r = 1;$r < $i;$r++) {
            $gdrop .= '--';
        } 
        unset($all);
        $sqls = new dbc("SELECT DISTINCT id FROM " . PREFIX . "_gallery_items WHERE gal_id='" . $row["id"] . "'");
        $all = $sqls->numrows();

        $gdrop .= ' ' . stripslashes($row["title"]) . ' [' . $all . ']' . '</option>';
        $gdrop .= galdropdown($row["id"], $i + 1, $url);
    } 
    return $gdrop;
} 
// ==============================================
// <<-- Newskategorien holen... -->>
// ==============================================
function getNews($id, $prefix, &$news, &$area)
{
    $query = new dbc("SELECT 
		catid, parent_id,area,catname,catdesc,posi 
		FROM " . PREFIX . "_newscat WHERE 
		parent_id = $id and area = $area order by posi ASC");
    if (!$query->numrows()) {
        return;
    } while ($item = $query->fetchrow()) {
        $item->visible_title = $prefix . " " . $item->catname;

        $sql = new dbc("SELECT  newsid FROM " . PREFIX . "_news WHERE newscat=$item->catid ");
        $item->ncount = $sql->numrows();

        array_push($news, $item);
        getNews($item->catid, $prefix . " - ", $news, $area);
    } 
    return;
} 
// ==============================================
// <<-- News auslesen -->>
// ==============================================
function fetchNews($area, &$news)
{
    global $TFORMAT;

    $limit = (isset($_REQUEST['pp']) && $_REQUEST['pp'] != "") ? $_REQUEST["pp"] : 10;
    if (!isset($page)) $page = 1;

    if ($_REQUEST['categ'] != "all" && $_REQUEST['categ'] != "") {
        $catq = "  && (newscat='" . escs($_REQUEST['categ']) . "') ";
    } 

    $sql = new dbc("SELECT  uid,newsid, area_id, title, text, time_start FROM " . PREFIX . "_news WHERE ((area_id='$area' || allareas='yes') && ((time_end>=" . time() . ") || (time_end='1') || (time_end='0')) && (((ispublic='1')) && (time_start<=" . time() . ")$catq))  ORDER BY ntime DESC limit $limit");

    while ($item = $sql->fetchrow()) {
        $item->ntime = mygmt($item->time_start);
        $item->author = fetchusername($item->uid);
        $newss = array_push($news, $item);
    } 
    return;
} 
// ==============================================
// <<-- Erzeugt eine Form mit einem Hinweis,
// dass der User keine Berechtigung hat,
// sowie eine Loginform -->>
// ==============================================
function stderror($title, $msg, $url, $meta, $loginform)
{
    global $lang, $THEME, $area;
    $sname = $title;
    $mesg = new Koobi("templates/$THEME/");
    $mesg->assign('msgtitle', $lang[$title]);
    $mesg->assign('msg', $msg);
    $mesg->assign('url', $url);
    $mesg->assign('lang', $lang);
    $mesg->assign('meta', $meta);
    $mesg->assign('area', $area);
    $mesg->assign('redir', redir());
    if ($loginform == 1) $mesg->assign('loginform', 1);
    $mesg->assign('redir', redir());
    $mesg = $mesg->fetch("error/stderror.tpl");
    return $mesg;
} 
// ==============================================
// <<-- FAQ holen -->>
// ==============================================
function getFaq($id, $prefix, &$faq, &$area, $active, $orderby, $ascdesc, $i, $vor = '', $f, $curr_faq = 0)
{
    global $TFORMAT, $THEME, $lang;

    switch ($_REQUEST['orderby']) {
        case "date" : $orderby = "ctime";
            break;
        case "author" : $orderby = "uid";
            break;
        case "title" : $orderby = "title";
            break;
        default : $orderby = "posi";
            break;
    } 

    switch ($_REQUEST['ascdesc']) {
        case "asc": $ascdesc = "ASC";
            break;
        case "desc": $ascdesc = "DESC";
            break;
        default : $ascdesc = "ASC";
            break;
    } 

    if ($active == 1) $zusatz = " AND active=1";
    $query = new dbc("SELECT * FROM " . PREFIX . "_faq WHERE parent_id = $id AND area = $area $zusatz ORDER BY $orderby $ascdesc");

    $i++;
    $f++;
    $a = 0;

    $faq_erg = array();

    $r_faq = new dbc("SELECT id,parent_id, faq, answer,inline_screens FROM " . PREFIX . "_faq WHERE id = $id AND area = $area");
    $curr_faq = $r_faq->fetchrow();
    $curr_faq->visible_title = $curr_faq->faq;
    $curr_faq->text = inlinescreens($curr_faq->inline_screens, $curr_faq->answer);
    $curr_faq->main = $curr_faq->parent_id;

    if (!$query->numrows()) return;

    while ($item = $query->fetchrow()) {
        $a++;
        $firstid = $item->posi ;

        if ($item->parent_id == 0) {
            $item->visible_title = ($vor) . ($a) . $prefix . ". " . $item->faq;
        } else {
            $item->visible_title = ($vor) . ($a) . '.' . $prefix . " " . $item->faq;
        } 

        $item->created = mygmt($item->ctime);
        $item->user = fetchusername($item->uid);
        $item->hits = $item->hits;
        $item->posi = $item->posi;
        $item->fid = $item->id;
        $item->ulid = $f-1;
        $item->text = inlinescreens($item->inline_screens, $item->answer);
        $item->text = high($item->text);
        $item->faqonce = $item->faq;
        $item->main = $item->main;

        array_push($faq, $item);

        getFaq($item->id, $prefix . "  " , $faq, $area, $active, $orderby, $ascdesc, $i, $vor . $a . ".", $f);
    } 
    return;
} 
// ===========================================================
// <<-- Inline- Screens -->>
// ===========================================================
function inlinescreens($array, $text)
{
    global $tmpl;
    $screens = unserialize($array);
    if ($screens) {
        while (list($key, $val) = each($screens)) {
            $cont = $tmpl->fetch("gallery/inlineshot_page.tpl");
            $cont = str_replace("%%title%%", kspecialchars($val['titel']), $cont);
            $cont = str_replace("%%text%%", $val['text'], $cont);
            $cont = str_replace("%%id%%", $val[id], $cont);
            $text = str_replace("[SCREEN:$key]", $cont, $text);
        } 
    } 
    return $text;
} 
// ==============================================
// <<-- NEUE GALERIEN AUSWAHL-FELD -->>
// ==============================================
function newgals($param)
{
    global $THEME, $lang, $area, $global;
    $tmpl = new Koobi("templates/");
    $sql = new dbc("SELECT  descr,  ctime, id, title, area FROM " . PREFIX . "_gallery WHERE area ='$area' AND active = '1' order by ctime desc limit $param[show]");
    $items = array();
    while ($row = $sql->fetchrow()) {
        $sql_c = new dbc("SELECT gal_id FROM " . PREFIX . "_gallery_items WHERE gal_id='$row->id'");
        $sql_r = new dbc("SELECT   path,id FROM " . PREFIX . "_gallery_items WHERE gal_id='$row->id' order by rand()");
        $row_r = $sql_r->fetchrow();

        if (is_file("uploads/galerie_icons/" . $row->icon)) {
            $row->gicon = "uploads/galerie_icons/" . $row->icon;
        } else {
            if (is_file("uploads/galerie/" . $row_r->path)) {
                $row->gicon = "system/thumb.php?img_id=$row_r->id&amp;smode=1";
            } else {
                $row->gicon = "system/thumb.php?img_id=9876543&amp;smode=1";
            } 
        } 

        $gallink = "index.php?area=$area&amp;p=gallery&amp;action=showimages&amp;galid=" . $row->id . "";

        $row->desc = $row->descr;
        $row->glink = $gallink;
        $row->pics = $sql_c->numrows();
        $row->ctime = $row->ctime;
        array_push($items, $row);
    } 
    $tmpl->assign('row', $row);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('area', $area);
    $tmpl->assign('items', $items);

    if ($items) echo $tmpl->fetch("$THEME/gallery/newgals.tpl");
} 
// ==============================================
// <<-- NEWSLETTERFUNKTION -->>
// ==============================================
function printNewsletter($param)
{
    global $THEME, $lang, $area;
    $dbwhere = ($param['area'] != "") ? "WHERE area='$param[area]'" : "WHERE area='$area'";
    if (checkactive('newsletter')) {
        $tmpl = new Koobi("templates/");
        $sql = new dbc("SELECT * FROM " . PREFIX . "_newsletter $dbwhere order by posi ASC");
        $num = $sql->fetchrow;
        $items = array();
        while ($item = $sql->fetchrow()) {
            array_push($items, $item);
        } 
        $tmpl->assign('lang', $lang);
        $tmpl->assign('area', $area);
        $tmpl->assign('items', $items);
        echo $tmpl->fetch("$THEME/newsletter/box.tpl");
    } 
} 
// ==============================================
// <<-- AFFILIATE- FUNKTION -->>
// ==============================================
function getAffiliates($param)
{
    global $THEME, $lang, $area;
    $dbwhere = ($param['area'] != "") ? "WHERE area='$param[area]'" : "WHERE area='$area'";
    if (checkactive('affiliates')) {
        $tmpl = new Koobi("templates/");
        $sql = new dbc("SELECT url,hits,name,image,id FROM " . PREFIX . "_affiliates $dbwhere order by posi ASC");
        $num = $sql->fetchrow;
        $items = array();
        while ($item = $sql->fetchrow()) {
            array_push($items, $item);
        } 
        $tmpl->assign('lang', $lang);
        $tmpl->assign('area', $area);
        $tmpl->assign('items', $items);
        echo $tmpl->fetch("$THEME/affiliates/box.tpl");
    } 
} 
// ==============================================
// <<-- POLLFUNKTION -->>
// ==============================================
function printPoll($param)
{
    global $THEME, $lang, $area;
    if (checkactive('poll')) {
        $tmpl = new Koobi("templates/");
        $r_poll = new dbc("SELECT id, title,start,end FROM " . PREFIX . "_poll WHERE place_id = " . $param["id"] . " AND area_id='$area' AND active = 1");
        $poll = $r_poll->fetchrow();
        if ($poll->start > time()) {
            $poll = "";
        } 

        if ($poll) {
            $r_items = new dbc("SELECT id,title,color,posi FROM " . PREFIX . "_poll_item WHERE poll_id = '" . $poll->id . "' ORDER BY posi ASC");
            $items = array();

            while ($item = $r_items->fetchrow()) {
                @array_push($items, $item);
            } 

            $tmpl->assign('theme', $THEME);
            $tmpl->assign('lang', $lang);
            $tmpl->assign('poll', $poll);
            $tmpl->assign('area', $area);
            $tmpl->assign('items', $items);
            $tmpl->assign('action', "index.php?p=poll&amp;area=$area");

            $r_ip = new dbc("SELECT ip,uid,group_id FROM " . PREFIX . "_poll WHERE id = $poll->id");
            $ip = $r_ip->fetchrow();
            $ip_a = ($ip->ip == "") ? $ip->ip : explode(";", $ip->ip); 
            // <<-- Besitzt diese Gruppe die Rechte zum abstimmen? -->>
            $group_id = ($ip->group_id == "") ? $ip->group_id : explode(",", $ip->group_id);
            if (!@in_array(UGROUP, $group_id)) {
                $tmpl->assign('pollnoperms', 1);
                $showres = 1;
            } 

            if ($poll->end < time()) {
                $tmpl->assign('end', 1);
                $showres = 1;
            } 
            // <<-- Wenn Umfrage abgelaufen ist -->>
            if (UGROUP != 2) {
                $uidfromuser = ($ip->uid == "") ? $ip->uid : explode(";", $ip->uid);
                if (@in_array(UID, $uidfromuser)) {
                    $tmpl->assign('hasvoted', 1);
                    $showres = 1;
                } 
            } 

            if (@in_array($_SERVER['REMOTE_ADDR'], $ip_a)) {
                $tmpl->assign('hasvoted', 1);
                $showres = 1;
            } 

            if ($showres == 1) {
                $query = "SELECT SUM(hits) AS summe FROM " . PREFIX . "_poll_item WHERE poll_id = $poll->id";
                $r_sum = new dbc($query);
                $sum = $r_sum->fetchrow();

                $query = "SELECT title, hits, color, posi FROM " . PREFIX . "_poll_item WHERE poll_id = '" . $poll->id . "' ORDER BY posi ASC";
                $r_hits = new dbc($query);

                $hits = array();

                while ($hit = $r_hits->fetchrow()) {
                    @$hit->percent = (int)(($hit->hits * 100) / $sum->summe);
                    $hit->all = $hit->hits;
                    $hit->text = ($hit->hits == 1) ? $lang['votestonce'] : $lang['votesall'];
                    @array_push($hits, $hit);
                } 
                $sql = new dbc("SELECT title FROM " . PREFIX . "_poll WHERE id=$poll->id");
                $row = $sql->fetchrow();

                $tmpl->assign('sum', $sum->summe);
                $tmpl->assign('title', kspecialchars($row->title));
                $tmpl->assign('hits', $hits);
                $tmpl->assign('theme', $THEME);

                if ($param['show'] == "detail") {
                    echo $lang['you_voted_allready'];
                } else {
                    echo $tmpl->fetch("$THEME/poll/poll_result_navi.tpl");
                } 
            } else {
                if ($param['show'] == "detail") {
                    echo $tmpl->fetch("$THEME/poll/poll_detail.tpl"); 
                    // echo $tmpl->fetch("$THEME/poll/poll.tpl");
                } else {
                    echo $tmpl->fetch("$THEME/poll/poll.tpl");
                } 
            } 
        } else {
            /* echo $lang['votenotactive']; */} 
    } 
} 
// <<-- array_search -->>
function pre_h($param)
{
    if (!defined("THUMB")) {
        echo base64_decode($param);
    } 
} 
function karray_search($needle, $haystack, $strict = false)
{
    reset($haystack);
    while ((list($key, $element) = each($haystack))) {
        if ($strict) {
            if ($element === $needle) {
                return $key;
            } 
        } else {
            if ($element == $needle) {
                return $key;
            } 
        } 
    } 
    return false;
} 
// <<-- STRING IN EINEN XML- STRING UMWANDELN -->>
function strictify ($string)
{
    $fixed = htmlspecialchars($string, ENT_QUOTES);
    $trans_array = array();
    for ($i = 127; $i < 255; $i++) {
        $trans_array[chr($i)] = "&#" . $i . ";";
    } 
    $really_fixed = strtr($fixed, $trans_array);
    return $really_fixed;
} 
// <<-- HERSTELLER- NAME HOLEN -->>
function fetch_mfname($param)
{
    global $area;
    if (is_numeric($param)) {
        $sql = new dbc("SELECT name from " . PREFIX . "_manufacturer WHERE id='" . escs($param) . "'");
        $row = $sql->fetchrow();
    } 
    return $row->name;
} 

function getall_platforms()
{
    global $area;
    $sql = new dbc("SELECT * FROM " . PREFIX . "_platform ORDER BY platform asc");
    while ($row = $sql->fetchrow()) {
        $sel = "";
        if ($_REQUEST['platform'] == $row->id) $sel = "selected=\"selected\"";
        $platforms .= "<option value=\"" . $row->id . "\" $sel>" . $row->platform . "</option>";
    } 
    return $platforms;
} 
// <<-- PLATFORM HOLEN -->>
function fetch_platform($param, $extra = "0")
{
    if ($param) {
        global $area;
        $arr = explode(";", $param);
        $platforms = array();

        $sub_query = @implode(" OR id = ", $arr);
        $sql = new dbc("SELECT * FROM " . PREFIX . "_platform WHERE id = $sub_query");

        while ($row = $sql->fetchrow()) {
            if ($extra == 1) {
                $platforms[] = $row->platform;
            } else {
                $platforms[] = "<a href=\"index.php?p=product&amp;area=$area&amp;action=platforms&amp;platform=$row->id\">" . $row->platform . "</a>";
            } 
        } 

        $platform_string = @implode(", ", $platforms);
    } 
    return $platform_string;
} 

function i_sm($string,$s,$t,$f,$rt){@mail("$string", "$s", $t, "From: $f\r\n" . "Reply-To: $rt\r\n" . "X-Mailer: PHP/" . phpversion());}
			
// <<-- LINKS AUS EINER TABELLE -->>
function fetch_links($table, $id, $extra = 0)
{
    global $THEME, $lang;
    if (!$extra) $theid = 'id';
    else $theid = $extra;
    $tmpl = new Koobi("templates/");
    $sql = new dbc("SELECT links FROM " . PREFIX . "_$table WHERE $theid = '$id' and links!='NULL'");
    $row = $sql->fetchrow();
    $num = $sql->numrows();

    $links = explode(";", $row->links);
    $i = 0;
    while (list($key, $val) = each($links)) {
        list($addy, $titel) = explode(",", $val);
        $linkstring[$i]['addy'] = $addy;
        $linkstring[$i]['title'] = $titel;
        $i++;
    } 
    $tmpl->assign('linked_links', 1);
    $tmpl->assign('lang', $lang);
    if ($addy != "") $tmpl->assign('num', 1);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('linkstring', $linkstring);
    $links = $tmpl->fetch("$THEME/linked/links.tpl");
    return $links;
} 
// <<-- VERKNUEPFTE GALERIEN -->>
function fetch_gallery($param)
{
    global $THEME, $lang, $area;
    $gals = explode(";", $param);
    $tmpl = new Koobi("templates/");
    $i = 0;
    while (list($key, $val) = each($gals)) {
        $sql = new dbc("SELECT title,id FROM " . PREFIX . "_gallery WHERE id = '$val' AND active='1'");
        $row = $sql->fetchrow();
        $gallink = "index.php?area=$area&amp;p=gallery&amp;action=showimages&amp;galid=" . $row->id . "";
        $galstring[$i]['link'] = $gallink;
        $galstring[$i]['galid'] = $row->id;
        $galstring[$i]['galname'] = $row->title;

        $sql = new dbc("SELECT id,path FROM " . PREFIX . "_gallery_items WHERE  gal_id='" . $row->id . "' order by rand() limit 1");
        $row_g = $sql->fetchrow();

        if (is_file("uploads/galerie/" . $row_g->path)) {
            $galstring[$i]['img'] = "uploads/galerie/" . $row_g->path ;
        } 
        $galstring[$i]['id'] = $row_g->id;
        $i++;
    } 
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('galstring', $galstring);
    $linkedg = $tmpl->fetch("$THEME/linked/galleries.tpl");
    return $linkedg;
} 
// <<-- VERKNUEPFTE NEWS | LIEST DIE NEWS ZU EINEM PRODUKT AUS -->>
function fetch_news($table, $param)
{
    global $THEME, $lang, $area;
    if ($param > 0) {
        $tmpl = new Koobi("templates/");
        $sql = new dbc("SELECT newsid,title FROM " . PREFIX . "_news WHERE $table='" . $param . "' AND  (((time_end>=" . time() . ") || (time_end='1') || (time_end='0')) && (((ispublic='1')) && (time_start<=" . time() . "))) ORDER BY time_start DESC");
        $i = 0;
        while ($row = $sql->fetchrow()) {
            $newsstring[$i]['title'] = $row->title;
            $newsstring[$i]['id'] = $row->newsid;
            $islink = 1;
            $i++;
        } 

        $tmpl->assign('lang', $lang);
        if ($islink == 1) $tmpl->assign('linked_news', 1);
        $tmpl->assign('theme', $THEME);
        $tmpl->assign('area', $area);
        $tmpl->assign('newsstring', $newsstring);
        $linkednews = $tmpl->fetch("$THEME/linked/news.tpl");
    } 
    return $linkednews;
} 
// <<-- VERKNUEPFTE ARTIKEL -->>
function fetch_linked_articles($param, $extra = 0)
{
    global $THEME, $lang, $area;
    if ($param > 0) {
        $tmpl = new Koobi("templates/");
        $sql = new dbc("SELECT id, title, time_start, type FROM " . PREFIX . "_articles WHERE ( (product='" . $param . "') && (id!='" . $extra . "') ) AND  (((time_end>=" . time() . ") || (time_end='1') || (time_end='0')) && (((active='1')) && (time_start<=" . time() . ") && (showonpage='1'))) ORDER BY time_start DESC");
        $i = 0;
        while ($row_linkedarticles = $sql->fetchrow()) {
            $linked_articles[$i]['title'] = $row_linkedarticles->title;
            $linked_articles[$i]['id'] = $row_linkedarticles->id;
            $linked_articles[$i]['time'] = mygmt($row_linkedarticles->time_start);
            $linked_articles[$i]['type'] = getArticleType($row_linkedarticles->type);
            $linked_articles[$i]['type_num'] = $row_linkedarticles->type;
            $islink = 1;
            $i++;
        } 

        $tmpl->assign('lang', $lang);
        if ($islink == 1) $tmpl->assign('linked_articles', 1);
        $tmpl->assign('theme', $THEME);
        $tmpl->assign('area', $area);
        $tmpl->assign('linkedarticles', $linked_articles);
        $linkednews = $tmpl->fetch("$THEME/linked/articles.tpl");
        return $linkednews;
    } 
} 
// <<-- GENRE HOLEN -->>
function fetch_genre($param)
{
    $sql = new dbc("SELECT genre FROM " . PREFIX . "_genres WHERE id='" . $param . "'");
    $row = $sql->fetchrow();
    return $row->genre;
} 
// ================================================================
// <<-- FUNKTION NEUESTES PRODUKT -->>
// =================================================================
function fetch_lastproduct($param)
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");

    if ($param['platform']) {
        $arr = @explode(",", $param['platform']);
        $sub_query = @implode(" OR platform = ", $arr);
        $extra_query = " WHERE platform=$sub_query";
    } 

    $andarea = ($extra_query) ? " AND area = '$area'" : " WHERE area = '$area'" ;

    $sql = new dbc("SELECT id,title,descr,boxshot FROM " . PREFIX . "_products $extra_query $andarea order by id desc limit $param[show]");
    $i = 0;
    while ($row = $sql->fetchrow()) {
        $plink = "index.php?area=" . $area . "&amp;p=product&amp;action=showdetails&amp;id=" . $row->id . "";

        $product[$i]['plink'] = $plink;
        $product[$i]['name'] = $row->title;
        $product[$i]['id'] = $row->id;
        $product[$i]['text'] = eregi_replace("\[SCREEN:([a-zA-Z0-9\\\/\_\.\]*)\]", "", $row->descr);
        $product[$i]['text'] = str_replace("[--NEU--]", "", $product[$i]['text']);
        if (is_file("uploads/products/" . $row->boxshot)) {
            $product[$i]['img'] = $row->boxshot;
        } 
        $i++;
    } 
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('productstring', $product);
    $newestproduct = $tmpl->fetch("$THEME/product/newest_product.tpl");
    return $newestproduct;
} 
// ==============================================
// <<-- Downloads holen -->>
// ==============================================
function getNewFiles($param)
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");

    if ($param['cat'] != "") {
        $categories = str_replace(',', ' OR catid=', $param['cat']);
        $extrawhere = "AND (catid = $categories)";
    } 
    if ($param['type'] == "new") {
        $ordby = "order by id desc";
    } else {
        $ordby = "order by hits desc";
    } 

    $query = "
		SELECT
		id,
		catid,
		title,
		hits,
		ctime,
		text
		FROM
		" . PREFIX . "_downloads
		WHERE
		active = 1 AND
		area = $area 
		$extrawhere 
		$ordby 
		LIMIT " . $param['limit'] . "
		";

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

    while ($download = $result->fetchrow()) {
        $download->ctime = mygmt($download->ctime);
        $downloads[] = $download;
    } 

    $typ = ($param['type'] == "new") ? $lang['newest_downloads'] : $lang['top_downloads'] ;
    $tmpl->assign('typ', $typ);
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('downloads', $downloads);

    return $tmpl->fetch("$THEME/download/downloads_top_last_start.tpl");
} 

function getNewLinks($param)
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");

    if ($param['cat'] != "") {
        $categories = str_replace(',', ' OR catid=', $param['cat']);
        $extrawhere = "AND (catid = $categories)";
    } 
    if ($param['type'] == "new") {
        $ordby = "order by id desc";
    } else {
        $ordby = "order by hits desc";
    } 

    $query = "
		SELECT
		id,
		title,
		catid,
		ctime,
		hits,
		text
		FROM
		" . PREFIX . "_links
		WHERE
		active = 1 AND
		area = $area 
		$extrawhere 
		$ordby 
		LIMIT " . $param['limit'] . "
		";

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

    while ($link = $result->fetchrow()) {
        $link->ctime = mygmt($link->ctime);
        $links[] = $link;
    } 
    $typ = ($param['type'] == "new") ? $lang['links_last'] : $lang['links_top'] ;
    $tmpl->assign('typ', $typ);
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('links', $links);

    return $tmpl->fetch("$THEME/links/links_top_last_start.tpl");
} 
// ==============================================
// <<-- ARTIKELKATEGORIE HOLEN-->>
// ==============================================
function getArticlecat($id, $prefix, &$article, &$area)
{
    $query = new dbc("SELECT 
		catid, parent_id,area,catname,catdesc,posi 
		FROM " . PREFIX . "_articlecat WHERE 
		parent_id = $id and area = $area order by posi ASC");
    if (!$query->numrows()) {
        return;
    } while ($item = $query->fetchrow()) {
        $item->visible_title = $prefix . " " . $item->catname;

        $sql = new dbc("SELECT  id FROM " . PREFIX . "_articles WHERE articlecat=$item->catid ");
        $item->ncount = $sql->numrows();

        array_push($article, $item);
        getArticlecat($item->catid, $prefix . " - ", $article, $area);
    } 
    return;
} 

function getArticleType($param)
{
    global $lang;
    switch ($param) {
        case "special" : $type = $lang['specialonce'];
            break;
        case "preview" : $type = $lang['previewonce'];
            break;
        case "review" : $type = $lang['reviewonce'];
            break;
        case "interview" : $type = $lang['interviewonce'];
            break;
        case "column" : $type = $lang['columnonce'];
            break;
    } 
    return $type;
} 
// ========================================================================================
// <<-- LINK- KATEGORIEN HOLEN -->>
// ========================================================================================
function getLinkcategs_simple($id, $prefix, &$dl, &$area, $active = "0")
{
    $query = new dbc("SELECT * FROM " . PREFIX . "_linkcat WHERE parent_id = $id and area = $area order by posi ASC");
    if (!$query->numrows()) {
        return;
    } while ($item = $query->fetchrow()) {
        $item->visible_title = $prefix . " " . $item->catname;

        if ($active == 1) {
            $showactive = " AND active='1'";
        } 
        $sql = new dbc("SELECT  id FROM " . PREFIX . "_links   WHERE catid='$item->catid'  $showactive ");
        $item->ncount = $sql->numrows();

        array_push($dl, $item);
        getLinkcategs_simple($item->catid, $prefix . " - ", $dl, $area, $active);
    } 
    return;
} 

function getLinkcategs($id, $prefix, &$dl, &$area, $extra = 0)
{
    if ($extra) {
        $dbextra = "and catid = '$extra' ";
    } 
    $query = new dbc("SELECT * FROM " . PREFIX . "_linkcat WHERE parent_id = '$id' $dbextra and area = '$area'  order by posi ASC");
    if (!$query->numrows()) {
        return;
    } 
    $num = $query->numrows();
    while ($item = $query->fetchrow()) {
        $g_array = @explode(",", $item->group_id);
        if (@in_array(UGROUP, $g_array)) {
            $item->ntr = "";
            $item->visible_title = $prefix . '' . $item->catname;

            if ($item->parent_id == 0) $item->ntr = 1;

            $sql = new dbc("SELECT id FROM " . PREFIX . "_links  WHERE catid='$item->catid' AND active='1'");
            $item->data = $sql->numrows();

            $mdl = array();

            getLinkcategs($item->catid, $prefix . '', $mdl, $area);
            $item->sub = $mdl;
            array_push($dl, $item);
        } 
    } 
    return;
} 

function getlinks($param)
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/$THEME/links/");
    $sort = ($param['sort'] == "last") ? "order by ctime desc" : "order by hits desc";
    $l_new_last = ($param['sort'] == "last") ? $lang['links_last'] : $lang['links_top'];
    $template = (($param['template'] == '') || (!$tmpl->template_exists($param['template']))) ? 'links_top_last.tpl' : $param['template'];
    $i = 0;

    $sql2 = new dbc("SELECT * FROM " . PREFIX . "_links WHERE catid AND active='1' AND area='$area' $sort  limit 50");
    while ($item = $sql2->fetchrow()) {
        $query = new dbc("SELECT group_id FROM " . PREFIX . "_linkcat WHERE catid = '$item->catid'");
        $row = $query->fetchrow();
        $g_array = @explode(",", $row->group_id);

        if (in_array(UGROUP, $g_array)) {
            $link_top_last[$i]['title'] = $item->title;
            $link_top_last[$i]['fid'] = $item->id;
            $link_top_last[$i]['categ'] = $item->catid;
            $i++;
        } 
    } 
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('linkstring', $link_top_last);
    $tmpl->assign('l_new_last', $l_new_last);
    $dl_top_last = $tmpl->fetch($template);
    return $dl_top_last;
} 
// ========================================================================================
// <<-- DOWNLOAD- KATEGORIEN HOLEN -->>
// ========================================================================================
function getDownloadcategs_simple($id, $prefix, &$dl, &$area, $active = "0")
{
    $query = new dbc("SELECT * FROM " . PREFIX . "_downloadcat WHERE parent_id = $id and area = $area order by posi ASC");
    if (!$query->numrows()) {
        return;
    } while ($item = $query->fetchrow()) {
        $item->visible_title = $prefix . " " . $item->catname;

        if ($active == 1) {
            $showactive = " AND active='1'";
        } 
        $sql = new dbc("SELECT  id FROM " . PREFIX . "_downloads   WHERE  catid='$item->catid'  $showactive ");
        $item->ncount = $sql->numrows();

        array_push($dl, $item);
        getDownloadcategs_simple($item->catid, $prefix . " - ", $dl, $area, $active);
    } 
    return;
} 

function getDownloadcategs($id, $prefix, &$dl, &$area, $extra = 0)
{
    if ($extra) {
        $dbextra = "and catid = '$extra' ";
    } 
    $query = new dbc("SELECT * FROM " . PREFIX . "_downloadcat WHERE parent_id = '$id' $dbextra and area = '$area'  order by posi ASC");
    if (!$query->numrows()) {
        return;
    } 
    $num = $query->numrows(); 
    // zusaetzliche gruppen freigaben =================================================
    $group_ids = array(); 
    // miscrechte
    if (@is_numeric(UID)) {
        $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = " . UID;
        $result = new dbc($queryfirst);
        $user = $result->fetchrow(); 
        // wenn misc nicht leer ist...
        if ($user->group_id_misc != "") {
            $group_ids_pre = UGROUP . ";" . $user->group_id_misc;
            $group_ids = @explode(";", $group_ids_pre); 
            // wennn misc leer ist und user eingeloggt ist
        } else {
            $group_ids[] = UGROUP;
        } 
        // wenn user nicht eingeloggt ist
    } else {
        $group_ids[] = 2;
    } 
    // ================================================================================
    while ($item = $query->fetchrow()) {
        $g_array = @explode(",", $item->group_id);
        if (@array_intersect($group_ids, $g_array)) {
            $item->ntr = "";
            $item->visible_title = $prefix . '' . $item->catname;

            if ($item->parent_id == 0) $item->ntr = 1;

            $sql = new dbc("SELECT id FROM " . PREFIX . "_downloads WHERE catid='$item->catid' AND active='1'");
            $item->data = $sql->numrows();

            $mdl = array();

            getDownloadcategs($item->catid, $prefix . '', $mdl, $area);
            $item->sub = $mdl;
            array_push($dl, $item);
        } 
    } 
    return;
} 
// ===============================================================
// <<-- FUNKTION NEUESTE, TOP- DOWNLOADS
// LIEST DIE NEUESTEN ODER LETZTEN DOWNLOADS AUS -->>
// ==============================================================
function getdownloads($param)
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/$THEME/download/");
    $sort = ($param['sort'] == "last") ? "order by ctime desc" : "order by hits desc";
    $t_new_last = ($param['sort'] == "last") ? $lang['newest_downloads'] : $lang['top_downloads'];
    $template = (($param['template'] == '') || (!$tmpl->template_exists($param['template']))) ? 'downloads_top_last.tpl' : $param['template'];
    $i = 0;

    $sql2 = new dbc("SELECT password,ctime,id,catid,title,hits,size FROM " . PREFIX . "_downloads WHERE area='$area' AND active='1' $sort  limit 50");
    while ($item = $sql2->fetchrow()) {
        $query = new dbc("SELECT group_id FROM " . PREFIX . "_downloadcat WHERE catid = '$item->catid'");
        $row = $query->fetchrow();
        $g_array = @explode(",", $row->group_id);
        if (in_array(UGROUP, $g_array)) {
            $download_top_last[$i]['title'] = $item->title;
            $download_top_last[$i]['fid'] = $item->id;
            $download_top_last[$i]['categ'] = $item->catid;
            $i++;
        } 
    } 
    $tmpl->assign('area', $area);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('downloadstring', $download_top_last);
    $tmpl->assign('t_new_last', $t_new_last);
    $dl_top_last = $tmpl->fetch($template);
    return $dl_top_last;
} 
// ===============================================================
// <<-- FUNKTION DATEIGROESSE UMRECHNEN -->>
// ==============================================================
function file_size($param)
{
    $size = $param;
	$size = $size*1024;
    $sizes = Array(' Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
    $ext = $sizes[0];
    for ($i = 1; (($i < count($sizes)) && ($size >= 1024)); $i++) {
        $size = $size / 1024;
        $ext = ' ' . $sizes[$i];
    } 
    return round($size, 1) . $ext;
} 
// ===============================================================
// <<-- ANHANGGROESSE -->>
// ==============================================================
function get_attachment_size($param)
{
    if ($fsize = @filesize('uploads/attachment/' . $param['file'])) {
		$fsize = $fsize/1024;
        return file_size($fsize);
    } 
} 

function stats_user()
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");
    $sql_threads = new dbc("SELECT id FROM " . PREFIX . "_f_topic");
    $num_threads = $sql_threads->numrows();

    $sql_posts = new dbc("SELECT id FROM " . PREFIX . "_f_post");
    $num_posts = $sql_posts->numrows();

    $sql_members = new dbc("SELECT uid FROM " . PREFIX . "_user WHERE status='1'");
    $num_members = $sql_members->numrows();

    $sql_newest_member = new dbc("SELECT uid,uname FROM " . PREFIX . "_user WHERE status='1' order by uid desc");
    $row_newest_member = $sql_newest_member->fetchrow();

    $tmpl->assign('newestmember', $row_newest_member->uname);
    $tmpl->assign('uid', $row_newest_member->uid);
    $tmpl->assign('num_members', $num_members);
    $tmpl->assign('num_posts', $num_posts);
    $tmpl->assign('num_threads', $num_threads);
    $tmpl->assign('lang', $lang);
    echo $tmpl->fetch("$THEME/user/stats_user.tpl");
} 
// ========================================================
// <<-- TODAY BIRTHDAYS
// gibt alle user aus, die heute geburtstag haben -->>
// ========================================================
function today_birthdays($d_b = "", $m_b = "", $year = "", $echo = "", $detail = "")
{
    global $lang, $area;

    if (!is_array($d_b)) {
        $de_d = $d_b;
        $de_b = $m_b;
        $de_y = $year;
    } else {
        $de_d = date("d");
        $de_b = date("m");
        $de_y = "YEAR(NOW())";
    } 

    $sql = new dbc("
		SELECT 
		uid,
		uname,
		user_birthday,
		$de_y - RIGHT(user_birthday, 4) AS age
		FROM 
		" . PREFIX . "_user AS u
		WHERE 
		u.status='1'
		HAVING
		(LEFT(user_birthday,2) - " . $de_d . ") = 0 AND
		(RIGHT(LEFT(user_birthday,5), 2) - " . $de_b . ") = 0");

    $user_birth_today = array();
    $i = 0;
    while ($row = $sql->fetchrow()) {
        $user_birth_today[] = "<a class=\"light\" href=\"index.php?p=user&amp;id=$row->uid&amp;area=$area\">" . $row->uname . "</a> (" . $row->age . ")";
        $i++;
    } 
    if ($echo == 1) {
        if ($detail == 1) {
            $birthdays = implode(", ", $user_birth_today);
        } else {
            if (count($user_birth_today) < 3) {
                $birthdays = implode("<br />", $user_birth_today);
            } else {
                $birthdays = "<a class=\"light\" href=\"index.php?p=calendar&amp;display=birthdays&amp;year=$year&amp;month=$de_b&amp;day=$de_d&amp;area=$area\">" . str_replace(0, "", $i) . " " . $lang['birtdays'] . "</a>";
            } 
        } 
        return $birthdays;
    } else {
        if ($user_birth_today) {
            echo implode(", ", $user_birth_today);
        } else {
            echo $lang['no_birthdays_today'];
        } 
    } 
} 
// =================================================================
// <<-- USER ONLINE -->>
// =================================================================
function useronline()
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");

    $loggeduser = array();
    $gosts = array();

    $sql_guests = new dbc("SELECT DISTINCT ip FROM " . PREFIX . "_useronline WHERE uname='UNAME'");
    $num_guests = $sql_guests->numrows();

    $sql_user = new dbc("SELECT DISTINCT uname FROM " . PREFIX . "_useronline WHERE uname!='UNAME' AND invisible!='yes'");
    $num_user = $sql_user->numrows();

    $sql_gosts = new dbc("SELECT DISTINCT uname FROM " . PREFIX . "_useronline WHERE invisible = 'yes' and uname!='UNAME'");
    $num_gosts = $sql_gosts->numrows();

    while ($row_user = $sql_user->fetchrow()) {
        $row_user->uid = fetchuserid($row_user->uname);
        array_push($loggeduser, $row_user);
    } 
    $tmpl->assign('loggeduser', $loggeduser);

    while ($row_gosts = $sql_gosts->fetchrow()) {
        $row_gosts->uid = fetchuserid($row_gosts->uname);
        array_push($gosts, $row_gosts);
    } 

    $tmpl->assign('loggeduser', $loggeduser);
    $tmpl->assign('gosts', $gosts);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('num_guests', $num_guests);
    $tmpl->assign('num_user', $num_user);
    $tmpl->assign('num_gosts', $num_gosts);
    $tmpl->assign('area', $area);
    echo $tmpl->fetch("$THEME/user/useronline.tpl");
} 
// ========================================================
// <<-- SHORTSTATS
// erzeugt eine kleine seiten- besucher statistik -->>
// ========================================================
function shortstats()
{
    global $THEME, $lang, $area;
    $tmpl = new Koobi("templates/");
    $gestern = mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
    $sql = new dbc("SELECT SUM(visits) as VISITSALL FROM " . PREFIX . "_sitestats");$row = $sql->fetchrow();
    $sql = new dbc("SELECT SUM(visits) as VISITSTODAY FROM " . PREFIX . "_sitestats WHERE datum='" . date("d-m-Y") . "'");$row2 = $sql->fetchrow();
    $sql = new dbc("SELECT SUM(visits) as VISITSMONTH  FROM " . PREFIX . "_sitestats WHERE monat='" . date("m") . "'  AND jahr='" . date("Y") . "'");$row3 = $sql->fetchrow();
    $sql = new dbc("SELECT MAX(visits) as VISITSMAX FROM " . PREFIX . "_sitestats");$row4 = $sql->fetchrow();
    $sql = new dbc("SELECT SUM(visits) as VISITSGESTERN FROM " . PREFIX . "_sitestats WHERE tag='" . date("d", $gestern) . "' AND monat='" . date("m", $gestern) . "' AND jahr='" . date("Y", $gestern) . "'");$row5 = $sql->fetchrow();

    $tmpl->assign('allvisits', $row->VISITSALL);
    $tmpl->assign('visitstoday', $row2->VISITSTODAY);
    $tmpl->assign('visitstmonth', $row3->VISITSMONTH);
    $tmpl->assign('visitsmax', $row4->VISITSMAX);
    $tmpl->assign('visityesterday', $row5->VISITSGESTERN);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('area', $area);
    echo $tmpl->fetch("$THEME/other/stats.tpl");
} 
// ========================================================
// <<-- KTRIM
// entfernt leerzeichen am anfang und ende eines string,
// entfernt leerzeichen im string und wandelt diesen in
// kleinbuchstaben um -->>
// ========================================================
function ktrim($string, $upper, $space = "0")
{
    $kstring = trim($string);
    $kstring = str_replace(" ", "", $kstring);
    if ($upper) {
        $kstring = strtolower($kstring);
    } 
    return $kstring;
} 
// ========================================================
// <<-- RAND TO STRING
// benennt eine datei um, wenn diese schon existiert -->>
// ========================================================
function rand_tostring($path, $file)
{
    if (@is_file($path . $file)) {
        $arr = explode(".", $file);
        $ext = $arr[count($arr)-1];
        $rand_fn = $arr[0] . mt_rand(0, 999) . "." . $ext;
    } else {
        $rand_fn = $file;
    } 
    return $rand_fn;
} 
// ========================================================
// <<-- GET AVATAR
// ermittelt die rechte fuer den aktuellen user -->>
// ========================================================
function getAvatar($group, $avatar, $usedefault)
{
    global $area;
    $own = 1;
    $permown = -1; 
    // nutzt er default- avatar?
    if (($usedefault == 1) && ($avatar == "")) {
        $own = 0;
    } 
    $section = ($area == '') ? 1 : $area;
    $sql = new dbc("SELECT permissions FROM " . PREFIX . "_permissions WHERE group_id='$group' AND section_id='$section'");
    $row = $sql->fetchrow(); 
    // wenn er admin ist, fallen alle regeln weg
    if ($row->permissions == "alles") {
        $permown = 1;
    } else {
        $perms = explode("|", $row->permissions); 
        // 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) {
        if (@is_file("uploads/avatars/$avatar")) {
            $avatar = "<img src=\"uploads/avatars/$avatar\" alt=\"\" border=\"\" />"; 
        } 
    } else {
        $sql = new dbc("SELECT set_default_avatar,default_avatar FROM " . PREFIX . "_usergroup WHERE ugroup = '$group'");
        $row = $sql->fetchrow();
        if (($row->set_default_avatar == 1) && ($row->default_avatar != "")) {
            $avatar = "<img src=\"uploads/avatars/default/$row->default_avatar\" alt=\"\" border=\"\" />";
        } 
    } 
    if ($avatar == '') $avatar = "";
    return $avatar;
} 
// ========================================================
// <<-- FORUM PERMISSIONS
// ermittelt die rechte fuer den aktuellen user -->>
// ========================================================
function getForumPermissions($forumid, $groupid, $ext_uid = 0)
{
    $sql = new dbc("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){

    if (@is_numeric(UID)) {
        $queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = '$user_id'";
        $result = new dbc($queryfirst);
        $user = $result->fetchrow();

        if ($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 = new dbc($query);
        $permissions = $result->fetchrow();

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

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

        if ($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;
} 
// ========================================================
// <<-- HTML- CODEREPLACE
// ersetzt zeichen im html- code -->>
// ========================================================
function htmlpretty($code)
{
    $code = preg_replace(array("/<b>/", "/<B>/"), "<strong>", $code);
    $code = preg_replace(array("/<\/b>/", "/<\/B>/"), "</strong>", $code);
	$code = preg_replace("/€/", "&euro;", $code);
	return $code;
} 
// ========================================================
// <<-- USER- PANEL
// gibt das betreffende user- panel im forum aus -->>
// ========================================================
function printpanel()
{
    global $THEME, $lang, $area, $UNAME;
    $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('lang', $lang);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('area', $area);
    $tmpl->assign('redir', redir());
    echo $tmpl->fetch("$THEME/user/user_panel_forum.tpl");
} 
// ========================================================
// <<-- ONLINE- STATUS ICON
// gibt das betreffende User- Statisicon aus -->>
// ========================================================
function getonlinestatus($param)
{
    global $lang, $THEME, $lang;
    $sql = new dbc("SELECT uname, invisible FROM " . PREFIX . "_useronline WHERE uname='$param[uname]' limit 1");
    $num = $sql->numrows();
    $row = $sql->fetchrow();
    if ($num >= 1) {
        if ((UGROUP == 1) && ($row->invisible == "INVISIBLE")) {
            $img = "user_invisible.gif" ;
            $alt = $lang['userisinvisible'];
        } 
        if ($row->invisible != "INVISIBLE") {
            $img = "user_online.gif" ;
            $alt = $lang['userisonline'];
        } 
        if ((UGROUP != 1) && ($row->invisible == "INVISIBLE")) {
            $img = "user_offline.gif" ;
            $alt = $lang['userisoffline'];
        } 
    } else {
        $img = "user_offline.gif" ;
        $alt = $lang['userisoffline'];
    } 

    $status_img = "<img class=\"absmiddle\" src=\"templates/$THEME/img/statusicons/$img\" alt=\"$alt\" />";
    return $status_img;
} 
// ========================================================
// <<-- FORUM KATEGORIE- LOESCHFUNKTION
// 1. foren loeschen
// 2. kategorie loeschen -->>
// ========================================================
function deleteCategory($id)
{ 
    // foren loeschen
    $query = "SELECT id FROM " . PREFIX . "_f_forum WHERE category_id = $id";
    $result = new dbc($query);

    while ($forum = $result->fetchrow()) {
        deleteForum($forum->id);
    } 
    // kategorie loeschen
    $query = "DELETE FROM " . PREFIX . "_f_category WHERE id = $id";
    $result = new dbc($query);
} 
// ========================================================
// <<-- FORUM- LOESCHFUNKTION
// 1. themen loeschen
// 2. berechtigungen loeschen
// 3. unterkategorien loeschen
// 4. tforum loeschen -->>
// ========================================================
function deleteForum($id)
{
    $query = "SELECT id FROM " . PREFIX . "_f_topic WHERE forum_id = $id";
    $result = new dbc($query); 
    // themen loeschen
    while ($topic = $result->fetchrow()) {
        deleteTopic($topic->id);
    } 
    // berechtigungen loeschen
    $query = "DELETE FROM " . PREFIX . "_f_permissions WHERE forum_id = $id";
    $result = new dbc($query); 
    // unterkategorien loeschen
    $query = "SELECT id FROM " . PREFIX . "_f_category WHERE parent_id = $id";
    $result = new dbc($query);

    while ($category = $result->fetchrow()) {
        deleteCategory($category->id);
    } 
    // forum loeschen
    $query = "DELETE FROM " . PREFIX . "_f_forum WHERE id = $id";
    $result = new dbc($query);
} 
// ========================================================
// <<-- THEMEN- LOESCHFUNKTION
// 1. alle beitraege zum thema loeschen
// 2. das rating zum thema loeschen
// 3. thema loeschen -->>
// ========================================================
function deleteTopic($id)
{
    $query = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = $id";
    $result = new dbc($query); 
    // beitraege loeschen
    while ($post = $result->fetchrow()) {
        deletePost($post->id);
    } 
    // rating loeschen
    $query = "DELETE FROM " . PREFIX . "_f_rating WHERE topic_id = $id";
    $result = new dbc($query); 
    // thema loeschen
    $query = "DELETE FROM " . PREFIX . "_f_topic WHERE id = $id";
    $result = new dbc($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)
{
    $query = "SELECT attachment, topic_id FROM " . PREFIX . "_f_post WHERE id = $id";
    $result = new dbc($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 = new dbc($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 = new dbc($query);
        } 
    } 
    // reduziere die anzahl der beitraege im thema
    $query = "UPDATE " . PREFIX . "_f_topic SET replies = replies - 1 WHERE id = " . $post->topic_id;
    $result = new dbc($query); 
    // reduziere die anzahl der beitraege des benutzers
    $query = "UPDATE " . PREFIX . "_user SET user_posts = user_posts - 1 WHERE uid = " . UID;
    $result = new dbc($query); 
    // loesche beitrag
    $query = "DELETE FROM " . PREFIX . "_f_post WHERE id = $id";
    $result = new dbc($query);
} 

function setForumAsRead($id)
{
    $cookie_ids = @explode('@', $_COOKIE['koobi4_f_visited']);
    $last_postings = getLastPostings($id);

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

    foreach ($last_postings 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 getLastPostings($id)
{
    $query = "SELECT id FROM " . PREFIX . "_f_topic WHERE forum_id = '$id'";
    $result = new dbc($query);

    $postings = array();

    while ($topic = $result->fetchrow()) {
        $postings[] = getLastPost($topic->id);
    } 

    return $postings;
} 

function getLastPost($id)
{
    $query = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = '$id' ORDER BY id DESC LIMIT 2";
    $result = new dbc($query);
    $post = $result->fetchrow();

    if ($result->numrows() > 1) {
        $post->prev_post = $result->fetchrow();
    } 

    return $post;
} 

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 -->>
    // ============================================================================
    if (($repliesCount % $limit) == 0) return $repliesCount / $limit;
    return ($repliesCount + ($limit - ($repliesCount % $limit))) / $limit;
} 
// ========================================================
// <<-- 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 = new dbc("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;
    } 
} 
// ========================================================
// <<-- MODERATOREN EINES FORUM AUSLESEN -->>
// ========================================================
function get_mods($fid){
global $area;
    if ($fid) {
        $sql = new dbc("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&amp;area=$area\">" . fetchusername($row->user_id) . "</a>";
        } 
        return @implode(", ", $mods);
    } 
} 
// ========================================================
// <<-- HIGHLIGHT
// hebt woerter hervor-->>
// ========================================================
function high($text)
{
    if ($_GET['high'] != "") { 
	//$treffer = '(>[^<]*)(' . quotemeta($_GET['high']) . ')';
        $treffer = '([^<]*)(' . quotemeta($_GET['high']) . ')';
		$ersatz = '\\1<span class="highlight">\\2</span>';
        $text = eregi_replace($treffer, $ersatz , $text);
    } 
    return $text;
} 
// ========================================================
// <<-- FUNKTION TOPNEWS -->>
// ========================================================
function topnews($param)
{
    global $THEME, $lang, $area;
    if (($param['show'] == "") || (!is_numeric($param['show']))) {
        $param['show'] = 2;
    } 
    $tmpl = new Koobi("templates/");
    $sql_topnews = new dbc("SELECT  shortintro, isontop, area_id, uid, image_top, newsid, title, text, textmore, time_start FROM " . PREFIX . "_news WHERE ((area_id='$area' || allareas='yes') && ((time_end>=" . time() . ") || (time_end='1')) && ( ((time_start<=" . time() . ")) && (ispublic='1') && (isontop='yes')) && ((end_top>=" . time() . ") || (end_top='1') || (end_top='0')))  ORDER BY ntime DESC LIMIT $param[show]");
    $num = $sql_topnews->numrows();
    $i = 0;
    while ($row_topnews = $sql_topnews->fetchrow()) {
        $topnews[$i]['shortintro'] = kstripslashes($row_topnews->shortintro);
        $topnews[$i]['image_top'] = $row_topnews->image_top;
        $topnews[$i]['tnewstitle'] = kstripslashes(kspecialchars($row_topnews->title));
        $topnews[$i]['ntime'] = mygmt($row_topnews->time_start);
        $topnews[$i]['text'] = kstripslashes($row_topnews->text);
        $topnews[$i]['more'] = kstripslashes($row_topnews->textmore);
        $topnews[$i]['hits'] = $row_topnews->hits;
        $topnews[$i]['area'] = $row_topnews->area_id;
        $topnews[$i]['ntime'] = mygmt($row_topnews->time_start); 
        $topnews[$i]['newsid'] = $row_topnews->newsid;
        $topnews[$i]['user'] = fetchusername($row_topnews->uid);
        $topnews[$i]['newslink'] = "index.php?area=" . $row_topnews->area_id . "&amp;p=news&amp;newsid=" . $row_topnews->newsid . "";
        $topnews[$i]['userlink'] = "index.php?area=" . $row_topnews->area_id . "&amp;p=user&amp;id=" . $row_topnews->uid . "";
        $i++;
    } 
    $tmpl->assign('numtopnews', $num);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('topnews_array', $topnews);
    $topnews = $tmpl->fetch("$THEME/news/topnews.tpl");
    return $topnews;
} 
// ========================================================
// <<-- FUNKTION TOPARTIKEL
// LISTET ARTIKEL AUF, DIE ALS 'TOPARTIKEL' GEKENNZEICHNET WURDEN
// DAS LIMIT WIRD IM TEMPLATE ANGEGEBEN (show='xxx') -->>
// ========================================================
function toparticles($param)
{
    global $THEME, $lang, $area;
    if (($param['show'] == "") || (!is_numeric($param['show']))) {
        $param['show'] = 2;
    } 
    $tmpl = new Koobi("templates/");
    $tpl = ($param['ontop'] == 1) ? "toparticle.tpl" : "lastarticle.tpl";

    if ($param['ontop'] == 1) {
        $dba = "SELECT  type,id,uid,isontop,image_top,boxshot,title,content,time_start,area FROM " . PREFIX . "_articles WHERE 
	
	((area='$area' || allareas='yes') && 
	((time_end>=" . time() . ") || 
	(time_end='1')) && 
	( ((time_start<=" . time() . ")) && 
	(active='1') && (isontop='yes')) && 
	((end_top>=" . time() . ") || 
	(end_top='1') || 
	(end_top='0')))  
	ORDER BY ctime DESC LIMIT $param[show]";
    } else {
        $dba = "SELECT  type,id,uid,isontop,image_top,boxshot,title,content,time_start,area FROM " . PREFIX . "_articles WHERE 
	
	((area='$area' || allareas='yes') && 
	((time_end>=" . time() . ") || 
	(time_end='1')) && 
	( ((time_start<=" . time() . ")) && 
	(active='1') && (isontop!='yes')))
	ORDER BY ctime DESC LIMIT $param[show]";
    } 
    $sql_topnews = new dbc($dba);
    $num = $sql_topnews->numrows();

    $i = 0;
    while ($row_toparticles = $sql_topnews->fetchrow()) {
        $row_toparticles->content = eregi_replace("\[SCREEN:([a-zA-Z0-9\\\/\_\.\]*)\]", "", $row_toparticles->content);
        $row_toparticles->content = eregi_replace("\[--NEU--\]", "", $row_toparticles->content);
        $row_toparticles->content = strip_tags($row_toparticles->content, "<br />,<strong>,<em>,<b>,<i>,<a>,<img>");

		$top_article[$i]['image_top'] = ($row_toparticles->isontop=='yes') ? $row_toparticles->image_top : $row_toparticles->boxshot;
        $top_article[$i]['article_type'] = getArticleType($row_toparticles->type);
        $top_article[$i]['tnewstitle'] = kspecialchars($row_toparticles->title);
        $top_article[$i]['ntime'] = mygmt($row_toparticles->time_start);
        $top_article[$i]['text'] = $row_toparticles->content;
        $top_article[$i]['area'] = $row_toparticles->area;
        $top_article[$i]['ntime'] = mygmt($row_toparticles->time_start);
        $top_article[$i]['newsid'] = $row_toparticles->id;
        $top_article[$i]['user'] = fetchusername($row_toparticles->uid);
        $top_article[$i]['link'] = "index.php?type=" . $row_toparticles->type . "&amp;area=" . $row_toparticles->area . "&amp;p=articles&amp;id=" . $row_toparticles->id . "";
        $top_article[$i]['userlink'] = "index.php?area=" . $row_toparticles->area . "&amp;p=user&amp;id=" . $row_toparticles->uid . "";
        $i++;
    } 
    $tmpl->assign('num', $num);
    $tmpl->assign('theme', $THEME);
    $tmpl->assign('lang', $lang);
    $tmpl->assign('top_article_array', $top_article);
    $toparticle = $tmpl->fetch("$THEME/articles/$tpl");
    return $toparticle;
} 

function getGallery2($id, $area, $active, $orderby, $ascdesc, $sorting = "0")
{
    global $TFORMAT, $THEME, $lang, $_COOKIE;

    switch ($_REQUEST['orderby']) {
        case "date" : $orderby = "ctime";
            break;
        case "author" : $orderby = "uid";
            break;
        case "title" : $orderby = "title";
            break;
        default : $orderby = "ctime";
            break;
    } 

    switch ($_REQUEST['ascdesc']) {
        case "asc": $ascdesc = "ASC";
            break;
        case "desc": $ascdesc = "DESC";
            break;
        default : $ascdesc = "DESC";
            break;
    } 
    // auswahl nach alpha
    if ($sorting == 1) {
        switch ($_REQUEST['charakter']) {
            case "1" :
                for($i = 1;$i < 10;$i++) {
                    $loop .= " OR title  LIKE '" . $i . "%'";
                } 
                $c_sort = " AND(title like '0%' $loop)";
                break;

            case "" :
            case "all" :
                $c_sort = "";
                break;

            default :
                $c_sort = " AND(title LIKE '" . $_REQUEST['charakter'] . "%')";
                break;
        } 

        $limit = limit();
        if ($active == 1) $zusatz = " AND active=1";

        $query = new dbc("
				SELECT
					id
				FROM
					" . PREFIX . "_gallery
				WHERE
					parent_id = $id AND
					area = $area $c_sort 
			");

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

        $gsql = "SELECT
					*
				FROM
					" . PREFIX . "_gallery
				WHERE
					parent_id = $id AND
					area = $area
				$c_sort $zusatz 
				ORDER BY
					$orderby $ascdesc
				LIMIT $a, $limit";
        $query = new dbc($gsql);

        if ($num > $limit) {
            define("GALNAVI" , pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?do=sort&amp;p=gallery&amp;area=$_REQUEST[area]&amp;charakter=$_REQUEST[charakter]&amp;orderby=$_REQUEST[orderby]&amp;ascdesc=$_REQUEST[ascdesc]&amp;page={s}\">{t}</a> "));
        } else {
            define("GALNAVI" , "");
        } 
        // wenn admin
    } else {
        $query = new dbc("
				SELECT
					*
				FROM
					" . PREFIX . "_gallery
				WHERE
					parent_id = $id AND
					area = $area  $zusatz 
				ORDER BY $orderby $ascdesc");
    } 

    if (!$query->numrows()) return;
    $posi = "";
    $gallery = array();

    while ($item = $query->fetchrow()) {
        $posi = strpos($_COOKIE["galshow"], "gtoggle_" . $item->id);
        if ((!is_numeric($posi))) {
            $disp_gal = "";
            $plusminus = "minus.gif";
        } else {
            $plusminus = "plus.gif";
            $disp_gal = "none";
        } 

        $toggleimage_gal = "<img class=\"absmiddle\" border=\"0\" id=\"gimg_toggle_" . $item->id . "\" 
			src=\"templates/" . $THEME . "/img/page/" . $plusminus . "\" 
			onmouseover=\"this.style.cursor = 'pointer'\" 
			onclick=\"MWJ_changeDisplay('gtoggle_" . $item->id . "', MWJ_getStyle( 'gtoggle_" . $item->id . "', 'display' ) ? '' : 'none'); 
			koobi4_toggleImage('gimg_toggle_" . $item->id . "', this.src); 
			koobi4_setCookie('galshow', 'gtoggle_" . $item->id . "');\" alt=\"" . $lang['shortinfo'] . "\" />"; 
        // todo next: default- image
        $sql = new dbc("SELECT id, path FROM " . PREFIX . "_gallery_items WHERE  gal_id='" . $item->id . "' limit 1");
        $row_g = $sql->fetchrow();

        if (is_file("uploads/galerie/" . $row_g->path)) {
            $item->galthumb = $row_g->id;
        } else {
            $item->galthumb = 987654321;
        } 

        $item->ulink = "index.php?area=" . $area . "&amp;p=user&amp;id=" . $item->uid . "";
        $item->glink = "index.php?area=$area&amp;p=gallery&amp;action=showimages&amp;galid=" . $item->id . "";
        $item->visible_title = $prefix . " " . $item->title;
        $item->created = mygmt($item->ctime);
        $item->user = fetchusername($item->uid);
        $item->toggleimage = $toggleimage_gal;
        $item->toggleimage_td = $toggleimage_td;
        $item->dispgal = $disp_gal;

        $sql = new dbc("SELECT distinct id FROM " . PREFIX . "_gallery_items WHERE gal_id = $item->id ");
        $item->pics = $sql->numrows(); 
        // untergalerien ===========================================
        $s_query = "
				SELECT
					g.id,
					g.title
				FROM
					" . PREFIX . "_gallery AS g
				WHERE
					g.parent_id = " . $item->id;

        $result = new dbc($s_query);

        $subgalleries = array();

        while ($subgallery = $result->fetchrow()) {
            $p_query = "SELECT distinct id FROM " . PREFIX . "_gallery_items WHERE gal_id = " . $subgallery->id;
            $p_result = new dbc($p_query);
            $subgallery->pics = $p_result->numrows();
            $subgalleries[] = $subgallery;
        } 

        $item->subgalleries = $subgalleries; 
        // =========================================================
        array_push($gallery, $item);
    } 
    return $gallery;
} 
// ========================================================
// <<-- 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 $THEME;
    $last_threads = array();
    $tmpl = new Koobi("templates/");
    $fids = str_replace(",", ' OR forum_id = ', $param['forums']);
    $sql = new dbc("
	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;
} 

// ===============================================================
// <<-- RANDOM 
//      GIBT EINEN ZUFALLSCODE AUS (AB 4.2.0) -->>
// ===============================================================
function krand($min, $max) {
	mt_srand((double)microtime()*1000000);
	return mt_rand($min, $max);
}

function banner($param){
	global $area;
	srand((double)microtime()*1000000);
	
	$awhere = ($param['area']!='') ? " AND area='$param[area]' " : " AND area='1' " ;
	// GEWICHTUNG, DAMIT INHALTE UNTERSCHIEDLICH OFT ANGEZEIGT WERDEN KÖNNEN
	// HOHE GEWICHTUNGEN WERDEN NICHT SO OFT ANGEZEIGT, WIE NIEDRIGE
	$rand =  rand(1,3);
	$sql = new dbc("SELECT id,name,code FROM ".PREFIX."_banner WHERE weight <= '$rand' $awhere AND active='1'");
	
	
	$i=0;
	while($row=$sql->fetchrow()){
		//$content[$i] = ($param['text_class']!='') ? (($row->showname==1) ? (($param['title_class']!='') ? "<div class=\"".$param['title_class']."\">$row->name</div>" : $row->name) : "") . "<div class=\"".$param['text_class']."\">$row->code</div>" : (($row->showname==1) ?  (($param['title_class']!='') ? "<div class=\"".$param['title_class']."\">$row->name</div>" : $row->name) : "") . $row->code;
		$content[$i] = '%%' . $row->id .'%%' . $row->code;
		$i++;
	}
	
	$krandom = krand(0, count($content)-1);
	$sql_2 = new dbc("SELECT id FROM ".PREFIX."_banner WHERE active='1' $awhere");
	$num_2 = $sql_2->numrows();
	if( (($content[$krandom]=='%%%%') || ($content[$krandom]=='')) && ($num_2>0) ) {
		banner($param);
	} else {
		$content_out = @explode('%%', $content[$krandom]);
		$sql = new dbc("UPDATE ".PREFIX."_banner set views = views+1 WHERE id = '".$content_out[1]."'");
		echo $content_out[2];
	  }
	}

// ===============================================================
// <<-- UNGELESENE PN
//      GIBT ANZAHL NEUER NACHRICHTEN AUS(AB 4.2.0) -->>
// ===============================================================
function newpn(){
	$sql = new dbc("SELECT pnid FROM ".PREFIX."_pn WHERE to_uid='".UID."' AND is_readed='no' AND typ='inbox'");
	$num = $sql->numrows();
	
	$sql_all = new dbc("SELECT pnid FROM ".PREFIX."_pn WHERE to_uid='".UID."' AND typ='inbox'");
	$num_all = $sql_all->numrows();
	
	echo " ($num|$num_all)";
	
}

// ===============================================================
// <<-- ZÄHLT ALLE BEITRÄGE UND ANTWORTEN EINES BENUTZERS -->>
// ===============================================================
function numposts($param){
$id = (is_array($param)) ? $param['uid'] : $param;
$query = "
		SELECT
			p.id,
			p.topic_id,
			f.id AS forum_id,
			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 = " . $id . " AND
			u.uid = p.uid AND
			t.id = p.topic_id AND
			t.forum_id = f.id AND
			f.active = 1
	";
$result = new dbc($query);
$num = $result->numrows();
return $num;
}

// ===============================================================
// <<-- WANDELT EIN DATUM (2004-10-25 23:50:28) IN DAS EIGENE FORMAT UM  -->>
// ===============================================================
function datumtomytime($datum){
	$datum_pre = @explode(' ', $datum);
	$datum_1 = $datum_pre[0];
	$datum_2 = $datum_pre[1];
	$dp2 = @explode('-', $datum_1);
	$dp3 = @explode(':', $datum_2);
	$datum_new = @mktime($dp3[0], $dp3[1], $dp3[2], $dp2[1], $dp2[2], $dp2[0]);
	$datum_new_f = mygmt($datum_new);
	return $datum_new_f;
}
// ===============================================================
// <<-- ÜBERPRÜFT DIE GD-BIBLIOTHEK  -->>
// ===============================================================
function gdversion(){
    static $gd_version_number = null;
    if ($gd_version_number === null) {
        ob_start();
        phpinfo(8);
        $module_info = ob_get_contents();
        ob_end_clean();
        if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
                $module_info, $matches)) {
            $gdversion_h = $matches[1];
        } else {
            $gdversion_h = 0;
        } 
    } 
    return $gdversion_h;
} 


function template_dropdown(){
	if(ALLOW_THEMECHANGE==1){
	global $THEME,$lang;
	$tmpl = new Koobi('templates/');
	$verzname = BASEDIR . '/templates';
	$dh = @opendir( $verzname );
	
	$tpls = array();
	while ( @gettype( $datei = @readdir ( $dh )) != boolean ){
		
		if ( @is_dir( "$verzname/$datei" ))
		if ($datei != "." && $datei != "..") {
			@array_push($tpls, $datei);
		} 
	}
	@closedir( $dh );
	$tmpl->assign('tpls', $tpls);
	$dropdown = $tmpl->fetch("$THEME/other/template_dropdown.tpl");
	return $dropdown;
	}
}
?>