<?php
if (!class_exists('vBShop_Item_Core'))
{
	die('No direct access allowed.');
}

class vBShop_Item_movethread extends vBShop_Item_Core
{
	/**
	* The constructor
	*
	* @param	vBulletin	vBulletin registry
	* @param	array		Item info
	*/	
	public function __construct(&$registry, &$item)
	{
		parent::__construct($registry, $item);
		
		// Set purchase template
		$this->config['purchasetemplate'] = 'dbtech_vbshop_configure_movethread';

		require_once(DIR . '/includes/functions_databuild.php');
		require_once(DIR . '/includes/functions_log_error.php');
		require_once(DIR . '/includes/functions_prefix.php');
	}
	
	/**
	* Function to call before every action
	*/	
	public function action()
	{
		if (!parent::action())
		{
			// This type is inactive
			return false;
		}
		
		// We made it!
		return true;
	}
	
	/**
	* Prints out an AdminCP form
	*/	
	public function print_admin_form($code)
	{
		global $vbphrase;

		print_forum_chooser($vbphrase['dbtech_vbshop_excluded_forums'], 'item[code][excluded][]', $code['excluded'], NULL, true, true);
		print_yes_no_row($vbphrase['dbtech_vbshop_own_threads_only'], 'item[code][onlyown]', $code['onlyown']);
	}
	
	/**
	* Form to purchase an item
	*/	
	public function render()
	{
		global $vbphrase;
		
		$userinfo = fetch_userinfo($this->purchaseinfo['userid']);
		cache_permissions($userinfo);
		$forumoptions = '';
		foreach ($this->registry->forumcache AS $forumid => $forum)
		{
			$fperms =& $userinfo['forumpermissions'][$forumid];
	
			if (
				!($fperms & $this->registry->bf_ugp_forumpermissions['canview']) 
				OR !($fperms & $this->registry->bf_ugp_forumpermissions['canviewthreads']) 
				OR !verify_forum_password($forumid, $forum['password'], false)
			)
			{
				// Skip this
				continue;
			}

			// Create the number option template
			$templater = vB_Template::create('option');
				$templater->register('optionvalue', 	$forumid);
				$templater->register('optiontitle', 	construct_depth_mark($forum['depth'], '--', $startdepth) . ' ' . $forum['title'] . ' ' . iif(!($forum['options'] & $this->registry->bf_misc_forumoptions['allowposting']), " ($vbphrase[forum_is_closed_for_posting])"));
				$templater->register('optionselected', 	(($this->config['configuration']['forumid'] == $forumid ? ' selected="selected"' : '') . ((in_array($forumid, $this->config['code']['excluded']) OR !($forum['options'] & $this->registry->bf_misc_forumoptions['allowposting'])) ? ' disabled="disabled"' : '')));
			$forumoptions .= $templater->render();
		}

		// Begin the purchase template
		$templater = vB_Template::create($this->config['purchasetemplate']);
			$templater->register('item', $this->config);
			$templater->register('forumoptions', $forumoptions);
		return $templater->render();
	}

	/**
	* Activate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function activate($purchaseid, $recipient = NULL, $dorebuild = true)
	{
		if (!parent::activate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't deactivate
			return false;
		}

		if (!$this->config['configuration']['threadid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['sourceforumid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['destforumid'])
		{
			// Nothin configured
			return true;
		}

		$threadinfo = fetch_threadinfo($this->config['configuration']['threadid']);
		if (!$threadinfo OR in_array($threadinfo['forumid'], $this->config['code']['excluded']))
		{
			// Excluded forum
			return true;
		}

		if ($threadinfo['postuserid'] != $this->registry->userinfo['userid'] AND $this->config['code']['onlyown'])
		{
			// We can only delete own threads
			return true;
		}

		if (!$this->purchaseinfo)
		{
			if (!$this->purchaseinfo = $this->registry->db->query_first_slave("
				SELECT *
				FROM " . TABLE_PREFIX . "dbtech_vbshop_purchase
				WHERE purchaseid = " . intval($purchaseid)
			))
			{
				// Purchase didn't exist
				return false;
			}
		}	

		// Now we need this
		$sourceforuminfo = fetch_foruminfo($this->config['configuration']['sourceforumid']);
		$destforuminfo = fetch_foruminfo($this->config['configuration']['destforumid']);

		if (!$destforuminfo['cancontainthreads'] OR $destforuminfo['link'])
		{
			// Skip this
			return true;
		}

		// Do the move
		$this->_execThreadMove($threadinfo, $sourceforuminfo, $destforuminfo);
		
		return true;
	}

	/**
	* Deactivate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function deactivate($purchaseid, $recipient = null, $dorebuild = true)
	{
		if (!parent::deactivate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't deactivate
			return false;
		}

		if (!$this->config['configuration']['threadid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['sourceforumid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['destforumid'])
		{
			// Nothin configured
			return true;
		}

		$threadinfo = fetch_threadinfo($this->config['configuration']['threadid']);
		if (!$threadinfo OR in_array($threadinfo['forumid'], $this->config['code']['excluded']))
		{
			// Excluded forum
			return true;
		}

		if ($threadinfo['postuserid'] != $this->registry->userinfo['userid'] AND $this->config['code']['onlyown'])
		{
			// We can only delete own threads
			return true;
		}

		// Now we need this
		$sourceforuminfo = fetch_foruminfo($this->config['configuration']['destforumid']);
		$destforuminfo = fetch_foruminfo($this->config['configuration']['sourceforumid']);

		if (!$destforuminfo['cancontainthreads'] OR $destforuminfo['link'])
		{
			// Skip this
			return true;
		}

		// Do the move
		$this->_execThreadMove($threadinfo, $sourceforuminfo, $destforuminfo);
		
		return true;
	}	
	
	/**
	* Configure an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function configure($purchaseid, $recipient = null)
	{
		global $vbphrase;
		
		if (!$this->can_configure($purchaseid))
		{
			// Can't configure this item
			return false;
		}
		
		// Ensure this is set
		$recipient = (!$recipient ? $this->registry->userinfo : $recipient);
		
		// Get the form code
		$code 			= $this->registry->input->clean_gpc('p', 'code', 			TYPE_ARRAY);
		$noConfigure 	= $this->registry->input->clean_gpc('p', '_noConfigure', 	TYPE_BOOL);
		
		if ($noConfigure)
		{
			// We're done, we wanted to let the recipient configure it themselves
			return true;
		}

		if ($code['threadid'])
		{
			$threadinfo = fetch_threadinfo($code['threadid']);
			if (!$threadinfo OR in_array($threadinfo['forumid'], $this->config['code']['excluded']))
			{
				// Excluded forum
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['dbtech_vbshop_thread_id'])));
			}

			if ($this->config['configuration']['threadid'] != $code['threadid'] AND $threadinfo['visible'] == 2)
			{
				// Already deleted
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['dbtech_vbshop_thread_id'])));
			}

			if ($this->config['configuration']['threadid'] != $code['threadid'] AND $this->config['configuration']['threadid'])
			{
				// Now we need this
				$sourceforuminfo2 = fetch_foruminfo($this->config['configuration']['destforumid']);
				$destforuminfo2 = fetch_foruminfo($this->config['configuration']['sourceforumid']);

				if ($destforuminfo2['cancontainthreads'] AND !$destforuminfo['link'])
				{
					// Do the move
					$this->_execThreadMove($threadinfo, $sourceforuminfo2, $destforuminfo2);
				}
			}

			if (!$this->purchaseinfo)
			{
				if (!$this->purchaseinfo = $this->registry->db->query_first_slave("
					SELECT *
					FROM " . TABLE_PREFIX . "dbtech_vbshop_purchase
					WHERE purchaseid = " . intval($purchaseid)
				))
				{
					// Purchase didn't exist
					return false;
				}
			}	

			// Now we need this
			$sourceforuminfo = fetch_foruminfo($threadinfo['forumid']);
			$destforuminfo = fetch_foruminfo($code['forumid']);

			// Move thread to new forum
			$this->_execThreadMove($threadinfo, $sourceforuminfo, $destforuminfo);

			if (!$this->config['configuration']['threadid'])
			{
				$code['sourceforumid'] = $threadinfo['forumid'];
				$code['destforumid'] = $code['forumid'];
			}
		}
		else
		{
			if ($this->config['configuration']['threadid'])
			{
				$threadinfo = fetch_threadinfo($this->config['configuration']['threadid']);

				// Now we need this
				$sourceforuminfo2 = fetch_foruminfo($this->config['configuration']['destforumid']);
				$destforuminfo2 = fetch_foruminfo($this->config['configuration']['sourceforumid']);

				if ($destforuminfo2['cancontainthreads'] AND !$destforuminfo['link'])
				{
					// Do the move
					$this->_execThreadMove($threadinfo, $sourceforuminfo2, $destforuminfo2);
				}
			}
		}

		if ($this->config['notifications_config'])
		{
			$userids = explode(',', $this->config['notifications_config']);
			foreach ((array)$userids as $userid)
			{
				// Send PM
				VBSHOP::sendPM(
					$userid,
					construct_phrase($vbphrase['dbtech_vbshop_new_configuration_x'],
						$this->config['title']
					),
					construct_phrase($vbphrase['dbtech_vbshop_x_just_configured_y'],
						$recipient['username'],
						$this->config['title'],
						$vbphrase['dbtech_vbshop_thread_id'] . ': ' . intval($code['threadid'])
					)
				);
			}
		}
		
		// Update flag
		$this->registry->db->query_write("
			UPDATE " . TABLE_PREFIX . "dbtech_vbshop_purchase
			SET configuration = " . $this->registry->db->sql_prepare(trim(serialize($code))) . "
			WHERE purchaseid = " . intval($purchaseid) . "
		");
		
		// Build purchase cache
		VBSHOP::build_purchases($recipient);				
	}

	protected function _execThreadMove($threadinfo, $sourceforuminfo, $destforuminfo)
	{
		// Move threads
		// If mod can not manage threads in destination forum then unstick all moved threads
		$this->registry->db->query_write("
			UPDATE " . TABLE_PREFIX . "thread
			SET forumid = $destforuminfo[forumid]
			WHERE threadid = $threadinfo[threadid]
		");

		remove_invalid_prefixes(array($threadinfo['threadid']), $destforuminfo['forumid']);

		// update canview status of thread subscriptions
		update_subscriptions(array('threadids' => array($threadinfo['threadid'])));

		// kill the post cache for these threads
		delete_post_cache_threads(array($threadinfo['threadid']));

		$modlog = array(
			0 => array(
				'userid'   =>& $this->purchaseinfo['userid'],
				'forumid'  =>& $threadinfo['forumid'],
				'threadid' => $threadinfo['threadid'],
			)
		);

		log_moderator_action($modlog, 'thread_moved_to_x', $destforuminfo['title']);

		if (intval($this->registry->versionnumber) == 4)
		{
			// Search index maintenance
			vB_Search_Indexcontroller_Queue::indexQueue('vBForum', 'Post', 'thread_data_change', $threadinfo['threadid']);
		}

		build_forum_counters($sourceforuminfo['forumid']);
		build_forum_counters($destforuminfo['forumid']);
	}	
}
?>