<?php

/*======================================================================*\
|| #################################################################### ||
|| # Yet Another Mass Private Message System v1.0.1 by mtha           # ||
|| # ---------------------------------------------------------------- # ||
|| # For use with vBulletin Version 3.6.x                             # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| # Discussion and support available at                              # ||
|| # http://www.vbulletin.org/forum/showthread.php?t=141622           # ||
|| #################################################################### ||
\*======================================================================*/

// ######################## SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// ##################### DEFINE IMPORTANT CONSTANTS #######################
define('CVS_REVISION', '$RCSfile: hn_masspm.php,v 1.0.1 by mtha - $Revision: 070310 $');

// #################### PRE-CACHE TEMPLATES AND DATA ######################
$phrasegroups = array('user', 'cpuser', 'messaging', 'cprofilefield','pm');
$specialtemplates = array();

// ########################## REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/adminfunctions_profilefield.php');
require_once(DIR . '/includes/adminfunctions_user.php');

// ############################# LOG ACTION ###############################
log_admin_action();

// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################

print_cp_header($vbphrase['mwaextraadmin3_hn_masspm_pm_manager']);

 // ##################### Start ##########################
if (empty($_REQUEST['do']))
{
	$_REQUEST['do'] = 'start';
}

// ###################### Send Mass PM ########################
if ($_REQUEST['do'] == 'dosendpm')
{
	$vbulletin->input->clean_array_gpc('p', array(
		'user'              => TYPE_ARRAY,
		'profile'           => TYPE_ARRAY,
		'serializeduser'    => TYPE_STR,
		'serializedprofile' => TYPE_STR,
		'septext'           => TYPE_NOTRIM,
		'perpage'           => TYPE_UINT,
		'startat'           => TYPE_UINT,
		'test'              => TYPE_BOOL,
		'receipt'						=> TYPE_BOOL,
		'savecopy'					=> TYPE_BOOL,
		'allowsmilie'				=> TYPE_BOOL,
		'from'              => TYPE_STR,
		'fromuserid'				=> TYPE_UINT,
		'subject'           => TYPE_STR,
		'message'           => TYPE_STR,
		'overridereceivepm'	=> TYPE_BOOL,
	));

//	require_once(DIR . '/includes/functions_misc.php');

	$message = $vbulletin->GPC['message'];
	$subject = $vbulletin->GPC['subject'];

	if (trim($subject) == '' || trim($message) == '')
	{
		print_stop_message('nosubject');
	}

	if ($vbulletin->GPC['fromuserid'])
	{
		$fromuser = $db->query_first("
					SELECT userid,username
					FROM " . TABLE_PREFIX . "user AS user
					WHERE user.userid = " . $vbulletin->GPC['fromuserid']
					);
	}

	if (!$fromuser)
	{
		$fromuser['userid'] = $vbulletin->userinfo['userid'];
		$fromuser['username'] = $vbulletin->userinfo['username'];
	}

	if (!empty($vbulletin->GPC['serializeduser']))
	{
		$vbulletin->GPC['user'] = @unserialize($vbulletin->GPC['serializeduser']);
		$vbulletin->GPC['profile'] = @unserialize($vbulletin->GPC['serializedprofile']);
	}

	$condition = fetch_user_search_sql($vbulletin->GPC['user'], $vbulletin->GPC['profile']);
	if (!$condition)
	{
		$condition = ' 1=1 ';
	}

	$finalcondition = "
		$condition "
		 . iif($vbulletin->GPC['overridereceivepm'], "", " AND (options & " . $vbulletin->bf_misc_useroptions['receivepm'] . ")");

	if (empty($vbulletin->GPC['perpage']))
	{
		$vbulletin->GPC['perpage'] = 500;
	}

	@set_time_limit(0);

	$counter = $db->query_first("
			SELECT COUNT(*) AS total
			FROM " . TABLE_PREFIX . "user AS user
			LEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON (userfield.userid = user.userid)
			LEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON (usertextfield.userid = user.userid)
			WHERE $finalcondition
			");

	if ($counter['total'] == 0)
	{
		print_stop_message('no_users_matched_your_query');
	}
	else
	{
		$users = $db->query_read("
				SELECT user.userid, user.usergroupid, user.username, user.email, user.joindate,
					useractivation.activationid
				FROM " . TABLE_PREFIX . "user AS user
				LEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON (userfield.userid = user.userid)
				LEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON (usertextfield.userid = user.userid)
				LEFT JOIN " . TABLE_PREFIX . "useractivation AS useractivation ON (useractivation.userid = user.userid AND useractivation.type = 0)
				WHERE $finalcondition
				ORDER BY userid
				LIMIT " . $vbulletin->GPC['startat'] . ", " . $vbulletin->GPC['perpage'] . "
				");
		if ($db->num_rows($users))
		{
			$page = $vbulletin->GPC['startat'] / $vbulletin->GPC['perpage'] + 1;
			$totalpages = ceil($counter['total'] / $vbulletin->GPC['perpage']);
			echo '<p><b>' . $vbphrase['mwaextraadmin3_hn_masspm_PMing'] . ' <br />' . construct_phrase($vbphrase['showing_users_x_to_y_of_z'], vb_number_format($vbulletin->GPC['startat'] + 1), iif ($vbulletin->GPC['startat'] + $vbulletin->GPC['perpage'] > $counter['total'], vb_number_format($counter['total']), vb_number_format($vbulletin->GPC['startat'] + $vbulletin->GPC['perpage'])), vb_number_format($counter['total'])) . '</b></p>';
			vbflush();
	
			$recipients = array();
			while ($user = $db->fetch_array($users))
			{
					$recipients[] = unhtmlspecialchars($user['username']);
//					$recipients[] = html_entity_decode($user['username']);
			}
	
			if (empty($recipients))
			{
				$pmusers = '';
			}
			else
			{
				$pmusers = implode(' ; ', $recipients);
			}

			echo "\n $pmusers \n";
	
			// create the DM to do error checking and insert the new PM
			$botpermissions['adminpermissions'] = 2;

			$pmdm =& datamanager_init('PM', $vbulletin, ERRTYPE_SILENT);
			$pmdm->overridequota = true;
			$pmdm->set('fromuserid', $fromuser['userid']);
			$pmdm->set('fromusername', $fromuser['username']);
			$pmdm->set_info('receipt', $vbulletin->GPC['receipt']);			//false	
			$pmdm->set_info('savecopy', $vbulletin->GPC['savecopy']); 	//false
			$pmdm->set('allowsmilie', $vbulletin->GPC['allowsmilie']);	//true
			$pmdm->set('title', $subject);
			$pmdm->set('message', $message);
			$pmdm->set_recipients($pmusers, $botpermissions);
			$pmdm->set('dateline', TIMENOW);
	
			$pmdm->pre_save();
			if (empty($pmdm->errors))
			{
				if (!$vbulletin->GPC['test'])
				{
					$pmdm->save();
					echo "<hr><b>$vbphrase[mwaextraadmin3_hn_masspm_noerror_sent]</b><hr>";
				}
				else
				{
					echo "<hr><b>$vbphrase[mwaextraadmin3_hn_masspm_noerror_test]</b><hr>";
				}
			}
			else
			{
				echo "<hr><b><font color=red>$vbphrase[mwaextraadmin3_hn_masspm_error_nopmsent]:</font></b><pre>";
				print_r($pmdm->errors);
				echo "</pre><hr> ";
			}
			unset($pmdm);
			vbflush();
	
			$_REQUEST['do'] = 'donext';
		}
		else
		{
			define('CP_REDIRECT', 'hn_masspm.php?' . $vbulletin->session->vars['sessionurl']);
			print_stop_message('mwaextraadmin3_hn_masspm_sent_successfully');
		}
	}
}


// *************************** Link to next page of PMs to send **********************
if ($_REQUEST['do'] == 'donext')
{
	$vbulletin->GPC['startat'] += $vbulletin->GPC['perpage'];

	print_form_header('hn_masspm', 'dosendpm');
	construct_hidden_code('test', $vbulletin->GPC['test']);
//	construct_hidden_code( 'receipt', $vbulletin->GPC['receipt']);
//	construct_hidden_code( 'savecopy', $vbulletin->GPC['savecopy']);
	construct_hidden_code('allowsmilie', $vbulletin->GPC['allowsmilie']);

	construct_hidden_code('serializeduser', serialize($vbulletin->GPC['user']));
	construct_hidden_code('serializedprofile', serialize($vbulletin->GPC['profile']));
	construct_hidden_code('fromuserid', $vbulletin->GPC['fromuserid']);
	construct_hidden_code('subject', $vbulletin->GPC['subject']);
	construct_hidden_code('message', $vbulletin->GPC['message']);
	construct_hidden_code('startat', $vbulletin->GPC['startat']);
	construct_hidden_code('perpage', $vbulletin->GPC['perpage']);
	construct_hidden_code('overridereceivepm', $vbulletin->GPC['overridereceivepm']);
	print_submit_row($vbphrase['next_page'], 0);
//	print_cp_redirect('',2);
}

// ###################### Send PM ########################
if ($_REQUEST['do'] == 'start')
{	
?>
<script type="text/javascript">
function check_all_usergroups(formobj, toggle_status)
{
	for (var i = 0; i < formobj.elements.length; i++)
	{
		var elm = formobj.elements[i];
		if (elm.type == "checkbox" && elm.name == 'user[usergroupid][]')
		{
			elm.checked = toggle_status;
		}
	}
}
</script>
<?php
	print_form_header('hn_masspm', 'dosendpm');
	print_table_header($vbphrase['mwaextraadmin3_hn_masspm_pm_manager']);
	print_yes_no_row($vbphrase['mwaextraadmin3_hn_masspm_test_pm_only'], 'test', 0);

//	print_yes_no_row($vbphrase['request_receipt_for_message'], 'receipt', 0);				// Doesnt work for BCC
//	print_yes_no_row($vbphrase['save_copy_in_sent_items_folder'], 'savecopy', 0);		// NOT RECOMMENDED 
	print_yes_no_row($vbphrase['allow_smilies'], 'allowsmilie', 1);

	print_yes_no_row($vbphrase['mwaextraadmin3_hn_masspm_overridereceivepm'],'overridereceivepm', 0);
	print_input_row($vbphrase['mwaextraadmin3_hn_masspm_pm_to_send_at_once'], 'perpage', 500);
	print_input_row($vbphrase['from'] . " " . $vbphrase['userid'], 'fromuserid', $vbulletin->userinfo['userid']);
	print_input_row($vbphrase['subject'], 'subject');
	print_textarea_row($vbphrase['mwaextraadmin3_hn_masspm_message'], 'message', '', 10, 50);

	print_table_break();
	print_table_header($vbphrase['search_criteria']);
	print_user_search_rows(true);

	print_table_break();
	print_submit_row($vbphrase['send']);
}
print_cp_footer();
?>