<?php
/*======================================================================*\
|| #################################################################### ||
|| # vBulletin 4.0.3
|| # ---------------------------------------------------------------- # ||
|| # Copyright 2000-2010 vBulletin Solutions Inc. All Rights Reserved. ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/

/**
* Determines whether we should redirect to registers page given the script context
* 	- query string parameter dofbredirect must be set to 1 to perform redirect
* 
* @return	bool, true if we do not want to redirect to register page for this script
*/
function do_facebook_redirect()
{
	// first make sure we are not already registering, logging in or making ajax request
	if (THIS_SCRIPT == 'register' OR THIS_SCRIPT == 'ajax')
	{
		return false;
	}

	// if we have already performed this check return cached value,
	// otherwise check for the proper query string param
	static $dofbredirect;
	if (!isset($dofbredirect))
	{
		global $vbulletin;
		$vbulletin->input->clean_array_gpc('r', array(
			'dofbredirect'	=> TYPE_BOOL
		));
		$dofbredirect = ($vbulletin->GPC_exists['dofbredirect'] AND $vbulletin->GPC['dofbredirect'] == 1);
	}

	return $dofbredirect;
}

/**
* Saves fb data into a user data manager
* 
* @param	vB_DataManager_User, the datamanager to save the fb form info into
*/
function save_fbdata($userdata)
{
	global $vbulletin;
	
	// save the data from the import form
	save_fbimportform_into_userdm($userdata);
	
	// save the facebook usergroup
	save_fbusergroup($userdata);
}

/**
* Saves an auto registered Facebook user
* 
* @param	vB_DataManager_User, the datamanager to set the fields into
* 
* @return	bool	true if saved worked, false otherwise
*/
function save_fbautoregister($userdata)
{
	global $vbulletin;

	$info = vB_Facebook::instance()->getFbAutoRegUserInfo();

	//make sure we have all the fields we need for auto reg
	if (empty($info['uid'])
		OR empty($info['name'])
		OR empty($info['contact_email']))
	{
		$userdata->error('not_enough_facebook_userinfo');
		return;
	}

	// make sure facebook account is not already associated with a vb account
	if (vB_Facebook::instance()->getVbUseridFromFbUserid())
	{
		$userdata->error('facebook_account_already_registered');
		return;
	}

	// set misc user data
	$userdata->set('email', $info['contact_email']);
	$userdata->set('username', $info['name']);
	$userdata->set('password', time().'@facebook');
	$userdata->set('usergroupid', ($vbulletin->options['moderatenewmembers'] ? 4 : 2));
	$userdata->set('languageid', $vbulletin->userinfo['languageid']);
	$userdata->set_usertitle('', false, $vbulletin->usergroupcache["$newusergroupid"], false, false);
	$userdata->set('timezoneoffset', $info['timezone']);
	$userdata->set('ipaddress', IPADDRESS);
	$userdata->set('fbuserid', $info['uid']);
	$userdata->set('fbname', $info['name']);
	$userdata->set('fbjoindate', time());
	$userdata->set('logintype', 'fb');

	// save the facebook usergroup
	save_fbusergroup($userdata);
	
	// NOTE: Disabled for now, we will put this back when we have time to revisit
	// uploading facebook avatar for guests
	//save_fbavatar($userdata, $info['pic_big'], true, $info['pic']);
}

/**
* Builds the form pieces for importing information from facebook conbect
* 
* @param	string	the context for this form, gets appeneded to the template name so we use the right template for context
* 
* @return	string	renedered template for this form
*/
function construct_fbimportform($context = 'register')
{
	global $vbulletin, $show;
	
	// NOTE: due to Facebook terms of service, we are not allowed to 
	// store data obtained from the user for more than 24 hours
	// so we are commenting out code that facilitates saving such data
	
	// get some basic account information from facebook
	$profileinfo = vB_Facebook::instance()->getVbProfileInfo();
	
	/* Disabled due to ToS
	// prepare birthday
	if (!empty($profileinfo['birthday']))
	{
		list($bd_month, $bd_day, $bd_year) = explode('/', $profileinfo['birthday']);
		$dayselected = array($bd_day => 'selected="selected"');
		$monthselected = array($bd_month => 'selected="selected"');
	}
	*/
	
	// set up show variables for each profile field
	foreach ($profileinfo as $field => $value) 
	{
		if (!empty($value))
		{
			$show['fb_'.$field] = true;
		}
	}
	
	// only allow uploading of avatar for registered users, not new users
	$show['avatarupload'] = !empty($vbulletin->userinfo['userid']);
	
	// as we add more options to facebook importer, we need
	// to union those options for this show variable
	$show['fb_additionaloptions'] = $show['avatarupload'];

	$templater = vB_Template::create('facebook_import'.$context);
	$templater->register('profileinfo', $profileinfo);
	/* Disabled due to ToS
	$templater->register('dayselected', $dayselected);
	$templater->register('monthselected', $monthselected);
	$templater->register('bd_year', $bd_year);
	*/
	return $templater->render();
}

/**
* Puts data from the facebook import form into the user datamanager
* 
* @param	vB_DataManager_User, the datamanager to save the fb form info into
*/
function save_fbimportform_into_userdm($userdata)
{
	global $vbulletin;
	$vbulletin->input->clean_array_gpc('p', array(
		'fbuserid'		=> TYPE_STR,
		'fbname'		=> TYPE_STR,
		'fboptions'		=> TYPE_ARRAY,
		'avatarurl'		=> TYPE_STR
	));

	// make sure the current facebook userid matches the one when the form was generated
	if ($vbulletin->GPC['fbuserid'] != vB_Facebook::instance()->getLoggedInFbUserId())
	{
		$userdata->error('facebookuseridmismatch');
	}
	
	// make sure facebook account is not already associated with a vb account
	else if (vB_Facebook::instance()->getVbUseridFromFbUserid($vbulletin->GPC['fbuserid']))
	{
		$userdata->error('facebook_account_already_registered');
	}
	
	// passed validation, now we save the data
	else
	{
		$userdata->set('fbuserid', $vbulletin->GPC['fbuserid']);
		$userdata->set('fbname', $vbulletin->GPC['fbname']);
		$userdata->set('fbjoindate', time());
		
		// now save any additional data to user profile from facebook
		$fboptions = $vbulletin->GPC['fboptions'];
	
		// save avatar
		if (!empty($fboptions['useavatar']) AND !empty($vbulletin->GPC['avatarurl']))
		{
			save_fbavatar($userdata, $vbulletin->GPC['avatarurl']);
		}
	}
}


/**
* Saves the facebook avatar specified from facebook url
* 
* @param	vB_DataManager_User, the datamanager to put any upload errors into
* @param	string,	the url to retrieve the avatar from
* @param	bool, flag denoting if we want to try a different URL if this one fails
* @param	string,	the url to retrieve the avatar from if the first one fails
* 
* @return	bool	true if saved worked, false otherwise
*/
function save_fbavatar($userdata, $avatarurl = '', $do_fallback = true, $fallback_avatarurl = '')
{
	global $vbulletin;

	// if we are not passed an avatar url, grab it from fb api
	if (empty($avatarurl))
	{
		$pf = vB_Facebook::instance()->getVbProfileInfo();
		$avatarurl = $pf['avatarurl'];
	}

	// begin custom avatar code
	require_once(DIR . '/includes/class_upload.php');
	require_once(DIR . '/includes/class_image.php');

	// grab permissions info from logged in user, if user not logged in, use permissions from registered usergroup
	$usergroup_info = !empty($vbulletin->userinfo['userid']) ? $vbulletin->userinfo['permissions'] : $vbulletin->usergroupcache[2];
	
	// if user does not have permission to user custom avatar, skip this step
	if (!($usergroup_info['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canuseavatar']))
	{
		return;
	}

	// initialize the uploader and populate with the avatar permissions
	$upload = new vB_Upload_Userpic($vbulletin);
	$upload->data =& datamanager_init('Userpic_Avatar', $vbulletin, ERRTYPE_STANDARD, 'userpic');
	$upload->image =& vB_Image::fetch_library($vbulletin);
	$upload->maxwidth = $usergroup_info['avatarmaxwidth'];
	$upload->maxheight = $usergroup_info['avatarmaxheight'];
	$upload->maxuploadsize = $usergroup_info['avatarmaxsize'];
	$upload->allowanimation = ($usergroup_info['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['cananimateavatar']) ? true : false;
	
		// upload and validate
	if (!$upload->process_upload($avatarurl))
	{	
		// check if we want to try a fallback url
		if ($do_fallback)
		{
			// if we are not passed a fallback url, grab smaller pic from FB api
			if (empty($fallback_avatarurl))
			{
				$pf = vB_Facebook::instance()->getVbProfileInfo();
				$fallback_avatarurl = $pf['fallback_avatarurl'];
			}

			// do this again, but don't use a fallback if that one fails
			return save_fbavatar($userdata, $fallback_avatarurl, false);
		}

		// not doing a fallback, so add to the errors and return false
		else
		{		
			$userdata->error($upload->fetch_error());
			return false;
		}
	}

	// if we get here, there were no errors, so return true
	return true;
}

/**
* Saves fb usergroup into the datamanager
* 
* @param	vB_DataManager_User, the datamanager to save the fb form info into
*/
function save_fbusergroup($userdata)
{
	global $vbulletin;
	
	// save additional fb usergroup if specified, making sure it is not already the primary usergroup
	if ($vbulletin->options['facebookusergroupid'] > 0 AND $vbulletin->options['facebookusergroupid'] != $userdata->fetch_field('usergroupid'))
	{
		$membergroupids = fetch_membergroupids_array($vbulletin->userinfo, false);
		$membergroupids[] = $vbulletin->options['facebookusergroupid'];
		$userdata->set('membergroupids', array_unique($membergroupids));
	}
}

/*======================================================================*\
|| ####################################################################
|| # CVS: $RCSfile$ - $Revision: 36076 $
|| ####################################################################
\*======================================================================*/
