<?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 (!is_object($vbulletin->db))
{
	exit;
}

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

if (defined('IN_CONTROL_PANEL'))
{
	define('ECHO_CRON_LOG', true);
}

$externals = array(0);
foreach (VBMAIL::$cache['mailinglist'] as $mailinglistid => $mailinglist)
{
	if (!$mailinglist['external'])
	{
		// Skip this
		continue;
	}
	
	// Store mailing list id
	$externals[] = $mailinglistid;
}

$users = $vbulletin->db->query_read_slave("
	SELECT
		user.userid,
		user.username,
		user.email,
		user.usergroupid,
		user.membergroupids,
		user.infractiongroupid,
		user.displaygroupid" . ($vbulletin->products['dbtech_vbshop'] ? ", user.dbtech_vbshop_purchase" : '') . "
	FROM `" . TABLE_PREFIX . "dbtech_vbmail_message` AS dbtech_vbmail_message
	INNER JOIN " . TABLE_PREFIX . "user AS user ON(user.email = dbtech_vbmail_message.fromaddress)
	WHERE dbtech_vbmail_message.fromaddress != ''
		AND dbtech_vbmail_message.bounce = '1'
		AND user.dbtech_vbmail_bounceflag = '0'
	GROUP BY dbtech_vbmail_message.fromaddress
	HAVING COUNT(*) >= " . intval($vbulletin->options['dbtech_vbmail_bounce_threshold'])
);
while ($user = $vbulletin->db->fetch_array($users))
{
	// Enable popup on new PM
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET pmpopup = 1
		WHERE userid = " . intval($user['userid'])
	);
	
	// Disable email related features - PM
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET options = options - " . $vbulletin->bf_misc_useroptions['emailonpm'] . "
		WHERE options & " . $vbulletin->bf_misc_useroptions['emailonpm'] . "
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Admin
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET options = options - " . $vbulletin->bf_misc_useroptions['adminemail'] . "
		WHERE options & " . $vbulletin->bf_misc_useroptions['adminemail'] . "
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Members
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET options = options - " . $vbulletin->bf_misc_useroptions['showemail'] . "
		WHERE options & " . $vbulletin->bf_misc_useroptions['showemail'] . "
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Friend Request
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET options = options - " . $vbulletin->bf_misc_useroptions['receivefriendemailrequest'] . "
		WHERE options & " . $vbulletin->bf_misc_useroptions['receivefriendemailrequest'] . "
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Auto Subscription
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET autosubscribe = 0
		WHERE (autosubscribe >= 1)
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Thread Subscriptions
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "subscribethread
		SET emailupdate = 0
		WHERE (emailupdate > 0)
			AND userid = " . intval($user['userid'])
	);

	// Disable email related features - Forum Subscriptions
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "subscribeforum
		SET emailupdate = 0
		WHERE (emailupdate > 0)
			AND userid = " . intval($user['userid'])
	);
	
	$subscriptions = VBMAIL::$db->fetchAll('
		SELECT * 
		FROM $dbtech_vbmail_subscription 
		WHERE userid = ? 
			AND subscribed = 1
			AND mailinglistid NOT :queryList
	', array(
		$user['userid'],
		':queryList' => VBMAIL::$db->queryList($externals)
	));
	foreach ($subscriptions as $subscription)
	{
		// We either subscribed or unsubscribed
		VBMAIL::$db->insert('dbtech_vbmail_subscriptionlog', array(
			'userid' 		=> $subscription['userid'],
			'mailinglistid' => $subscription['mailinglistid'],
			'dateline' 		=> TIMENOW,
			'subscribed' 	=> 0,
			'reason' 		=> 'unsubscribed_bounce',
		));
	}

	// Le unsubscribe from things
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "dbtech_vbmail_subscription
		SET subscribed = '0'
		WHERE userid = " . intval($user['userid']) . "
			AND mailinglistid NOT IN(" . implode(',', $externals) . ")
	");
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "user
		SET dbtech_vbmail_bounceflag = '1'
		WHERE userid = " . intval($user['userid'])
	);

	// Ensure we have the permissions array
	cache_permissions($user, false);
	
	// Send PM
	$retval = VBMAIL::sendPM(
		$user,
		$vbphrase['dbtech_vbmail_bouncealert_title'],
		construct_phrase($vbphrase['dbtech_vbmail_bouncealert_body'],
			$user['username'],
			$user['email'],
			$vbulletin->options['dbtech_vbmail_bounce_threshold'],
			$vbulletin->options['bburl']
		)
	);

	if (defined('IN_CONTROL_PANEL') AND is_array($retval))
	{
		
	}
	
	// Log this user
	log_cron_action('User Unsubscribed: ' . $user['username'], $nextitem);
}

$users = $vbulletin->db->query_read_slave("
	SELECT user.userid, user.username
	FROM `" . TABLE_PREFIX . "dbtech_vbmail_message` AS dbtech_vbmail_message
	INNER JOIN " . TABLE_PREFIX . "dbtech_vbmail_user AS user ON(user.email = dbtech_vbmail_message.fromaddress)
	WHERE dbtech_vbmail_message.fromaddress != ''
		AND dbtech_vbmail_message.bounce = '1'
		AND user.dbtech_vbmail_bounceflag = '0'
	GROUP BY dbtech_vbmail_message.fromaddress
	HAVING COUNT(*) >= " . intval($vbulletin->options['dbtech_vbmail_bounce_threshold'])
);
while ($user = $vbulletin->db->fetch_array($users))
{
	$subscriptions = VBMAIL::$db->fetchAll('
		SELECT * 
		FROM $dbtech_vbmail_subscription 
		WHERE userid = ? 
			AND subscribed = 1
			AND mailinglistid :queryList
	', array(
		$user['userid'],
		':queryList' => VBMAIL::$db->queryList($externals)
	));
	foreach ($subscriptions as $subscription)
	{
		// We either subscribed or unsubscribed
		VBMAIL::$db->insert('dbtech_vbmail_subscriptionlog', array(
			'userid' 		=> $subscription['userid'],
			'mailinglistid' => $subscription['mailinglistid'],
			'dateline' 		=> TIMENOW,
			'subscribed' 	=> 0,
			'reason' 		=> 'unsubscribed_bounce',
		));
	}

	// Le unsubscribe from things
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "dbtech_vbmail_subscription
		SET subscribed = '0'
		WHERE userid = " . intval($user['userid']) . "
			AND mailinglistid IN(" . implode(',', $externals) . ")
	");
	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "dbtech_vbmail_user
		SET dbtech_vbmail_bounceflag = '1'
		WHERE userid = " . intval($user['userid'])
	);
	
	// Log this user
	log_cron_action('User Unsubscribed: ' . $user['username'], $nextitem);
}

log_cron_action('Users Unsubscribed', $nextitem);