<?php
// ======================================================================== //
//   KOOBI - CMS                                                            //
//   SCRiPTMAFiA 2005 - THE DiRTY HANDS ON YOUR SCRiPTS                     //
//                                                                          //
//   DREAM4 - AM MICHELSGRUND 7 - 69469 WEINHEIM - GERMANY                  //    
//   TEL. +49(0) 6201 - 980442 / FAX. +49(0) 6201 - 64809                   //
// ======================================================================== //

// =========================================================
// <<-- zugriffsrechte -->>
// =========================================================
$cat_query = new dbc("SELECT group_id FROM " . PREFIX . "_f_forum WHERE id = '" . escs($_POST['forum_id']) . "'");
while ($category = $cat_query->fetchrow_assoc()) {
	
	// miscrechte
	include ( BASEDIR . "/system/misc_ids.php");
	
	$groups = explode(",", $category['group_id']);
	if (array_intersect($group_ids, $groups)) {
		$permissions = getForumPermissionsByUser(escs($_POST['forum_id']), UID);
	}
}
// =========================================================

if ( ($islogged == 0) || $permissions[FORUM_PERMISSION_CAN_CREATE_TOPIC] == 0 ) {
	$EOUT = msg("nopermission", "nopermission_t", str_replace("__URL__", "index.php?p=showforums&amp;area=$area", $lang['redirect']), "index.php?p=showforums&amp;area=$area");
	$NOOUT = 1;
}

$error_array = array();

if ($_POST["topic"] == "") {
	array_push($error_array, str_replace("{0}", $lang['f_field_topic'], $lang['f_err_field_missing']));
}

if ($_POST["text"] == "") {
	array_push($error_array, str_replace("{0}", $lang['f_field_message'], $lang['f_err_field_missing']));
}

if ( count($error_array) || ($_REQUEST['preview']==1) ) {
	
	$tmpl->assign("smilie", SMILIES);
	
	$stitle = $lang["forumtitle"];
	$sname = simpletitle($stitle);
	
	// 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);
		
		
		// attachments anhaengen
		if($_POST['attach_hidden']>=1){ 
			foreach($_POST['attach_hidden'] as $attachment){
				$sql = new dbc("SELECT * FROM " . PREFIX ."_f_attachment WHERE id='$attachment'");
				$row_a = $sql->fetchrow();
				
				$h_attachments_only_show[] = '
				<div id="div_'.$row_a->id.'" style="display:">
				<input type="hidden" name="attach_hidden[]" id="att_'.$row_a->id.'" value="'.$row_a->id.'" />
				&bull; '.$row_a->orig_name.'
				<a title="'.$lang['del_attachment_alt'].'" href="javascript:;" 
				onclick="if(confirm(\''.$lang['confirm_del_attachment'].'\'))
				{
					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 src="templates/'.$THEME.'/img/forum/del_attach.gif" alt="'.$lang['del_attachment_alt'].'" border="0" hspace="2" /></a>
				</div>';
			}
			
			$tmpl->assign("h_attachments_only_show", $h_attachments_only_show);
		}
		
		$tmpl->assign("preview_text", $preview_text);
		$tmpl->assign("preview_text_form", stripslashes($_REQUEST['text']));
		
		
		
		$items = array();
		$tmpl->assign("items", $items);
	}
	
	
	
	$tmpl->assign("forum_id", $_POST["forum_id"]);
	$tmpl->assign("new_topic", 1);
	$tmpl->assign("navigation", getNavigation($_POST["forum_id"], "topic"));
	$tmpl->assign("bbcodes", BBCODESITE);
	//$tmpl->assign("max_post_length", MAXLENGTH_POST);
	$tmpl->assign("lang", $lang);
	
	$tmpl->assign("posticons", getPosticons());
	$tmpl->assign("listemos", listsmilies());
	
	$tmpl->assign("topic", oform($_POST["topic"]));
	$tmpl->assign("subject", oform($_POST["subject"]));
	$tmpl->assign("message", oform($_POST["text"]));
	
	$tmpl->assign("listfonts",  fontdropdown());
	$tmpl->assign("sizedropdown",  sizedropdown());
	$tmpl->assign("colordropdown",  colordropdown());
	
	$tmpl->assign("errors", $error_array);
	$tmpl->assign("topicform", $tmpl->fetch("forums/topicform.tpl"));
	$tmpl->assign("threadform", $tmpl->fetch("forums/threadform.tpl"));
	$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/addtopic.tpl")));
	
	} else {
	
	// TODO status: ANNOUNCEMENT | STICKY | MOVED | ...
	$status = ($_POST["status"] == "") ? "-" : $_POST['status'];
	
	// posticon: NULL | ...
	$posticon = $_POST["posticon"];
	
	// topic name
	$topic = addslashes($_POST["topic"]);
	
	$forum_id = $_POST["forum_id"];
	
	// antwort- benachrichtigung
	$notification = ($_REQUEST['notification'] != "") ? ';' . UID : '';
	// topic eintragen
	
	// wenn forum moderiert ist
	$sql = new dbc("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($_REQUEST['subaction'] == "announce"){
			$announce = "type,";
			$type = "'100',";
		}
		if($_REQUEST['subaction'] == "attention"){
			$announce = "type,";
			$type = "'1',";
		}
	}
	
	if($permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1) {
		if($_REQUEST['subaction'] == "close"){
			$status = 1;
		}
	}
	
	$new_topic_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',
	'".time()."'
	)";
	
	$db_result = $new_topic_result = new dbc($new_topic_query);
	$topic_id = $new_topic_result->getid();
	
	
	// mail an mods senden
	if($opened == 2){
		$sql = new dbc("SELECT user_id FROM " . PREFIX . "_f_mods WHERE forum_id = '$forum_id'");
		while($row = $sql->fetchrow()){
			$sql2 = new dbc("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&area=$area";
			
			$username = (UNAME == 'UNAME') ? $lang['gguest'] : UNAME;
			$body = str_replace("__USER__", $username, $lang['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","\n\n", $body);

			@mail($row2->email, $lang['subject_to_mods_moderated'], stripslashes($body),
			"From: $pref[sendemail]\r\n"
			."Reply-To: $pref[sendemail]\r\n"
			."X-Mailer: PHP/" . phpversion());
		}
	}
	
	
	
	$q_rating = "INSERT INTO " . PREFIX . "_f_rating (topic_id, rating, ip) VALUES ($topic_id, '', '')";
	$r_rating = new dbc($q_rating);
	
	// title: NULL | ...
	$title = ( $_POST["subject"] == "" ) ? "" : $_POST["subject"];
	
	$message = substr($_POST["text"], 0, MAXLENGTH_POST);
	
	if ($_POST["parseurl"]) {
		$message = parseurl($message);
	}
	
	$disable_bbcode = ( $_POST["disablebb"] ) ? 0 : 1;
	$disable_smilies = ( $_POST["disablesmileys"] ) ? 0 : 1;
	$use_sig = ( $_POST["usesig"] ) ? 1 : 0;
	
	//$attachments = @implode(";", $_POST['attachment']);
	if($_POST['attach_hidden']>=1){
		foreach($_POST['attach_hidden'] as $file){
			if($file!=""){
				$attached_files[] = $file;
			}
		}
		$attachments = @implode(";", $attached_files);
	} else {
		$attachments = @implode(";", $_POST['attachment']);
	}
	
	$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 = new dbc($new_post_query);
	
	
	
	
	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&area=$area";
		
		$username = (UNAME == 'UNAME') ? $lang['gguest'] : UNAME;
		$body_s = ($opened==2) ? $lang['body_to_mods_moderated'] : $lang['f_msg_newtopic_body_adminnotification'];
		$body_s = str_replace("__DATUM__", $datum, $body_s);
		$body_s = str_replace("__USER__", $username, $body_s);
		$body_s = str_replace(array("__SUBJECT__","__BETREFF__"),  "\"$title\"" , $body_s);
		$body_s = str_replace("__LINK__", $link, $body_s);
		$body_s = str_replace("__MESSAGE__", $message, $body_s);
		$body_s = str_replace("\n","\n\n", $body_s);
		
		$exsubject = ($opened==2) ? " ($lang[f_munlock])" : ""; 
		
		foreach ($mails as $send_mail) {
		@mail($pref['sendemail'], $lang['f_newthemamsg'] . $exsubject , stripslashes($body_s),
			"From: $pref[sendemail]\r\n"
			."Reply-To: $pref[sendemail]\r\n"
			."X-Mailer: PHP/" . phpversion());
		}
		
		
	}
	
	// FEHLER
	if (!$db_result) {
		$EOUT = msg("f_posterror", "f_posterrormsg", str_replace("__URL__", $_REQUEST['redir'], $lang['redirect']), $_REQUEST['redir']);
		// neuer topic wurde erfolgreich erstellt
	} else {
		if(UID != 0){
		$q_post_increment = "UPDATE " . PREFIX . "_user SET user_posts = user_posts + 1 WHERE uid = '".UID."'";
		$r_post_increment = new dbc($q_post_increment);
		}
		
		$msg = ($opened == 2) ? "f_newthemamsg_moderated" : "f_newthemamsg";
		$EOUT = msg("f_newthema", $msg, str_replace("__URL__", "index.php?p=showforum&amp;fid=$forum_id&amp;area=$area", $lang['redirect']), "index.php?p=showforum&amp;fid=$forum_id&amp;area=$area");
		$NOOUT = 1;
	}
}

?>