<?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 # ||
|| #################################################################### ||
\*======================================================================*/

require_once(DIR . '/includes/facebook/facebook.php');

/**
 * vBulletin wrapper for the facebook client api, singleton
 *
 * @package vBulletin
 * @author Michael Henretty, vBulletin Development Team
 * @version $Revision: 35941 $
 * @since $Date: 2010-03-24 12:21:57 -0700 (Wed, 24 Mar 2010) $
 * @copyright vBulletin Solutions Inc.
 */
class vB_Facebook
{
	/**
	 * A reference to the singleton instance
	 *
	 * @var vB_Facebook
	 */
	protected static $instance = null;

	/**
	 * The facebook client api object
	 *
	 * @var Facebook
	 */
	protected $facebook = null;

	/**
	 * The facebook userid if logged in
	 *
	 * @var int
	 */
	protected $registry = null;

	/**
	 * The facebook userid if logged in
	 *
	 * @var int
	 */
	protected $fb_userid = null;

	/**
	 * The associated vBulletin userid if available
	 *
	 * @var int
	 */
	protected $vb_userid = null;

	/**
	 * The user infomation array we want to grab from fb api by default
	 *
	 * @var array
	 */
	protected $fb_userinfo = array();
	protected $userinfo_fields = array(
		'uid',
		'name',
		'first_name',
		'last_name',
		'timezone',
		'contact_email',
		'locale',
		'current_location',
		'affiliations',
		'profile_url',
		'sex',
		'contact_email',
		'pic_square',
		'pic',
		'pic_big',
		'about_me',
		'activities',
		'birthday_date',
		'books',
		'current_location',
		'interests',
		'movies',
		'music',
		'political',
		'profile_blurb',
		'quotes',
		'website',
		'work_history'
	);

	/**
	 * Returns an instance of the facebook client api object
	 *
	 * @return vB_Facebook
	 */
	public static function instance()
	{
		if (!isset(self::$instance))
		{
			// boot up the facebook api
			self::$instance = new vB_Facebook();
		}

		return self::$instance;
	}


	/**
	 * Constructor
	 *
	 * @param int $apikey	the api key for the facebook user
	 * @param int $secret	the facebook secret for the application
	 */
	protected function __construct()
	{
		// cache a reference to the registry object
		global $vbulletin;
		$this->registry = $vbulletin;

		// initialize fb api and grab fb userid to cache locally
		try
		{
			$this->facebook = new Facebook($this->registry->options['facebookapikey'], $this->registry->options['facebooksecret']);
			$this->fb_userid = $this->facebook->api_client->users_getLoggedInUser();
		}
		catch (Exception $e)
		{
			$this->fb_userid = false;
		}
	}


	/**
	 * Checks the fb userid returned from api to make sure its valid
	 *
	 * @return bool, fb userid if logged in, false otherwise
	 */
	private function isValidUser()
	{
		// check for null restuls, or error code (<1000)
		return (!empty($this->fb_userid) AND !$this->fb_userid < 1000);
	}


	/**
	 * Checks if the current user is logged into facebook
	 *
	 * @return bool
	 */
	public function userIsLoggedIn()
	{
		// make sure facebook is connect also enabled
		return self::instance()->isValidUser();
	}


	/**
	 * Checks for a currrently logged in user through facebook api
	 *
	 * @return mixed, fb userid if logged in, false otherwise
	 */
	public function getLoggedInFbUserId()
	{
		if (!$this->isValidUser())
		{
			return false;
		}

		return $this->fb_userid;
	}


	/**
	 * Grabs logged in user info from faceboook if user is logged in
	 *
	 * @param array, strings of field names to get from facebook
	 * @return mixed, fb userid if logged in, false otherwise
	 */
	public function getFbUserInfo($fields = false)
	{
		// grab the fb userid
		if (!$fb_userid = $this->getLoggedInFbUserId())
		{
			return false;
		}
		
		// check for cached versions of this, and return it if so
		if (!empty($this->fb_userinfo))
		{
			return $this->fb_userinfo;
		}

		// attempt to grab userinfo from fb api
		try
		{
			// if user info array is passed in use that, otherwise use default
			$this->fb_userinfo = $this->facebook->api_client->users_getInfo($fb_userid, $this->userinfo_fields);
		}
		catch (Exception $e)
		{
			return false;
		}

		// if facebook returns error code, simply return false
		$this->fb_userinfo = ( (is_array($this->fb_userinfo)AND!empty($this->fb_userinfo)) ? $this->fb_userinfo[0] : array());
		return $this->fb_userinfo;
	}


	/**
	 * Grabs logged in user info from faceboook if user is logged in
	 *
	 * @return mixed, fb userid if logged in, false otherwise
	 */
	public function getFbAboutMeUserInfo($force_reload = false)
	{
		return $this->getFbUserInfo();
	}


	/**
	 * Grabs logged in user info from faceboook if user is logged in
	 * - this information is specifically for auto-registration
	 *
	 * @return mixed, fb userid if logged in, false otherwise
	 */
	public function getFbAutoRegUserInfo()
	{
		return $this->getFbUserInfo();
	}


	/**
	 * Checks if current facebook user is associated with a vb user, and returns vb userid if so
	 *
	 * @param int, facebook userid to check in vb database, if not there well user current
	 * 		logged in user
	 * @return mixed, vb userid if one is associated, false if not
	 */
	public function getVbUseridFromFbUserid($fb_userid = false)
	{
		// if no fb userid was passed in, attempt to use current logged in fb user
		// but if no current fb user, there cannot be an associated vb account, so return false
		if (empty($fb_userid) AND !$fb_userid = $this->getLoggedInFbUserId())
		{
			return false;
		}

		// check if vB userid is already cached in this object
		if ($fb_userid == $this->getLoggedInFbUserId() AND !empty($this->vb_userid))
		{
			return $this->vb_userid;
		}

		// otherwise we have to grab the vb userid from the database
		$user = $this->registry->db->query_first("
			SELECT userid
			FROM `" . TABLE_PREFIX . "user`
			WHERE fbuserid = $fb_userid
		");
		$this->vb_userid = (!empty($user['userid']) ? $user['userid'] : false);

		return $this->vb_userid;
	}

	/**
	 * Builds an array of information facebook we can use to populate vb user profile fields
	 *
	 * @param array, profile information from facebook
	 * @return mixed, the biography blurb to user for vb profile, or false if there is none
	 */
	public function getVbProfileInfo()
	{
		global $show;

		// the array we are going to return, populated with FB data
		$profilefields = array(
			'fbuserid' => '',
			'fbname' => '',
			'biography' => '',
			'location' => '',
			'interests' => '',
			'occupation' => '',
			'homepageurl' => '',
			'birthday' => '',
			'avatarurl' => '',
			'fallback_avatarurl' => ''
		);

		// grab fb account information
		$fb_info = $this->getFbAboutMeUserInfo();

		// NOTE: due to Facebook terms of service, we are not allowed to
		// store most data obtained from the user for more than 24 hours
		// so we are commenting out code that facilitates saving such data
		/*
		$profilefields['interests'] .= (!empty($fb_info['interests']) ? $fb_info['interests'].' ' : '');
		$profilefields['interests'] .= (!empty($fb_info['activities']) ? $fb_info['activities'].' ' : '');
		$profilefields['interests'] .= (!empty($fb_info['books']) ? $fb_info['books'].' ' : '');
		$profilefields['interests'] .= (!empty($fb_info['movies']) ? $fb_info['movies'].' ' : '');
		$profilefields['interests'] .= (!empty($fb_info['music']) ? $fb_info['music'].' ' : '');
		$profilefields['interests'] .= (!empty($fb_info['quotes']) ? $fb_info['quotes'].' ' : '');

		if (is_array($fb_info['work_history']) AND !empty($fb_info['work_history']))
		{
			// dont use location info
			if (isset($fb_info['work_history'][0]['location']))
			{
				unset($fb_info['work_history'][0]['location']);
			}
			// remove empty items
			array_filter($fb_info['work_history'][0]);
			$profilefields['occupation'] .= implode(', ', $fb_info['work_history'][0]);
		}

		$profilefields['biography'] .= (!empty($fb_info['about_me']) ? $fb_info['about_me'] : '');
		$profilefields['location'] .= (!empty($fb_info['current_location']) ? implode(', ', $fb_info['current_location']) : '');
		$profilefields['homepageurl'] .= (!empty($fb_info['website']) ? $fb_info['website'] : '');
		$profilefields['birthday'] .= (!empty($fb_info['birthday_date']) ? $fb_info['birthday_date'] : '');
		*/
		$profilefields['fbuserid'] .= (!empty($fb_info['uid']) ? $fb_info['uid'] : '');
		$profilefields['fbname'] .= (!empty($fb_info['name']) ? $fb_info['name'] : '');
		$profilefields['avatarurl'] .= (!empty($fb_info['pic_big']) ? $fb_info['pic_big'] : '');
		$profilefields['fallback_avatarurl'] .= (!empty($fb_info['pic']) ? $fb_info['pic'] : '');

		return $profilefields;
	}

	/**
	 * Logs out the current facebook user from facebook session
	 *
	 * @param string, the url page will return to after loggin out of facebook (required)
	 */
	public function doLogoutFbUser($return_url = null)
	{
		// if we are not given a return url, use the forum home
		if (empty($return_url))
		{
			$return_url = $this->registry->options['bburl'] . '/' . $this->registry->options['forumhome'] . '.php' . $this->registry->session->vars['sessionurl_q'];
		}

		$this->facebook->logout($return_url);
	}
}

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