<?php
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*\
<< ******************************************************************** >>
<< * ---------------------------------------------------------------- * >>
<< * Copyright ©2011-2012 Ozzy47                                      * >>
<< * All Rights Reserved. 											  * >>
<< * This file may not be redistributed in whole or significant part. * >>
<< * ---------------------------------------------------------------- * >>
<< * You are not allowed to use this on your server unless the files  * >>
<< * you downloaded were done so with permission.					  * >>
<< * ---------------------------------------------------------------- * >>
<< ******************************************************************** >>
\*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/

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

// #################### PRE-CACHE TEMPLATES AND DATA ######################
$phrasegroups = array('user', 'cpuser', 'messaging', 'cprofilefield', 'profilefield');
$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();

// ######################## CHECK ADMIN PERMISSIONS #######################
if (!can_administer('canadminusers'))
{
	print_cp_no_permission();
}

// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################
//$vbphrase['vbulletin_message'] = $vbphrase['dbtech_vbsuper_pm_error_occurred'];

print_cp_header($vbphrase['dbtech_vbsuper_pm_mass_pm_cp_header']);

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

// *************************** Send a page of emails **********************
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,
		'from'              => TYPE_STR,
		'subject'           => TYPE_STR,
		'message'           => TYPE_STR,
		'delay'				=> TYPE_UINT,
		'allowsmilie'		=> TYPE_BOOL,
		'bypass_pm_off'		=> TYPE_BOOL,	
	));
	
	if ($vbulletin->GPC['subject'] == '')
	{
		print_stop_message('dbtech_vbsuper_pm_no_subject');
	}
	
	if ($vbulletin->GPC['message'] == '')
	{
		print_stop_message('dbtech_vbsuper_pm_no_message');
	}

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

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

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

	$fromuser = fetch_userinfo($vbulletin->GPC['from']);

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

	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('dbtech_vbsuper_pm_no_users_matched');
	}
	else
	{
		$users = $db->query_read("
			SELECT user.userid, user.usergroupid, user.username, user.email, user.joindate, user.lastvisit, user.lastactivity, user.lastpost,
				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['dbtech_vbsuper_pm_sending_pm'] . '<br />' . construct_phrase($vbphrase['dbtech_vbsuper_pm_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>';
	
			$recipients = array();
			while ($user = $db->fetch_array($users))
			{
				echo "$user[userid] - $user[username] .... \n";
				vbflush();
				
				$joindate = vbdate($vbulletin->options['dateformat'], $user['joindate']);
				$lastvisit = vbdate($vbulletin->options['dateformat'], $user['lastvisit']);
				$lastactivity = vbdate($vbulletin->options['dateformat'], $user['lastactivity']);
				$lastpost = vbdate($vbulletin->options['dateformat'], $user['lastpost']);
				
				$sendmessage = $vbulletin->GPC['message'];
				/*DBTECH_PRO_START*/
				$sendmessage = str_replace(
					array('{lastvisit}', '{lastactivity}', '{lastpost}', '{joindate}', '{email}', '{username}', '{userid}', '{bburl}', '{bbtitle}'),
					array($lastvisit, $lastactivity, $lastpost, $joindate, $user['email'], $user['username'], $user['userid'], $vbulletin->options['bburl'], $vbulletin->options['bbtitle']),
					$vbulletin->GPC['message']
				);
				/*DBTECH_PRO_END*/
				
				$pmdm =& datamanager_init('PM', $vbulletin, ERRTYPE_SILENT);
				$pmdm->overridequota = true;
				$pmdm->set('fromuserid', $fromuser['userid']);
				$pmdm->set('fromusername', $fromuser['username']);
				$pmdm->set_info('receipt', false);
				$pmdm->set_info('savecopy', false);
				$pmdm->set('title', $vbulletin->GPC['subject']);
				$pmdm->set('message', $sendmessage);
				$pmdm->set_recipients($user['username'], $fromuser['permissions']);
				$pmdm->set('dateline', TIMENOW);
				$pmdm->set('allowsmilie', $vbulletin->GPC['allowsmilie']);	//true
				$pmdm->pre_save();
				if (empty($pmdm->errors))
				{
					if (!$vbulletin->GPC['test'])
					{
						echo $vbphrase['dbtech_vbsuper_pm_sending_pm'] . " \n";
						$pmdm->save();
					}
					else
					{
						echo $vbphrase['dbtech_vbsuper_pm_test'] . " ... \n";
					}
				}
				unset($pmdm);
				
				echo $vbphrase['dbtech_vbsuper_pm_okay'] . "<br />\n";
				vbflush();
			}
	
			$_REQUEST['do'] = 'donext';
		}
		else
		{
			define('CP_REDIRECT', 'vbsuper_pm_mass_pm.php?' . $vbulletin->session->vars['sessionurl']);
			print_stop_message('dbtech_vbsuper_pm_mass_sent_successfully');
		}
	}
}

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

	print_form_header('vbsuper_pm_mass_pm', 'dosendpm', false, true, 'donext');
		
	construct_hidden_code('test', $vbulletin->GPC['test']);
	construct_hidden_code('serializeduser', sign_client_string(serialize($vbulletin->GPC['user'])));
	construct_hidden_code('serializedprofile', sign_client_string(serialize($vbulletin->GPC['profile'])));
	construct_hidden_code('from', $vbulletin->GPC['from']);
	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('delay', $vbulletin->GPC['delay']);
	construct_hidden_code('allowsmilie', $vbulletin->GPC['allowsmilie']);
	construct_hidden_code('bypass_pm_off', $vbulletin->GPC['bypass_pm_off']);	

	print_submit_row($vbphrase['dbtech_vbsuper_pm_mass_next_page'], 0);
	if (!$vbulletin->GPC['test'])
	{
		print_form_auto_submit('donext');
	}
	vbflush();
}

// *************************** Main email form **********************
if ($_REQUEST['do'] == 'start')
{
	//Javascript to check all checkboxes	
	?>
	<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('vbsuper_pm_mass_pm', 'dosendpm');
	
	print_table_header($vbphrase['dbtech_vbsuper_pm_mass_pm_cp_header']);
	
	print_yes_no_row($vbphrase['dbtech_vbsuper_pm_test_pm'], 'test', 0);
	print_input_row($vbphrase['dbtech_vbsuper_pm_sent_batch'], 'perpage', 500);
	/*DBTECH_PRO_START*/
	print_input_row($vbphrase['dbtech_vbsuper_pm_batch_delay'], 'delay', 0);
	/*DBTECH_PRO_END*/
	print_yes_no_row($vbphrase['dbtech_vbsuper_pm_allow_smilies'], 'allowsmilie', 1);
	print_yes_no_row($vbphrase['dbtech_vbsuper_pm_bypass_pm_off'],'bypass_pm_off', 0);
	print_input_row($vbphrase['dbtech_vbsuper_pm_from'], 'from', $vbulletin->userinfo['userid']);
	print_input_row($vbphrase['dbtech_vbdonate_subject'], 'subject');
	print_textarea_row($vbphrase['dbtech_vbsuper_pm_message'], 'message', '', 10, 50);

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

	print_table_break();
	print_submit_row($vbphrase['dbtech_vbsuper_pm_send']);
}

print_cp_footer();

/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*\
<< ********************************************************************* >>
<< * Created: 09:30, Fri June 8th 2012                                 * >>
<< * VER: 1.0.0                                                        * >>
<< ********************************************************************* >>
\*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
?>