<?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);
}

if ($vbulletin->options['dbtech_vbmail_enablebouncehandle'])
{
	// Initialise the IMAP class
	require_once(DIR . '/dbtech/vbmail/includes/class_imap.php');
	VBMAIL_IMAP::init($vbulletin);
	
	// Open the mail connection
	VBMAIL_IMAP::open();
	
	// List messages
	$messages = VBMAIL_IMAP::listMessages(1, $vbulletin->options['dbtech_vbmail_maxmessages']);
	
	// grab message ids
	$messageids = array_keys($messages);
	
	// Store messages we've already inserted
	$existing = array();
	
	if (count($messageids))
	{
		// Grab messages
		$messagelist = $vbulletin->db->query_read_slave("
			SELECT * FROM " . TABLE_PREFIX . "dbtech_vbmail_message
			WHERE messageid IN(" . implode(',', $messageids) . ")
		");
		while ($existingmessages = $vbulletin->db->fetch_array($messagelist))
		{
			// Store this in the existing array
			$existing[$existingmessages['messageid']] = $existingmessages;
		}
	}
	
	foreach ($messages as $messageid => $message)
	{
		if (!$existing[$messageid])
		{
			// init data manager
			$dm =& VBMAIL::initDataManager('Message', $vbulletin, ERRTYPE_SILENT);
					
			// category fields
			foreach ($message AS $key => $val)
			{
				// Only set changed values
				$dm->set($key, $val);
			}
		
			// Save! Hopefully.
			$dm->save();
			unset($dm);	
			
			// Log
			log_cron_action('Collected Message: ' . $messageid, $nextitem);
		}
		
		// Now finally delete the message
		VBMAIL_IMAP::delete($messageid);
	}
	
	// Close imap connection
	VBMAIL_IMAP::close();
}

log_cron_action('Mail Collected', $nextitem);