Skip to content

Instantly share code, notes, and snippets.

@crisu83
Created February 19, 2013 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisu83/4991047 to your computer and use it in GitHub Desktop.
Save crisu83/4991047 to your computer and use it in GitHub Desktop.
Facebook application component for Yii.
<?php
/**
* FacebookConnect class file.
* @author Christoffer Niska <ChristofferNiska@gmail.com>
* @copyright Copyright &copy; Christoffer Niska 2011-
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
/**
* Facebook connection application component.
*/
require(dirname(__FILE__) . '/../../vendors/facebook/facebook.php'); // Yii::import() will not work in this case
class FacebookConnect extends CApplicationComponent
{
/**
* @property string Facebook application id.
*/
public $appId;
/**
* @property string Facebook application secret.
*/
public $appSecret;
/**
* @property string the application namespace.
*/
public $appNamespace;
/**
* @property boolean whether file uploads are enabled.
*/
public $fileUpload;
protected $_userId;
protected $_facebook;
/**
* Initializes this component.
*/
public function init()
{
$config = array(
'appId' => $this->appId,
'secret' => $this->appSecret
);
if ($this->fileUpload !== null)
$config['fileUpload'] = $this->fileUpload;
$this->_facebook = new Facebook($config);
}
/**
* Logs in the current user using facebook.
* @return boolean whether the user was logged in successfully
*/
public function login()
{
$profile = $this->api('me');
$user = User::model()->findByAttributes(array('email'=>$profile['email']));
if (!empty($profile))
{
if ($user === null)
{
$user = new User();
$user->name = $profile['username'];
$user->email = $profile['email'];
$user->fbuid = $profile['id'];
$user->status = User::STATUS_ACTIVATED;
$user->activated = new CDbExpression('NOW()');
}
// todo: change this once we have collected the data for the existing users.
else
{
if (empty($user->name))
$user->name = $profile['username'];
if (empty($user->email))
$user->email = $profile['email'];
if (empty($user->fbuid))
$user->fbuid = $profile['id'];
if (empty($user->password))
$user->setNewPassword(uniqid('', true)); // set random passwords for FB users
if ((int) $user->status === User::STATUS_UNACTIVATED)
{
$user->status = User::STATUS_ACTIVATED;
$user->activated = new CDbExpression('NOW()');
}
}
$user->save(false);
}
if ($user !== null)
{
// NOTE: Facebook users are not authenticated using a password
// so we can simply generate a random one to prevent misuse.
$identity = new UserIdentity($user->name, $user->password);
$identity->authenticate(UserIdentity::AUTH_TYPE_FACEBOOK);
if ((int) $identity->errorCode === UserIdentity::ERROR_NONE)
{
$duration = 3600 * 24 * 30; // 30 days
Yii::app()->user->login($identity, $duration);
return true;
}
}
return false;
}
/**
* Registers an Open Graph action with Facebook.
* @param string $action the action to register.
* @param array $params the query parameters.
*/
public function registerAction($action, $params=array())
{
if (!isset($params['access_token']))
$params['access_token'] = $this->facebook->getAccessToken();
$this->api('me/'.$this->appNamespace.':'.$action, $params);
}
/**
* Returns the model for the currently logged in Facebook user.
* @return User the user model.
*/
public function loadUser()
{
$fbuid = $this->getUserId();
return $fbuid > 0 ? User::model()->findByAttributes(array('fbuid'=>$fbuid)) : null;
}
/**
* @return integer the Facebook user id.
*/
public function getUserId()
{
if ($this->_userId !== null)
return $this->_userId;
else
{
$userId = 0;
try
{
$userId = $this->_facebook->getUser();
}
catch (FacebookApiException $e)
{
}
return $this->_userId = $userId;
}
}
/**
* Returns the locale based on the application language.
* @return string the locale.
*/
public function getLocale()
{
$language = Yii::app()->language;
if ($language !== null)
{
$pieces = explode('_', $language);
if (count($pieces) === 2)
return $pieces[0].'_'.strtoupper($pieces[1]);
}
return 'en_US';
}
/**
* Calls the Facebook API.
* @param string $query the query to send.
* @param array $params the query paramters.
* @return array the response.
*/
public function api($query, $params=array())
{
$data = array();
if (!empty($params))
$query .= '?'.http_build_query($params);
try
{
$data = $this->_facebook->api('/'.$query);
}
catch (FacebookApiException $e)
{
}
return $data;
}
/**
* @return Facebook the Facebook application instance.
*/
public function getFacebook()
{
return $this->_facebook;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment