<?php

/*
 *	W-AGORA 4.0
 *	-----------
 *	$Id: admin_notes.php,v 1.23 2005/02/01 23:46:43 mdruilhe Exp $
 *	Usage:		Delete /edit individual note(s) in forum
 *	Author:		Marc Druilhe <mdruilhe@w-agora.com>
 */

require	("init_admin.inc");
require	("$cfg_file");

function getForumInfo ($forum) {
	global $cfg_dir, $ext, $db;
	global $dest_db, $dest_dir_notes;

	include ("$cfg_dir/$forum.$ext");
	$dest_dir_notes = $bn_dir_notes;

	$dest_forum = $db->getForum($GLOBALS["site"], $forum);
	$dest_db = $dest_forum["bn_db"];
}


$h_state = (isset($h_state))? $h_state : "all";

# include messages
# ----------------
	if (!empty($bn_msgs) && file_exists ("$bn_dir/$bn_msgs") ) {
		include "$bn_dir/$bn_msgs";
	} elseif (file_exists ("$bn_dir_default/msgs.$ext") ) {
		include ("$bn_dir_default/msgs.$ext");
	}

# fields definition
# -----------------
	if (!empty($bn_fields) && file_exists ("$bn_dir/$bn_fields") ) {
		include "$bn_dir/$bn_fields";
	} elseif (file_exists ("$bn_dir_default/fields.$ext") ) {
		include ("$bn_dir_default/fields.$ext");
	}

# Set core variables (managed by w-agora)
# this code is here for compatibility w/ old fields def. files (bn_var is reset)
# ------------------------------------------------------------------------------
	if (isset ($bn_var)) {
		unset ($bn_var);
	}
	$bn_var = array (
		"unixdate",		// timestamp (creation date)
		"userid",		// user ID
		"password",		// MD5 encoded password
		"filename",		// name of HTML note
		"mail_reply",	// set to "1" if replies to this note must be sent by email
		"hidden",		// set to 1 if note must be approved by the moderator
		"hits",			// hits count
		"closed",		// closed thread (RFU)
		"ip"			// logged IP address of sender
	);

# force w-agora variables to be listed
# ------------------------------------
	reset ($bn_var);
	while ( list(, $var) = each($bn_var) ) {
		$list_var[$var] = 1;
	}

# listing outline
# ---------------
/*
	if (!empty($bn_list_vars) && file_exists ("$bn_dir/$bn_list_vars") ) {
		include "$bn_dir/$bn_list_vars";
	} elseif (file_exists ("$bn_dir_default/list.$ext") ) {
		include ("$bn_dir_default/list.$ext");
	}
*/
# redefine listing
# ----------------
	if (empty($bn_delete_even_first_line) ) { // even first line should not be empty if defined
		$list_var["username"] = 1;
		$list_var["subject"] = 1;

		$bn_maxthreads = 10;
		$bn_depth_limit = 6;

		$bn_pad = "&nbsp;&nbsp;&nbsp;&nbsp;";
		$bn_delete_header = "<table cellspacing=\"0\" width=\"100%\">";
		$bn_before_line = '
if($hidden==1) {
	$hide_text = COLUMN_SHOW_NOTE;
	$hide_action = "show";
	$mouseover = "hidden_mouseover";
	$mouseout = "hidden_mouseout";
} else {
	$hide_action = "hide";
	if(empty($childs)) {
		$hide_text = COLUMN_HIDE_NOTE;
	}
	$mouseover = "mouseover";
	$mouseout = "mouseout";
}
		';

		$bn_delete_odd_first_line = "<tr class=\"\$mouseout\" onmouseout=\"changeclass(this,'\$mouseout')\" onmouseover=\"changeclass(this, '\$mouseover')\"><td class=\"s_label\">\$pad * <input type=\"checkbox\" name=\"keys[]\" value=\"\$key\"> <i>\$formated_date</i>&nbsp;&nbsp;<a href='view.$ext?site=$site&bn=$bn&key=\$key' target='view'><img src='\$icon_dir/popup.gif' border=0 align=absmiddle alt='" . ALT_POPUP . "'>&nbsp;\$subject</a></td><td width=150 class=s_label nowrap>&nbsp; \$username </td><td width=130 class=s_label nowrap><a href='$WA_SELF?bn=$bn&keys[0]=\$key&action=confirm_delete&first=$first&h_state=$h_state'><img src='\$icon_dir/delete.gif' align=absmiddle border=0 alt='" . ALT_DELETE_NOTE	. "'></a>&nbsp;&nbsp;&nbsp;<a href='$WA_SELF?bn=$bn&key=\$key&action=edit&h_state=$h_state&first=$first'><img src='\$icon_dir/edit.gif' align=absmiddle border=0 alt='" . ALT_EDIT_NOTE . "'></a>&nbsp;&nbsp;|&nbsp; <a href='$WA_SELF?bn=$bn&key=\$key&action=\$hide_action&h_state=$h_state&first=$first'>\$hide_text</a> </td></tr>";
		$bn_delete_even_first_line = $bn_delete_odd_first_line;
		$bn_delete_begin_level = "";
		$bn_delete_odd_line = $bn_delete_odd_first_line;
		$bn_delete_even_line = $bn_delete_odd_first_line;
		$bn_delete_end_level = "";
		$bn_delete_end_thread = "";
		$bn_delete_footer = "</table>";
	}

# Note template
# -------------
	if (!empty($bn_template) && file_exists ("$bn_dir/$bn_template") ) {
		include "$bn_dir/$bn_template";
	} elseif (file_exists ("$bn_dir_default/template.$ext") ) {
		include ("$bn_dir_default/template.$ext");
	}

	$this_forum = $db->getForum($site, $bn);
	$bn_db = $this_forum["bn_db"];
	$totalthreads = $this_forum["totalthreads"];
	$totalnotes = $this_forum["totalnotes"];

	switch ($action) {

		case "search":
			if (!empty($pattern) ) {
				$where="subject like '%$pattern%' or body like '%pattern%'";
			}
		break;

		case "show":
		case "hide":
			$key = $HTTP_GET_VARS['key'];
			$note = $db->getNote ($bn_db, $key);
			if ($note < 0) {
				die (sprintf(ERROR_NOTE_NOT_FOUND, $msg[0]));
			}
			$hide = ($action=="show") ? 0 : 1;
			$values = array ("hidden"=>$hide);
			$ret = $db->updateTable ($bn_db, $values, "cle=$key");
			if ($ret==0) {
				$db->updateNewest ($bn_db, $note["thread"]);
				$db->updateForumStats ($site, $bn_db);
				// If the note has been switched from hidden to shown then send an email to the list
				if ($action=="show") {
					if ($note['userid'] != 'guest') {
						$db->updateUserStats($site, $bn, $note['userid'], $note['unixdate']);					
					}
					$note['hidden'] = 0;
					include "$inc_dir/mail.$ext";
					mail_note ($note);
				}
			}
		break;

		case "confirm_delete":
			display_header (TITLE_DELETE_NOTES);

			$count = Count ($keys);

			if ($count < 1) {
				MsgForm (CAPTION_SELECT_NOTES, "$WA_SELF?site=$site&bn=$bn&first=$first&last=$last&h_state=$h_state", LABEL_BACK);
				display_footer();
			}

			beginForm();
			hiddenField ("action", "dodelete");
			hiddenField ("first", $first);
			hiddenField ("last", $last);
			hiddenField ("h_state", $h_state);
			echo "&nbsp;&nbsp<b>" . LABEL_DELETE_FOL_NOTES . "</b> :<br>";
			echo "<table cellpadding=10><tr><td>";
			for ($i=0; $i < $count; $i++) {
				$j = $i + 1;
				$note = $db->getNote($bn, $keys[$i]);
				echo "<INPUT TYPE='hidden' NAME=keys[$i] VALUE='$keys[$i]'>";
				echo " * <b>$j - </b><font color=red><i>[" . $note['subject'] . "]</i></font><br><span class=s_label><font	color=#999999>" . $note['summary'] . "</font></span><br>";
			}
			echo "</td></tr></table>";
			echo "<CENTER>";
			submitButton ("submit", LABEL_CONFIRM);
			backButton ("back", BUTTON_CANCEL );
			?></CENTER><?
			endForm();
			?></body></html><?
			exit;
		break;

		case "confirm_copy":
			display_header (TITLE_COPY_NOTES);

			$count = Count ($keys);

			if ($count < 1) {
				MsgForm (CAPTION_SELECT_NOTES, "$WA_SELF?site=$site&bn=$bn&first=$first&last=$last&h_state=$h_state", LABEL_BACK);
				display_footer();
			}

			beginForm();
			hiddenField ("action", "copy");
			hiddenField ("first", $first);
			hiddenField ("last", $last);
			hiddenField ("h_state", $h_state);
			hiddenField ("dest_forum", "$dest_forum");
			if (isset($movemessages) ) hiddenField ("movemessages", "1");

			echo "&nbsp;&nbsp<b>" . LABEL_COPY_FOL_NOTES . "</b> :<br>";
			echo "<table cellpadding=10><tr><td>";
			foreach ($keys as $key) {
				$note = $db->getNote($bn, $key);
				if (!$note["parent"] || !in_array($note["parent"],$keys)) { // Shows only parent notes
					echo "<INPUT TYPE='hidden' NAME=keys[] VALUE='$key'>";
					echo "<b> - </b><font color=red><i>[" . $note['subject'] . "]</i></font><br><span class=s_label><font	color=#999999>" . $note['summary'] . "</font></span><br>";
				}
			}
			echo "</td></tr></table>";
			echo "<CENTER>";

			table_header (LABEL_SELECT_DEST_THREAD);

			require_once ("$cfg_dir/$dest_forum.$ext");

			// NOTE: Only copying between forums in the same db is allowed.

			// For future implementation of multiple db, here's the code for connecting to another db:
			/*require_once ("$inc_dir/$bn_access.$ext");
			$db_class = "${bn_access}_access";
			$db = new $db_class;
			$ret = $db->openDB($dbhost, $dbport, $dbadmuser, $dbadmpassword, $dbname, $site);
			if ($ret != 0) {
				include "$site_cfg_file";
				include "$bn_dir/$bn_msgs";
				MsgForm (sprintf(ERROR_DATABASE, $ret), "$WA_SELF?site=$site", "");
				display_footer();
			}*/

			$expnd="all";
			$bn_maxthreads = 10;
			$bn_depth_limit = 6;

			$threads_order = "thread DESC";
			$ret = $db->listThreads ($dest_forum, $newfirst, $newlast, "", 1, $bn_maxthreads,true);
			if (!is_array ($ret) || ($ret < 0)) {
				msgWarning (sprintf(ERROR_DATABASE, $ret));
				display_footer();
			}

			if ($ret["total"] == 0) {
				msgWarning (sprintf(ERROR_NO_ENTRY_FOUND, $msg[0]));
				display_footer();
			}

			$newlast= $ret["last"]; hiddenField ("newlast", $newlast);
			$newfirst = $ret["first"]; hiddenField ("newfirst", $newfirst);
			$prev = (isset($ret["prev"])) ? $ret["prev"] : 0;
			$next = (isset($ret["next"])) ? $ret["next"] : 0;

			$bn_pad = "&nbsp; &nbsp; &nbsp;";
			$bn_copy_header = "";
			$bn_before_line = '
$hide_text = ($hidden==1) ? COLUMN_SHOW_NOTE : COLUMN_HIDE_NOTE;
$hide_action = ($hidden==1) ? "show" : "hide";
$mouseover = ($hidden==1) ? "hidden_mouseover" : "mouseover";
$mouseout = ($hidden==1) ? "hidden_mouseout" : "mouseout";
			';

			$bn_copy_odd_first_line = "<tr class=\"\$mouseout\" onmouseout=\"changeclass(this,'\$mouseout')\" onmouseover=\"changeclass(this, '\$mouseover')\"><td class=\"s_label\"><input type=\"radio\" name=\"destkey\" VALUE=\"\$key\">\$pad<a href='view.$ext?site=$site&bn=$bn&key=\$key' target='view'><img src='\$icon_dir/popup.gif' border=0 align=absmiddle alt='" . ALT_POPUP . "'>&nbsp;\$subject</a> &nbsp;(<i>\$username</i>)</td><td class=s_label nowrap><i>\$formated_date</i></td></tr>";
			$bn_copy_even_first_line = $bn_copy_odd_first_line;
			$bn_copy_begin_level = "";
			$bn_copy_odd_line = $bn_copy_odd_first_line;
			$bn_copy_even_line = $bn_copy_odd_first_line;
			$bn_copy_end_level = "";
			$bn_copy_end_thread = "";
			$bn_copy_footer = "";

			echo "<table cellspacing=\"0\" width=\"100%\">\n";
			echo "<tr class=\"mouseout\" onmouseout=\"changeclass(this,'mouseout')\" onmouseover=\"changeclass(this,'mouseover')\"><td class=s_label><input type=\"radio\" name=\"destkey\" value=\"0\"><i> (".OPEN_NEW_THREAD.")</i></td><td class=\"s_label\" nowrap=\"nowrap\"></td></tr>\n";
			$db->displayList (0, "copy");
			echo "</table>\n";

			if ($prev || $next) {
				echo "<HR><CENTER><TABLE><TR><TD width='100' align=center>&nbsp;";
				if ($prev) {
					echo "<input type='submit' onclick=\"document.all['action'].value='confirm_copy'; document.all['newlast'].value=$newfirst; document.all['newfirst'].value=''\" value=\"".LABEL_PREV_PAGE."\">";
				}
				echo "</TD><TD width='100' align=center>&nbsp;";
				if ($next) {
					echo "<input type='submit' onclick=\"document.all['action'].value='confirm_copy'; document.all['newfirst'].value=$newlast; document.all['newlast'].value=''\" value=\"".LABEL_NEXT_PAGE."\">";
				}
				echo "</TD></TR></TABLE></CENTER>\n";
			}

			echo "&nbsp;<br>\n";
			submitButton ("submit", LABEL_CONFIRM);
			echo "<input type=\"button\" value=\"".BUTTON_CANCEL."\" onclick=\"location='$WA_SELF?site=$site&bn=$bn&first=$first&last=$last&h_state=$h_state'\">";
			?></CENTER><?
			endForm();
			?></body></html><?
			exit;
		break;

		case "copy":
			if (!is_array ($keys) ) {
				msgWarning (ERROR_NO_THREAD);
				break;
			}
			if (!isset($dest_forum) ) {
				msgWarning (ERROR_NO_DEST_FORUM);
				break;
			}
			getForumInfo($dest_forum);

			reset ($db_var);
			while ( list(, $var) = each($db_var) ) {
				$list_var[$var] = 1;
			}

			echo "&nbsp;&nbsp<b>" . str_replace("{FORUM}",$dest_forum, LABEL_COPYING_NOTES) . "</b>";
			// For each note selected :
			// --------------------------
			reset ($keys);
			while (list (, $key) = each ($keys) ) {

				$ret = $db->copyNote ($bn_db, $key, $bn_dir_notes, $dest_db, $destkey, $dest_dir_notes);
				if ($ret < 0) {
					msgWarning (str_replace("{FORUM}",$bn, str_replace("{NOTE}", $key, ERROR_COPY_NOTE)));
				}
				if ( isset($movemessages) && ($ret == 0 ) ) {
					$notes=array_keys($db->all_replies);
					$ret = $db->mDeleteNotes ($bn_db, $notes, $bn_dir_notes);
				}

				if ($ret < 0) {
					msgWarning (str_replace("{FORUM}",$bn, str_replace("{NOTE}", $key, ERROR_DELETE_NOTE)));
				}
			}
		break;

		case "dodelete":
			if (!isset($keys)&&!empty($key)) {
				$keys[0] = $key;
			}
			$count = Count ($keys);
			if ($count <1) {
				MsgForm (CAPTION_SELECT_NOTES, "$WA_SELF?site=$site", LABEL_BACK);
				display_footer();
			}

			// Execute before_access program
			$bn_action="delete";
			if (!empty($bn_before_access)) {
				if (file_exists ("$bn_dir/$bn_before_access") ) {
					include "$bn_dir/$bn_before_access";
				} else {
					include "$bn_dir_default/$bn_before_access";
				}
			} elseif (file_exists ("$bn_dir_default/before_access.$ext") ) {
				include ("$bn_dir_default/before_access.$ext");
			}

			// delete selected notes
			$ret = $db->mDeleteNotes ($bn_db, $keys, $bn_dir_notes);
			if ($ret < 0) {
				MsgForm (sprintf(ERROR_DATABASE, $ret), "$WA_SELF", LABEL_BACK);
				display_footer();
			}

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

		case "edit":
			$redirect_url = "admin_notes.$ext?site=$site&bn=$bn&first=$first&last=$last&h_state=$h_state";

			$no_thanks_msg = 1;
			$bn_action = "edit";

			if (!empty($bn_style)) {
				if (file_exists ("$bn_dir/$bn_style") ) {
					include "$bn_dir/$bn_style";
				} else {
					include "$bn_dir_default/$bn_style";
				}
			} elseif (file_exists ("$bn_dir_default/style.$ext") ) {
				include ("$bn_dir_default/style.$ext");
			}
			echo "<br>&nbsp;&nbsp;" . LABEL_EDIT_NOTE . "<br><br>";
			echo "<center>";
			$form_title = TITLE_EDIT_FORM;
			$note = $db->getNote($bn,$key);

			while ( list( $var, $val ) = each( $note)) {
				if (is_string ($var)) {
					if ($bn_html_var[$var]) {
						if ($bn_use_smileys) {
							$val = strip_smileys($val);
						}
						if ($bn_auto_url) {
							$val = strip_url($val);
						}
					}
					$$var = kill_quotes(stripSlashes($val));
				}
			}
			// DELETE
			$delete_url = "";
			if ($bn_delete) {
				$delete_url = "delete.$ext?bn=$bn&key=$key&first=$first&last=$last&sort=$sort&where=$where&expnd=$thread";
				$delete_text = LABEL_DELETE_MESSAGE;
				$delete_link = anchor ($delete_url, "", $delete_text, LABEL_DELETE_THIS_MESSAGE);
			}

			// CLOSE
			$close_url = "";
			if ($is_moderator) {
				$close_url = "close.$ext?bn=$bn&key=$key&first=$first&last=$last&sort=$sort&where=$where&expnd=$thread";
				$close_text = LABEL_CLOSE_OPEN_THREAD;
				$close_link = anchor ($close_url, "", $close_text);
			}

		# Execute before_access program
		# -----------------------------
			if (!empty($bn_before_access)) {
				if (file_exists ("$bn_dir/$bn_before_access") ) {
					include "$bn_dir/$bn_before_access";
				} else {
					include "$bn_dir_default/$bn_before_access";
				}
			} elseif (file_exists ("$bn_dir_default/before_access.$ext") ) {
				include ("$bn_dir_default/before_access.$ext");
			}

		# Display form
		# ------------
			$setUserField = false;		// Don't set username and password from cookies, get it from the note
			$form_action = "update.$ext";
			$back_form="admin_notes";

			include "$inc_dir/form.$ext";

			echo "</center></body></html>";
			exit;
		break;


	case "post":
			$redirect_url = "admin_notes.$ext?site=$site&bn=$bn&first=$first&last=$last&h_state=$h_state";

			$no_thanks_msg = 1;
			$bn_action = "post";

			$username = $auth->user['username'];
			$useraddress = $auth->user['useraddress'];

			if (!empty($bn_style)) {
				if (file_exists ("$bn_dir/$bn_style") ) {
					include "$bn_dir/$bn_style";
				} else {
					include "$bn_dir_default/$bn_style";
				}
			} elseif (file_exists ("$bn_dir_default/style.$ext") ) {
				include ("$bn_dir_default/style.$ext");
			}
			echo "<center>";
			$form_title = TITLE_POST_FORM;

		# Execute before_access program
		# -----------------------------
			if (!empty($bn_before_access)) {
				if (file_exists ("$bn_dir/$bn_before_access") ) {
					include "$bn_dir/$bn_before_access";
				} else {
					include "$bn_dir_default/$bn_before_access";
				}
			} elseif (file_exists ("$bn_dir_default/before_access.$ext") ) {
				include ("$bn_dir_default/before_access.$ext");
			}

		# Display form
		# ------------
			$setUserField = false;		// Don't set username and password from cookies, get it from the note
			$form_action = "insert.$ext";
			$back_form="admin_notes";
			echo '<br><br>';
			include "$inc_dir/form.$ext";

			echo "</center></body></html>";
			exit;
		break;
		default:
		break;

	}


# FORM has not been sent Displays notes list
# --------------------------------------------

	$expnd="all";
	display_header (LABEL_EDIT_NOTES);

	if(!empty($pattern) ) {
		$ret = $db->listNotes ($bn_db, $first, $last, "unixdate desc", $where, 0);
	} elseif($h_state== "all") {
		$threads_order = "thread DESC";
		$ret = $db->listThreads ($bn_db, $first, $last, "", 1, $bn_maxthreads, true);
	} else {
		$where = "hidden = $h_state";
		$bn_maxnotes = 20;
		$ret = $db->listNotes ($bn_db, $first, $last, "unixdate desc", $where, $bn_maxnotes);
	}

	if (!is_array ($ret) || ($ret < 0)) {
		msgWarning (sprintf(ERROR_DATABASE, $ret));
		display_footer();
	}

	$states = array (
		"all" => LABEL_ALL_NOTES,
		"1" => LABEL_HIDDEN,
		"0" => LABEL_VISIBLE
	);

	beginForm();
	hiddenField ("action", "search");
	echo "<center>" . LABEL_SEARCH_IN_FORUM. " : " . getTextField("pattern", "") . "&nbsp;" . getSubmitButton("submit", LABEL_SEARCH) . "</center><br>";
	endForm();

	$list_box = getListBox("h_state", $states, $h_state, 0, "window.location=('$WA_SELF?bn=$bn&site=$site&h_state='+this.options[this.selectedIndex].value)");
	$sub_button = getSubmitButton("submit", LABEL_SHOW);
	beginForm();
	echo "<center>" . LABEL_DISPLAY_NOTES . ": $list_box &nbsp; $sub_button </center><br>";
	endForm();

	table_header (sprintf(LABEL_NOTES_IN_FORUM, $bn));
	beginForm();
	$last= $ret["last"];
	$first = $ret["first"];

	hiddenField ("h_state", $h_state);
	hiddenField ("first", $first);
	hiddenField ("last", $last);

	$total_items = (empty($ret['totalthreads'])) ? $ret['total'] : $ret['totalthreads'];
	print '<div align="right">' . getNavBar("$WA_SELF?bn=$bn&h_state=$h_state", $total_items, $first, $bn_maxthreads);
	echo "</div><hr noshade>";

	if ($ret['total'] == 0) {
		msgWarning (sprintf(ERROR_NO_ENTRY_FOUND, $msg[0]).'<br/>');
	} else {
		$db->displayList (0, 'delete');	
	}


	if (!isset($ret["prev"])) $ret["prev"] = 0;
	if (!isset($ret["next"])) $ret["next"] = 0;

	echo "<hr noshade><TABLE width=100%><TR><td align=\"center\">";
	resetButton ("reset", LABEL_UNSELECT );
	echo "</TD><TD align=\"right\" nowrap=\"nowrap\">";

	print getNavBar("$WA_SELF?bn=$bn&h_state=$h_state", $total_items, $first, $bn_maxthreads);

	echo "</TD></TR></TABLE>\n";

# Now check if other availables forums in this site for which the moderator is responsible
# ----------------------------------------------------------------------------------------
	if ($auth->level > MODER) {
		$dest_forums =  $db->getForums($site, "", "", 0);
	} else {
		$dest_forums =  $db->getForums($site, $auth->userid, "", 0);
	}

	$db->closeDB();

	echo "<br><font size='+1'><B>" . LABEL_SELECT_ACTION . "</B></font>";
	echo "<br><li> ";
	radioButton ("action", "confirm_delete", "confirm_delete", ACTION_MESSAGES_DELETE);
	echo "<li>";
	radioButton ("action", "confirm_copy", "", ACTION_MESSAGES_COPY);
	listBox ("dest_forum", $dest_forums, "$bn");
	echo "&nbsp;&nbsp;";
	checkBox ("movemessages", "1", $move, ACTION_MESSAGES_MOVE);

	echo "<br><CENTER>";
	submitButton ("", LABEL_EXECUTE);
	echo "</CENTER>";
	endForm();
	table_footer ();
?>
</BODY>
</HTML>
