<?php
/******************************************************************************
* VisualWarning.php                                                           *
*******************************************************************************
* SMF: Simple Machines Forum - MOD                                            *
* =========================================================================== *
* Software Version:           1.0	                                      *
* Software by:                Matthew Wolf (a.k.a Grudge)		      *
* Updates:  http://www.simplemachines.org 		                      *
*******************************************************************************
* This program is free software; you may redistribute it and/or modify it     *
* under the terms of the provided license as published by Lewis Media.        *
*                                                                             *
* This program is distributed in the hope that it is and will be useful,      *
* but WITHOUT ANY WARRANTIES; without even any implied warranty of            *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                        *
*                                                                             *
* See the "license.txt" file for details of the Simple Machines license.      *
* The latest version can always be found at http://www.simplemachines.org.    *
******************************************************************************/

if (!defined('SMF'))
	die('Hacking attempt...');
	
include_once($sourcedir . '/Subs-Post.php');

function AddWarning()
{
	global $context, $scripturl, $db_prefix, $modSettings, $user_info, $sourcedir;
	global $ID_MEMBER, $txt, $topic, $enable_ubbc;
	
	loadTemplate('VisualWarning');
	$context['sub_template'] = 'add_warning';
	$context['page_title'] = $txt['visual_raise'];
	
	// Permission
	isAllowedTo('visual_warn_any');
	
	if (!isset($_REQUEST['user']))
		fatal_error("hacker");
	// Important
	$context['topic'] = $topic;
	$context['back'] = isset($_REQUEST['back']) ? $_REQUEST['back'] : -1;
	$context['memberID'] = $_REQUEST['user'];
	$context['msg'] = isset($_REQUEST['msg']) ? $_REQUEST['msg'] : -1;
	$context['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : -1;
	
	$request = db_query("
			SELECT ID_GROUP
			FROM {$db_prefix}members
			WHERE ID_MEMBER='$_REQUEST[user]' LIMIT 1", __FILE__, __LINE__);
	$row = mysql_fetch_assoc($request);
	if ($row['ID_GROUP']== 1)
		fatal_error("You CANNOT warn admins/mods");
	$request = db_query("
			SELECT ID, memberID, warningText, messageID, time, level 
			FROM {$db_prefix}vwarnings 
			WHERE MemberID='$_REQUEST[user]' LIMIT 1", __FILE__, __LINE__);
	$row = mysql_fetch_assoc($request);
	
	if($row){
		$request = db_query("
				SELECT body
				FROM {$db_prefix}messages
				WHERE ID_MSG = $context[msg] LIMIT 1", __FILE__, __LINE__);
		$message = mysql_fetch_assoc($request);

		if ($enable_ubbc)
			$message['body'] = doUBBC($message['body']);
		$context['previous'] = array(
			'warnid' => $row['ID'],
			'body' => $message['body'],
			'level' => $row['level'],
			'time' => timeformat($row['time']),
			'warningtext' => $row['warningText'],
		);
	}
	obExit();
}


function AddWarning2()
{
	global $scripturl, $db_prefix, $settings, $modSettings, $txt, $sourcedir, $forum_version;

	// Permission
	isAllowedTo('visual_warn_any');

	// Load the language file for sendpm.
	loadLanguage('InstantMessage');

	if ($_REQUEST['timelast'] == "")
		$_REQUEST['timelast'] = -1;

	$_REQUEST['level'] = isset($_REQUEST['level']) ? (int) $_REQUEST['level'] : 0;
	$_REQUEST['msg'] = isset($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : 0;
	$_REQUEST['user'] = isset($_REQUEST['user']) ? (int) $_REQUEST['user'] : 0;
	$_REQUEST['timelast'] = isset($_REQUEST['timelast']) ? (int) $_REQUEST['timelast'] : 0;

	// Sorry dude but admins only here
	if ($_REQUEST['level'] > 3)
		is_admin();

	// Sort out the message.
	$message = htmlspecialchars($_REQUEST['warningmsg'], ENT_QUOTES);
	preparsecode($message);
	
	$request = db_query("
			SELECT ID_MEMBER, memberName, warning, emailAddress
			FROM {$db_prefix}members
			WHERE ID_MEMBER = $_REQUEST[user] LIMIT 1", __FILE__, __LINE__);
	$member = mysql_fetch_assoc($request);
	if ($_REQUEST['msg'] != -1){
		$request = db_query("
				SELECT body
				FROM {$db_prefix}messages
				WHERE ID_MSG = $_REQUEST[msg] LIMIT 1", __FILE__, __LINE__);
		list($body) = mysql_fetch_row($request);
	}
	else
		$body = '';
	// Make the warnings things look pretty
	if ($_REQUEST['msg'] != -1 && $body != '' && $_REQUEST['level'] > 0 && $_REQUEST['level'] < 5){
		if ($_REQUEST['level'] == 1){
			$warn = 'warn';
		}
		elseif ($_REQUEST['level'] == 2){
			$warn = 'mute';
		}
		else {
			$warn = 'ban';
		}
		$body .= "\n[center]"
		 . ($modSettings['visualw_image_' . $warn] != "" ? 
		 '[img]' . $settings['images_url'] . '/' . $modSettings['visualw_image_' . $warn] . '[/img]' 
		 : '') 
		 . ($modSettings['visualw_color_' . $warn] != "" ? 
		 '&nbsp;' . $message 
		 : '') . '[/center]';
		// Update the message
		db_query("
			UPDATE {$db_prefix}messages
			SET body = '$body'
			WHERE ID_MSG = $_REQUEST[msg]", __FILE__, __LINE__);
	}
	// firstly update the user profile for the new warning
	db_query("
		UPDATE {$db_prefix}members
		SET warning = $_REQUEST[level]
		WHERE ID_MEMBER = $_REQUEST[user]", __FILE__, __LINE__);
	// Now if the warning has been changed to zero - delete the members entry in the warning table
	if ($_REQUEST['level'] == 0)
	{
		$_REQUEST['warnid'] = (int) $_REQUEST['warnid'];
		if ($_REQUEST['warnid'] != -1)
		db_query("
			DELETE FROM {$db_prefix}vwarnings
			WHERE ID = $_REQUEST[warnid] LIMIT 1", __FILE__, __LINE__);
	}
	else{
		if ($_REQUEST['level'] == 3){
			is_admin();
			// Ban this user! (Modifications for SMF 1.1 by Permutations)
			$ban_time = time();
			$expire_time = ( $_REQUEST['timelast'] != -1 ) ? ( time() + 24 * 60 * 60 * (int) $_REQUEST['timelast'] ) : 'NULL';
			$the_version = strtr($forum_version, array('SMF ' => ''));
			$major_version = substr( $the_version, 0, 3 );		
			if ( $major_version == '1.1' ) {
				// each user banned by Visual Warning is in a separate group so notes can be added for each individual
				$ban_group_name = 'VW_'.$_REQUEST['user'];
				db_query("
					INSERT INTO {$db_prefix}ban_groups (name, ban_time, expire_time, cannot_access, reason, notes)
					VALUES ('$ban_group_name', $ban_time, $expire_time, 1, '$message', '$txt[visual_warning_management]')", __FILE__, __LINE__);
				$id_ban_group = db_insert_id();
				db_query("
					INSERT INTO {$db_prefix}ban_items (ID_BAN_GROUP, ID_MEMBER)
					VALUES ($id_ban_group, $_REQUEST[user])", __FILE__, __LINE__);
			}
			elseif ( $major_version == '1.0' ) {		
				db_query("
					INSERT INTO {$db_prefix}banned (ID_MEMBER, ban_type, reason, notes, restriction_type, ban_time, expire_time)
					VALUES ($_REQUEST[user], 'user_ban', '$message', '$txt[visual_warning_management]', 'full_ban', $ban_time, $expire_time)", __FILE__, __LINE__);
			}
		}			
		// for all the rest just update the table with the new details!
		elseif($_REQUEST['warnid'] == -1){
			$time=time();
			db_query("
				INSERT INTO {$db_prefix}vwarnings
				(memberID, messageID, warningText, time, level, timeToWarn, set_by)
				VALUES ($_REQUEST[user],$_REQUEST[msg],'$message',
				" . time() . ", $_REQUEST[level], $_REQUEST[timelast], '{$user_info['user_name']}')",__FILE__, __LINE__);
		}
		else{
			db_query("
				UPDATE {$db_prefix}vwarnings
				SET time = " . time() . ", level=$_REQUEST[level], messageID=$_REQUEST[msg],
				warningText='$message', timeToWarn=$_REQUEST[timelast]
				WHERE ID=$_REQUEST[warnid]", __FILE__, __LINE__);
		}
	}
	// Send user warning IM
	if($member['warning'] != $_REQUEST['level']){
		$imsubject = $member['warning'] > $_REQUEST['level'] ? $txt['visual_reduced'] : $txt['visual_official_warning'];
#		$immessage = $member['memberName'] . "\n\n";
		$immessage = "";
		if($member['warning'] < $_REQUEST['level']){
			if ($_REQUEST['msg'] != -1 && $_REQUEST['topic'] != -1) {
				$immessage .= $txt['visual_received_warning'] . 
					"\n\n $scripturl?topic=$_REQUEST[topic].msg$_REQUEST[msg]#msg$_REQUEST[msg]\n\n";
				$immessage .= "[quote]".$body."[/quote]";
			}
			else
				$immessage .= $txt['visual_warning_increased'];
		}
		else
			$immessage .= $txt['visual_warning_reduced'];
		$recs = array(
			'to' => array($member['ID_MEMBER']),
			'bcc' => array()
		);
		sendpm($recs, $imsubject, $immessage, 0);
	}
	if ($_REQUEST['back'] != -1)
		redirectexit("$scripturl?action=$back");
	elseif ($_REQUEST['msg'] != -1 && $_REQUEST['topic'] != -1)
		redirectexit("topic=$_REQUEST[topic].msg$_REQUEST[msg]#msg$_REQUEST[msg]");
	else
		redirectexit();
}

function ListWarnings()
{
	
	global $scripturl, $db_prefix, $settings, $modSettings, $ID_MEMBER, $txt, $context;

	loadTemplate('VisualWarning');
	$context['sub_template'] = 'list_warnings';
	$context['page_title'] = $txt['visual_warning_management'];
	
	adminIndex('warning_manager');
	
	// Permission
	isAllowedTo('visual_warn_any');
	
	$request = db_query("
		SELECT w.ID, w.memberID, w.warningText, w.time, w.level, m.memberName, m.realName
		FROM {$db_prefix}vwarnings as w
			LEFT JOIN {$db_prefix}members as m ON (m.ID_MEMBER = w.memberID)
		WHERE w.level > 0 AND w.level < 3
		ORDER BY w.time", __FILE__, __LINE__);

	$context['warnings'] = array();
	$warnText = array(
		1 => 'warn',
		2 => 'mute'
	);
	while ($row = mysql_fetch_assoc($request))
	{
		$context['warnings'][] = array(
			'memberID' => $row['memberID'],
			'time' => timeformat($row['time']),
			'memberName' => $row['memberName'],
			'realName' => $row['realName'],
			'level' => $txt['visual_text_' . $warnText[$row['level']]],
			'warningText' => $row['warningText']
		);
	}
	obExit();
}


function ListWarnings2(){
	global $scripturl, $db_prefix, $settings, $modSettings, $txt;

	// Permission
	isAllowedTo('visual_warn_any');
	
	if (empty($_REQUEST['lower']))
		$_REQUEST['lower'] = array();

	foreach ($_REQUEST['lower'] as $id => $dummy)
	{
		$id = (int) $id;
		db_query("
			UPDATE {$db_prefix}members
			SET warning = warning - 1
			WHERE ID_MEMBER = $id AND warning > 0", __FILE__, __LINE__);
		$request = db_query("
			SELECT level FROM
			{$db_prefix}vwarnings
			WHERE memberID = $id LIMIT 1", __FILE__, __LINE__);
		list($level) = mysql_fetch_row($request);
		if ($level == 1)
			db_query("
				DELETE FROM
				{$db_prefix}vwarnings
				WHERE memberID = $id", __FILE__, __LINE__);
		else
			db_query("
				UPDATE {$db_prefix}vwarnings
				SET level = level - 1, timeToWarn = -1
				WHERE memberID = $id", __FILE__, __LINE__);
	}
	redirectexit("action=warnlist");
}

function Manager(){
	
	global $scripturl, $db_prefix, $settings, $modSettings, $enable_ubbc, $txt, $context, $sourcedir;
	
	$context['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	$display=40;

	// Permissions
	isAllowedTo('visual_approve_any');
	
	loadTemplate('VisualWarning');
	$context['sub_template'] = 'pmod_manager';
	$context['page_title'] = $txt['visual_postmod_manager'];
	
	adminIndex('postmod_manager');
		
	$request = db_query("
		SELECT p.ID, p.ID_MEMBER, p.ID_POLL, p.subject, p.body,
			m.realName, m.memberName
		FROM {$db_prefix}postmoderation as p
			LEFT JOIN {$db_prefix}members as m ON (m.ID_MEMBER = p.ID_MEMBER)
		ORDER BY p.posterTime
		LIMIT $context[start], $display", __FILE__, __LINE__);
	$numrows = mysql_num_rows($request);
	$context['posts'] = array();
	while ($row = mysql_fetch_assoc($request))
	{
		preparsecode($row['body']);
		if ($enable_ubbc)
			$row['body'] = doUBBC($row['body']);
		$context['posts'][] = array(
			'ID' => $row['ID'],
			'ID_POLL'=> $row['ID_POLL'],
			'ID_MEMBER' => $row['ID_MEMBER'],
			'subject' => $row['subject'],
			'body' => $row['body'],
			'realName' => $row['realName'],
			'memberName' => $row['memberName']
		);
	}
	$context['pageIndex'] = constructPageIndex("$scripturl?action=warnpmman", $context['start'], $numrows, $display);
	obExit();
}

function Manager2(){
	global $scripturl, $db_prefix, $settings, $modSettings, $sourcedir, $txt;

	// Permissions
	isAllowedTo('visual_approve_any');

	if (empty($_REQUEST['message']))
		$_REQUEST['message'] = array();

	foreach ($_REQUEST['message'] as $id => $dummy)
	{
		$id = (int) $id;
		$request = db_query("
				SELECT ID, ID_MEMBER, ID_BOARD, ID_POLL, ID_TOPIC, subject, posterName,
				posterEmail, posterTime, posterIP, body, icon, smiliesEnabled
				FROM {$db_prefix}postmoderation
				WHERE ID = $id LIMIT 1", __FILE__, __LINE__);
		$row = mysql_fetch_assoc($request);
		// Due to current sorting methods only this will work! :(
		$row['posterTime'] = time();
		if($txt['visual_postmod_approve'] == $_REQUEST['waction'])
		{  //approve
			$time=time();
			$row['body'] = addslashes($row['body']);
			$row['subject'] = addslashes($row['subject']);
			// Insert the post.
			db_query("
				INSERT INTO {$db_prefix}messages
					(ID_BOARD, ID_TOPIC, ID_MEMBER, subject, posterName, posterEmail, posterTime,
                               		posterIP, smileysEnabled, body, icon)
				VALUES ($row[ID_BOARD], $row[ID_TOPIC], $row[ID_MEMBER], '$row[subject]', '$row[posterName]', '$row[posterEmail]',
				'$row[posterTime]','$row[posterIP]', '$row[smiliesEnabled]', '$row[body]',
				'$row[icon]')", __FILE__, __LINE__);
				$ID_MSG = mysql_insert_id();
			// Post count
			db_query("
				UPDATE {$db_prefix}members
				SET posts = posts + 1
				WHERE ID_MEMBER = $row[ID_MEMBER]", __FILE__, __LINE__);
			if ($row['ID_TOPIC'] == 0 || $row['ID_TOPIC'] == -1) //new topic
			{
				if ($ID_MSG > 0)
				{
					// Insert the new topic.
					db_query("
						INSERT INTO {$db_prefix}topics
							(ID_BOARD, ID_MEMBER_STARTED, ID_MEMBER_UPDATED, ID_FIRST_MSG, ID_LAST_MSG,
							numViews, ID_POLL)
						VALUES ($row[ID_BOARD], $row[ID_MEMBER], $row[ID_MEMBER], $ID_MSG, $ID_MSG,
							0, $row[ID_POLL])", __FILE__, __LINE__);
					$topic = mysql_insert_id();
					if ($topic > 0)
					{
						// Fix the message with the topic.
						db_query("
							UPDATE {$db_prefix}messages
							SET ID_TOPIC = $topic
							WHERE ID_MSG = $ID_MSG
							LIMIT 1", __FILE__, __LINE__);
						// Increase the number of posts and topics on the board.
						db_query("
							UPDATE {$db_prefix}boards
							SET numPosts = numPosts + 1, numTopics = numTopics + 1
							WHERE ID_BOARD = $row[ID_BOARD]
							LIMIT 1", __FILE__, __LINE__);
		
						// There's been a new topic AND a new post today.
						if (!empty($modSettings['trackStats']))
							trackStats(array('topics' => '+', 'posts' => '+'));
		
						// Update all the stats so everyone knows about this new topic and message.
						updateStats('topic');
						updateStats('message');
						updateLastMessages($row['ID_BOARD']);
					}
				}
			$newTopic = true;
			}
			else
			{	
				if ($ID_MSG > 0)
				{
					// Check this is the most recent reply
					$request = db_query("
						SELECT ID_MSG
						FROM {$db_prefix}messages
						WHERE ID_TOPIC = $row[ID_TOPIC]
						ORDER BY posterTime LIMIT 1", __FILE__, __LINE__);
					list($lastMsg) = mysql_fetch_row($request);
					// Update the number of replies and the lock/sticky status.
					db_query("
						UPDATE {$db_prefix}topics
						SET " . ($lastMsg == $ID_MSG ? 'ID_MEMBER_UPDATED = ' . $row['ID_MEMBER'] . '
						, ID_LAST_MSG = ' . $ID_MSG . ',' : '') . "
							numReplies = numReplies + 1
						WHERE ID_TOPIC = $row[ID_TOPIC]
						LIMIT 1", __FILE__, __LINE__);
					// Update the post count.
					db_query("
						UPDATE {$db_prefix}boards
						SET numPosts = numPosts + 1
						WHERE ID_BOARD = $row[ID_BOARD]
						LIMIT 1", __FILE__, __LINE__);

					// Statistics...
					if (!empty($modSettings['trackStats']))
						trackStats(array('posts' => '+'));

					// Update the *other* stats.
					updateStats('message');
					updateLastMessages($row['ID_BOARD']);
				}
			$newTopic = false;
			}
			//now just delete the post from the moderation list!
			db_query("
				DELETE
				FROM {$db_prefix}postmoderation
				WHERE id=$row[ID] LIMIT 1", __FILE__, __LINE__);
		}
		else{ //delete
			if ($row['ID_POLL'] > 0)//delete poll entry too
			{
				// Remove all poll choices.
				db_query("
					DELETE FROM {$db_prefix}poll_choices
					WHERE ID_POLL = $row[ID_POLL]", __FILE__, __LINE__);
				// Remove the poll itself.
				db_query("
					DELETE FROM {$db_prefix}polls
					WHERE ID_POLL = $row[ID_POLL]
					LIMIT 1", __FILE__, __LINE__);
			}
			db_query("
				DELETE
				FROM {$db_prefix}postmoderation
				WHERE ID = $row[ID] LIMIT 1", __FILE__, __LINE__);
		}
		
	}
	redirectexit("action=warnpmman;start=$_REQUEST[start]");
}

?>
