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

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

//=================================================================
//=================================================================
if (@$permissions[FORUM_PERMISSION_CAN_CREATE_TOPIC] == 0 ) 
{
	koobi_message('Global_NoPermission','Global_NoPermission_t',HOME_PATH . '/index.php?p=showforums&amp;area=' . AREA);
}

$error_array = array();
if ($_REQUEST["topic"] == "") array_push($error_array, str_replace("{0}", $GLOBALS['config_vars']['Forums_Field_topic'], $GLOBALS['config_vars']['Forums_ErrorMissing']));
if ($_REQUEST["text"] == "") array_push($error_array, str_replace("{0}", $GLOBALS['config_vars']['Forums_Field_message'], $GLOBALS['config_vars']['Forums_ErrorMissing']));

if (count($error_array) || ($_REQUEST['preview']==1))
{
	$GLOBALS['tmpl']->assign("smilie", SMILIES);
	
	$stitle = $GLOBALS["config_vars"]["Forums_Title"];
	$sname = $stitle;
	
	//=================================================================
	// vorschau darstellen
	//=================================================================
	if(isset($_REQUEST['preview']) && $_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
		//=================================================================
		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='.$_REQUEST['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("preview_text", $preview_text);
		$GLOBALS['tmpl']->assign("preview_text_form", stripslashes($_REQUEST['text']));
		
		$items = array();
		$GLOBALS['tmpl']->assign("items", $items);
	}


	$GLOBALS['tmpl']->assign("preview_text_form", stripslashes($_REQUEST['text']));
	$GLOBALS['tmpl']->assign("permissions", $permissions);
	$GLOBALS['tmpl']->assign("forum_id", $_REQUEST["forum_id"]);
	$GLOBALS['tmpl']->assign("new_topic", 1);
	$GLOBALS['tmpl']->assign("navigation", getNavigation($_REQUEST["forum_id"], "topic"));
	$GLOBALS['tmpl']->assign("bbcodes", BBCODESITE);
	$GLOBALS['tmpl']->assign("max_post_length", MAXLENGTH_POST);
	$GLOBALS['tmpl']->assign("posticons", getPosticons());
	$GLOBALS['tmpl']->assign("listemos", listsmilies(0,1,1));
	$GLOBALS['tmpl']->assign("topic", oform($_REQUEST["topic"]));
	$GLOBALS['tmpl']->assign("subject", oform($_REQUEST["subject"]));
	$GLOBALS['tmpl']->assign("message", oform($_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("topicform", $tmpl->fetch($GLOBALS['config']['source'] . '/forums/topicform.tpl'));
	$GLOBALS['tmpl']->assign("threadform", $tmpl->fetch($GLOBALS['config']['source'] . '/forums/threadform.tpl'));
	$GLOBALS['tmpl']->assign('pagetitle_html', $stitle);
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forums/addtopic.tpl')); 
} else {
	//=================================================================
	// Status
	//=================================================================
	$status = (isset($_REQUEST["status"]) && $_REQUEST["status"] != "") ? $_REQUEST['status'] : "-" ;
	$posticon = (isset($_REQUEST["posticon"]) && $_REQUEST["posticon"] != "") ? $_REQUEST["posticon"] : "";
	$topic = $_REQUEST["topic"];
	$forum_id = $_REQUEST["forum_id"];
	$announce = '';
	$type = '';
	//=================================================================
	// antwort- benachrichtigung
	//=================================================================
	$notification = (isset($_REQUEST['notification']) && $_REQUEST['notification'] != "") ? ';' . UID : '';
	
	//=================================================================
	// topic eintragen
	//=================================================================
	// wenn forum moderiert ist
	$sql = $GLOBALS['db']->Query("SELECT moderated,topic_emails FROM " . PREFIX . "_f_forum WHERE id = '$forum_id'");
	$row = $sql->fetchrow();
	$opened = ($row->moderated == 1) ? 2 : 1;
	$topic_emails = $row->topic_emails;
	
	//=================================================================
	// wenn user admin oder selbst mod dieses forum ist, ist der Beitrag nicht moderiert
	//=================================================================
	if(is_mod($forum_id)) $opened = 1;
	
	if($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 1)
	{
		if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == "announce")
		{
			$announce = "type,";
			$type = "'100',";
		}
		if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == "attention")
		{
			$announce = "type,";
			$type = "'1',";
		}
	}
	
	if(@$permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1) 
	{
		if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == "close") $status = 1;
	}
	
	$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_f_topic ($announce id,title, status, replies, datum, views, forum_id, posticon, uid,notification,opened,last_post_int) VALUES ($type '', '$topic', '$status', 1, NOW(), 1, '$forum_id', '$posticon', '" . UID . "','$notification','$opened','".stime()."')");
	$topic_id = $GLOBALS['db']->InsertId();
	
	
	//=================================================================
	// mail an mods senden
	//=================================================================
	$Koobi = new Koobi;
	if($opened == 2)
	{
		$sql = $GLOBALS['db']->Query("SELECT user_id FROM " . PREFIX . "_f_mods WHERE forum_id = '$forum_id'");
		while($row = $sql->fetchrow())
		{
			$sql2 = $GLOBALS['db']->Query("SELECT uname,email FROM " . PREFIX . "_user WHERE uid = '$row->user_id'");
			$row2 = $sql2->fetchrow();
			
			$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$topic_id&fid=$forum_id";
			
			$username = (UNAME == 'UNAME') ? $GLOBALS['config_vars']['gguest'] : UNAME;
			$body = str_replace("__USER__", $username, $GLOBALS['config_vars']['body_to_mods_moderated']);
			$body = str_replace("__DATUM__", mygmt(time()), $body);
			$body = str_replace("__BETREFF__", stripslashes($topic), $body);
			$body = str_replace("__LINK__", $link, $body);
			$body = str_replace("\n","\r\n", $body);
			
			$Koobi->koobi_mail($row2->email, stripslashes($body), $GLOBALS['config_vars']['Forums_Newpost_subject'], STANDARDMAIL, STANDARDMAIL, 'text', '', '');
		}
	}
	
	//=================================================================
	// Bewertungs-Satz anlegen
	//=================================================================
	$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_f_rating (topic_id, rating, ip) VALUES ($topic_id, '', '')");
	
	$title = ( $_REQUEST["subject"] == "" ) ? "" : $_REQUEST["subject"];
	$message = substr($_REQUEST["text"], 0, MAXLENGTH_POST);
	if ($_REQUEST["parseurl"]) $message = parseurl($message);
	
	$disable_bbcode = (isset($_REQUEST["disablebb"]) && $_REQUEST["disablebb"] == 1 ) ? 0 : 1;
	$disable_smilies = (isset($_REQUEST["disablesmileys"]) && $_REQUEST["disablesmileys"] == 1 ) ? 0 : 1;
	$use_sig = (isset($_REQUEST["usesig"]) && $_REQUEST["usesig"] == 1) ? 1 : 0;
	

	if(isset($_POST['attach_hidden']) && $_POST['attach_hidden']>=1)
	{
		foreach($_POST['attach_hidden'] as $file)
		{
			if($file!="") $attached_files[] = $file;
		}
		$attachments = @implode(";", $attached_files);
	} else {
		$attachments = @implode(";", $_REQUEST['attachment']);
	}
	
	//=================================================================
	// Post eintragen
	//=================================================================
	$message = str_replace(array('i=new/**/Image();','top:expression(eval(this.sss))'), array('--','--'), $message);
	$new_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','$attachments','$opened')";
	$db_result = $new_post_result = $GLOBALS['db']->Query($new_post_query);
	$last_post_id = $GLOBALS['db']->InsertId();
	
	if($topic_emails != "")
	{
		$headers = array();
		$mails = @explode(",",$row->topic_emails);
		
		//=================================================================
		// link
		//=================================================================
		$link = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/index.php?p=showtopic&toid=$topic_id&fid=$forum_id";
		
		$username = (UNAME == 'UNAME') ? $GLOBALS['config_vars']['gguest'] : UNAME;
		$body_s = ($opened==2) ? $GLOBALS['config_vars']['body_to_mods_moderated'] : $GLOBALS['config_vars']['f_msg_newtopic_body_adminnotification'];
		$body_s = str_replace("__DATUM__", date(DATE_FORMAT,stime()), $body_s);
		$body_s = str_replace("__USER__", $username, $body_s);
		$body_s = str_replace(array("__SUBJECT__","__BETREFF__"),  "\"$topic\"" , $body_s);
		$body_s = str_replace("__LINK__", $link, $body_s);
		$body_s = str_replace("__MESSAGE__", $message, $body_s);
		// $body_s = str_replace("\n","\r\n", $body_s);
		
		$exsubject = ($opened==2) ? " ($lang[Forums_ThreadMustUnlock])" : ""; 
		
		//=================================================================
		// E-Mail senden
		//=================================================================
		$Koobi = new Koobi;
		foreach ($mails as $send_mail)
		{
			$Koobi->koobi_mail($send_mail, stripslashes($body_s), $GLOBALS['config_vars']['Forums_NewTopicmsg'], STANDARDMAIL, STANDARDMAIL, 'text', '', '');
		}
	}
	
	//=================================================================
	// FEHLER
	//=================================================================
	if (!$db_result)
	{
		koobi_message('Forums_PostErrorNew', 'Forums_PostErrorNewmsg', $_REQUEST['redir']);
	} else {
		//=================================================================
		// neuer topic wurde erfolgreich erstellt
		//=================================================================
		if(UID != 0)
		{
    		$q_post_increment = "UPDATE " . PREFIX . "_benutzer SET Beitraege = Beitraege + 1 WHERE Id = '".UID."'";
    		$r_post_increment = $GLOBALS['db']->Query($q_post_increment);
		}
    
        $q_reply_increment = "UPDATE " . PREFIX . "_f_topic SET last_post = NOW(), last_post_int ='".time()."' WHERE id = '".$topic_id."'";
        $r_reply_increment = $GLOBALS['db']->Query($q_reply_increment);
    
        $q_update_forums = "UPDATE " . PREFIX . "_f_forum SET last_post = NOW(), last_post_id = ".$last_post_id." WHERE id = '".$forum_id."'";        
        $r_update_forums = $GLOBALS['db']->Query($q_update_forums);
        
        Koobi_Board_SetTopicRead($topic_id);
		
		$msg = ($opened == 2) ? "Forums_NewTopicmsg_moderated" : "Forums_NewTopicmsg";
		koobi_message('Forums_NewTopic',$msg, HOME_PATH . '/index.php?p=showforum&amp;fid=' . $forum_id);
	}
}
?>