<?php
if (!$this->condition)
{
	// Shorthand
	$user = array(
		'userid' 		=> $this->fetch_field('userid'),
		'username' 		=> $this->fetch_field('username'),
		'salt' 			=> $this->fetch_field('salt'),
		'email' 		=> $this->fetch_field('email'),
		'languageid' 	=> $this->fetch_field('languageid'),
	);

	// Ensure we can fetch bitfields
	require_once(DIR . '/includes/adminfunctions_options.php');
	$bitfields = fetch_bitfield_definitions('nocache|dbtech_vbmailpermissions');
	
	$usergroupids = array_merge(array($this->fetch_field('usergroupid')), explode(',', $this->fetch_field('membergroupids')));
	$bit = 0;
	foreach ((array)VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
	{
		$subscribe = false;
		foreach ($mailinglist['permissions'] as $usergroupid => $permissions)
		{
			if (!in_array($usergroupid, $usergroupids))
			{
				// We're not a member of this UG
				continue;
			}
			
			if (!($permissions & (int)$bitfields['defaultsubscribed']))
			{
				// Not default subscribed
				continue;
			}
			
			// Set the bitfield
			$subscribe = true;
		}

		if ($subscribe AND $user['userid'])
		{
			// Subscribe this user
			VBMAIL::subscribeUser($user, $mailinglist, 'newuser');
		}
	}
}

if ($check = $this->dbobject->query_first_slave("SELECT userid FROM " . TABLE_PREFIX . "userban WHERE userid = $userid"))
{
	$subscriptions = VBMAIL::$db->fetchAll('
		SELECT * 
		FROM $dbtech_vbmail_subscription 
		WHERE userid = ?
			AND subscribed = 1
	', array(
		$userid
	));
	foreach ($subscriptions as $subscription)
	{
		// Unsubscribe
		VBMAIL::$db->update('dbtech_vbmail_subscription', array(
			'subscribed' 	=> 0
		), 'WHERE userid = ' . $userid . ' AND mailinglistid = ' . $subscription['mailinglistid']);

		VBMAIL::$db->insert('dbtech_vbmail_subscriptionlog', array(
			'userid' 		=> $userid,
			'mailinglistid' => $subscription['mailinglistid'],
			'dateline' 		=> TIMENOW,
			'subscribed' 	=> 0,
			'reason' 		=> 'banned'
		));

		if ($mailinglist = VBMAIL::$cache['mailinglist'][$subscription['mailinglistid']])
		{
			// init data manager
			$dm =& VBMAIL::initDataManager('Mailinglist', $this->registry, ERRTYPE_SILENT);
				$dm->set_existing($mailinglist);
				$dm->set('unsubscriptions', 'unsubscriptions + 1', false);
			$dm->save();
		}
	}
}
?>