<?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'] == 'mailinglist' OR empty($_REQUEST['action']))
{
	$mailinglists_by_owner 	= array();
	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		// Index by categoryid
		$mailinglists_by_owner[($mailinglist['ownerid'] ? 1 : 0)][$mailinglistid] = $mailinglist;
	}

	print_cp_header($vbphrase['dbtech_vbmail_mailinglist_management']);

	// Table header
	$headings = array();
	$headings[] = $vbphrase['title'];
	$headings[] = $vbphrase['description'];
	$headings[] = $vbphrase['active'];
	$headings[] = $vbphrase['display_order'];
	if (VBMAIL::$isPro) $headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbmail_mailinglist_external']);
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbmail_mailinglist_owner']);
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbmail_mailinglist_fromemail']);
	$headings[] = $vbphrase['dbtech_vbmail_subscribed_users'];
	$headings[] = $vbphrase['dbtech_vbmail_unsubscribed_users'];
	$headings[] = $vbphrase['edit'];
	$headings[] = $vbphrase['delete'];


	if (count($mailinglists_by_owner))
	{
		$lookup = array();
		foreach (VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
		{
			if (!$mailinglist['ownerid'])
			{
				// System owned
				continue;
			}

			// Lookup userid
			$lookup[] = $mailinglist['ownerid'];
		}

		if (count($lookup))
		{
			$lookup = VBMAIL::$db->fetchAllSingleKeyed('SELECT username, userid FROM $user WHERE userid :queryList', 'userid', 'username', array(':queryList' => VBMAIL::$db->queryList($lookup)));
		}

		print_form_header('vbmail', 'mailinglist');
		construct_hidden_code('action', 'displayorder');
		print_table_header($vbphrase['dbtech_vbmail_mailinglist_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbmail_mailinglist_management_descr'], false, count($headings));

		foreach ($mailinglists_by_owner as $ownertype => $mailinglists)
		{
			print_table_header($vbphrase['dbtech_vbmail_mailinglisttype_' . $ownertype], count($headings));
			print_cells_row($headings, 0, 'thead');
			foreach ($mailinglists as $mailinglistid => $mailinglist)
			{
				// Table data
				$cell = array();
				$cell[] = $mailinglist['title'];
				$cell[] = nl2br($mailinglist['description']);
				$cell[] = ($mailinglist['active'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
				$cell[] = "<input type=\"text\" class=\"bginput\" name=\"order[$mailinglistid]\" value=\"$mailinglist[displayorder]\" tabindex=\"1\" size=\"3\" title=\"" . $vbphrase['edit_display_order'] . "\"" . iif($vbulletin->debug, " title=\"name=&quot;order[$mailinglistid]&quot; value=&quot;$mailinglist[displayorder]&quot;\"") . " />";
				if (VBMAIL::$isPro) $cell[] = ($mailinglist['external'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
				$cell[] = ($lookup[$mailinglist['ownerid']] ? $lookup[$mailinglist['ownerid']] : '<span class="col-i"><strong>' . $vbphrase['dbtech_vbmail_no_owner'] . '</strong></span>');
				$cell[] = $mailinglist['fromemail'];
				$cell[] = construct_link_code($vbphrase['dbtech_vbmail_view_subscribed_users'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglist&amp;action=subscribers&amp;type=subscribed&amp;mailinglistid=' . $mailinglistid);
				$cell[] = construct_link_code($vbphrase['dbtech_vbmail_view_unsubscribed_users'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglist&amp;action=subscribers&amp;type=unsubscribed&amp;mailinglistid=' . $mailinglistid);
				$cell[] = construct_link_code($vbphrase['edit'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglist&amp;action=modify&amp;mailinglistid=' . $mailinglistid);
				$cell[] = construct_link_code($vbphrase['delete'], 'vbmail.php?' . $vbulletin->session->vars['sessionurl'] . 'do=mailinglist&amp;action=delete&amp;mailinglistid=' . $mailinglistid);

				// Print the data
				print_cells_row($cell, 0, 0, -5, 'middle', 0, 1);
			}
		}
		print_submit_row($vbphrase['save_display_order'], false, count($headings), false, "<input type=\"button\" id=\"addnew\" class=\"button\" value=\"" . str_pad($vbphrase['dbtech_vbmail_add_new_mailinglist'], 8, ' ', STR_PAD_BOTH) . "\" tabindex=\"1\" onclick=\"window.location = 'vbmail.php?do=mailinglist&amp;action=modify'\" />");
	}
	else
	{
		print_form_header('vbmail', 'mailinglist');
		construct_hidden_code('action', 'modify');
		print_table_header($vbphrase['dbtech_vbmail_mailinglist_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbmail_no_mailinglists'], false, count($headings));
		print_submit_row($vbphrase['dbtech_vbmail_add_new_mailinglist'], false, count($headings));
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$mailinglistid = $vbulletin->input->clean_gpc('r', 'mailinglistid', TYPE_UINT);
	$mailinglist = ($mailinglistid ? VBMAIL::$cache['mailinglist']["$mailinglistid"] : false);

	if (!is_array($mailinglist))
	{
		// Non-existing mailinglist
		$mailinglistid = 0;
	}

	$permissions = array();
	foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup)
	{
		$bit = 65;
		if ($usergroup['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel'])
		{
			// Admin
			$bit = 89;
		}
		else if ($usergroup['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['ismoderator'])
		{
			// SMod
			$bit = 89;
		}
		else if ($usergroupid == 5)
		{
			$bit = 89;
		}
		else if (!($usergroup['genericoptions'] & $vbulletin->bf_ugp_genericoptions['isnotbannedgroup']) OR in_array($usergroupid, array(1, 3, 4)))
		{
			// Banned, guest, email conf, COPPA
			$bit = 0;
		}

		// Default usergroup permissions
		$permissions[$usergroupid] = $bit;
	}

	$defaults = array(
		'title' 		=> 'Mailing List',
		'description' 	=> 'A mailing list that notifies people of wondrous things.',
		'active' 		=> 1,
		'displayorder'	=> 10,
		'permissions'	=> $permissions,
		'ownerid'		=> 0,
		'fromemail'		=> $vbulletin->options['webmasteremail'],
		'smtp'			=> array(
			'override' => 0,
		),
	);

	if (extension_loaded('suhosin') AND (ini_get('suhosin.post.max_vars') > 0) AND (ini_get('suhosin.post.max_vars') < 2048))
	{
		$hasSuhosin = '
			You appear to have <strong>Suhosin</strong> installed on your server and configured to be too restrictive for vBulletin and vBMail to work correctly.<br />
			<br />
			Please note that if you have a large number of usergroups, certain parts of this page may not work as intended.<br />
			<br />
			If you encounter this issue, you may be able to work around this by adding the following code to your .htaccess file:<br />
			<br />
<pre>php_flag suhosin.cookie.encrypt Off
php_value suhosin.request.max_vars 2048
php_value suhosin.get.max_vars 2048
php_value suhosin.post.max_vars 2048</pre>
			<br />
			These are the values vBulletin Support Staff suggest.';
	}
	if (version_compare(PHP_VERSION, '5.3.9') >= 0 AND ini_get('max_input_vars') < 10000)
	{
		$hasSuhosin = '
			You appear to have <strong>PHP 5.3.9</strong> or higher installed on your server and configured to be too restrictive for vBulletin and vBMail to work correctly.<br />
			<br />
			Please note that if you have a large number of usergroups, certain parts of this page may not work as intended.<br />
			<br />
			If you encounter this issue, you may be able to work around this by adding the following code to your .htaccess file:<br />
			<br />
<pre>php_value max_input_vars 10000</pre>
			<br />
			or altering your php.ini file to increase max_input_vars to 10000.';
	}

	if ($mailinglistid)
	{
		// Edit
		print_cp_header(strip_tags(construct_phrase($vbphrase['dbtech_vbmail_editing_x_y'], $vbphrase['dbtech_vbmail_mailinglist'], $mailinglist['title'])));
		print_form_header('vbmail', 'mailinglist');
		construct_hidden_code('action', 'update');
		construct_hidden_code('mailinglistid', $mailinglistid);
		if ($hasSuhosin)
		{
			print_table_start();
			print_description_row($hasSuhosin);
			print_table_break();
		}
		print_table_header(construct_phrase($vbphrase['dbtech_vbmail_editing_x_y'], $vbphrase['dbtech_vbmail_mailinglist'], $mailinglist['title']));

		if (!isset($mailinglist['mailperpage']))
		{
			// Upgrade
			$mailinglist['mailperpage'] = 500;
		}
	}
	else
	{
		// Add
		print_cp_header($vbphrase['dbtech_vbmail_add_new_mailinglist']);
		print_form_header('vbmail', 'mailinglist');
		construct_hidden_code('action', 'update');
		if ($hasSuhosin)
		{
			print_table_start();
			print_description_row($hasSuhosin);
			print_table_break();
		}
		print_table_header($vbphrase['dbtech_vbmail_add_new_mailinglist']);

		$mailinglist = $defaults;
	}

	print_description_row($vbphrase['dbtech_vbmail_main_settings'], false, 2, 'optiontitle');
	print_input_row($vbphrase['title'], 										'mailinglist[title]', 			$mailinglist['title']);
	print_textarea_row($vbphrase['description'], 								'mailinglist[description]', 	$mailinglist['description']);
	print_yes_no_row($vbphrase['active'],										'mailinglist[active]',			$mailinglist['active']);
	print_input_row($vbphrase['display_order'], 								'mailinglist[displayorder]', 	$mailinglist['displayorder']);
	print_description_row($vbphrase['dbtech_vbmail_mailinglist_settings'], false, 2, 'optiontitle');
	if (VBMAIL::$isPro)
	{
		if (!$mailinglistid)
		{
			print_yes_no_row($vbphrase['dbtech_vbmail_mailinglist_external'], 	'mailinglist[external]', 		$mailinglist['external']);
		}
		else
		{
			construct_hidden_code('mailinglist[external]', $mailinglist['external']);
			print_label_row($vbphrase['dbtech_vbmail_mailinglist_external'], 									($mailinglist['external'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>'));
		}
	}
	else
	{
		// Ensure this is always off for Lite
		construct_hidden_code('mailinglist[external]', '0');
	}
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_owner'], 				'mailinglist[ownerid]', 		$mailinglist['ownerid']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_fromemail'], 			'mailinglist[fromemail]', 		$mailinglist['fromemail']);
	/*DBTECH_PRO_START*/
	print_yes_no_row($vbphrase['dbtech_vbmail_mailinglist_instantsend'], 		'mailinglist[instantsend]', 	$mailinglist['instantsend']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_mailperpage'], 		'mailinglist[mailperpage]', 	$mailinglist['mailperpage']);
	print_description_row($vbphrase['dbtech_vbmail_smtp_settings'], false, 2, 'optiontitle');
	print_yes_no_row($vbphrase['dbtech_vbmail_mailinglist_smtp_override'], 		'mailinglist[smtp][override]', 	$mailinglist['smtp']['override']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_smtp_host'], 			'mailinglist[smtp][host]', 		$mailinglist['smtp']['host']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_smtp_port'], 			'mailinglist[smtp][port]', 		$mailinglist['smtp']['port']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_smtp_user'], 			'mailinglist[smtp][user]', 		$mailinglist['smtp']['user']);
	print_input_row($vbphrase['dbtech_vbmail_mailinglist_smtp_pass'], 			'mailinglist[smtp][pass]', 		$mailinglist['smtp']['pass']);
	print_select_row($vbphrase['dbtech_vbmail_mailinglist_smtp_tls'], 			'mailinglist[smtp][tls]', 		array(
																													'none' 	=> $vbphrase['none'],
																													'ssl' 	=> 'SSL',
																													'tls' 	=> 'TLS'
																												), $mailinglist['smtp']['tls']);
	/*DBTECH_PRO_END*/

	if ($hasSuhosin)
	{
		print_submit_row(($mailinglistid ? $vbphrase['save'] : $vbphrase['dbtech_vbmail_add_new_mailinglist']));
	}
	else
	{
		print_table_break();
	}
	if (($mailinglistid OR !$hasSuhosin)/* AND (!$mailinglistid OR ($mailinglistid AND !$mailinglist['external']))*/)
	{
		// Bitfields
		require_once(DIR . '/includes/adminfunctions_options.php');
		$permissions = fetch_bitfield_definitions('nocache|dbtech_vbmailpermissions');

		// Table header
		$headings = array();
		$headings[] = $vbphrase['usergroup'];
		foreach ((array)$permissions as $permissionname => $bit)
		{
			if (!in_array($permissionname, array('cannotview', 'canview', 'cansendmail', 'canmanage', 'canviewstats')) AND $mailinglist['external'])
			{
				// External mailing lists don't get these permissions
				continue;
			}

			$headings[] = $vbphrase['dbtech_vbmail_permission_' . $permissionname];
		}

		if ($hasSuhosin)
		{
			print_form_header('vbmail', 'mailinglist');
			construct_hidden_code('action', 'updatemailinglistpermissions');
			construct_hidden_code('mailinglistid', $mailinglistid);
		}
		print_table_header($vbphrase['dbtech_vbmail_mailinglist_permissions'], count($headings));
		print_cells_row($headings, 0, 'thead');

		foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup)
		{
			if (!isset($mailinglist['permissions'][$usergroupid]))
			{
				// Set defaults
				$mailinglist['permissions'][$usergroupid] = $defaults['permissions'][$usergroupid];
			}

			// Table data
			$cell = array();
			$cell[] = $usergroup['title'];
			foreach ((array)$permissions as $permissionname => $bit)
			{
				if (!in_array($permissionname, array('cannotview', 'canview', 'cansendmail', 'canmanage', 'canviewstats')) AND $mailinglist['external'])
				{
					// External mailing lists don't get these permissions
					continue;
				}

				// Set disabled flag
				$disabled = (in_array($permissionname, array('cansubscribe', 'nounsubscribe', 'defaultsubscribed', 'cansendmail', 'canmanage')) AND in_array($usergroupid, array(1, 8)));

				$cell[] = '<center>
					<input type="hidden" name="permissions[' . $usergroupid . '][' . $permissionname . ']" value="0" />
					<input type="checkbox" name="permissions[' . $usergroupid . '][' . $permissionname . ']" value="1"' .
						($disabled ? ' disabled="disabled"' : '') .
						(($mailinglist['permissions'][$usergroupid] & $bit) ? ' checked="checked"' : '') .
						($vbulletin->debug ? ' title="name=&quot;permissions[' . $usergroupid . '][' . $permissionname . ']&quot;"' : '') . '/>
				</center>';
			}

			// Print the data
			print_cells_row($cell, 0, 0, -5, 'middle', 0, 1);
		}
		if ($hasSuhosin)
		{
			print_submit_row(($mailinglistid ? $vbphrase['save'] : $vbphrase['dbtech_vbmail_add_new_mailinglist']), false, count($headings));
		}
		else
		{
			print_table_break();
		}
	}

	if (!$hasSuhosin)
	{
		print_submit_row(($mailinglistid ? $vbphrase['save'] : $vbphrase['dbtech_vbmail_add_new_mailinglist']), false);
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'mailinglistid' 	=> TYPE_UINT,
		'mailinglist' 		=> TYPE_ARRAY,
		'permissions' 		=> TYPE_ARRAY,
	));

	// Ensure we can fetch bitfields
	require_once(DIR . '/includes/adminfunctions_options.php');
	$bitfields = fetch_bitfield_definitions('nocache|dbtech_vbmailpermissions');

	if (count($vbulletin->GPC['permissions']))
	{
		$permarray = array();
		foreach ((array)$vbulletin->GPC['permissions'] as $usergroupid => $permvalues)
		{

			$permarray[$usergroupid] = 0;
			foreach ((array)$permvalues as $bitfield => $bit)
			{
				// Update the permissions array
				$permarray[$usergroupid] += ($bit ? $bitfields[$bitfield] : 0);
			}
		}

		// Set the perm array
		$vbulletin->GPC['mailinglist']['permissions'] = $permarray;
	}

	// init data manager
	$dm =& VBMAIL::initDataManager('Mailinglist', $vbulletin, ERRTYPE_CP);

	// set existing info if this is an update
	if ($vbulletin->GPC['mailinglistid'])
	{
		if (!$existing = VBMAIL::$cache['mailinglist'][$vbulletin->GPC['mailinglistid']])
		{
			// Couldn't find the mailinglist
			print_stop_message('dbtech_vbmail_invalid_x', $vbphrase['dbtech_vbmail_mailinglist'], $vbulletin->GPC['mailinglistid']);
		}

		// Set existing
		$dm->set_existing($existing);

		// Added
		$phrase = $vbphrase['dbtech_vbmail_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbmail_added'];
	}

	// mailinglist fields
	foreach ($vbulletin->GPC['mailinglist'] AS $key => $val)
	{
		if (!$vbulletin->GPC['mailinglistid'] OR $existing[$key] != $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	}

	// Save! Hopefully.
	$mailinglistid = $dm->save();

	if (!$existing)
	{
		// Ensure this is set
		$vbulletin->GPC['mailinglistid'] = $vbulletin->GPC['mailinglist']['mailinglistid'] = $mailinglistid;
	}

	if (!$vbulletin->GPC['mailinglist']['external'])
	{
		$usergroupids = array();
		foreach ((array)$vbulletin->GPC['mailinglist']['permissions'] as $usergroupid => $permissions)
		{
			if (!($permissions & (int)$bitfields['defaultsubscribed']))
			{
				// Not default subscribed
				continue;
			}

			if ($existing['permissions'][$usergroupid] == $permissions)
			{
				// No change
				continue;
			}

			// Add to usergroupids
			$usergroupids[] = $usergroupid;
		}
	}

	if (count($usergroupids))
	{
		// Fire ze mailqueue
		vbmail_start();

		$users = VBMAIL::$db->fetchAllObject('
			SELECT user.*
			FROM $user AS user
			LEFT JOIN $dbtech_vbmail_subscription AS subscription ON(subscription.mailinglistid = ?)
			WHERE (
					FIND_IN_SET(' . implode(', membergroupids) OR FIND_IN_SET(', $usergroupids) . ', membergroupids)
					OR usergroupid :queryList
				)
				AND user.dbtech_vbmail_bounceflag = \'0\'
				AND subscription.subscribed IS NULL
		', array(
			$vbulletin->GPC['mailinglistid'],
			':queryList' => VBMAIL::$db->queryList($usergroupids)
		));
		while ($user = VBMAIL::$db->fetchCurrent())
		{
			// Subscribe this user
			VBMAIL::subscribeUser($user, $vbulletin->GPC['mailinglist'], 'defaultsubscribed', false);
		}

		// Ze mailqueue ended
		vbmail_end();
	}

	define('CP_REDIRECT', 'vbmail.php?do=mailinglist');
	print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_mailinglist'], $phrase);
}

// #############################################################################
if ($_POST['action'] == 'updatemailinglistpermissions')
{
	$vbulletin->input->clean_array_gpc('p', array(
		'mailinglistid'		=> TYPE_UINT,
		'permissions' 		=> TYPE_ARRAY,
	));

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

	// Ensure we can fetch bitfields
	require_once(DIR . '/includes/adminfunctions_options.php');
	$bitfields = fetch_bitfield_definitions('nocache|dbtech_vbmailpermissions');

	$permarray = array();
	foreach ((array)$vbulletin->GPC['permissions'] as $usergroupid => $permvalues)
	{

		$permarray[$usergroupid] = 0;
		foreach ((array)$permvalues as $bitfield => $bit)
		{
			// Update the permissions array
			$permarray[$usergroupid] += ($bit ? $bitfields[$bitfield] : 0);
		}
	}

	// Set the perm array
	$vbulletin->GPC['mailinglist']['permissions'] = $permarray;

	// init data manager
	$dm =& VBMAIL::initDataManager('Mailinglist', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
		$dm->set('permissions', $vbulletin->GPC['mailinglist']['permissions']);
	$dm->save();

	$usergroupids = array();
	foreach ($vbulletin->GPC['mailinglist']['permissions'] as $usergroupid => $permissions)
	{
		if (!($permissions & (int)$bitfields['defaultsubscribed']))
		{
			// Not default subscribed
			continue;
		}

		if ($existing['permissions'][$usergroupid] == $permissions)
		{
			// No change
			continue;
		}

		// Add to usergroupids
		$usergroupids[] = $usergroupid;
	}

	if (count($usergroupids))
	{
		// Fire ze mailqueue
		vbmail_start();

		$users = VBMAIL::$db->fetchAllObject('
			SELECT user.*
			FROM $user AS user
			LEFT JOIN $dbtech_vbmail_subscription AS subscription ON(subscription.mailinglistid = ?)
			WHERE (
					FIND_IN_SET(' . implode(', membergroupids) OR FIND_IN_SET(', $usergroupids) . ', membergroupids)
					OR usergroupid :queryList
				)
				AND user.dbtech_vbmail_bounceflag = \'0\'
				AND subscription.subscribed IS NULL
		', array(
			$vbulletin->GPC['mailinglistid'],
			':queryList' => VBMAIL::$db->queryList($usergroupids)
		));
		while ($user = VBMAIL::$db->fetchCurrent())
		{
			// Subscribe this user
			VBMAIL::subscribeUser($user, $vbulletin->GPC['mailinglist'], 'defaultsubscribed', false);
		}

		// Ze mailqueue ended
		vbmail_end();
	}

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

// #############################################################################
if ($_POST['action'] == 'displayorder')
{
	$vbulletin->input->clean_array_gpc('p', array('order' => TYPE_ARRAY));

	if (is_array($vbulletin->GPC['order']))
	{
		foreach ($vbulletin->GPC['order'] as $mailinglistid => $displayorder)
		{
			if (!$existing = VBMAIL::$cache['mailinglist'][$mailinglistid])
			{
				// Couldn't find the mailinglist
				continue;
			}

			if ($existing['displayorder'] == $displayorder)
			{
				// No change
				continue;
			}

			// init data manager
			$dm =& VBMAIL::initDataManager('Mailinglist', $vbulletin, ERRTYPE_CP);
				$dm->set_existing($existing);
				$dm->set('displayorder', $displayorder);
			$dm->save();
			unset($dm);
		}
	}

	define('CP_REDIRECT', 'vbmail.php?do=mailinglist');
	print_stop_message('saved_display_order_successfully');
}

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

	print_cp_header(construct_phrase($vbphrase['dbtech_vbmail_delete_x'], $vbphrase['dbtech_vbmail_mailinglist']));
	print_delete_confirmation('dbtech_vbmail_mailinglist', $vbulletin->GPC['mailinglistid'], 'vbmail', 'mailinglist', 'dbtech_vbmail_mailinglist', array('action' => 'kill'), '', 'title');
	print_cp_footer();
}

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

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

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

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

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

	print_cp_header($vbphrase['dbtech_vbmail_' . $vbulletin->GPC['type'] . '_users']);

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

	$status = ($vbulletin->GPC['type'] == 'subscribed' ? 1 : 0);
	$sqlconds = array();
	$hook_query_fields = $hook_query_joins = '';

	if ($vbulletin->GPC['perpage'] < 1)
	{
		$vbulletin->GPC['perpage'] = 25;
	}

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

	$counter = $db->query_first_slave("
		SELECT COUNT(*) AS total
		FROM " . TABLE_PREFIX . "dbtech_vbmail_subscription
		WHERE subscribed = '$status'
			AND mailinglistid = " . intval($mailinglist['mailinglistid'])
	);
	$totalpages = ceil($counter['total'] / $vbulletin->GPC['perpage']);

	if ($vbulletin->GPC['pagenumber'] < 1)
	{
		$vbulletin->GPC['pagenumber'] = 1;
	}
	$startat = ($vbulletin->GPC['pagenumber'] - 1) * $vbulletin->GPC['perpage'];

	$logs = $db->query_read_slave("
		SELECT user.*
			$hook_query_fields
		FROM " . TABLE_PREFIX . "dbtech_vbmail_subscription AS dbtech_vbmail_subscription
		LEFT JOIN " . TABLE_PREFIX . ($mailinglist['external'] ? 'dbtech_vbmail_' : '') . "user AS user USING(userid)
		$hook_join_fields
		WHERE dbtech_vbmail_subscription.subscribed = '$status'
			AND mailinglistid = " . intval($mailinglist['mailinglistid']) . "
		ORDER BY username ASC
		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=mailinglist&action=subscribers&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=" . $vbulletin->GPC['type'] . "&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=mailinglist&action=subscribers&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=" . $vbulletin->GPC['type'] . "&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=mailinglist&action=subscribers&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=" . $vbulletin->GPC['type'] . "&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=mailinglist&action=subscribers&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=" . $vbulletin->GPC['type'] . "&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$totalpages'\">";
		}
	}

	if ($vbulletin->GPC['type'] == 'subscribed')
	{
		$subscribe = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['dbtech_vbmail_add_user_to_mailinglist'] . "\" tabindex=\"1\" onclick=\"window.location='vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=mailinglist&action=managesubscription&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=unsubscribed&returntype=subscribed'\">";
	}
	else
	{
		if (!$db->num_rows($logs))
		{
			print_stop_message('no_results_matched_your_query');
		}
	}

	$headings = array();
	$headings[] = $vbphrase['username'];
	$headings[] = $vbphrase['action'];

	print_form_header('', '');
	print_table_header(construct_phrase($vbphrase['dbtech_vbmail_' . $vbulletin->GPC['type'] . '_users_viewer_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[] = "<a href=\"user.php?" . $vbulletin->session->vars['sessionurl'] . "do=edit&u=$log[userid]\"><b>$log[username]</b></a>";
		$cell[] = construct_link_code($vbphrase[($vbulletin->GPC['type'] == 'subscribed' ? 'unsubscribe' : 'dbtech_vbmail_resubscribe')], "vbmail.php?" . $vbulletin->session->vars['sessionurl'] . "do=mailinglist&action=managesubscription&mailinglistid=" . $vbulletin->GPC['mailinglistid'] . "&type=" . $vbulletin->GPC['type'] . "&u=$log[userid]");

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

		print_cells_row($cell, 0, 0, -4);
	}

	print_table_footer(count($headings), "$subscribe &nbsp; $firstpage $prevpage &nbsp; $nextpage $lastpage");

	//}
	//else
	//{
		//print_stop_message('no_results_matched_your_query');
	//}
}

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

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

	if (!$vbulletin->GPC['userid'])
	{
		if (!$vbulletin->GPC['username'])
		{
			// Print username form
			print_cp_header($vbphrase['dbtech_vbmail_subscription_management']);
			print_form_header('vbmail', 'mailinglist');
			construct_hidden_code('action', 		'managesubscription');
			construct_hidden_code('mailinglistid', 	$vbulletin->GPC['mailinglistid']);
			construct_hidden_code('type', 			$vbulletin->GPC['type']);
			construct_hidden_code('returntype', 	$vbulletin->GPC['returntype']);
			print_table_header($vbphrase['dbtech_vbmail_subscription_management']);
			print_input_row(($mailinglist['external'] ? $vbphrase['email'] : $vbphrase['username']), 'username');
			print_submit_row($vbphrase['save'], false);
		}
		else
		{
			// Lookup username
			if ($existing = $db->query_first_slave("SELECT userid FROM " . TABLE_PREFIX . ($mailinglist['external'] ? 'dbtech_vbmail_' : '') . "user WHERE username = " . $db->sql_prepare(htmlspecialchars_uni($vbulletin->GPC['username']))))
			{
				// Set the user id
				$vbulletin->GPC['userid'] = $existing['userid'];
			}
			else
			{
				if ($mailinglist['external'])
				{
					$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) . "'
						)
					");
					$vbulletin->GPC['userid'] = $db->insert_id();
				}
				else
				{
					print_stop_message('no_users_matched_your_query');
				}
			}
		}
	}

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

		// 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
			print_stop_message('no_users_matched_your_query');
		}

		// 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_admin',
			));
		}

		// Do redirect
		define('CP_REDIRECT', 'vbmail.php?do=mailinglist&action=subscribers&mailinglistid=' . $vbulletin->GPC['mailinglistid'] . '&type=' . ($vbulletin->GPC['returntype'] ? $vbulletin->GPC['returntype'] : $vbulletin->GPC['type'])/*($vbulletin->GPC['type'] == 'subscribed' ? 'unsubscribed' : 'subscribed')*/);
		print_stop_message('dbtech_vbmail_x_y', $vbphrase['dbtech_vbmail_mailinglist'], $vbphrase['dbtech_vbmail_edited']);
	}
}

print_cp_footer();