<?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                   //
// ======================================================================== //

$q_forum = "
	SELECT
		f.id,
		t.uid
	FROM
		" . PREFIX . "_f_forum AS f,
		" . PREFIX . "_f_topic AS t
	WHERE
		t.id = " . $_POST['toid'] . " AND
		t.forum_id = f.id
	";

$r_forum = new dbc($q_forum);
$forum = $r_forum->fetchrow();

// =========================================================
// <<-- zugriffsrechte -->>
// =========================================================
$cat_query = new dbc("SELECT group_id FROM " . PREFIX . "_f_forum WHERE id = '" . $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($forum->id, UID);
	}
}

// =========================================================

// ist user moderator
$is_moderator = false;

$query = "
	SELECT
		user_id
	FROM
		" . PREFIX . "_f_mods
	WHERE
		forum_id = '" . $forum->id . "'";


$result = new dbc($query);

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) {
		$EOUT = msg('nopermission', 'nopermission_t', str_replace("__URL__", "index.php?p=showtopic&amp;toid=" . $_POST['toid'], $lang['redirect']), "index.php?p=showtopic&amp;toid=" . $_POST['toid']);
		$NOOUT = 1;
	}
} else {
	// kann nicht auf andere themen antworten
	if ($permissions[FORUM_PERMISSION_CAN_REPLY_OTHER_TOPIC] == 0 && UGROUP != 1 && !$is_moderator) {
		$EOUT = msg('nopermission', 'nopermission_t', str_replace("__URL__", "index.php?p=showtopic&amp;toid=" . $_POST['toid'], $lang['redirect']), "index.php?p=showtopic&amp;toid=" . $_POST['toid']);
		$NOOUT = 1;
	}
}

$error_array = array();


// kein text eingegeben
if ($_POST["text"] == "") {
	array_push($error_array, $lang['f_err_commentmissing']);
}

// wenn fehler oder vorschau
if ( count($error_array) || ($_REQUEST['preview']==1) ) {
	
	$tmpl->assign("smilie", SMILIES);
	$navigation = getNavigation($_POST["toid"], "topic");
	
	$stitle = $lang["forumtitle"];
	$sname = simpletitle(str_replace($lang['f_navi_separator'], " - ", 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);
		
		// 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("permissions", $permissions);
		$tmpl->assign("pre_error", 1);
		$tmpl->assign("preview_text", $preview_text);
		$tmpl->assign("preview_text_form", stripslashes($_REQUEST['text']));
		$tmpl->assign("f_id", $_POST['f_id']);
		
		
		
		$items = array();
		include("addpost_last.php");
		$tmpl->assign("items", $items);
	}
	
	
	$tmpl->assign("topic_id", $_POST["toid"]);
	$tmpl->assign("navigation", $navigation);
	$tmpl->assign("bbcodes", BBCODESITE);
	$tmpl->assign("lang", $lang);
	$tmpl->assign("posticons", getPosticons());
	$tmpl->assign("listemos", listsmilies());
	$tmpl->assign("subject", oform($_POST["subject"]));
	$tmpl->assign("message", $_POST["text"]);
	$tmpl->assign("listfonts",  fontdropdown());
	$tmpl->assign("sizedropdown",  sizedropdown());
	$tmpl->assign("colordropdown",  colordropdown());
	$tmpl->assign("errors", $error_array);
	$tmpl->assign("threadform", $tmpl->fetch("forums/threadform.tpl"));
	$tmpl->assign("content", parsetrue("container/".container("forum"), $stitle, $tmpl->fetch("forums/addtopic.tpl")));
	
} else {
	
	$topic_id = $_POST["toid"];
	$title = ( $_POST["subject"] == "" ) ? '' : addslashes($_POST["subject"]);
	$message = substr($_POST["text"], 0, MAXLENGTH_POST);
	
	// automatisch url umwandeln
	if ($_POST["parseurl"]) { $message = parseurl($message);}
	
	// ueberpruefung bbcodes
	$disable_bbcode = ( $_POST["disablebb"] ) ? 0 : 1;
	$disable_smilies = ( $_POST["disablesmileys"] ) ? 0 : 1;
	$use_sig = ( $_POST["usesig"] ) ? 1 : 0;
	$notification = ( $_POST["notification"] ) ? 1 : 0;
	
	// abos auslesen
	$q_notification = "SELECT notification, forum_id FROM " . PREFIX . "_f_topic WHERE id = '$topic_id'";
	$r_notification = new dbc($q_notification);
	$r_notification = $r_notification->fetchrow();
	
	$forum_id = $r_notification->forum_id;
	$user_ids = explode(";",$r_notification->notification);
	
	// attachments anhaengen
	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']);
	}
	
	// wenn topic, keine posts
	$last_post_id = -1;
	
	// editieren
	if ($_POST['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 = new dbc("UPDATE ".PREFIX."_f_topic SET
			$announce 
			$sep 
			$status 
			WHERE
			id = '$_REQUEST[toid]'");
			
		}
		
		// befinden sich anhaenge am beitrag?
		$attachments = ($attachments!="") ? "attachment = '$attachments'," : "attachment = '',";
		
		$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 = '" . $_POST['p_id'] ."'";
		
		// u.U. das Thema aendern
		$query = "
			SELECT
				t.uid,
				t.id
			FROM
				" . PREFIX . "_f_topic AS t,
				" . PREFIX . "_f_post AS p
			WHERE
				p.id = " . $_POST['p_id'] . " AND
				t.id = p.topic_id
		";
		
		$result = new dbc($query);
		$topic = $result->fetchrow();
		
		// nur der themenstarter (admin und moderator auch) darf das thema aendern
		if ($topic->uid == UID || UGROUP == 1 || $is_moderator) {
			if ($_POST['topic'] != '') {
				$title = addslashes($_POST['topic']);
				$query = "
					UPDATE
						" . PREFIX . "_f_topic
					SET
						title = '$title',
						posticon = '" . $_POST['posticon'] . "'
					WHERE
						id = '" . $topic->id . "'";
				
				$result = new dbc($query);
			}
		}
		
		// neu einfuegen
	} else {
				
		// muessen beitraege moderiert werden?
		$sql = new dbc("SELECT moderated_posts,post_emails FROM " . PREFIX . "_f_forum WHERE id = '$forum_id'");
		$row = $sql->fetchrow();
		
		$opened = ($row->moderated_posts == 1) ? 2 : 1;
		if(is_mod($forum_id)) { $opened = 1; }
		
		// aktionen
		if($permissions[FORUM_PERMISSIONS_CAN_CLOSE_TOPIC] == 1) {
			if($_REQUEST['subaction'] == "close"){
				$sql = new dbc("UPDATE " . PREFIX . "_f_topic SET status='1' WHERE id = '" . $topic_id ."'");
			}
		}
		
		if($permissions[FORUM_PERMISSIONS_CAN_CHANGE_TOPICTYPE] == 1) {
			if($_REQUEST['subaction'] == "announce"){
				$announce = "type='100'";
				$sql = new dbc("UPDATE " . PREFIX . "_f_topic SET type='100' WHERE id = '" . $topic_id ."'");
			}
			if($_REQUEST['subaction'] == "attention"){
				$sql = new dbc("UPDATE " . PREFIX . "_f_topic SET type='1' WHERE id = '" . $topic_id ."'");
			}
		}
		
		$attachment = ($_REQUEST['action']=="quote") ? '' : $attachments;
		
		// post eintragen
		$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
		$q_last_post = "SELECT id FROM " . PREFIX . "_f_post WHERE topic_id = $topic_id ORDER BY id DESC";
		$r_last_post = new dbc($q_last_post);
		$last_post = $r_last_post->fetchrow();
		$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 ($_POST['action'] != "edit") {
		
			if($row->post_emails != ""){
				$mails = @explode(",",$row->post_emails);
				
				// welche seite?
				$sql = new dbc("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') ? $lang['gguest'] : UNAME;
				$body_msg = ($opened==2) ? $lang['f_msg_newpost_body_adminnotification_toactivate'] : $lang['f_msg_newpost_body_adminnotification'];
				$subject_msg = ($opened==2) ? $lang['f_msg_newpost_subject'] . ' ' . $lang['f_munlock_post'] : $lang['f_msg_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","\n\n", $body);
				
				foreach ($mails as $send_mail) {
					@mail($pref['sendemail'], $subject_msg, stripslashes($body),
					"From: $pref[sendemail]\r\n"
					."Reply-To: $pref[sendemail]\r\n"
					."X-Mailer: PHP/" . phpversion());
				}
			}
		}
		// ================================================================
		// <<-- EMAILS AN ABONNENTEN -->>
		// ================================================================
		// welche seite?
		$sql = new dbc("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) );
		
		foreach ($users as $mail_to) {
			if ( $mail_to != "" ) {
				$sql = new dbc ("SELECT uname,email FROM " . PREFIX . "_user WHERE uid = '$mail_to'");
				$row_u = $sql->fetchrow();
				
				$username = (UNAME == 'UNAME') ? $lang['gguest'] : UNAME;
				
				$n_body = $lang['f_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);
				$n_body = str_replace("\n","\n\n", $n_body);
				
				
				@mail($row_u->email, $lang['f_msg_newpost_subject'] , stripslashes($n_body),
							"From: $pref[sendemail]\r\n"
							."Reply-To: $pref[sendemail]\r\n"
							."X-Mailer: PHP/" . phpversion());
			}
		}
		
		// ========================= 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 = new dbc($q_newrec);
		}
	} else {
		// ansonsten user aus notification entfernen
		$sql = new dbc("SELECT notification FROM " . PREFIX . "_f_topic WHERE id = '$topic_id'");
		$row = $sql->fetchrow();
		$new = @str_replace(";" . UID, "", $row->notification);
		$sql = new dbc("UPDATE " . PREFIX . "_f_topic SET notification='$new' WHERE id = '$topic_id'");
	}
	
	$db_result = $new_post_result = new dbc($q_post_query);
	$new_id = $new_post_result->getid();
	
	// FEHLER
	if (!$db_result) {
		$EOUT = msg("f_posterror", "f_posterrormsg", str_replace("__URL__", $_REQUEST['redir'], $lang['redirect']), $_REQUEST['redir']);
		$NOOUT = 1;
	}
	// POST erfolgreich eingetragen
	if ($_POST["p_id"] == "") {
		$q_post_increment = "UPDATE " . PREFIX . "_user SET user_posts = user_posts + 1 WHERE uid = $UID";
		$r_post_increment = new dbc($q_post_increment);
		
		$q_reply_increment = "UPDATE " . PREFIX . "_f_topic SET replies = replies + 1, last_post = NOW(), last_post_int ='".time()."' WHERE id = '".$topic_id."'";
		$r_reply_increment = new dbc($q_reply_increment);
		
		$q_update_forums = "UPDATE " . PREFIX . "_f_forum SET last_post = NOW() WHERE id = '".$forum_id."'";
		$r_update_forums = new dbc($q_update_forums);
	}
	
	
	$sql = new dbc("SELECT topic_id FROM " . PREFIX . "_f_post WHERE topic_id = '".$topic_id."'");
	$count = $sql->numrows();
	$page = getPageNum($count, 15);
	
	if ($_POST['p_id'] != "") {
		$EOUT = msg("f_msg_post_edit", "f_postsuccess", str_replace("__URL__", "index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id", $lang['redirect']), "index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id");
	} else {
		$msg = ($opened == 2) ? "f_newpostmsg_moderated" : "f_postsuccess";
		$EOUT = msg("f_posterror", $msg, str_replace("__URL__", "index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id", $lang['redirect']), "index.php?p=showtopic&amp;toid=$topic_id&amp;pp=15&amp;page=$page#pid_$last_post_id");
	}
	
	$NOOUT = 1;
	
}
?>