<?php

/*
 *  W-AGORA 4.0
 *  -----------
 *  $Id: insert.php,v 1.86 2005/06/04 10:14:43 mdruilhe Exp $
 *  Usage:      Insert a note in the database
 *  Author:     Marc Druilhe <mdruilhe@w-agora.com>
 */

# initialization stuff
# --------------------
	if (!empty($_POST['preview'])) {
		$bn_action="preview";
		$bn_action_mode="R";
	} else {
		$bn_action="insert";
		$bn_action_mode="W";
	}
	require ("init.inc");

	$actiontype = (empty($_POST['actiontype'])) ? $bn_action : $_POST['actiontype'] ;
	// Some installations (multimania.fr..) seems to lose/unset $key
	if (isset ($_POST['key'])) {
		$key = $_POST['key'];
	} elseif (isset ($_GET['key'])) {
		$key = $_GET['key'];
	}

# A forum must be selected
# ------------------------
	if (empty($bn)) {
		die (ERROR_NO_FORUM_SPECIFIED);
	}

# Set the script name to return to in case of error
# --------------------------------------------------
	$back_form = (isset($back_form)) ? "$back_form" : "post";
	$back = "$back_form.$ext";
	if (!empty($key) ) {
		$back.= "?key=$key";
	}

# (4.x) Initialize user info if user authenticated
# ------------------------------------------------
	if ($forum["type"] == "pub") {
		// public forum (password protected note) => save password in case of preview
		$userpw = $password;
	}

	if ($is_authenticated) {
		// 1) if user is authenticated then set userid/password from authentication datas
		$userid = $auth->user["userid"];
		$password = $auth->user["password"];
		if ($is_moderator) {
			// We allow moderator to "spoof" identity
			$username = empty($username) ? $auth->user["username"] : $username;
			$useraddress = empty($useraddress) ? $auth->user["useraddress"] : $useraddress;
		} else {
			$username = $auth->user["username"];
			$useraddress = $auth->user["useraddress"];
		}
	} elseif ( $auth->authenticate($username, $password) ) {
		// 2) we try to authenticate the use from the username/password set in the form 
		$username = $auth->user["username"];
		$useraddress = $auth->user["useraddress"];
		$userid = $auth->user["userid"];
		$password = $auth->user["password"];
	} elseif (!empty($useraddress)) {
		// 3) still not authenticated, we try to authenticate him using email/password from the form
		$u = $db->getUser($site, $useraddress, 'useraddress');
		if (is_array($u) ) {
			if ( $auth->authenticate($u['userid'], $password) ) {
				$username = $auth->user["username"];
				$useraddress = $auth->user["useraddress"];
				$userid = $auth->user["userid"];
				$password = $auth->user["password"];
			} else {
				// This email exists => identity spoofing ???
				if (!empty($before_access)) include $before_access;
				display_header (TITLE_ERROR, $header_footer);
				msgForm (ERROR_INVALID_PASSWORD, $back, 'back', '', 'post');
				display_footer ($header_footer);			    
			}
		} else {
			$userid = "guest";
			$password = empty($password) ? md5(uniqid("")) : md5($password);
		}
	} else {
		// 4) unauthenticated user => we set 'guest' userid + random password (so only moderator can later edit the note)
		$userid = "guest";
		$password = empty($password) ? md5(uniqid("")) : md5($password);
	}

	if ( ($actiontype=='insert') || ($actiontype=='preview') ) {
	    
# Check that the user email address is valid if set
# --------------------------------------------------
		$useraddress=str_replace (" ", "", $useraddress);
		if (empty($useraddress)) {
			$valid_address = 0;
		} else {
			if (validate_email ($useraddress, MAIL_CHECK_DNS)) {
				$valid_address = 1;
			} else {
				if (!empty($before_access)) include $before_access;
				display_header (TITLE_ERROR, $header_footer);
				msgForm (ERROR_INVALID_EMAIL, "$back", "back", "", "post");
				display_footer ($header_footer);
			}
		}

		if ($mail_reply) {
			if (!$valid_address) {
				if (!empty($before_access)) include $before_access;
				display_header (TITLE_ERROR, $header_footer);
				msgForm (ERROR_INVALID_EMAIL, "$back", "back", "", "post");
				display_footer ($header_footer);
			}
		} else {
			$mail_reply = 0;
		}

# Check that all required fields are set
# --------------------------------------
		if (isset($subject)) {
			// remove trailing whitespace
			$subject = chop($subject);
		}

		if (!empty($url)) {
			if ($url=='http://') {
				$url='';
			} elseif (!ereg('://', $url)) {
				$url = 'http://'.$url;
			}
		}

		if (is_array($bn_bind_var)) {
			reset($bn_bind_var);
			while (list($field, $required) = each($bn_bind_var)) {
				if ($required && isset($_POST[$field]) && ($$field=="") ) {
					if (!empty($before_access)) include $before_access;
					display_header (LABEL_POST, $header_footer);
					$alert = sprintf (ERROR_MISSING_FIELD, $field);
					msgForm ("$alert", "$back", "back", "", "post");
					display_footer ($header_footer);
				}
			}
		}
	}
	
# set some default values
# -----------------------
	if (empty($icon) ) {
		$icon = "icon1.gif";
	} else {
		// prevent abusers to select an image outside ./images/icons
		$icon = basename (preg_replace("/\s/", "", $icon)); 
		if (! @file_exists("$icon_dir/$icon")) {
			$icon = "icon1.gif";
		}
	}
	
	if (empty($subject)) {
		// Build subject from body if subject not set as required field
		$lines = explode("\n", str_replace("\r", '', strip_tags($body)));
		$maxlen = (int) $bn_var_size['subject'];
		if (strlen($lines[0]) > $maxlen) {
			$subject = substr($lines[0], 0, $maxlen-3). '...';
		} else {
			$subject = substr($lines[0], 0, $maxlen);
		}
	}

# (4.x) set hidden flag if it is a moderated forum
# ------------------------------------------------
	if (!$is_moderator && $forum["moderated"] == "1") {
		$hidden = 1;
		$fields["hidden"] = 1;
	}

# (4.x) logs the IP address
# -------------------------
	$ip = get_remote_ip();
	if (is_banned_ip($ip)) {
		msgForm ("You're not allowed to post to this forum anymore!", "list.$ext", "close");
		die();
	}

# populate note array with all global variables as defined in bn_var
# ------------------------------------------------------------------
	/* variables handled by w-agora */
	for (reset ($bn_var); $field=current($bn_var); next($bn_var)) {
		$$field=kill_html(chop(strip_magic_quotes($$field)));
		$fields[$field]=$$field;
	}

	/* user's defined variables */
	for (reset ($db_var); $field=current($db_var); next($db_var)) {
		$$field=ereg_replace ("\\\\", "\\\\", chop(strip_magic_quotes($$field)));
		if ($bn_allow_html && $bn_html_var[$field] && $html_tags) {
			$$field = strip_banned_tags($$field);
		} else {
			$$field = kill_html($$field);
		}
		if ($bn_auto_url && $bn_html_var[$field]) {
			$$field = checkURL ($$field);
		}
		if ($bn_use_smileys && $bn_html_var[$field]) {
			$$field = add_smileys($$field);
		}
		$fields[$field]=$$field;
	}

	$unixdate = $now;   

# Handle attachments (either uploaded from the browser or choosen on the server)
# ------------------------------------------------------------------------------
	$thanks_msg = "";

	include "$inc_dir/fileupload.$ext";
	$fu = new FileUpload;
	$fu->init ($site, $bn_db, $bn_dir_notes);

	$att_count = 0;
	$att_size = 0;
	$total_att_count = 0;
	$total_att_size = 0;

	$attkey = (isset($attkey) ) ? $attkey : $now;

	if ($bn_file_upload) {
		$attachments = $fu->getUploadedFiles($attkey, "P");
		if (is_array ($attachments) ) {
			$att_count = $attachments["att_count"];
			$att_size = $attachments["att_size"];
			if (is_array($pcfile_name)) {
				reset ($pcfile_name);
				$names = implode (", ", $pcfile_name);
				$pcfile_name = $names;
			}
			$pcfile_size = $att_size;   // backward compatibility
			$thanks_msg .= str_replace ('{NAME}', $pcfile_name, str_replace('{SIZE}', $pcfile_size, MSG_FILE_UPLOADED));
			$total_att_count += $att_count;
			$total_att_size += $att_size;
		}
	}

	if ($bn_browse_server && !empty($server_file) ) {
		$files = $fu->getServerFiles($attkey, "P");
		if (is_array ($files) ) {
			$att_count = $files["att_count"];
			$att_size = $files["att_size"];
			$thanks_msg .= sprintf(MSG_FILE_COPIED, $attachment);
			$total_att_count += $att_count;
			$total_att_size += $att_size;
		}
	}

# Set attachments needing to be deleted (just set a flag, deletion will
# be effective later
# -----------------------------------------------------------------------------
	if (is_array ($del_att) ) {
		$db->setDeleteAttachment ($bn_db, $attkey, $del_att);
	}

# Set attachments inline state
# -----------------------------------------------------------------------------
	if (is_array ($inline_att) ) {
		reset($inline_att);
		while (list($id, $mode) = each($inline_att)) {
			$db->setInlineAttachment ($bn_db, $attkey, $id, $mode);
		}
	}

# set $filename before calling before_access & building note[]
# (in a next version $filename should be equal to the key value returned by insert() )
	$filename = ($bn_doc_type == "static") ? "$now.html" : "none";

# Set user_* profile variables
# ----------------------------
	if ( ($actiontype=='preview') && $is_authenticated) {
		reset($auth->user);
		while ( list($var, $val) = each($auth->user) ){
			$GLOBALS["user_$var"] = $val;
		}
		$userid = $auth->user['userid'];
	}

# Set summary (can be redefined into the before_access)
# -----------------------------------------------------
	$summary = get_summary (strip_magic_quotes($_POST['body']));

# Execute before_access program
# -----------------------------
	if (!empty($before_access)) include $before_access;

# reload note fields array with possibly modified values (from before_access)
# ---------------------------------------------------------------------------
	for (reset ($fields); $field=key($fields); next($fields)) {
		$fields[$field]=$$field;
	}

# If Preview or Apply mode then display the note ... 
# -------------------------------------------------
	switch ($actiontype) {
	 case 'upload':
	 case 'copy':
	 case 'delete':
	 case 'preview':
		display_header (LABEL_POST, $header_footer);
		if ($actiontype=='preview') {
			$viewkey = $attkey;
			unset($attachments); // set in viewnote.php
			include "$inc_dir/viewnote.$ext";
			print '<hr noshade>';	    
		}

#		... then display the form
#		-------------------------
		if (isset($_POST) ) {
			reset ($_POST);
			while ( list( $var, $val ) = each( $_POST)) {
				if (is_string ($var) && ($var != 'quoted_text') ) {
					$$var = kill_quotes(strip_magic_quotes($val));
				}
			}
		} else {
			reset ($fields);
			while ( list( $var, $val ) = each( $fields)) {
				if (is_string ($var)) {
					if ($bn_use_smileys && $bn_html_var[$var]) {
						$$var = strip_smileys($$var);
					}
					if ($bn_auto_url && $bn_html_var[$var]) {
						$$var = strip_url($$var);
					}
					if ($var != 'quoted_text') {
						$$var = kill_quotes($$var);					
					}
				}
			}
		}

		// restore password before sending the form (only for public (password protected) forums
		if ($forum["type"] == "pub") {
			$password = $userpw;
		}

		$setUserField = false;      // don't reset username and address
		$form_action = "insert.$ext";
		if ($back_form=='post') {
			$bn_action = (empty($key)) ? 'post' : 'reply';
		} elseif ($back_form=='view') {
			$bn_action = 'reply';
		} else {
			$bn_action = $back_form;
		}
		if (!isset($html_tags)) $html_tags=0;
		include "$inc_dir/form.$ext";
		display_footer ($header_footer);
		break;
	}

# ... Else: Insert into database
# ------------------------------
	if (empty($key) ) {
		$newkey = $db->insertNote ($bn_db, $now, $fields);
	} else {
		$old_note = $db->getNote ($bn_db, $key);
		if ($old_note["closed"]==1) {
			if ($is_moderator) {
				$fields["closed"] = 1;
			} else {
				display_header (TITLE_ERROR, $header_footer);
				msgForm (MSG_THREAD_IS_CLOSED, "view.$ext?bn=$bn&key=$key", "close");
				display_footer ($header_footer);
			}
		}
		$newkey = $db->threadNote ($bn_db, $now, $key, $fields);
	}

	if ($newkey < 0) {
		display_header (TITLE_ERROR, $header_footer);
		msgForm (sprintf(ERROR_DATABASE, $newkey), "$back", "back", "", "post");
		display_footer ($header_footer);
	} else {
		$thread = $fields["thread"];
	}

# Attach all temporary files that were previously uploaded (in preview mode)
# --------------------------------------------------------------------------
	$db->validateAttachments ($bn_db, $bn_dir_notes, $attkey, $newkey);

# write note to the HTML document
# -------------------------------
	if ($filename != "none") {
		$fd = @fopen ("$bn_dir_notes/$filename", "w+");
		if (!$fd) {
			$file="$bn_dir_notes/$filename";
			msgForm (sprintf (ERROR_CREATE_FILE, $file), "$back", "back", "", "post");
			/* we could remove note, but it still can be built from the database */
			display_footer ($header_footer);
		}
		if (isSet($body)) {
			$body = format_text($body);
		}
		$doc = str_replace('"', '\"', $bn_doc_var);
		eval ("\$tmp=stripSlashes(\"$doc\");");
		fputs ($fd, "$tmp");
		fclose ($fd);
	}

# (4.x) update users stats
# ------------------------
	if ($is_authenticated && !$hidden) {
		$ret = $db->updateUserStats($site, $bn, $userid, $now);
	}

# (4.1.3) add entry to the LOG
# ----------------------------
	if (!$bn_no_stats) {
		$db->addLogEntry ($bn, 'insert', $userid, $thread, $newkey, $ip);
	}

# start search indexation
# -----------------------
	if ($bn_search && ($bn_doc_type == "static") && ($bn_search_engine != "none") ) {
		include "$inc_dir/$bn_search_engine.$ext";
		$search->indexNotes();
	}

# subscribe user to this thread if required
# -----------------------------------------
	if ($mail_reply == 1) {
		$db->subscribeUser ($site, $bn_db, $useraddress, $thread);
	} else {
		$db->unSubscribeUser ($site, $bn_db, $useraddress, $thread);
	}

# Send mail to main moderator and subscribed users
# ------------------------------------------------------
	include "$inc_dir/mail.$ext";
	mail_note ($fields);

# Initialize success message (check moderated option)
# ---------------------------------------------------
	$thanks_msg .= sprintf(MSG_THANKS, $msg[0]);
	if ($hidden) {
		$thanks_msg .= str_replace('{FORUM}', $msg[1], str_replace('{MSG}', $msg[0], MSG_NEED_APPROVE));
	}

# set the next page to be displayed
# ---------------------------------
	if (empty($redirect_url) ) {
		if ($bn_post_return == "list") {
			$redirect_url = "list.$ext?bn=$bn";
		} elseif ($bn_post_return == "thread") {
			$redirect_url = "view.$ext?bn=$bn&key=$thread";
		} elseif ($hidden) {
			$redirect_url = "list.$ext?bn=$bn";
		} else {
			$redirect_url = "view.$ext?bn=$bn&key=$newkey";
		}
		if (!empty($folder)) {
			$redirect_url .= "&folder=$folder";
		}
		$redirect_url = "$bn_base_url/$redirect_url";	// HTTP 1.1 requires full URI
	}
	
# Display "thanks message" or redirect to the next page
# -----------------------------------------------------
	if ( ($bn_popup && $popup) || $hidden) {
		// We force the message to be displayed to be able to close the window
	    $bn_no_thanks_msg = 0;
	}

	if (!$bn_no_thanks_msg && !$no_thanks_msg) {
		display_header (LABEL_POST, $header_footer);
		msgForm ($thanks_msg, $redirect_url, "close");
		display_footer ($header_footer);
	} else {
		if (!@header ("Location: $redirect_url")) {
			display_header (LABEL_POST, $header_footer);
			msgForm ($thanks_msg, $redirect_url, "close");
			display_footer ($header_footer);
		}
	}
?>