<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # 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.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// #############################################################################
if ($_REQUEST['action'] == 'bounce' OR empty($_REQUEST['action']))
{
	print_cp_header($vbphrase['dbtech_vbmail_bounced_mail_list']);

	// ###################### Start modify #######################
	print_form_header('vbmail', 'bounce');
	construct_hidden_code('action', 'view');
	print_table_header($vbphrase['dbtech_vbmail_bounced_mail_list']);
	print_input_row($vbphrase['log_entries_to_show_per_page'], 'perpage', 100);
	print_select_row($vbphrase['show_only_entries_generated_by'], 'bounce', array(
		-1 	=> $vbphrase['dbtech_vbmail_all_mail'],
		0 	=> $vbphrase['dbtech_vbmail_bounceflag_0'],
		1 	=> $vbphrase['dbtech_vbmail_bounceflag_1']
	), -1);
	print_time_row($vbphrase['start_date'], 'startdate', 0, 0);
	print_time_row($vbphrase['end_date'], 'enddate', 0, 0);
	print_select_row($vbphrase['order_by'], 'orderby', array(
		'subject' 		=> $vbphrase['subject'],
		'fromaddress' 	=> $vbphrase['from'],
		'date' 			=> $vbphrase['date'],
		'bounce' 		=> $vbphrase['dbtech_vbmail_bounceflag']
	), 'date');
	print_submit_row($vbphrase['view'], 0);

	// ###################### Start modify #######################
	print_form_header('vbmail', 'bounce');
	construct_hidden_code('action', 'prune');
	print_table_header($vbphrase['dbtech_vbmail_prune_bounced_mail_list']);
	print_yes_no_row($vbphrase['dbtech_vbmail_are_you_sure_prune'], 'doprune', 0);
	print_time_row($vbphrase['start_date'], 'startdate', 0, 0);
	print_time_row($vbphrase['end_date'], 'enddate', 0, 0);
	print_submit_row($vbphrase['dbtech_vbmail_prune'], 0);
}

// #############################################################################
if ($_REQUEST['action'] == 'view')
{
	print_cp_header($vbphrase['dbtech_vbmail_bounced_mail_list']);

	$vbulletin->input->clean_array_gpc('r', array(
		'perpage'    => TYPE_UINT,
		'pagenumber' => TYPE_UINT,
		'bounce'     => TYPE_INT,
		'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['bounce'] > -1)
	{
		$sqlconds[] = "message.bounce = '" . $vbulletin->GPC['bounce'] . "'";
	}

	if ($vbulletin->GPC['startdate'])
	{
		$sqlconds[] = "message.dateline >= " . $vbulletin->GPC['startdate'];
	}

	if ($vbulletin->GPC['enddate'])
	{
		$sqlconds[] = "message.dateline <= " . $vbulletin->GPC['enddate'];
	}

	//($hook = vBulletinHook::fetch_hook('admin_modlogviewer_query')) ? eval($hook) : false;

	$counter = $db->query_first_slave("
		SELECT COUNT(*) AS total
		FROM " . TABLE_PREFIX . "dbtech_vbmail_message 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'];

	switch($vbulletin->GPC['orderby'])
	{
		case 'bounce':
			$order = 'message.bounce ASC, dateline DESC';
			break;
		case 'date':
		default:
			$order = 'dateline DESC';
	}

	$logs = $db->query_read_slave("
		SELECT message.*
			$hook_query_fields
		FROM " . TABLE_PREFIX . "dbtech_vbmail_message AS message
		$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['first_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=1'\">";
			$prevpage = "<input type=\"button\" class=\"button\" value=\"&lt; " . $vbphrase['prev_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&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['next_page'] . " &gt;\" tabindex=\"1\" onclick=\"window.location='vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$nxt'\">";
			$lastpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['last_page'] . " &raquo;\" tabindex=\"1\" onclick=\"window.location='vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$totalpages'\">";
		}

		$headings = array();
		$headings[] = $vbphrase['id'];
		$headings[] = "<a href=\"vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=subject&page=" . $vbulletin->GPC['pagenumber'] . "\">" . str_replace(' ', '&nbsp;', $vbphrase['subject']) . "</a>";
		$headings[] = "<a href=\"vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=fromaddress&page=" . $vbulletin->GPC['pagenumber'] . "\">" . $vbphrase['from'] . "</a>";
		$headings[] = "<a href=\"vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=date&page=" . $vbulletin->GPC['pagenumber'] . "\">" . $vbphrase['date'] . "</a>";
		$headings[] = "<a href=\"vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&action=view&bounce=" . $vbulletin->GPC['bounce'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=bounce&page=" . $vbulletin->GPC['pagenumber'] . "\">" . $vbphrase['dbtech_vbmail_bounced_mail'] . "</a>";
		$headings[] = $vbphrase['options'];

		?>
		<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 = "vbmail.php?<?php echo $vbulletin->session->vars['sessionurl_js']; ?>do=bounce&action=" + value + "&messageid=" + userinfo;
			}
		}
		</script>
		<?php

		print_form_header('', '');
		print_description_row(construct_link_code($vbphrase['restart'], "vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce"), false, count($headings), 'thead', 'right');
		print_table_header(construct_phrase($vbphrase['dbtech_vbmail_bounced_mail_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))
		{
			// Ensure we got the proper log username
			//$log['username'] = ($log['username'] ? $log['username'] : ($log['cmdusername'] ? $log['cmdusername'] : 'N/A'));

			$cell = array();
			$cell[] = $log['messageid'];
			$cell[] = "<a href=\"vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=bounce&amp;action=modify&amp;messageid=$log[messageid]\">$log[subject]</a>";
			$cell[] = "<a href=\"mailto:$log[fromaddress]\">$log[fromaddress]</a>";
			$cell[] = '<span class="smallfont">' . vbdate($vbulletin->options['logdateformat'], $log['dateline']) . '</span>';
			$cell[] = ($log['bounce'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');

			//($hook = vBulletinHook::fetch_hook('admin_modlogviewer_query_loop')) ? eval($hook) : false;

			$cell[] = "\n\t<select name=\"u$log[messageid]\" onchange=\"js_usergroup_jump($log[messageid]);\" class=\"bginput\">
			<option value=\"togglebounce\">" . $vbphrase['dbtech_vbmail_toggle_bounced_mail_flag'] . "</option>
			<option value=\"modify\">$vbphrase[view] / " . $vbphrase['edit'] . "</option>
			<option value=\"delete\">" . $vbphrase['delete'] . "</option>\n\t</select><input type=\"button\" class=\"button\" value=\"" . $vbphrase['go'] . "\" onclick=\"js_usergroup_jump($log[messageid]);\" />\n\t";

			//$cell[] = construct_link_code($vbphrase['view'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=bounce&amp;action=view&amp;messageid=' . $log['messageid']);
			//$cell[] = construct_link_code($vbphrase['delete'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=bounce&amp;action=delete&amp;messageid=' . $log['messageid']);

			//print_cells_row($cell, 0, 0, -4);
			print_cells_row($cell, false, false, 0, 'top', false, true);
		}

		print_table_footer(count($headings), "$firstpage $prevpage &nbsp; $nextpage $lastpage");
	}
	else
	{
		print_stop_message('no_results_matched_your_query');
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$messageid = $vbulletin->input->clean_gpc('r', 'messageid', TYPE_UINT);
	$message = ($messageid ? $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_message WHERE messageid = " . intval($messageid)) : false);

	if (!is_array($message))
	{
		// Non-existing message
		print_cp_no_permission();
	}

	// Edit
	print_cp_header(strip_tags(construct_phrase($vbphrase['dbtech_vbmail_editing_x_y'], $vbphrase['dbtech_vbmail_message'], $message['subject'])));
	print_form_header('vbmail', 'bounce');
	construct_hidden_code('action', 'update');
	construct_hidden_code('messageid', $messageid);
	print_table_header(construct_phrase($vbphrase['dbtech_vbmail_editing_x_y'], $vbphrase['dbtech_vbmail_message'], $message['subject']));
	print_input_row($vbphrase['from'], 						'message[fromaddress]', $message['fromaddress']);
	print_label_row($vbphrase['date'],												vbdate($vbulletin->options['dateformat'], $message['dateline']) . ' ' . vbdate($vbulletin->options['timeformat'], $message['dateline']));
	print_label_row($vbphrase['subject'],											$message['subject']);
	//print_label_row($vbphrase['dbtech_vbmail_mail_headers'],						nl2br($headers));
	print_label_row($vbphrase['message'],											nl2br($message['body']));
	print_yes_no_row($vbphrase['dbtech_vbmail_is_bounce'],	'message[bounce]',		$message['bounce']);
	print_submit_row($vbphrase['save']);
}

// #############################################################################
if ($_POST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'messageid' => TYPE_UINT,
		'message' 	=> TYPE_ARRAY,
	));

	if (!$existing = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_message WHERE messageid = " . intval($vbulletin->GPC['messageid'])))
	{
		// Couldn't find the message
		print_stop_message('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_message'], $vbulletin->GPC['messageid']);
	}

	// init data manager
	$dm =& VBMAIL::initDataManager('Message', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
		foreach ($vbulletin->GPC['message'] AS $key => $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	$dm->save();

	define('CP_REDIRECT', 'vbmail.php?do=bounce');
	print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_message'], $vbphrase['dbtech_vbmail_edited']);
}

// #############################################################################
if ($_REQUEST['action'] == 'delete')
{
	$vbulletin->input->clean_gpc('r', 'messageid', TYPE_UINT);

	print_cp_header(construct_phrase($vbphrase['dbtech_vbmail_delete_x'], $vbphrase['dbtech_vbmail_message']));
	print_delete_confirmation('dbtech_vbmail_message', $vbulletin->GPC['messageid'], 'vbmail', 'bounce', 'dbtech_vbmail_message', array('action' => 'kill'), '', 'subject');
	print_cp_footer();
}

// #############################################################################
if ($_POST['action'] == 'kill')
{
	$vbulletin->input->clean_gpc('r', 'messageid', TYPE_UINT);

	if (!$existing = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_message WHERE messageid = " . intval($vbulletin->GPC['messageid'])))
	{
		// Couldn't find the message
		print_stop_message('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_message'], $vbulletin->GPC['messageid']);
	}

	// init data manager
	$dm =& VBMAIL::initDataManager('Message', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
	$dm->delete();

	define('CP_REDIRECT', 'vbmail.php?do=bounce');
	print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_message'], $vbphrase['dbtech_vbmail_deleted']);
}

// #############################################################################
if ($_REQUEST['action'] == 'togglebounce')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('r', array(
		'messageid' => TYPE_UINT,
	));

	if (!$existing = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_message WHERE messageid = " . intval($vbulletin->GPC['messageid'])))
	{
		// Couldn't find the message
		print_stop_message('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_message'], $vbulletin->GPC['messageid']);
	}

	// Update bounce flag
	$newbounce = ($existing['bounce'] ? '0' : '1');

	// init data manager
	$dm =& VBMAIL::initDataManager('Message', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
		$dm->set('bounce', $newbounce);
	$dm->save();

	define('CP_REDIRECT', 'vbmail.php?do=bounce');
	print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_message'], $vbphrase['dbtech_vbmail_edited']);
}

// #############################################################################
if ($_REQUEST['action'] == 'prune')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'doprune'    => TYPE_BOOL,
		'startdate'  => TYPE_UNIXTIME,
		'enddate'    => TYPE_UNIXTIME,
	));

	if (!$vbulletin->GPC['doprune'])
	{
		// Nothing to do
		print_stop_message('nothing_to_do');
	}

	$sqlconds = array();

	if ($vbulletin->GPC['startdate'])
	{
		$sqlconds[] = "dateline >= " . $vbulletin->GPC['startdate'];
	}

	if ($vbulletin->GPC['enddate'])
	{
		$sqlconds[] = "dateline <= " . $vbulletin->GPC['enddate'];
	}

	//($hook = vBulletinHook::fetch_hook('admin_modlogviewer_query')) ? eval($hook) : false;

	$counter = $db->query_write("
		DELETE FROM " . TABLE_PREFIX . "dbtech_vbmail_message
		" . (!empty($sqlconds) ? "WHERE " . implode("\r\n\tAND ", $sqlconds) : "") . "
	");

	define('CP_REDIRECT', 'vbmail.php?do=bounce');
	print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_message'], $vbphrase['dbtech_vbmail_deleted']);
}

print_cp_footer();