<?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);

// ##################### DEFINE IMPORTANT CONSTANTS #######################
define('CVS_REVISION', '$RCSfile$ - $Revision: 56040 $');

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

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

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

$vbulletin->input->clean_array_gpc('r', array(
	'userid'   => TYPE_INT,
));

// ############################# LOG ACTION ###############################
log_admin_action(!empty($vbulletin->GPC['userid']) ? 'user id = ' . $vbulletin->GPC['userid'] : '');

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

print_cp_header($vbphrase['dbtech_vbsuper_pm_stats_cp_header']);

// ###################### Start Remove User's PMs #######################
if ($_REQUEST['do'] == 'removepms')
{

	print_delete_confirmation('user', $vbulletin->GPC['userid'], 'vbsuper_pm_stats', 'killpms', 'private_messages_belonging_to_the_user');
}

// ###################### Start Remove User's PMs #######################
if ($_POST['do'] == 'killpms')
{

	$result = delete_user_pms($vbulletin->GPC['userid']);

	define('CP_REDIRECT', "user.php?do=edit&amp;u=" . $vbulletin->GPC['userid']);
	print_stop_message('deleted_x_pms_y_pmtexts_and_z_receipts', $result['pms'], $result['pmtexts'], $result['receipts']);
}

// ###################### Start Remove PMs Sent by User #######################
if ($_REQUEST['do'] == 'removesentpms')
{

	print_delete_confirmation('user', $vbulletin->GPC['userid'], 'vbsuper_pm_stats', 'killsentpms', 'private_messages_sent_by_the_user');
}

// ###################### Start Remove User's PMs #######################
if ($_POST['do'] == 'killsentpms')
{

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

	if (!$user['userid'])
	{
		print_stop_message('invalid_user_specified');
	}

	$pmtextids = '0';
	$pmtexts = $db->query_read("SELECT pmtextid FROM " . TABLE_PREFIX . "pmtext WHERE fromuserid = " . $vbulletin->GPC['userid']);
	while ($pmtext = $db->fetch_array($pmtexts))
	{
		$pmtextids .= ",$pmtext[pmtextid]";
	}
	$db->free_result($pmtexts);

	define('CP_REDIRECT', "user.php?do=edit&amp;u=" . $vbulletin->GPC['userid']);

	if ($pmtextids == '0')
	{
		print_stop_message('no_private_messages_matched_your_query');
	}
	else
	{
		$pmids = '0';
		$pmarray = array();
		$pms = $db->query_read("
			SELECT pm.*, user.username
			FROM " . TABLE_PREFIX . "pm AS pm
			LEFT JOIN " . TABLE_PREFIX . "user AS user USING(userid)
			WHERE pm.pmtextid IN($pmtextids)
		");
		while ($pm = $db->fetch_array($pms))
		{
			$pmids .= ",$pm[pmid]";
			$pmarray["$pm[username]"][] = $pm;
		}
		$db->free_result($pms);

		$users = array();

		foreach($pmarray AS $username => $pms)
		{
			$pmunread = 0;
			foreach($pms AS $pm)
			{
				if ($pm['messageread'] == 0)
				{
					$pmunread ++;
				}
			}
			$pmtotal = sizeof($pms);
			$users["$pm[userid]"] = array('pmtotal' => $pmtotal, 'pmunread' => $pmunread);
		}

		$db->query_write("DELETE FROM " . TABLE_PREFIX . "pm WHERE pmid IN($pmids)");

		if (!empty($users))
		{
			$pmtotalsql = 'CASE userid ';
			$pmunreadsql = 'CASE userid ';
			foreach($users AS $id => $x)
			{
				$pmtotalsql .= "WHEN $id THEN pmtotal - $x[pmtotal] ";
				$pmunreadsql .= "WHEN $id THEN pmunread - $x[pmunread] ";
			}
			$pmtotalsql .= 'ELSE pmtotal END';
			$pmunreadsql .= 'ELSE pmunread END';

			$userids = implode(', ', array_keys($users));

			$db->query_write("
				UPDATE " . TABLE_PREFIX . "user
				SET pmtotal = $pmtotalsql,
				pmunread = $pmunreadsql
				WHERE userid IN($userids)
			");
			$db->query_write("
				UPDATE " . TABLE_PREFIX . "user
				SET pmpopup = IF(pmpopup=2 AND pmunread = 0, 1, pmpopup)
				WHERE userid IN($userids)
			");
		}

		print_stop_message('deleted_private_messages_successfully');
	}
}

// ############################# start user pm stats #########################
if ($_REQUEST['do'] == 'pmfolderstats')
{

	$user = $db->query_first("
		SELECT user.*, usertextfield.*
		FROM " . TABLE_PREFIX . "user AS user
		INNER JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield USING(userid)
		WHERE user.userid = " . $vbulletin->GPC['userid'] . "
	");

	if (!$user['userid'])
	{
		print_stop_message('invalid_user_specified');
	}

	$foldernames = array('0' => $vbulletin->options['inboxname'], '-1' => $vbulletin->options['sentitemsname']);
	$foldernames = unserialize($user['pmfolders']);
	$foldernames['-1'] = $vbphrase['dbtech_vbsuper_pm_sent_items'];
	$foldernames['0'] = $vbphrase['dbtech_vbsuper_pm_inbox'];
	$folders = array();
	$pms = $db->query_read("
		SELECT COUNT(*) AS messages, folderid
		FROM " . TABLE_PREFIX . "pm
		WHERE userid = $user[userid]
		GROUP BY folderid
	");
	if (!$db->num_rows($pms))
	{
		print_stop_message('no_matches_found');
	}
	while ($pm = $db->fetch_array($pms))
	{
		$pmtotal += $pm['messages'];
		$folders[$foldernames[$pm['folderid']]] = $pm['messages'];
	}

	print_form_header('user', 'edit');
	construct_hidden_code('userid', $user['userid']);
	print_table_header(construct_phrase($vbphrase['dbtech_vbsuper_pm_statistics_user'], $user['username']) . "<b> (userid: $user[userid])</b>");
	print_cells_row(array($vbphrase['dbtech_vbsuper_pm_statistics_folders'], $vbphrase['dbtech_vbsuper_pm_statistics_num_mesg']), 1);
	foreach($folders AS $foldername => $messages)
	{
		print_cells_row(array($foldername, $messages));
	}
	print_cells_row(array('<b>' . $vbphrase['dbtech_vbsuper_pm_statistics_total_stored'] . '</b>', "<b>$pmtotal</b>"));
	print_description_row('<div align="center">' . construct_link_code($vbphrase['dbtech_vbsuper_pm_statistics_del_all_pms'], "vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=removepms&amp;u=" . $vbulletin->GPC['userid']) . '</div>', 0, 2, 'thead');
	print_submit_row($vbphrase['dbtech_vbsuper_pm_statistics_edit_user'], 0);
}


// ############################# start PM stats #########################

	//Build Filter Menu
	if ($_REQUEST['do'] == 'pm_stats')
	{
		
		print_cp_header($vbphrase['dbtech_vbsuper_pm_log_pms_stored']);
		
		print_form_header('vbsuper_pm_stats', 'view_stats');
		construct_hidden_code('action', 'view_stats');
		print_table_header($vbphrase['dbtech_vbsuper_pm_log_pms_stored']);
		print_input_row($vbphrase['dbtech_vbsuper_pm_user_entries_to_show_per_page'], 'perpage', 50);
		print_select_row($vbphrase['dbtech_vbsuper_pm_order_by_user'], 'orderby', array(
			'DESC' 	=> $vbphrase['dbtech_vbsuper_pm_desc'],
			'ASC' 	=> $vbphrase['dbtech_vbsuper_pm_asc']
		));
		print_submit_row($vbphrase['dbtech_vbsuper_pm_view'], 0);
	}

	//Build PM Stats Log
	if ($_REQUEST['do'] == 'view_stats')
	{
		print_cp_header($vbphrase['dbtech_vbsuper_pm_log_pms_stored']);
		
		$vbulletin->input->clean_array_gpc('r', array(
			'username' => TYPE_STR,
	        'userid' => TYPE_STR,
			'perpage'    => TYPE_UINT,
			'pagenumber' => TYPE_UINT,
			'orderby'    => TYPE_NOHTML,
		));
		
		$sqlconds = array();
		$hook_query_fields = $hook_query_joins = '';
		
		if ($vbulletin->GPC['perpage'] < 1)
		{
			$vbulletin->GPC['perpage'] = 15;
		}
		
		//Get PM Count
		$sqlconds[] = 'pmtotal >0';
			
		$counter = $db->query_first("
			SELECT COUNT(*) AS total
			FROM " . TABLE_PREFIX . "user AS pm
			" . (!empty($sqlconds) ? "WHERE " . implode("\r\n\tAND ", $sqlconds) : "") . "
		");
		
		$totalpages = ceil($counter['total'] / $vbulletin->GPC['perpage']);
		
		if ($vbulletin->GPC['pagenumber'] < 1)
		{
			$vbulletin->GPC['pagenumber'] = 1;
		}
		$startat = ($vbulletin->GPC['pagenumber'] - 1) * $vbulletin->GPC['perpage'];
		
		$order = ' userid ' . $vbulletin->GPC['orderby'];
		
		$logs = $db->query_read("
			SELECT COUNT( * ) 
				AS total, 
				pm.userid, 
				user.username, 
				user.lastactivity, 
				user.email, 
				user.usertitle, 
				user.joindate, 
				user.posts, 
				user.lastpost, 
				user.pmunread, 
				user.pmtotal
			FROM " . TABLE_PREFIX . "pm AS pm
			INNER JOIN " . TABLE_PREFIX . "user AS user ON (pm.userid = user.userid)
			GROUP BY pm.userid
			HAVING total > 0
			ORDER BY $order
			LIMIT $startat, " . $vbulletin->GPC['perpage'] . "
		");	
		
		if ($db->num_rows($logs))
		{
			if ($vbulletin->GPC['pagenumber'] != 1)
			{
				$prv = $vbulletin->GPC['pagenumber'] - 1;
				$firstpage = "<input type=\"button\" class=\"button\" value=\"&laquo; " . $vbphrase['dbtech_vbsuper_pm_first_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_stats&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=1'\">";
				$prevpage = "<input type=\"button\" class=\"button\" value=\"&lt; " . $vbphrase['dbtech_vbsuper_pm_prev_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_stats&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$prv'\">";
			}
		
			if ($vbulletin->GPC['pagenumber'] != $totalpages)
			{
				$nxt = $vbulletin->GPC['pagenumber'] + 1;
				$nextpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['dbtech_vbsuper_pm_next_page'] . " &gt;\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_stats&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$nxt'\">";
				$lastpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['dbtech_vbsuper_pm_last_page'] . " &raquo;\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_stats&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$totalpages'\">";
			}
			
			$headings = array();
			$headings[] = $vbphrase['dbtech_vbsuper_pm_member'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_total'];
			$headings[] = 'Total Unread';
			$headings[] = $vbphrase['dbtech_vbsuper_pm_last_activity'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_user_email'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_user_title'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_user_join_date'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_user_post_count'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_user_last_post'];
			/*DBTECH_PRO_START*/
			$headings[] = $vbphrase['dbtech_vbsuper_pm_statistics_options'];
			/*DBTECH_PRO_END*/
		
			?>
			<script type="text/javascript">
			function js_usergroup_jump(userinfo)
			{
				var value = eval("document.cpform.u" + userinfo + ".options[document.cpform.u" + userinfo + ".selectedIndex].value");
				if (value != "")
				{
					window.location = "vbsuper_pm_stats.php?<?php echo $vbulletin->session->vars['sessionurl_js']; ?>do=view&action=" + value + "&messageid=" + userinfo;
				}
			}
			</script>
			<?php	
		
			print_form_header('', '');
			print_description_row(construct_link_code($vbphrase['restart'], "vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=pm_stats"), false, count($headings), 'thead', 'right');
			print_table_header(construct_phrase($vbphrase['dbtech_vbsuper_pm_stats_list_page_x_y_there_are_z_total_log_entries'], vb_number_format($vbulletin->GPC['pagenumber']), vb_number_format($totalpages), vb_number_format($counter['total'])), count($headings));
			print_cells_row($headings, 1);
	
			while ($log = $db->fetch_array($logs))
			{			
				// a little javascript for the options menus
				?>
				<script type="text/javascript">
				function js_pm_jumper(userid,username)
				{
					value = eval("document.cpform.u" + userid + ".options[document.cpform.u" + userid + ".selectedIndex].value");
					var page = '';
					switch (value)
					{
						case 'pmstats': page = "vbsuper_pm_stats.php?do=pmfolderstats&u=" + userid; break;
						case 'profile': page = "user.php?do=edit&u=" + userid; break;
						case 'pmuser': page = "../private.php?do=newpm&u=" + userid; break;
						case 'delete': page = "vbsuper_pm_stats.php?do=removepms&u=" + userid; break;
					}
					if (page != '')
					{
						window.location = page + "&s=<?php echo $vbulletin->session->vars['sessionhash']; ?>";
					}
					else
					{
						window.location = "mailto:" + value;
					}
				}
				</script>
				<?php				
				
				$cell = array();
				$cell[] = "<a href=\"" . fetch_seo_url('member|bburl', $log) . "\" target=\"_blank\">$log[username]</a>";
				$cell[] = $log['total'];
				$cell[] = $log['pmunread'];
				$cell[] = vbdate($vbulletin->options['dateformat'], $log['lastactivity']);
				$cell[] = $log['email'];
				$cell[] = $log['usertitle'];
				$cell[] = vbdate($vbulletin->options['dateformat'], $log['joindate']);					
				$cell[] = $log['posts'];
				$cell[] = vbdate($vbulletin->options['dateformat'], $log['lastpost']);
				/*DBTECH_PRO_START*/
				$cell[] = "
			<select name=\"u$log[userid]\" onchange=\"js_pm_jumper($log[userid], '$log[username]');\" tabindex=\"1\" class=\"bginput\">
				<option value=\"pmstats\">" . $vbphrase['dbtech_vbsuper_pm_view_statistics'] . "</option>
				<option value=\"profile\">" . $vbphrase['dbtech_vbsuper_pm_statistics_edit_user'] . "</option>
				" . (!empty($$log['email']) ? "<option value=\"$log[email]\">" . $vbphrase['dbtech_vbsuper_pm_send_email'] . "</option>" : "") . "
				<option value=\"pmuser\">" . $vbphrase['dbtech_vbsuper_pm_send_pm'] . "</option>
				<option value=\"delete\">" . construct_phrase($vbphrase['dbtech_vbsuper_pm_statistics_del_all_pms']) . "</option>
				<!--<option value=\"caca\">" . $vbphrase['view_private_message_statistics'] . "</option>-->
			</select><input type=\"button\" class=\"button\" value=\"$vbphrase[dbtech_vbsuper_pm_go]\" onclick=\"js_pm_jumper($log[userid], '$log[username]');\" tabindex=\"1\" />\n\t";
				/*DBTECH_PRO_END*/
		
				print_cells_row($cell, false, false, 0, 'top', false, true);
			}
		
			print_table_footer(count($headings), "$firstpage $prevpage &nbsp; $nextpage $lastpage");
		}
		else
		{
			print_stop_message('dbtech_vbsuper_pm_no_results_matched_your_query');
		}
	}
// ############################# START PM LOG ###########################

	//Build Filter Menu
	if ($_REQUEST['do'] == 'pm_log')
	{	
		print_cp_header($vbphrase['dbtech_vbsuper_pm_list_private_messages']);
		
		print_form_header('vbsuper_pm_stats', 'view_log');
		construct_hidden_code('action', 'view_log');
		print_table_header($vbphrase['dbtech_vbsuper_pm_list_private_messages']);
		print_input_row($vbphrase['dbtech_vbsuper_pm_log_entries_to_show_per_page'], 'perpage', 100);
		print_time_row($vbphrase['dbtech_vbsuper_pm_auto_responder_start_date'], 'startdate', 0, 0);
		print_time_row($vbphrase['dbtech_vbsuper_pm_auto_responder_end_date'], 'enddate', 0, 0);
		print_select_row($vbphrase['dbtech_vbsuper_pm_order_by'], 'orderby', array(
			'DESC' 	=> $vbphrase['dbtech_vbsuper_pm_desc'],
			'ASC' 	=> $vbphrase['dbtech_vbsuper_pm_asc']
		));
		print_submit_row($vbphrase['dbtech_vbsuper_pm_view'], 0);
	}		

	//Build PM Log
	if ($_REQUEST['do'] == 'view_log')
	{
		print_cp_header($vbphrase['dbtech_vbsuper_pm_log_cp_header']);
		
		$vbulletin->input->clean_array_gpc('r', array(
			'username' => TYPE_STR,
	        'userid' => TYPE_STR,
			'perpage'    => TYPE_UINT,
			'pagenumber' => TYPE_UINT,
			'orderby'    => TYPE_NOHTML,
			'startdate'  => TYPE_UNIXTIME,
			'enddate'    => TYPE_UNIXTIME,
		));
		
		$sqlconds = array();
		$hook_query_fields = $hook_query_joins = '';
		
		if ($vbulletin->GPC['perpage'] < 1)
		{
			$vbulletin->GPC['perpage'] = 15;
		}
		
		if ($vbulletin->GPC['startdate'])
		{
			$sqlconds[] = "dateline >= " . $vbulletin->GPC['startdate'];
		}
		
		if ($vbulletin->GPC['enddate'])
		{
			$sqlconds[] = "dateline <= " . $vbulletin->GPC['enddate'];
		}
		
		//Get PM Count	
		$counter = $db->query_first("
			SELECT COUNT(*) AS total
			FROM " . TABLE_PREFIX . "pmtext AS message
			" . (!empty($sqlconds) ? "WHERE " . implode("\r\n\tAND ", $sqlconds) : "") . "
		");
		$totalpages = ceil($counter['total'] / $vbulletin->GPC['perpage']);
		
		if ($vbulletin->GPC['pagenumber'] < 1)
		{
			$vbulletin->GPC['pagenumber'] = 1;
		}
		$startat = ($vbulletin->GPC['pagenumber'] - 1) * $vbulletin->GPC['perpage'];
		
		$order = ' dateline ' . $vbulletin->GPC['orderby'];
		
		$logs = $db->query_read("
			SELECT pmtextid, fromuserid, fromusername, touserarray, title, dateline, message
				$hook_query_fields
			FROM " . TABLE_PREFIX . "pmtext AS pm
			$hook_join_fields
			" . (!empty($sqlconds) ? "WHERE " . implode("\r\n\tAND ", $sqlconds) : "") . "
			ORDER BY $order
			LIMIT $startat, " . $vbulletin->GPC['perpage'] . "
		");
		
		if ($db->num_rows($logs))
		{
			if ($vbulletin->GPC['pagenumber'] != 1)
			{
				$prv = $vbulletin->GPC['pagenumber'] - 1;
				$firstpage = "<input type=\"button\" class=\"button\" value=\"&laquo; " . $vbphrase['dbtech_vbsuper_pm_first_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_log&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&startdate=" . $vbulletin->GPC['startdate'] . "&enddate=" . $vbulletin->GPC['enddate'] . "&page=1'\">";
				$prevpage = "<input type=\"button\" class=\"button\" value=\"&lt; " . $vbphrase['dbtech_vbsuper_pm_prev_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_log&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&startdate=" . $vbulletin->GPC['startdate'] . "&enddate=" . $vbulletin->GPC['enddate'] . "&page=$prv'\">";
			}
		
			if ($vbulletin->GPC['pagenumber'] != $totalpages)
			{
				$nxt = $vbulletin->GPC['pagenumber'] + 1;
				$nextpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['dbtech_vbsuper_pm_next_page'] . " &gt;\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_log&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&startdate=" . $vbulletin->GPC['startdate'] . "&enddate=" . $vbulletin->GPC['enddate'] . "&page=$nxt'\">";
				$lastpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['dbtech_vbsuper_pm_last_page'] . " &raquo;\" tabindex=\"1\" onclick=\"window.location='vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=view_log&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&startdate=" . $vbulletin->GPC['startdate'] . "&enddate=" . $vbulletin->GPC['enddate'] . "&page=$totalpages'\">";
			}
			
			$headings = array();
			$headings[] = $vbphrase['dbtech_vbsuper_pm_id_num'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_from_member'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_message_title'];
			/*DBTECH_PRO_START*/
			if (in_array($vbulletin->userinfo['userid'], preg_split('#\s*,\s*#s', $vbulletin->config['SpecialUsers']['superadministrators'], -1, PREG_SPLIT_NO_EMPTY)))
			{
			$headings[] = $vbphrase['dbtech_vbsuper_pm_message_content'];
			}
			/*DBTECH_PRO_END*/
			$headings[] = $vbphrase['dbtech_vbsuper_pm_to_member'];
			$headings[] = $vbphrase['dbtech_vbsuper_pm_date_sent'];
		
			?>
			<script type="text/javascript">
			function js_usergroup_jump(userinfo)
			{
				var value = eval("document.cpform.u" + userinfo + ".options[document.cpform.u" + userinfo + ".selectedIndex].value");
				if (value != "")
				{
					window.location = "vbsuper_pm_stats.php?<?php echo $vbulletin->session->vars['sessionurl_js']; ?>do=view&action=" + value + "&messageid=" + userinfo;
				}
			}
			</script>
			<?php
	
			//Get recipients to display on the main log page		
			function dbtech_vbsuper_pm_show_recipients($array1, $array2)
			{
				if (is_array($array1))
				{
					foreach ($array1 as $value)
					{
						$display .= htmlspecialchars_uni($value);
						$display .= ', ';
					}
					if (is_array($array2))
					{
						foreach ($array2 as $value)
						{
							$display .= htmlspecialchars_uni($value);
							$display .= ', ';
						}
					}
					$display = substr($display, 0, -2);
				}
				else
				{
					$display .= $vbphrase['dbtech_vbsuper_pm_can_not_be_displayed'];
				}
				// return the list of receipients
				return $display;
			}		
		
			print_form_header('', '');
			print_description_row(construct_link_code($vbphrase['restart'], "vbsuper_pm_stats.php?" . $vbulletin->session->vars['sessionurl'] . "do=pm_log"), false, count($headings), 'thead', 'right');
			print_table_header(construct_phrase($vbphrase['dbtech_vbsuper_pm_log_list_page_x_y_there_are_z_total_log_entries'], vb_number_format($vbulletin->GPC['pagenumber']), vb_number_format($totalpages), vb_number_format($counter['total'])), count($headings));
			print_cells_row($headings, 1);
	
			while ($log = $db->fetch_array($logs))
			{
				$toarray = array_values(unserialize($log['touserarray']));
				
				$cell = array();
				$cell[] = $log['pmtextid'];
				$cell[] = "<a href=\"user.php?" . $vbulletin->session->vars['sessionurl'] . "do=edit&amp;u=$log[fromuserid]\">$log[fromusername]</a>";
				$cell[] = $log['title'];
				/*DBTECH_PRO_START*/
				if (in_array($vbulletin->userinfo['userid'], preg_split('#\s*,\s*#s', $vbulletin->config['SpecialUsers']['superadministrators'], -1, PREG_SPLIT_NO_EMPTY)))
				{
				$cell[] = "<a href=\"vbsuper_pm_stats.php?do=showpm&pmtextid=$log[pmtextid]\"> $vbphrase[dbtech_vbsuper_pm_view_message]</a>";
				}
				/*DBTECH_PRO_END*/
				$cell[] = dbtech_vbsuper_pm_show_recipients($toarray[0], $toarray[1]);			
				$cell[] = vbdate($vbulletin->options['logdateformat'], $log['dateline']);
		
				print_cells_row($cell, false, false, 0, 'top', false, true);
			}
		
			print_table_footer(count($headings), "$firstpage $prevpage &nbsp; $nextpage $lastpage");
		}
		else
		{
			print_stop_message('dbtech_vbsuper_pm_no_results_matched_your_query');
		}
	}
// ############################# END PM LOG #############################

/*DBTECH_PRO_START*/
// ############## Start Show PM ########################################

	if ($_REQUEST['do'] == 'showpm')
	{
		if (!in_array($vbulletin->userinfo['userid'], preg_split('#\s*,\s*#s', $vbulletin->config['SpecialUsers']['superadministrators'], -1, PREG_SPLIT_NO_EMPTY)))
		{
			print_stop_message('dbtech_vbsuper_pm_sorry_cannot_view_messages');
		}
		
	    if ($vbulletin->options['storecssasfile'])
	    {
	        $vbcsspath = 'clientscript/vbulletin_css/style' . str_pad($style['styleid'], 5, '0', STR_PAD_LEFT) . $vbulletin->stylevars['textdirection']['string'][0] . '/';
	        $head_insert = '<link rel="stylesheet" type="text/css" href="' . $vbcsspath . 'bbcode.css' . '?d=\' . $style[\'dateline\'] . \'" />';
	    }
	    else
	    {
	        // textdirection var added to prevent cache if admin modified language text_direction. See bug #32640
	        $vbcsspath = 'css.php?styleid=' . $style['styleid'] . '&amp;langid=' . LANGUAGEID . '&amp;d=' . $style['dateline'] . '&amp;td=' . $vbulletin->stylevars['textdirection']['string'] . '&amp;sheet=';
	        $head_insert = '<link rel="stylesheet" type="text/css" href="' . $vbcsspath . 'bbcode.css" />';
	    }
	
	    $vbulletin->input->clean_array_gpc('r', array(
	        'pmtextid' => TYPE_UINT,
	    ));
	
	    $pmtextid = $vbulletin->GPC['pmtextid'] ? $vbulletin->GPC['pmtextid'] : 0;
	
	    if (!$pmtextid)
	    {
	        print_stop_message('dbtech_vbsuper_pm_invalid_parameters');
	    }
	
	    $sql = 'SELECT
	                pm.*
	            FROM
	                ' . TABLE_PREFIX . 'pmtext AS pm
	            WHERE
	                pm.`pmtextid` = ' . $pmtextid . '
	            LIMIT 1';
	
	    $pm = $db->query_first($sql);
	    if (empty($pm))
	    {
	        print_stop_message('dbtech_vbsuper_pm_msg_not_found');
	    }
	
		require_once(DIR . '/includes/class_bbcode.php');
		$bbcode_parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
		// force to not allow html and images

	    print_cp_header($vbphrase['dbtech_vbsuper_pm_viewing_pm_cp_header']);
	    print_table_start();
	    print_table_header(construct_phrase($vbphrase['dbtech_vbsuper_pm_viewing_pm'], $pm['pmtextid']), 2);
	    $toarray = array_values(unserialize($pm['touserarray']));
	
		//Display recipient username with link to edit user
		function dbtech_vbsuper_pm_link_recipients($array)
		{
			if (is_array($array))
			{
				foreach ($array as $value)
				{
					$username = dbtech_vbsuper_pm_fetch_recipient_userid(htmlspecialchars_uni($value));
					$display .= ' <b><a href = "user.php?do=edit&u=' . $username . '">' . $value . '';
					$display .= '</a></b>';
					$display .= ',<br />';
				}	
				$display = substr($display, 0, -7);
			}
			else
			{
				$display .= $vbphrase['dbtech_vbsuper_pm_can_not_be_displayed'];
			}
			// return the list of receipients
			return $display;
		}
	 
		//Get recipient userid  
		function dbtech_vbsuper_pm_fetch_recipient_userid($username)
		{
			global $db;
			$result = $db->query_first("
				SELECT userid
				FROM " . TABLE_PREFIX . "user
				WHERE LOWER(username) = LOWER('" . $db->escape_string($username) . "')
			");
			return $result['userid'];
		}   
	    
	
	    if (verify_id('user', $pm['fromuserid'], false))
	    {
	        print_label_row($vbphrase['dbtech_vbsuper_pm_from_member'], '<a href="user.php?do=edit&u=' . $pm['fromuserid'] . '" alt="" title=""><b>' . $pm['fromusername'] . '</b></a>');
	    }
	    else
	    {
	        print_label_row($vbphrase['dbtech_vbsuper_pm_from_member'], "<b>" . $pm['fromusername'] . "</b>");
	    }
	
		if (is_array($toarray[0]))
		{
			print_label_row($vbphrase['dbtech_vbsuper_pm_to_member'], dbtech_vbsuper_pm_link_recipients($toarray[0]));
		}
		if (is_array($toarray[1]))
		{
			print_label_row($vbphrase['dbtech_vbsuper_pm_bcc_to_member'], dbtech_vbsuper_pm_link_recipients($toarray[1]));
		}    
	
	
	    print_label_row($vbphrase['dbtech_vbsuper_pm_date_pm'], vbdate($vbulletin->options['logdateformat'], $pm['dateline']));
	    print_label_row($vbphrase['dbtech_vbsuper_pm_message_title'], $pm['title']);
		print_label_row($vbphrase['dbtech_vbsuper_pm_message_content'], $bbcode_parser->parse($pm['message'], 'privatemessage'));    
	
		print_table_footer(6,(construct_phrase($vbphrase['dbtech_vbsuper_pm_view_end'], $pm['pmtextid'])));      
	}

	print_cp_footer();

// ############## End Show Pm ##########################################
/*DBTECH_PRO_END*/

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