<?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.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/
@set_time_limit(0);
ignore_user_abort(1);

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

// Add to the navbits
$navbits['vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists'] = $pagetitle = $vbphrase['dbtech_vbmail_mailing_lists'];

// #############################################################################
if ($_REQUEST['action'] == 'mailinglists' OR empty($_REQUEST['action']))
{
	// Array of subscription statuses
	$subscriptions = array();

	if ($vbulletin->userinfo['userid'])
	{
		$subscriptions = VBMAIL::$db->fetchAllSingleKeyed('
			SELECT *
			FROM $dbtech_vbmail_subscription
			WHERE userid = ?
		', 'mailinglistid', 'subscribed', array(
			$vbulletin->userinfo['userid']
		));
	}

	// Store list of userIds to lookup
	$userIds = array();
	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		if (!$mailinglist['active'])
		{
			// Inactive mailinglist
			continue;
		}

		if (isset($userIds[$mailinglist['ownerid']]))
		{
			// Ignore this
			continue;
		}
		$userIds[$mailinglist['ownerid']] = $mailinglist['ownerid'];
	}

	if (count($userIds) > 0)
	{
		$usernames = VBMAIL::$db->fetchAll('
			SELECT *
			FROM $user
			WHERE userid :queryList
		', array(
			':queryList' => VBMAIL::$db->queryList($userIds)
		));
		foreach ($usernames as $key => $username)
		{
			// Grab the markup username
			fetch_musername($username);

			// Store this in the lookup
			$userIds[$username['userid']] = $username['musername'];
		}
		unset($usernames);
	}

	// Set no owner
	$userIds[0] = $vbphrase['dbtech_vbmail_no_owner'];

	$mailids = array();
	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		if (!$mailinglist['active'])
		{
			// Inactive mailing list
			continue;
		}

		if (!$mailinglist['lastmailid'])
		{
			// Haven't mailed yet
			continue;
		}

		// Set mail id
		$mailids[] = $mailinglist['lastmailid'];
	}

	// Grab all the mails
	$lastmail = array();
	if (count($mailids))
	{
		$mails = VBMAIL::$db->fetchALl('
			SELECT mailid, subject
			FROM $dbtech_vbmail_mail
			WHERE mailid :queryList
		', array(
			':queryList' => VBMAIL::$db->queryList($mailids)
		));
		foreach ($mails as $mail)
		{
			// Store the last mail
			$lastmail[$mail['mailid']] = $mail['subject'];
		}
		unset($mails);
	}

	$show['unsubscribestats'] = false;

	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		if (!$mailinglist['active'])
		{
			// Inactive mailing list
			continue;
		}

		// Load the permissions
		$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

		if ($permarray['cannotview'] AND !$permarray['canview'])
		{
			// Can't view this mailing list
			continue;
		}

		if (($permarray['canviewstats'] OR $permarray['canmanage'] OR ($mailinglist['ownerid'] == $vbulletin->userinfo['userid'] AND $vbulletin->userinfo['userid'])))
		{
			// We can see at least one pair of stats
			$show['unsubscribestats'] = true;
		}
	}

	$mailinglists = '';
	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		if (!$mailinglist['active'])
		{
			// Inactive mailing list
			continue;
		}

		// Set various variables
		$mailinglist['owner'] 		= $userIds[$mailinglist['ownerid']];
		$mailinglist['description'] = nl2br($mailinglist['description']);

		// Load the permissions
		$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

		if ($permarray['cannotview'] AND !$permarray['canview'])
		{
			// Can't view this mailing list
			continue;
		}

		// Permission checks for send mail
		$show['sendmail'] = ((!$permarray['cansendmail'] AND !$permarray['canmanage'] AND $mailinglist['ownerid'] != $vbulletin->userinfo['userid']) OR !$vbulletin->userinfo['userid']) ? false : true;
		$show['unsubscribestats_bit'] = (($permarray['canviewstats'] OR $permarray['canmanage'] OR ($mailinglist['ownerid'] == $vbulletin->userinfo['userid'] AND $vbulletin->userinfo['userid']))) ? true : false;

		if ($mailinglist['external'])
		{
			$show['subscribe'] = false;
			$show['unsubscribe'] = false;
		}
		else
		{
			$show['subscribe'] = ($permarray['cansubscribe'] ? true : false);
			$show['unsubscribe'] = (!$permarray['nounsubscribe'] ? true : false);
		}

		// Add the last mail
		$mailinglist['lastmail'] = $lastmail[$mailinglist['lastmailid']];
		$mailinglist['lastmaildate'] = ($mailinglist['lastmaildateline'] ? vbdate($vbulletin->options['timeformat'], $mailinglist['lastmaildateline']) . ' - ' . vbdate($vbulletin->options['dateformat'], $mailinglist['lastmaildateline']) : 'N/A');

		$templater = vB_Template::create('dbtech_vbmail_mailinglist_bit');
			$templater->register('mailinglist', 		$mailinglist);
			$templater->register('permissions', 		$permarray);
			$templater->register('subscribed', 			(bool)$subscriptions[$mailinglistid]);
			$templater->register('subscriptionhash', 	VBMAIL::create_subscriptionhash($vbulletin->userinfo, $mailinglist));
		$mailinglists .= $templater->render();
	}

	// Mail sending form
	$page_templater = vB_Template::create('dbtech_vbmail_mailinglist');
		$page_templater->register('mailinglists', 	$mailinglists);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'history')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' => TYPE_UINT,
		'pagenumber'  	=> TYPE_UINT,
		'perpage'     	=> TYPE_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']] OR !$mailinglist['active'])
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ($permarray['cannotview'] AND !$permarray['canview'])
	{
		// Can't view this mailing list
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	$show['unsubscribestats'] = (($permarray['canviewstats'] OR $permarray['canmanage'] OR ($mailinglist['ownerid'] == $vbulletin->userinfo['userid'] AND $vbulletin->userinfo['userid']))) ? true : false;
	$show['deletemail'] = (($permarray['canmanage'] OR ($mailinglist['ownerid'] == $vbulletin->userinfo['userid'] AND $vbulletin->userinfo['userid']))) ? true : false;

	// Ensure there's no errors or out of bounds with the page variables
	if ($vbulletin->GPC['pagenumber'] < 1)
	{
		$vbulletin->GPC['pagenumber'] = 1;
	}
	$pagenumber = $vbulletin->GPC['pagenumber']; // $vbulletin->options['dbtech_vbshout_maxshouts']
	$perpage = (!$vbulletin->GPC['perpage'] OR $vbulletin->GPC['perpage'] > 25) ? 25 : $vbulletin->GPC['perpage'];

	// Count number of users
	$count = VBMAIL::$db->fetchOne('
		SELECT COUNT(*)
		FROM $dbtech_vbmail_mail AS mail
		WHERE mail.mailinglistid = ?
			###AND mail.visible = 1
	', array(
		$mailinglist['mailinglistid']
	));

	// Ensure every result is as it should be
	sanitize_pageresults($count, $pagenumber, $perpage);

	// Find out where to start
	$startat = ($pagenumber - 1) * $perpage;

	// Constructs the page navigation
	$pagenav = construct_page_nav(
		$pagenumber,
		$perpage,
		$count,
		'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&amp;action=history&amp;mailinglistid=' . $mailinglist['mailinglistid'],
		"&amp;perpage=$perpage"
	);

	// Fetch users
	$results = VBMAIL::$db->fetchAll('
		SELECT mailid, subject, dateline, unsubscriptions
		FROM $dbtech_vbmail_mail AS mail
		WHERE mail.mailinglistid = ?
			###AND mail.visible = 1
		ORDER BY dateline DESC
		LIMIT :limitStart, :limitEnd
	', array(
		$mailinglist['mailinglistid'],
		':limitStart' => $startat,
		':limitEnd' => $perpage,
	));

	$mail = '';
	foreach ($results as $result)
	{
		// Convert date
		$result['date'] = ($result['dateline'] ? vbdate($vbulletin->options['timeformat'], $result['dateline']) . ' ' . vbdate($vbulletin->options['dateformat'], $result['dateline']) : 'N/A');

		$templater = vB_Template::create('dbtech_vbmail_history_bit');
			$templater->register('mail', $result);
		$mail .= $templater->render();
	}
	unset($results);

	// Add to the navbits
	$navbits[] = $pagetitle = $vbphrase['dbtech_vbmail_mail_history'] = construct_phrase($vbphrase['dbtech_vbmail_mail_history'], $mailinglist['title']);

	// Mail sending form
	$page_templater = vB_Template::create('dbtech_vbmail_history');
		$page_templater->register('pagenav', 		$pagenav);
		$page_templater->register('pagenumber', 	$pagenumber);
		$page_templater->register('perpage', 		$perpage);
		$page_templater->register('mail', 			$mail);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'viewmail')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailid' 	=> TYPE_UINT,
	));

	if (!$mail = VBMAIL::$db->fetchRow('SELECT * FROM $dbtech_vbmail_mail WHERE mailid = ?', array($vbulletin->GPC['mailid'])))
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['email'], $vbulletin->GPC['mailid'])));
	}

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$mail['mailinglistid']] OR !$mailinglist['active'])
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $mail['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ($permarray['cannotview'] AND !$permarray['canview'])
	{
		// Can't view this mailing list
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $mail['mailinglistid'])));
	}

	// Add to the navbits
	$navbits['vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&amp;action=history&amp;mailinglistid=' . $mail['mailinglistid']] = construct_phrase($vbphrase['dbtech_vbmail_mail_history'], $mailinglist['title']);
	$navbits[] = $pagetitle = construct_phrase($vbphrase['dbtech_vbmail_viewing_mail_x'], $mail['subject']);

	// Convert date
	$mail['date'] = ($mail['dateline'] ? vbdate($vbulletin->options['timeformat'], $mail['dateline']) . ' ' . vbdate($vbulletin->options['dateformat'], $mail['dateline']) : 'N/A');

	// Mail sending form
	$page_templater = vB_Template::create('dbtech_vbmail_viewmail');
		$page_templater->register('mail', 		$mail);
		$page_templater->register('pagetitle', 	$pagetitle);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'deletemail')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailid' 	=> TYPE_UINT,
	));

	if (!$mail = VBMAIL::$db->fetchRow('SELECT * FROM $dbtech_vbmail_mail WHERE mailid = ?', array($vbulletin->GPC['mailid'])))
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['email'], $vbulletin->GPC['mailid'])));
	}

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$mail['mailinglistid']] OR !$mailinglist['active'])
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $mail['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ((!$permarray['canmanage'] AND $mailinglist['ownerid'] != $vbulletin->userinfo['userid']) OR !$vbulletin->userinfo['userid'])
	{
		// Can't view this mailing list
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $mail['mailinglistid'])));
	}

	// Delete mail
	VBMAIL::$db->delete('dbtech_vbmail_mail', array($vbulletin->GPC['mailid']), 'WHERE mailid = ?');

	// Set redirect URL
	$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&action=history&mailinglistid=' . $mail['mailinglistid'];
	eval(print_standard_redirect('redirect_dbtech_vbmail_mail_deleted'));
}

// #############################################################################
if ($_REQUEST['action'] == 'sendmail')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' => TYPE_UINT,
		'templateid' 	=> TYPE_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']] OR !$mailinglist['active'])
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ((!$permarray['cansendmail'] AND !$permarray['canmanage'] AND $mailinglist['ownerid'] != $vbulletin->userinfo['userid']) OR !$vbulletin->userinfo['userid'])
	{
		// This item isn't to be displayed
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_send_mail'])));
	}

	// Add to the navbits
	$navbits[] = $pagetitle = construct_phrase($vbphrase['dbtech_vbmail_send_mail'], $mailinglist['title']);

	if (!isset($_GET['templateid']))
	{
		// Create the number option template
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	0);
			$templater->register('optiontitle', 	$vbphrase['dbtech_vbmail_create_new_mail']);
			$templater->register('optionselected', 	'selected="selected" style="font-weight:normal"');
		$templateoptions = $templater->render();

		$options = array();
		$templates = VBMAIL::$db->fetchAll('
			SELECT templateid, mailinglistid, subject, permanent
			FROM $dbtech_vbmail_template
			WHERE mailinglistid :queryList
			ORDER BY dateline DESC, mailinglistid ASC
		', array(
			':queryList' => VBMAIL::$db->queryList(array(0, $mailinglist['mailinglistid']))
		));
		foreach ($templates as $template)
		{
			// Store array of options sorted by mailinglistid
			$templater = vB_Template::create('option');
				$templater->register('optionvalue', 	$template['templateid']);
				$templater->register('optiontitle', 	$template['subject']);
				$templater->register('optionselected', 	'style="font-weight:normal"');
			$options[$template['mailinglistid']][$template['permanent']] .= $templater->render();
		}
		unset($templates);

		foreach ($options as $mailinglistid => $optiontypes)
		{
			foreach ($optiontypes as $optiontype => $opshuns)
			{
				$templater = vB_Template::create('optgroup');
					$templater->register('optgroup_label', 		($mailinglistid ? $mailinglist['title'] : $vbphrase['dbtech_vbmail_global_templates']) . ' (' . $vbphrase['dbtech_vbmail_templatetype_' . $optiontype] . ')');
					$templater->register('optgroup_options', 	$opshuns);
					$templater->register('optgroup_extra', 		' style="font-weight:bold;"');
				$templateoptions .= $templater->render();
			}
		}

		// Template select form
		$page_templater = vB_Template::create('dbtech_vbmail_sendmail_choosetemplate');
			$page_templater->register('pagetitle', 		$pagetitle);
			$page_templater->register('templates', 		$templateoptions);
			$page_templater->register('mailinglist', 	$mailinglist);
		$HTML = $page_templater->render();
	}
	else
	{
		$message = '';
		if ($vbulletin->GPC['templateid'])
		{
			if (!$template = VBMAIL::$db->fetchRow('
				SELECT subject, message, keywords
				FROM $dbtech_vbmail_template
				WHERE templateid = ?
			', array(
				$vbulletin->GPC['templateid']
			)))
			{
				// Reset this, template not found
				$vbulletin->GPC['templateid'] = 0;
			}
			else
			{
				$message = $template['message'];
			}
		}

		// Unserialize this
		$template['keywords'] = @unserialize($template['keywords']);
		$template['keywords'] = (is_array($template['keywords']) ? $template['keywords'] : array());

		$keywords = '';
		foreach (VBMAIL::$cache['keyword'] as $keywordid => $keyword)
		{
			// Whether they're currently subscribed to this keyword
			$keyword['checked'] = ($template['keywords'][$keywordid] ? ' checked="checked"' : '');

			// Mail sending form
			$templater = vB_Template::create('dbtech_vbmail_keywords_bit');
				$templater->register('keyword', 		$keyword);
			$keywords .= $templater->render();
		}

		require_once(DIR . '/includes/functions_editor.php');
		$editorid = construct_edit_toolbar($message, false, 'nonforum', false, false, false);

		// Mail sending form
		$page_templater = vB_Template::create('dbtech_vbmail_sendmail');
			$page_templater->register('subject', 		$template['subject']);
			$page_templater->register('editorid', 		$editorid);
			$page_templater->register('messagearea', 	$messagearea);
			$page_templater->register('mailinglist', 	$mailinglist);
			$page_templater->register('templateid', 	$vbulletin->GPC['templateid']);
			$page_templater->register('keywords', 		$keywords);
		$HTML = $page_templater->render();
	}
}

// #############################################################################
if ($_POST['action'] == 'dosendmail')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' => TYPE_UINT,
		'wysiwyg' 		=> TYPE_BOOL,
		'subject' 		=> TYPE_STR,
		'message' 		=> TYPE_STR,
		'savedraft' 	=> TYPE_STR,
		'savetemplate' 	=> TYPE_STR,
		'deletetemplate'=> TYPE_STR,
		'templateid' 	=> TYPE_UINT,
		'keywords' 		=> TYPE_ARRAY_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']] OR !$mailinglist['active'])
	{
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Set this so we know what we can use in mail_send hook
	VBMAIL::$pluginglobals['mailinglist'] = $mailinglist;

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ((!$permarray['cansendmail'] AND !$permarray['canmanage'] AND $mailinglist['ownerid'] != $vbulletin->userinfo['userid']) OR !$vbulletin->userinfo['userid'])
	{
		// This item isn't to be displayed
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_send_mail'])));
	}

	if ($vbulletin->GPC['subject'] == '' OR $vbulletin->GPC['message'] == '' OR !is_valid_email($mailinglist['fromemail']))
	{
		// Something was missin'
		eval(standard_error(fetch_error('please_complete_required_fields')));
	}

	$isHTML = (strpos($vbulletin->GPC['message'], '&lt;!DOCTYPE') !== false OR strpos($vbulletin->GPC['message'], '<!DOCTYPE') !== false);
	if ($vbulletin->GPC['wysiwyg'] AND !$isHTML)
	{
		// We were using WYSIWYG editor
		if (!file_exists(DIR . '/includes/functions_wysiwyg.php'))
		{
			// New editor
			require_once(DIR . '/includes/class_wysiwygparser.php');
			$html_parser = new vB_WysiwygHtmlParser($vbulletin);
			$message = $html_parser->parse_wysiwyg_html_to_bbcode($vbulletin->GPC['message'], true);
		}
		else
		{
			// Old editor
			require_once(DIR . '/includes/functions_wysiwyg.php');
			$message = convert_wysiwyg_html_to_bbcode($vbulletin->GPC['message'], true);
		}
	}
	else
	{
		// Not WYSIWYG, interpret as-is
		$message = $vbulletin->GPC['message'];
	}

	if (!$isHTML)
	{
		if (!function_exists('convert_url_to_bbcode'))
		{
			// Ensure we can convert URL to BBCode
			require_once(DIR . '/includes/functions_newpost.php');
		}

		// Convert URL to BBCode
		$message = convert_url_to_bbcode($message);
	}

	foreach ($vbulletin->GPC['keywords'] as $keywordid => $onoff)
	{
		if (!$onoff)
		{
			// Invalid keyword
			unset($vbulletin->GPC['keywords'][$keywordid]);
			continue;
		}

		if (!$keyword = VBMAIL::$cache['keyword'][$keywordid])
		{
			// Invalid keyword
			unset($vbulletin->GPC['keywords'][$keywordid]);
			continue;
		}

		if (!$keyword['active'])
		{
			// Inactive keyword
			unset($vbulletin->GPC['keywords'][$keywordid]);
			continue;
		}
	}

	// Default let lite mods handle it
	$handled = false;

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

	/*DBTECH_PRO_START*/
	if (!$handled)
	{
		if ($vbulletin->GPC['savedraft'] OR $vbulletin->GPC['savetemplate'] OR $vbulletin->GPC['deletetemplate'])
		{
			$handled = true;

			if ($vbulletin->GPC['templateid'])
			{
				// Get info on existing template
				$existing = VBMAIL::$db->fetchRow('SELECT * FROM $dbtech_vbmail_template WHERE templateid = ?', array($vbulletin->GPC['templateid']));
			}

			if ($vbulletin->GPC['deletetemplate'])
			{
				// Delete template
				VBMAIL::$db->delete('dbtech_vbmail_template', array($vbulletin->GPC['templateid']), 'WHERE templateid = ?');
			}
			else
			{
				// The array of data
				$data = array(
					'mailinglistid' => $vbulletin->GPC['mailinglistid'],
					'subject' => $vbulletin->GPC['subject'],
					'message' => $message,
					'dateline' => TIMENOW,
					'permanent' => ($vbulletin->GPC['savedraft'] ? '0' : '1'),
					'keywords' => trim(serialize($vbulletin->GPC['keywords']))
				);

				if ($vbulletin->GPC['templateid'])
				{
					if (
						($existing['permanent'] AND $vbulletin->GPC['savedraft'])
						OR (!$existing['permanent'] AND $vbulletin->GPC['savetemplate'])
					)
					{
						// Draft saved as a template OR template saved as draft
						VBMAIL::$db->insert('dbtech_vbmail_template', $data);
					}
					else
					{
						// Save changes
						VBMAIL::$db->update('dbtech_vbmail_template', $data, 'WHERE templateid = ' . intval($vbulletin->GPC['templateid']));
					}
				}
				else
				{
					// New template or draft
					VBMAIL::$db->insert('dbtech_vbmail_template', $data);
				}
			}

			// Set redirect URL
			$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&action=sendmail&mailinglistid=' . $vbulletin->GPC['mailinglistid'];
		}
	}
	/*DBTECH_PRO_END*/

	if (!$handled)
	{
		if ($vbulletin->GPC['templateid'])
		{
			// If this was a draft, delete it
			VBMAIL::$db->delete('dbtech_vbmail_template', array($vbulletin->GPC['templateid'], '0'), 'WHERE templateid = ? AND permanent = ?');
		}

		if (!$isHTML)
		{
			// Set some values
			$fielddefs = array('allowhtml', 'allowbbcode', 'allowbbimagecode');
			$backup = array();

			foreach ($fielddefs as $field)
			{
				// Back up these values
				$backup[$field] = $vbulletin->options[$field];
				$vbulletin->options[$field] = true;
			}

			// Parse the BBCode that we generated
			require_once(DIR . '/includes/class_bbcode.php');
			$parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
			$message = $parser->parse($message, 'nonforum', false);
			unset($parser);

			foreach ($fielddefs as $field)
			{
				// Back up these values
				$vbulletin->options[$field] = $backup[$field];
			}
		}

		// Get the Mail ID from the history
		$mailid = VBMAIL::$db->insert('dbtech_vbmail_mail', array(
			'mailinglistid' => $vbulletin->GPC['mailinglistid'],
			'subject' => $vbulletin->GPC['subject'],
			'message' => $message,
			'dateline' => TIMENOW,
			'keywords' => trim(serialize($vbulletin->GPC['keywords']))
		));

		// init data manager
		$timenow = TIMENOW;
		$dm =& VBMAIL::initDataManager('Mailinglist', $vbulletin, ERRTYPE_SILENT);
			$dm->set_existing($mailinglist);
			$dm->set('lastmailid', 			$mailid);
			$dm->set('lastmaildateline', 	$timenow);
		$dm->save();

		// Set redirect URL
		$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&action=mailqueue&mailid=' . $mailid . '&mailqueuehash=' . md5(md5($mailid) . $vbulletin->userinfo['salt']);
	}

	// Success phrase
	eval(print_standard_redirect('redirect_dbtech_vbmail_mail_sent'));
}

// #############################################################################
if ($_REQUEST['action'] == 'mailqueue')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailid' 		=> TYPE_UINT,
		'mailqueuehash' => TYPE_STR,
		'perpage' 		=> TYPE_UINT,
		'startat' 		=> TYPE_UINT,
	));

	if (!$mail = VBMAIL::$db->fetchRow('SELECT * FROM $dbtech_vbmail_mail WHERE mailid = ?', array($vbulletin->GPC['mailid'])))
	{
		// This item isn't to be displayed
		$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
		eval(print_standard_redirect('redirect_dbtech_vbmail_mail_sent'));
	}

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$mail['mailinglistid']] OR !$mailinglist['active'])
	{
		// Invalid mailing list
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $mail['mailinglistid'])));
	}

	if ($vbulletin->GPC['mailqueuehash'] != md5(md5($mail['mailid']) . $vbulletin->userinfo['salt']))
	{
		// This item isn't to be displayed
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_send_mail'])));
	}

	// Set this so we know what we can use in mail_send hook
	VBMAIL::$pluginglobals['mailinglist'] = $mailinglist;
	VBMAIL::$pluginglobals['mailinglist']['mailid'] = $mail['mailid'];

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ((!$permarray['cansendmail'] AND !$permarray['canmanage'] AND $mailinglist['ownerid'] != $vbulletin->userinfo['userid']) OR !$vbulletin->userinfo['userid'])
	{
		// This item isn't to be displayed
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_send_mail'])));
	}

	if ($mail['subject'] == '' OR $mail['message'] == '' OR !is_valid_email($mailinglist['fromemail']))
	{
		// Something was missin'
		eval(standard_error(fetch_error('please_complete_required_fields')));
	}

	if (empty($vbulletin->GPC['perpage']))
	{
		$vbulletin->GPC['perpage'] = 500;
		/*DBTECH_PRO_START*/
		$vbulletin->GPC['perpage'] = $mailinglist['mailperpage'] ? $mailinglist['mailperpage'] : $vbulletin->GPC['perpage'];
		/*DBTECH_PRO_END*/
	}

	$isHTML = (strpos($mail['message'], '&lt;!DOCTYPE') !== false OR strpos($mail['message'], '<!DOCTYPE') !== false);

	if (!function_exists('fetch_phrase'))
	{
		require_once(DIR . '/includes/functions_misc.php');
	}

	// Unserialize this
	$mail['keywords'] = @unserialize($mail['keywords']);
	$mail['keywords'] = (is_array($mail['keywords']) ? $mail['keywords'] : array());

	$keywords = array();
	foreach (VBMAIL::$cache['keyword'] as $keywordid => $keyword)
	{
		if (!$keyword['active'])
		{
			// Inactive keyword
			continue;
		}

		if (!$mail['keywords'][$keywordid])
		{
			// Not a part of mail sending
			continue;
		}

		// Store the keyword id
		$keywords[] = $keywordid;
	}

	// Fire ze mailqueue
	vbmail_start();

	// get users to mail
	$users = $db->query_read_slave("
		SELECT user.*" . ($mailinglist['external'] ? ', -1 AS languageid' : '') . "
		FROM " . TABLE_PREFIX . "dbtech_vbmail_subscription AS subscription
		LEFT JOIN " . TABLE_PREFIX . ($mailinglist['external'] ? 'dbtech_vbmail_' : '') . "user AS user USING(userid)
		WHERE subscription.subscribed = '1'
			AND subscription.mailinglistid = " . intval($mailinglist['mailinglistid']) . "
			AND user.dbtech_vbmail_bounceflag = '0'
		ORDER BY user.userid ASC
		LIMIT " . $vbulletin->GPC['startat'] . ", " . $vbulletin->GPC['perpage'] . "
	");
	if ($db->num_rows($users))
	{
		// Begin list of users we've mailed this session
		$userlist = '';
		while ($user = $db->fetch_array($users))
		{
			VBMAIL::$pluginglobals['user'] = $user;

			$continue = true;
			if (count($keywords))
			{
				// Begin storing this array
				$keywordsubscriptions = array();

				// Get our current subscription values
				$subscriptionkeywords = $db->query_read_slave("
					SELECT keywordid, subscribed
					FROM " . TABLE_PREFIX . "dbtech_vbmail_subscriptionkeyword
					WHERE userid = " . intval($user['userid']) . "
						AND mailinglistid = " . intval($mailinglist['mailinglistid']) . "
						AND keywordid IN (" . implode(',', $keywords) . ")
				");
				while ($subscriptionkeyword = $db->fetch_array($subscriptionkeywords))
				{
					// Store the keyword subscription
					$keywordsubscriptions[$subscriptionkeyword['keywordid']] = $subscriptionkeyword['subscribed'];
				}

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

				foreach ($keywords as $keywordid)
				{
					if (!isset($keywordsubscriptions[$keywordid]))
					{
						// Hardcode to default
						$keywordsubscriptions[$keywordid] = $user['dbtech_vbmail_defaultkeyword'];
					}

					if ($keywordsubscriptions[$keywordid])
					{
						// We're receiving this mail
						$continue = false;
						break;
					}
				}
			}
			else
			{
				// We're not skipping
				$continue = false;
			}

			// Set user list data
			$userlist .= "$user[userid] - $user[username] .... \n";

			// Load the permissions
			$permarray = VBMAIL::load_mailinglist_permissions($mailinglist, $user);

			// Set unsubscribe hash
			$hash = VBMAIL::create_subscriptionhash($user, $mailinglist);

			$unsubscribelink = $vbulletin->options['bburl'] . '/vbmail.php?do=mailinglists&amp;action=managesubscription&amp;mailinglistid=' . $mailinglist['mailinglistid'] . '&amp;u=' . $user['userid'] . '&amp;type=subscribed&subscriptionhash=' . $hash;
			$subscribelink = $vbulletin->options['bburl'] . '/vbmail.php?do=mailinglists&amp;action=managesubscription&amp;mailinglistid=' . $mailinglist['mailinglistid'] . '&amp;u=' . $user['userid'] . '&amp;type=subscribe&subscriptionhash=' . $hash;

			// Do some variable replacements
			$uniquesubject = str_replace(
				array('{userid}', '{username}', '{email}', '{mailinglist}', '{forumtitle}'),
				array($user['userid'], $user['username'], $user['email'], $mailinglist['title'], $vbulletin->options['bbtitle']),
				$mail['subject']
			);
			$uniquemessage = str_replace(
				array('{userid}', '{username}', '{email}', '{mailinglist}', '{forumtitle}', '{unsubscribelink}', '{subscribelink}'),
				array(
					$user['userid'],
					$user['username'],
					$user['email'],
					$mailinglist['title'],
					$vbulletin->options['bbtitle'],
					'<a href="' . $unsubscribelink . '">' . fetch_phrase('dbtech_vbmail_unsubscribe', 'dbtech_vbmail', '', false, false, $user['languageid']) . '</a> ( ' . $unsubscribelink . ' )',
					'<a href="' . $subscribelink . '">' . fetch_phrase('dbtech_vbmail_subscribe', 'dbtech_vbmail', '', false, false, $user['languageid']) . '</a> ( ' . $subscribelink . ' )'
				),
				$mail['message']
			);

			if (!$permarray['nounsubscribe'] OR $mailinglist['external'])
			{
				// We can unsubscribe
				$uniquemessage .= '<p style="font-size:11px;">' . construct_phrase(fetch_phrase('dbtech_vbmail_unsubscribelink', 'dbtech_vbmail', '', false, false, $user['languageid']),
					$mailinglist['title'],
					$vbulletin->options['bburl'],
					$mailinglist['mailinglistid'],
					$user['userid'],
					$hash,
					($permarray['cansubscribe'] ? construct_phrase(fetch_phrase('dbtech_vbmail_keywordmanagelink', 'dbtech_vbmail', '', false, false, $user['languageid']),
						$vbulletin->options['bburl'],
						$mailinglist['mailinglistid']
					) : ''),
					$mail['mailid'],
					$vbulletin->options['bbtitle'],
					$user['email']
				) . '</p>';
			}

			if ($show['vbmail_branding'] AND !$show['_dbtech_branding_override'])
			{
				$brandingVariables = array(
					'flavour' 			=> 'Mailing List provided by ',
					'productid' 		=> 107,
					'utm_source' 		=> str_replace('www.', '', htmlspecialchars_uni($_SERVER['HTTP_HOST'])) . ' (email)',
					'utm_content' 		=> (VBMAIL::$isPro ? 'Pro' : 'Lite'),
					'referrerid' 		=> $vbulletin->options['dbtech_vbmail_referral'],
					'title' 			=> 'vBMail',
					'displayversion' 	=> $vbulletin->options['dbtech_vbmail_displayversion'],
					'version' 			=> '2.1.3 Patch Level 1',
					'producttype' 		=> $show['dbtech_vbmail_producttype']
				);
				$uniquemessage .= '<p style="font-size:11px;">' . $brandingVariables['flavour'] . '
					<a rel="nofollow" href="http://www.dragonbyte-tech.com/vbecommerce.php' . ($brandingVariables['productid'] ? '?productid=' . $brandingVariables['productid'] . '&do=product&' : '?') . 'utm_source=' . $brandingVariables['utm_source'] . '&utm_campaign=product&utm_medium=' . urlencode(str_replace(' ', '+', $brandingVariables['title'])) . '&utm_content=' . $brandingVariables['utm_content'] . ($brandingVariables['referrerid'] ? '&referrerid=' . $brandingVariables['referrerid'] : '') . '" target="_blank">' . $brandingVariables['title'] . '</a>.
					<a rel="nofollow" href="http://www.dragonbyte-tech.com/?utm_source=' . $brandingVariables['utm_source'] . '&utm_campaign=site&utm_medium=' . urlencode(str_replace(' ', '+', $brandingVariables['title'])) . '&utm_content=' . $brandingVariables['utm_content'] . ($brandingVariables['referrerid'] ? '&referrerid=' . $brandingVariables['referrerid'] : '') . '" target="_blank">Copyright &copy; ' . date('Y') . ' DragonByte Technologies Ltd.</a>
				</p>';
			}

			if (intval($vbulletin->versionnumber) > 3)
			{
				$stylevar['textdirection'] = vB_Template_Runtime::fetchStyleVar('textdirection');
				$stylevar['languagecode'] = vB_Template_Runtime::fetchStyleVar('languagecode');
			}

			if (!$isHTML)
			{
				$uniquemessage = '<html dir="' . $stylevar['textdirection'] . '" lang="' . $stylevar['languagecode'] . '">' . $uniquemessage . '</html>';
			}

			if (!$vbulletin->GPC['test'])
			{
				// Queue up the email
				$userlist .= $vbphrase['emailing'] . " \n";

				if ($continue)
				{
					// Skipping due to keyword subscriptions
					$userlist .= "Skipping (keyword subscriptions) ... \n";
				}
				else
				{
					if (!((int)$user['options'] & $vbulletin->bf_misc_useroptions['adminemail']) AND !$mailinglist['external'])
					{
						// Skipping due to keyword subscriptions
						$userlist .= "Skipping (Admin Email flag) ... \n";
					}
					else
					{
						// By default we're not sending instantly
						$instantSend = false;

						/*DBTECH_PRO_START*/
						$instantSend = (bool)$mailinglist['instantsend'];
						/*DBTECH_PRO_END*/

						// Actually mail em
						vbmail($user['email'], $uniquesubject, $uniquemessage, $instantSend, $mailinglist['fromemail']);
					}
				}
			}
			else
			{
				$userlist .= "Test ... \n";
			}
			$userlist .= $vbphrase['okay'] . "<br />\n";
		}

		// Ze mailqueue ended
		vbmail_end();

		// Get rid of this
		unset(VBMAIL::$pluginglobals['mailinglist'], VBMAIL::$pluginglobals['user']);

		// Increment start at
		$vbulletin->GPC['startat'] += $vbulletin->GPC['perpage'];

		// Redirect to next page
		$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists&action=mailqueue&mailid=' . $mail['mailid'] . '&mailqueuehash=' . md5(md5($mail['mailid']) . $vbulletin->userinfo['salt']) . '&startat=' . $vbulletin->GPC['startat'];
		standard_redirect($userlist, true);
	}
	else
	{
		if ($vbulletin->GPC['test'])
		{
			// T'was a test email only
			$db->query_first_slave("DELETE FROM " . TABLE_PREFIX . "dbtech_vbmail_mail WHERE mailid = " . intval($vbulletin->GPC['mailid']));
		}

		$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
		eval(print_standard_redirect('redirect_dbtech_vbmail_mail_sent'));
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'managesubscription')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'type' 				=> TYPE_STR,
		'mailinglistid' 	=> TYPE_UINT,
		'userid' 			=> TYPE_UINT,
		'subscriptionhash' 	=> TYPE_NOHTML,
		'mailid' 			=> TYPE_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	if (!$vbulletin->GPC['userid'] OR $vbulletin->GPC['userid'] == $vbulletin->userinfo['userid'] AND !$mailinglist['external'])
	{
		// We're doing it for ourselves
		$user = $vbulletin->userinfo;
	}
	else
	{
		// Lookup username
		if (!$user = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . ($mailinglist['external'] ? 'dbtech_vbmail_' : '') . "user WHERE userid = " . intval($vbulletin->GPC['userid'])))
		{
			// Invalid user
			eval(standard_error(fetch_error('no_users_matched_your_query')));
		}
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist, $user);

	if (!$mailinglist['external'])
	{
		if ($vbulletin->GPC['type'] == 'subscribed')
		{
			if ($permarray['nounsubscribe'])
			{
				// Cannot unsubscribe
				eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_unsubscribe'])));
			}
		}
		else
		{
			if (!$permarray['cansubscribe'])
			{
				// Cannot subscribe
				eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_subscribe'])));
			}
		}
	}

	if (VBMAIL::create_subscriptionhash($user, $mailinglist) != $vbulletin->GPC['subscriptionhash'])
	{
		// Invalid subscription hash
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_invalid_subscription_hash'])));
	}

	// Reverse type
	$subscribeflag = ($vbulletin->GPC['type'] == 'subscribed' ? 0 : 1);

	// Update db
	$db->query_write("
		UPDATE " . TABLE_PREFIX . "dbtech_vbmail_subscription
		SET subscribed = '$subscribeflag'
		WHERE userid = " . intval($user['userid']) . "
			AND mailinglistid = " . intval($mailinglist['mailinglistid'])
	);

	// Check if this existed
	$exists = $db->affected_rows();
	if (!$exists AND $subscribeflag)
	{
		// Subscribe this user
		VBMAIL::subscribeUser($user, $mailinglist, 'subscriptionlink');
	}
	else if ($exists)
	{
		// We either subscribed or unsubscribed
		VBMAIL::$db->insert('dbtech_vbmail_subscriptionlog', array(
			'userid' 		=> $user['userid'],
			'mailinglistid' => $mailinglist['mailinglistid'],
			'dateline' 		=> TIMENOW,
			'subscribed' 	=> $subscribeflag,
			'reason' 		=> (!$subscribeflag ? 'un' : '') . 'subscribed',
			'mailid' 		=> $vbulletin->GPC['mailid']
		));
	}

	if ($vbulletin->GPC['mailid'])
	{
		// We have a mail id
		if ($mail = $db->query_first_slave("SELECT unsubscriptions FROM " . TABLE_PREFIX . "dbtech_vbmail_mail WHERE mailid = " . intval($vbulletin->GPC['mailid'])))
		{
			// Mail id was valid
			if (!$subscribeflag OR $mail['unsubscriptions'])
			{
				// We're either unsubscribing, or we can decrement it successfully
				$db->query_write("
					UPDATE " . TABLE_PREFIX . "dbtech_vbmail_mail
					SET unsubscriptions = unsubscriptions " . (!$subscribeflag ? '+' : '-') . " 1
					WHERE mailid = " . intval($vbulletin->GPC['mailid'])
				);
			}
		}
	}

	if (!$subscribeflag OR $mailinglist['unsubscriptions'])
	{
		// We're either unsubscribing, or we can decrement it successfully

		// init data manager
		$dm =& VBMAIL::initDataManager('Mailinglist', $vbulletin, ERRTYPE_SILENT);
			$dm->set_existing($mailinglist);
			$dm->set('unsubscriptions', 'unsubscriptions ' . (!$subscribeflag ? '+' : '-') . ' 1', false);
		$dm->save();
	}

	if (!$subscribeflag AND $vbulletin->options['dbtech_vbmail_enable_unsubscribe_feedback'])
	{
		// Init this
		$unsubscribereasons = '';

		if (!function_exists('fetch_phrase'))
		{
			require_once(DIR . '/includes/functions_misc.php');
		}

		foreach (VBMAIL::$cache['feedback'] as $feedback)
		{
			if (array_key_exists('dbtech_vbmail_unsubscribefeedback_' . $feedback['feedbackid'] . '_title', $vbphrase))
			{
				// Set the language versions of this
				$feedback['title'] 			= fetch_phrase('dbtech_vbmail_unsubscribefeedback_' . $feedback['feedbackid'] . '_title', 		'global', '', false, false, $user['languageid']);
			}

			if (array_key_exists('dbtech_vbmail_unsubscribefeedback_' . $feedback['feedbackid'] . '_description', $vbphrase))
			{
				// Set the language versions of this
				$feedback['description'] 	= fetch_phrase('dbtech_vbmail_unsubscribefeedback_' . $feedback['feedbackid'] . '_description', 'global', '', false, false, $user['languageid']);
			}

			// Mail sending form
			$templater = vB_Template::create('dbtech_vbmail_unsubscribe_feedback_bit');
				$templater->register('feedback', $feedback);
			$unsubscribereasons .= $templater->render();
		}

		// Mail sending form
		$page_templater = vB_Template::create('dbtech_vbmail_unsubscribe_feedback');
			$page_templater->register('mailinglist', 		$mailinglist);
			$page_templater->register('mailid', 			intval($vbulletin->GPC['mailid']));
			$page_templater->register('userid', 			intval($user['userid']));
			$page_templater->register('subscriptionhash', 	$vbulletin->GPC['subscriptionhash']);
			$page_templater->register('mailid', 			intval($vbulletin->GPC['mailid']));
			$page_templater->register('unsubscribereasons', $unsubscribereasons);
		$HTML = $page_templater->render();
	}
	else
	{
		// Do redirect
		$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
		eval(print_standard_redirect('redirect_dbtech_vbmail_subscription_changed', true, true));
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'unsubscribefeedback')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' 			=> TYPE_UINT,
		'userid' 					=> TYPE_UINT,
		'subscriptionhash' 			=> TYPE_NOHTML,
		'mailid' 					=> TYPE_UINT,
		'unsubscribereason' 		=> TYPE_NOHTML,
		'unsubscribereason_other' 	=> TYPE_NOHTML,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	if (!$vbulletin->GPC['userid'] OR $vbulletin->GPC['userid'] == $vbulletin->userinfo['userid'] AND !$mailinglist['external'])
	{
		// We're doing it for ourselves
		$user = $vbulletin->userinfo;
	}
	else
	{
		// Lookup username
		if (!$user = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . ($mailinglist['external'] ? 'dbtech_vbmail_' : '') . "user WHERE userid = " . intval($vbulletin->GPC['userid'])))
		{
			// Invalid user
			eval(standard_error(fetch_error('no_users_matched_your_query')));
		}
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist, $user);

	if (!$mailinglist['external'])
	{
		if ($vbulletin->GPC['type'] == 'subscribed')
		{
			if ($permarray['nounsubscribe'])
			{
				// Cannot unsubscribe
				eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_unsubscribe'])));
			}
		}
		else
		{
			if (!$permarray['cansubscribe'])
			{
				// Cannot subscribe
				eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_subscribe'])));
			}
		}
	}

	if (VBMAIL::create_subscriptionhash($user, $mailinglist) != $vbulletin->GPC['subscriptionhash'])
	{
		// Invalid subscription hash
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_invalid_subscription_hash'])));
	}

	if ($vbulletin->GPC['unsubscribereason'] != 'other')
	{
		if (!$feedback = VBMAIL::$cache['feedback'][$vbulletin->GPC['unsubscribereason']])
		{
			// Invalid subscription hash
			eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_feedback'], $vbulletin->GPC['unsubscribereason'])));
		}

		// We can assume this is the global language version
		$unsubscribereason = $feedback['title'];
	}
	else
	{
		if (!function_exists('fetch_phrase'))
		{
			require_once(DIR . '/includes/functions_misc.php');
		}

		// Fetch global language version
		$unsubscribereason = fetch_phrase('dbtech_vbmail_unsubscribereason_other', 'dbtech_vbmail', '', false, false, $vbulletin->options['languageid']);
	}

	$info = array(
		'username' 		=> $user['username'],
		'mailinglist' 	=> $mailinglist['title'],
		'bbtitle' 		=> $vbulletin->options['bbtitle'],
		'pagetext' 		=> ($unsubscribereason . ($vbulletin->GPC['unsubscribereason_other'] ? "\n\n------------\n" . $vbulletin->GPC['unsubscribereason_other'] . "\n------------" : ''))
	);

	eval(fetch_email_phrases('dbtech_vbmail_new_unsubscription_mailinglist', $vbulletin->options['languageid']));

	// FIRE ZE EMAILZ
	vbmail($vbulletin->options['webmasteremail'], $subject, $message, true);

	// Do redirect
	$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
	eval(print_standard_redirect('redirect_dbtech_vbmail_subscription_changed', true, true));
}

/*DBTECH_PRO_START*/
// #############################################################################
if ($_REQUEST['action'] == 'subscribeexternal')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' 	=> TYPE_UINT,
		'email' 			=> TYPE_STR,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	if (!$mailinglist['active'])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	if (!$mailinglist['external'])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if ($permarray['cannotview'] AND !$permarray['canview'])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	if ($existing = $db->query_first_slave("SELECT userid FROM " . TABLE_PREFIX . "dbtech_vbmail_user WHERE username = " . $db->sql_prepare(htmlspecialchars_uni($vbulletin->GPC['email']))))
	{
		// Set the user id
		$userid = $existing['userid'];
	}
	else
	{
		$salt = '';
		for ($i = 0; $i < 30; $i++)
		{
			$salt .= chr(rand(33, 126));
		}

		// Insert into dbtech_vbmail_user table
		$db->query_write("
			INSERT INTO `" . TABLE_PREFIX . "dbtech_vbmail_user`
				(`username`, `email`, `usergroupid`, `salt`)
			VALUES (
				" . $db->sql_prepare(htmlspecialchars_uni($vbulletin->GPC['username'])) . ",
				" . $db->sql_prepare(htmlspecialchars_uni($vbulletin->GPC['username'])) . ",
				'2',
				'" . addslashes($salt) . "'
			)
		");
		$userid = $db->insert_id();
	}

	// Lookup username
	if (!$user = $db->query_first_slave("SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_user WHERE userid = " . intval($userid)))
	{
		// Invalid user
		eval(standard_error(fetch_error('no_users_matched_your_query')));
	}

	$subscribed = 1;

	// Update db
	$db->query_write("
		UPDATE " . TABLE_PREFIX . "dbtech_vbmail_subscription
		SET subscribed = '$subscribed'
		WHERE userid = " . intval($userid) . "
			AND mailinglistid = " . intval($mailinglist['mailinglistid'])
	);

	// Check if this existed
	$exists = $db->affected_rows();
	if (!$exists)
	{
		// Subscribe this user
		VBMAIL::subscribeUser($user, $mailinglist, 'subscriptionlink');
	}
	else
	{
		// We either subscribed or unsubscribed
		VBMAIL::$db->insert('dbtech_vbmail_subscriptionlog', array(
			'userid' 		=> $user['userid'],
			'mailinglistid' => $mailinglist['mailinglistid'],
			'dateline' 		=> TIMENOW,
			'subscribed' 	=> 1,
			'reason' 		=> 'subscribed',
		));
	}

	// Do redirect
	$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
	eval(print_standard_redirect('redirect_dbtech_vbmail_subscription_changed'));
}
/*DBTECH_PRO_END*/

// #############################################################################
if ($_REQUEST['action'] == 'managekeywordsubscription')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' 	=> TYPE_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if (!$permarray['cansubscribe'])
	{
		// Cannot subscribe
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_subscribe'])));
	}

	$keywordStatus = array();
	$keywords = $db->query_read_slave("
		SELECT keywordid, subscribed
		FROM " . TABLE_PREFIX . "dbtech_vbmail_subscriptionkeyword
		WHERE userid = " . intval($vbulletin->userinfo['userid']) . "
			AND mailinglistid = " . intval($mailinglist['mailinglistid'])
	);
	while ($keyword = $db->fetch_array($keywords))
	{
		// Set keyword status
		$keywordStatus[$keyword['keywordid']] = $keyword['subscribed'];
	}

	$keywords = '';
	foreach (VBMAIL::$cache['keyword'] as $keywordid => $keyword)
	{
		if (isset($keywordStatus[$keywordid]))
		{
			// Whether they're currently subscribed to this keyword
			$keyword['checked'] = ($keywordStatus[$keywordid] ? ' checked="checked"' : '');
		}
		else
		{
			// Default values
			$keyword['checked'] = ($vbulletin->userinfo['dbtech_vbmail_defaultkeyword'] ? ' checked="checked"' : '');
		}

		// Mail sending form
		$templater = vB_Template::create('dbtech_vbmail_keywords_bit');
			$templater->register('keyword', 		$keyword);
			$templater->register('class', 			'alt1');
		$keywords .= $templater->render();
	}

	// Add to the navbits
	$navbits[] = $pagetitle = construct_phrase($vbphrase['dbtech_vbmail_manage_keyword_subscriptions'], $mailinglist['title']);

	// Mail sending form
	$page_templater = vB_Template::create('dbtech_vbmail_keywords');
		$page_templater->register('keywords', 		$keywords);
		$page_templater->register('mailinglist', 	$mailinglist);
		$page_templater->register('pagetitle', 		$pagetitle);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_POST['action'] == 'domanagekeywordsubscription')
{
	$vbulletin->input->clean_array_gpc('r', array(
		'mailinglistid' 	=> TYPE_UINT,
		'keywords' 			=> TYPE_ARRAY_UINT,
	));

	if (!$mailinglist = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
	{
		// Couldn't find the mailinglist
		eval(standard_error(fetch_error('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid'])));
	}

	// Load the permissions
	$permarray = VBMAIL::load_mailinglist_permissions($mailinglist);

	if (!$permarray['cansubscribe'])
	{
		// Cannot subscribe
		eval(standard_error(fetch_error('dbtech_vbmail_error_x', $vbphrase['dbtech_vbmail_cannot_subscribe'])));
	}


	foreach ($vbulletin->GPC['keywords'] as $keywordid => $value)
	{
		if (!$existing = VBMAIL::$cache['keyword'][$keywordid])
		{
			// Doesn't exist
			continue;
		}

		// Update subscription status
		$db->query_write("
			REPLACE INTO " . TABLE_PREFIX . "dbtech_vbmail_subscriptionkeyword
				(userid, mailinglistid, keywordid, subscribed)
			VALUES (
				" . intval($vbulletin->userinfo['userid']) . ",
				" . intval($mailinglist['mailinglistid']) . ",
				" . intval($keywordid) . ",
				'" . intval($value) . "'
			)
		");
	}

	// Do redirect
	$vbulletin->url = 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglists';
	eval(print_standard_redirect('redirect_dbtech_vbmail_subscription_changed'));
}

// draw cp nav bar
VBMAIL::setNavClass('mailinglists');