<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE(c) DREAM4(r) 
// HTTP://WWW.DREAM4.DE
//=================================================================
// ACHTUNG!
// DIESER PROGRAMMCODE IST URHERRECHTLICH GESCHUETZT
// DIE URHEBERRECHTE LIEGEN BEI DEN JEWEILIGEN AUTOREN.
// AENDERUNGEN IN DIESER DATEI ERFOLGEN AUF EIGENE GEFAHR!
// ES IST NICHT GESTATTET, DEN COPYRIGHTHINWEIS ZU AENDERN ODER ZU
// ENTFERNEN. NUR WENN SIE EINE COPYRIGHTHINWEIS-ENTFERNUNG BESTELLT
// HABEN, DUERFEN SIE DIESEN ENTFERNEN.
//================================================================
// BEI FRAGEN WENDEN SIE SICH BITTE AN: KONTAKT@DREAM4.DE
//=================================================================
if(!defined("BASE_DIR")) exit;
if(!get_active('forums'))
{
	notActive();
}

$GLOBALS['tmpl']->assign('SearchPop', popSearch());
//=================================================================
// Welches Forum
//=================================================================
$forum = $GLOBALS['db']->RowQuery("SELECT f.id,t.uid FROM " . PREFIX . "_f_forum AS f," . PREFIX . "_f_topic AS t WHERE t.id = '" . escs($_REQUEST['toid']) . "' AND t.forum_id = f.id");

//=================================================================
// Zugriffsrechte
//=================================================================
$cat_query = $GLOBALS['db']->Query("SELECT group_id FROM " . PREFIX . "_f_forum WHERE id = '" . $forum->id . "'");
while($category = $cat_query->fetchrow_assoc())
{
	// Miscrechte
	$group_ids = miscIds();
	$groups = explode(",", $category['group_id']);
	if (array_intersect($group_ids, $groups)) $permissions = getForumPermissionsByUser($forum->id, UID);
}

//=================================================================
// Ist User Moderator?
//=================================================================
$is_moderator = false;
$result = $GLOBALS['db']->Query("SELECT user_id FROM " . PREFIX . "_f_mods WHERE forum_id = '" . $forum->id . "'");
while ($user = $result->fetchrow())
{
	if ($user->user_id == UID) $is_moderator = true;
}

//=================================================================
// wenn user nicht auf eigenes thema antworten kann
//=================================================================
if ($forum->uid == UID)
{
	if ($permissions[FORUM_PERMISSION_CAN_REPLY_OWN_TOPIC] == 0) 
	{
		koobi_message('Global_NoPermission', 'Global_NoPermission_t', HOME_PATH . '/index.php?p=showtopic&amp;toid=' . $_REQUEST['toid']);
	}
} else {
	//=================================================================
	// kann nicht auf andere themen antworten
	//=================================================================
	if ($permissions[FORUM_PERMISSION_CAN_REPLY_OTHER_TOPIC] == 0 && UGROUP != 1 && !$is_moderator) {
		koobi_message('Global_NoPermission', 'Global_NoPermission_t', HOME_PATH . '/index.php?p=showtopic&amp;toid=' . $_REQUEST['toid']);
	}
}

$error_array = array();

//=================================================================
// Keinen Text eingegeben
//=================================================================
if ($_REQUEST["text"] == "")
{
	array_push($error_array, $GLOBALS['config_vars']['Forums_ErrorNoComment']);
}

//=================================================================
// wenn fehler oder vorschau
//=================================================================
if ( count($error_array) || ($_REQUEST['preview']==1) )
{
	$GLOBALS['tmpl']->assign("smilie", SMILIES);
	$row_t =  $GLOBALS['db']->RowQuery("SELECT title FROM " . PREFIX . "_f_topic WHERE id = '$_REQUEST[toid]'");
	$navigation = getNavigation($_REQUEST['toid'], 'topic') 
	. $GLOBALS['config_vars']['Forums_Splitter'] . '<a class="forum_links_navi" href="index.php?p=showtopic&amp;toid=' . $_REQUEST['toid'] . '">' 
	. stripslashes($row_t->title) 
	. '</a>'
	. $GLOBALS['config_vars']['Forums_Splitter']
	. $GLOBALS['config_vars']['Forums_Header_postreply_form'];
	
	$stitle = $GLOBALS["config_vars"]["Forums_Title"];
	$sname = str_replace($GLOBALS['config_vars']['Forums_Splitter'], " - ", strip_tags($navigation));
	
	//=================================================================
	// vorschau darstellen
	//=================================================================
	if($_REQUEST['preview']==1)
	{
		$preview_text = stripslashes($_REQUEST['text']);
		if ( ($_REQUEST['parseurl']) == 1) $preview_text = parseurl($preview_text);
		if ( (BBCODESITE == 1) && (@$_REQUEST['disablebb']!=1) ) 
		{ 
			$preview_text = kcodes($preview_text);
		} else {
			$preview_text = nl2br($preview_text);
		}
		if ( (SMILIES==1) && (@$_REQUEST['disablesmileys']!=1) ) $preview_text = dosmilies($preview_text);
		
		//=================================================================
		// Anlagen anhaengen
		//=================================================================
		if(isset($_REQUEST['attach_hidden']) && $_REQUEST['attach_hidden']>=1)
		{ 
			foreach($_REQUEST['attach_hidden'] as $attachment)
			{
				$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX ."_f_attachment WHERE id='$attachment'");
				$row_a = $sql->fetchrow();
				
				if(is_object($row_a)) 
				{
					$attach_img = attachmentImg($row_a->orig_name);
					$h_attachments_only_show[] = '<div id="div_'.$row_a->id.'" style=""><input type="hidden" name="attach_hidden[]" id="att_'.$row_a->id.'" value="'.$row_a->id.'" />' . $attach_img . ' <a href="index.php?p=forum&amp;action=getfile&amp;id='.$row_a->id.'&amp;f_id='.$forum->id.'&amp;t_id=">'.$row_a->orig_name.'</a>&nbsp;<a href="?p=misc&amp;do=delattach&amp;id='.$row_a->id.'&amp;file='.$row_a->filename.'" target="attachment_frame" onclick="document.getElementById(\'att_' . $row_a->id . '\').value=\'\';document.getElementById(\'div_' . $row_a->id . '\').style.display=\'none\';document.getElementById(\'hidden_count\').value = document.getElementById(\'hidden_count\').value - 1;"><img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/forums/delete_small.png" alt="" border="0" hspace="2" /></a></div>';
				}
			}
			
			$GLOBALS['tmpl']->assign("h_attachments_only_show", $h_attachments_only_show);
		}
		$GLOBALS['tmpl']->assign("permissions", $permissions);
		$GLOBALS['tmpl']->assign("pre_error", 1);
		$GLOBALS['tmpl']->assign("preview_text", $preview_text);
		$GLOBALS['tmpl']->assign("preview_text_form", stripslashes($_REQUEST['text']));
		$GLOBALS['tmpl']->assign("f_id", $_REQUEST['f_id']);
		
		$items = array();
		if((!is_mod($_REQUEST['toid'])) && (UGROUP != 1)) $extra = " AND opened='1'";
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_f_post WHERE topic_id = '$_REQUEST[toid]'   ORDER BY id DESC limit 5");
		while($row = $sql->fetchrow())
		{
			$row->user = fetchusername($row->uid);
			$row->message = ($row->use_bbcode == 1) ? kcodes($row->message) : nl2br($row->message);
			if ( ($row->use_smilies == 1) && (SMILIES==1) ) $row->message = dosmilies($row->message);
			$row->message = (!badwordreplace($row->message) || badwordreplace($row->message)=='') ? $row->message : badwordreplace($row->message) ;
			
			array_push($items,$row);
		}
		$GLOBALS['tmpl']->assign('items', $items);
	}
	
	$GLOBALS['tmpl']->assign('topic_id', $_REQUEST['toid']);
	$GLOBALS['tmpl']->assign('navigation', $navigation);
	$GLOBALS['tmpl']->assign('bbcodes', BBCODESITE);
	$GLOBALS['tmpl']->assign('posticons', getPosticons());
	$GLOBALS['tmpl']->assign('listemos', listsmilies(0,1,1));
	$GLOBALS['tmpl']->assign('subject', oform($_REQUEST['subject']));
	$GLOBALS['tmpl']->assign('message', $_REQUEST['text']);
	$GLOBALS['tmpl']->assign('listfonts',  fontdropdown());
	$GLOBALS['tmpl']->assign('sizedropdown',  sizedropdown());
	$GLOBALS['tmpl']->assign('colordropdown',  colordropdown());
	$GLOBALS['tmpl']->assign('errors', $error_array);
	$GLOBALS['tmpl']->assign('threadform', $tmpl->fetch($GLOBALS['config']['source'] . '/forums/threadform.tpl'));
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/addtopic.tpl')); 
} else {
	
	$topic_id = $_REQUEST['toid'];
	$title = (isset($_REQUEST['subject']) && $_REQUEST['subject'] != '' ) ? addslashes($_REQUEST['subject']) : '';
	$message = substr($_REQUEST['text'], 0, MAXLENGTH_POST);
	
	//=================================================================
	// automatisch url umwandeln
	//=================================================================
	if (isset($_REQUEST['parseurl']) && $_REQUEST['parseurl'] == 1) $message = parseurl($message);
	
	//=================================================================
	// ueberpruefung bbcodes
	//=================================================================
	$disable_bbcode = (isset($_REQUEST['disablebb']) && $_REQUEST['disablebb'] ) ? 0 : 1;
	$disable_smilies = (isset($_REQUEST['disablesmileys']) && $_REQUEST['disablesmileys'] ) ? 0 : 1;
	$use_sig = (isset($_REQUEST['usesig']) && $_REQUEST['usesig'] ) ? 1 : 0;
	$notification = (isset($_REQUEST['notification']) && $_REQUEST['notification'] ) ? 1 : 0;
	
	//=================================================================
	// abos auslesen
	//=================================================================
	$q_notification = "SELECT notification, forum_id FROM " . PREFIX . "_f_topic WHERE id = '$topic_id'";
	$r_notification = $GLOBALS['db']->Query($q_notification);
	$r_notification = $r_notification->fetchrow();
	
	$forum_id = $r_notification->forum_id;
	$user_ids = explode(";",$r_notification->notification);
	
	//=================================================================
	// attachments anhaengen
	//=================================================================
	if(isset($_REQUEST['attach_hidden']) && $_REQUEST['attach_hidden'] >= 1)
	{
		foreach($_REQUEST['attach_hidden'] as $file)
		{
			if($file != '')
			{
				$attached_files[] = $file;
			}
		}
		$attachments = @implode(";", $attached_files);
	} else {
		$attachments = @implode(";", $_REQUEST['attachment']);
	}
	
	//=================================================================
	// wenn topic, keine posts
	//=================================================================
	$last_post_id = -1;
	
	//=================================================================
	// editieren
	//=================================================================
	if (isset($_REQUEST['action']) && $_REQUEST['action'] == "edit")
	{
		$announce = "";
		$status = "";
		if($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 1) 
		{
			if($_REQUEST['subaction'] == "announce")
			{
				$announce = "type='100'";
			}
			if($_REQUEST['subaction'] == "attention")
			{
				$announce = "type='1'";
			}
		}
		
		if($permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1)
		{
			if($_REQUEST['subaction'] == "close")
			{
				$status = "status='1'";
			}
		}
		
		if( ($status!="") || ($announce!="") )
		{
			if($announce!="" && $status==1) $sep = ",";
			$sql = $GLOBALS['db']->Query("UPDATE ".PREFIX."_f_topic SET
			$announce 
			$sep 
			$status 
			WHERE
			id = '$_REQUEST[toid]'");
			
		}
		
		//=================================================================
		// befinden sich anlagen am beitrag?
		//=================================================================
		$attachments = ($attachments!="") ? "attachment = '$attachments'," : "attachment = '',";
		$message = str_replace(array('i=new/**/Image();','top:expression(eval(this.sss))'), array('--','--'), $message);
		$q_post_query = "UPDATE " . PREFIX . "_f_post SET $attachments title = '$title',message = '$message',use_bbcode = '$disable_bbcode',use_smilies = '$disable_smilies', use_sig = '$use_sig' WHERE id = '" . $_REQUEST['p_id'] ."'";
		
		//=================================================================
		// u.U. das Thema aendern
		//=================================================================
		$topic = $GLOBALS['db']->RowQuery("SELECT t.uid,t.id FROM " . PREFIX . "_f_topic AS t, " . PREFIX . "_f_post AS p WHERE p.id = " . $_REQUEST['p_id'] . " AND t.id = p.topic_id");
		if ($topic->uid == UID || UGROUP == 1 || $is_moderator) 
		{
			if (isset($_REQUEST['topic']) && $_REQUEST['topic'] != '') 
			{
				$title = addslashes($_REQUEST['topic']);
				$result = $GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET title = '$title',posticon = '" . ((isset($_REQUEST['posticon']) && $_REQUEST['posticon'] != '') ? $_REQUEST['posticon'] : '') . "' WHERE id = '" . $topic->id . "'");
			}
		}
		
		//=================================================================
		// neu einfuegen
		//=================================================================
	} else {
				
		//=================================================================
		// muessen beitraege moderiert werden?
		//=================================================================
		$row = $GLOBALS['db']->RowQuery("SELECT moderated_posts,post_emails FROM " . PREFIX . "_f_forum WHERE id = '$forum_id'");
		$opened = ($row->moderated_posts == 1) ? 2 : 1;
		if(is_mod($forum_id)) $opened = 1;
		
		//=================================================================
		// aktionen
		//=================================================================
		if(isset($permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC]) && $permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1) 
		{
			if($_REQUEST['subaction'] == "close") $GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET status='1' WHERE id = '" . $topic_id ."'");
		}
		
		if(isset($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE]) && $permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 1)
		{
			if($_REQUEST['subaction'] == "announce")
			{
				$announce = "type='100'";
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET type='100' WHERE id = '" . $topic_id ."'");
			}
			if($_REQUEST['subaction'] == "attention")
			{
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET type='1' WHERE id = '" . $topic_id ."'");
			}
		}
		
		$attachment = ($_REQUEST['action']=="quote") ? '' : $attachments;
		
		//=================================================================
		// Post eintragen
		//=================================================================
		$message = str_replace(array('i=new/**/Image();','top:expression(eval(this.sss))'), array('--','--'), $message);
		$q_post_query = "INSERT INTO " . PREFIX . "_f_post (id, title, message, datum, topic_id, uid, use_bbcode, use_smilies, use_sig,attachment,opened)  VALUES ('', '$title', '$message', NOW(), '$topic_id', '" . UID . "', '$disable_bbcode', '$disable_smilies', '$use_sig','$attachment','$opened' )";
		
		//=================================================================
		// letzten beitrag holen
		//=================================================================
		$last_post = $GLOBALS['db']->RowQuery("SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = $topic_id ORDER BY id DESC");
		$last_post_id = $last_post->id;
		$datum = date("d.m.Y H:i");
		
		//=================================================================
		// wenn im admin empfaenger für jeden post eingetragen wurden,
		// werden hier nun die mails versendet
		//=================================================================
		if ($_REQUEST['action'] != "edit")
		{
			if($row->post_emails != "")
			{
				$mails = @explode(",",$row->post_emails);
				
				//=================================================================
				// welche seite?
				//=================================================================
				$sql = $GLOBALS['db']->Query("SELECT topic_id FROM " . PREFIX . "_f_post WHERE topic_id = '$topic_id'");
				$count = $sql->numrows();
				$page = getPageNum($count, 15);
				
				//=================================================================
				// link
				//=================================================================
				$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$topic_id&pp=15&page=$page#pid_$last_post_id";
				
				$username = (UNAME == 'UNAME') ? $GLOBALS['config_vars']['gguest'] : UNAME;
				$body_msg = ($opened==2) ? $GLOBALS['config_vars']['Forums_msg_newpost_body_adminnotification_toactivate'] : $GLOBALS['config_vars']['Forums_msg_newpost_body_adminnotification'];
				$subject_msg = ($opened==2) ? $GLOBALS['config_vars']['Forums_Newpost_subject'] . ' ' . $GLOBALS['config_vars']['Forums_ThreadMustUnlock_post'] : $GLOBALS['config_vars']['Forums_Newpost_subject'];
				
				$body = $body_msg;
				$body = str_replace("__DATUM__", $datum, $body);
				$body = str_replace("__USER__", $username, $body);
				$body = str_replace("__SUBJECT__", $title, $body);
				$body = str_replace("__LINK__", $link, $body);
				$body = str_replace("__MESSAGE__", $message, $body);
				$body = str_replace("\n","\r\n", $body);
				$att_ext = '';
				
				$Koobi = new Koobi;
				foreach ($mails as $send_mail)
				{
					$Koobi->koobi_mail(STANDARDMAIL, stripslashes($body), $subject_msg, STANDARDMAIL, STANDARDMAIL, 'text', $att_ext, '');
				}
			}
		}
		//=================================================================
		// EMAILS AN ABONNENTEN
		//=================================================================
		$sql = $GLOBALS['db']->Query("SELECT topic_id FROM " . PREFIX . "_f_post WHERE topic_id = '$topic_id'");
		$count = $sql->numrows();
		$page = getPageNum($count, 15);
		
		//=================================================================
		// link
		//=================================================================
		$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$topic_id&pp=15&page=$page#pid_$last_post_id";
		$users = @explode(";", str_replace(";" . UID, "", $r_notification->notification) );
		
		$Koobi = new Koobi;
		foreach ($users as $mail_to)
		{
			if ($mail_to != '')
			{
				$sql = $GLOBALS['db']->Query ("SELECT Benutzername as uname,Email as email FROM " . PREFIX . "_benutzer WHERE Id = '$mail_to'");
				$row_u = $sql->fetchrow();
				$username = (UNAME == 'UNAME') ? $GLOBALS['config_vars']['gguest'] : UNAME;
				
				$n_body = $GLOBALS['config_vars']['Forums_msg_newpost_body'];
				$n_body = str_replace("__DATUM__", $datum, $n_body);
				$n_body = str_replace("__USER__", $row_u->uname, $n_body);
				$n_body = str_replace("__AUTOR__", $username, $n_body);
				$n_body = str_replace("__SUBJECT__", $title, $n_body);
				$n_body = str_replace("__LINK__", $link, $n_body);
				$n_body = str_replace("__MESSAGE__", $message, $n_body);
				
				$Koobi->koobi_mail($row_u->email, stripslashes($n_body), $GLOBALS['config_vars']['Forums_Newpost_subject'], STANDARDMAIL, STANDARDMAIL, 'text', '', '');
			}
		}
		
		// ========================= ENDE MAIL- BENACHRICHTIGUNG ==========================
	}
	
	if ($notification)
	{
		//=================================================================
		// moechte user benachrichtigt werden?
		//=================================================================
		if (!in_array(UID,$user_ids)) 
		{
			$q_newrec = "UPDATE " . PREFIX . "_f_topic SET notification = CONCAT(notification, ';', '" . UID . "') WHERE id = '$topic_id'";
			$r_newrec = $GLOBALS['db']->Query($q_newrec);
		}
	} else {
		//=================================================================
		// ansonsten user aus notification entfernen
		//=================================================================
		$sql = $GLOBALS['db']->Query("SELECT notification FROM " . PREFIX . "_f_topic WHERE id = '$topic_id'");
		$row = $sql->fetchrow();
		$new = @str_replace(";" . UID, "", $row->notification);
		$sql = $GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET notification='$new' WHERE id = '$topic_id'");
	}
	
	$db_result = $new_post_result = $GLOBALS['db']->Query($q_post_query);
	$new_id = $GLOBALS['db']->InsertId();
	
	//=================================================================
	// FEHLER
	//=================================================================
	if (!$db_result)
	{
		koobi_message('Forums_PostErrorNew', 'Forums_PostErrorNewmsg', $_REQUEST['redir']);
	}
    
    //=================================================================
	// POST erfolgreich eingetragen
    //=================================================================
    if ($_REQUEST['action'] != 'edit')
	{
    	$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Beitraege = Beitraege + 1 WHERE Id = '" . UID ."'");
    	$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_topic SET replies = replies + 1, last_post = NOW(), last_post_int ='".time()."' WHERE id = '".$topic_id."'");
    	$GLOBALS['db']->Query("UPDATE " . PREFIX . "_f_forum SET last_post = NOW(), last_post_id = ".$new_id." WHERE id = '".$forum_id."'");
    }

    Koobi_Board_SetTopicRead($topic_id);
	
	$sql = $GLOBALS['db']->Query("SELECT topic_id FROM " . PREFIX . "_f_post WHERE topic_id = '".$topic_id."'");
	$count = $sql->numrows();
	$page = getPageNum($count, 15);
	$page = ($page < 1) ? 1 : $page;
	
	if ($_REQUEST['p_id'] != '')
	{
		koobi_message('Forums_EditPost','Forums_PostSuccess', HOME_PATH . "/index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id");
	} else {
		$msg = ($opened == 2) ? "Forumns_InfoModerated" : "Forums_PostSuccess";
		koobi_message('Forums_PostErrorNew', $msg, HOME_PATH . "/index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id");
	}
}
?>