/** * 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 { // init the facebook graph api $this->facebook = new Facebook_vUrl(array( 'appId' => $this->registry->options['facebookappid'], 'secret' => $this->registry->options['facebooksecret'], 'cookie' => true )); // check for valid session without pinging facebook if ($this->fb_session = $this->facebook->getSession()) { $this->fb_userid = $this->fb_session['uid']; // make sure local copy of fb session is up to date $this->validateFBSession(); } } catch (Exception $e) { $this->fb_userid = null; } }
function try_connect($pubit = 0, $stUrl = '', $PublishMessage = '') { $myparams =& JComponentHelper::getParams('com_fbjconnect'); $getappid = $myparams->get('appid'); $getappsec = $myparams->get('appsecret'); $access_token = ""; $uid = ""; $postresult = false; $facebook = new Facebook(array('appId' => $getappid, 'secret' => $getappsec, 'cookie' => true)); $session = $facebook->getSession(); $me = null; $uid = ""; if ($session) { try { $access_token = $facebook->getAccessToken(); $me = $facebook->api('/me'); $uid = $facebook->getUser(); if ($pubit == 1) { $fbpic = JURI::base() . 'modules/mod_jfbgconnect/fgimage.jpg'; $postresult = $facebook->api('/me/feed/', 'post', array('access_token' => $access_token, 'picture' => $fbpic, 'link' => $stUrl, 'message' => $PublishMessage)); } } catch (FacebookApiException $e) { error_log($e); } } return array($uid, $me, $session, $access_token, $postresult); }
function fb() { $this->load->config('facebook'); include_once APPPATH . 'third_party/facebook.php'; $facebook = new Facebook(array('appId' => $this->config->item('facebook_app_id'), 'secret' => $this->config->item('facebook_api_secret'), 'cookie' => true)); $session = $facebook->getSession(); if (isset($session['uid'])) { $me = $facebook->api('/me'); // kalo login fb apakah ada user ini $rows = $this->db->get_where('meta', array('fb_id' => $session['uid']))->row(); if ($rows) { $row = $this->ion_auth->get_user_by_email($me['email']); $this->ion_auth_model->update_last_login($row->id); $session_data = array('email' => $row->email, 'id' => $row->id, 'user_id' => $row->id, 'group_id' => $row->group_id, 'group' => $row->group); $this->session->set_userdata($session_data); redirect($this->url_if_login); } else { $this->session->set_flashdata('message', 'Can\'t Find Your FB accounts mapping to our database member'); redirect('member/registration/'); } } else { $this->session->set_flashdata('message', 'Please Login To Your Facebook First'); redirect('member/login', 'refresh'); } }
protected function setUpFacebookInteractions($options) { // Create our Facebook Application instance $facebook = new Facebook(array('appId' => $options['facebook_app_id']->option_value, 'secret' => $options['facebook_api_secret']->option_value, 'cookie' => false)); //check status of current FB user $session = $facebook->getSession(); $fb_user = null; if ($session) { $fb_user_id = $facebook->getUser(); $fb_user = $facebook->api('/me'); } // login or logout url will be needed depending on current user state. if (isset($fb_user)) { $logoutUrl = $facebook->getLogoutUrl(); $fbconnect_link = '<img src="https://graph.facebook.com/' . $fb_user_id . '/picture" style="float:left;">' . $fb_user['name'] . '<br /><a href="' . $logoutUrl . '"> <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"></a>'; } else { $redirect_uri = urlencode('http://' . $_SERVER['SERVER_NAME'] . THINKUP_BASE_URL . 'account/?p=facebook'); $params = array('req_perms' => 'offline_access,read_stream,user_likes,user_location,user_website,' . 'read_friendlists', 'redirect_uri' => $redirect_uri); $loginUrl = $facebook->getLoginUrl($params); $fbconnect_link = '<a href="' . $loginUrl . '"><img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"></a>'; } $this->addToView('fbconnect_link', $fbconnect_link); $status = self::processPageActions($fb_user); $this->addInfoMessage($status["info"]); $this->addErrorMessage($status["error"]); $this->addSuccessMessage($status["success"]); $logger = Logger::getInstance(); $user_pages = array(); $instance_dao = DAOFactory::getDAO('InstanceDAO'); $owner_instances = $instance_dao->getByOwnerAndNetwork($this->owner, 'facebook'); $ownerinstance_dao = DAOFactory::getDAO('OwnerInstanceDAO'); foreach ($owner_instances as $instance) { $tokens = $ownerinstance_dao->getOAuthTokens($instance->id); $access_token = $tokens['oauth_access_token']; if ($instance->network == 'facebook') { //not a page $pages = FacebookGraphAPIAccessor::apiRequest('/' . $instance->network_user_id . '/likes', $access_token); if (@$pages->data) { $user_pages[$instance->network_user_id] = $pages->data; } } } //print_r($user_pages); $this->addToView('user_pages', $user_pages); $owner_instance_pages = $instance_dao->getByOwnerAndNetwork($this->owner, 'facebook page'); if (count($owner_instance_pages) > 0) { $this->addToView('owner_instance_pages', $owner_instance_pages); } $this->addToView('owner_instances', $owner_instances); if (isset($options['facebook_api_key'])) { $this->addToView('fb_api_key', $options['facebook_api_key']->option_value); } }
public function authenticate() { $facebook = new Facebook(array('appId' => $this->consumerKey, 'secret' => $this->consumerSecret, 'cookie' => true)); $session = $facebook->getSession(); if ($session) { $myFacebookInfo = $facebook->api('/me'); if ($myFacebookInfo && isset($myFacebookInfo['id'])) { $identity = new stdClass(); $identity->user_type = "facebook"; //Check user exists in database. $facebookTable = VC_Db_TableAdapter_Locator::get("FacebookUser"); $userTable = VC_Db_TableAdapter_Locator::get("User"); $userInfoInDb = $facebookTable->findFacebookUserByFacebookId($myFacebookInfo['id']); if (!$userInfoInDb) { //If not exist in db //Insert to DB $insertUserData = array(); $insertUserData['display_name'] = $myFacebookInfo['name']; $insertUserData['type'] = "facebook"; $newUserId = $userTable->insertUser($insertUserData); if ($newUserId) { //Insert user to Facebook Table $insertUserFBData = array(); $insertUserFBData['id'] = $newUserId; $insertUserFBData['facebook_id'] = $myFacebookInfo['id']; //$insertUserFBData['display_name'] = $myFacebookInfo['name']; $insertUserFBData['email'] = $myFacebookInfo['email']; $newFacebookUserId = $facebookTable->insertUser($insertUserFBData); $biUserTable = new VC_Db_TableAdapter_BI_BiUser(); $biUserTable->insertBiUser($newUserId); if (!$newFacebookUserId) { $log = VC_Log::getLog(); $log->logMessage("Could not insert facebook user to USER table.", Zend_Log::ERR); } $identity->user_name = $myFacebookInfo['name']; $identity->email = $myFacebookInfo['email']; $identity->user_id = $newUserId; } else { $log = VC_Log::getLog(); $log->logMessage("Could not insert facebook user to USER table.", Zend_Log::ERR); throw new VC_Exception("Could not insert Facebook user to database"); } } else { //TODO: Update information to DB again $identity->user_name = $myFacebookInfo['name']; $identity->email = $myFacebookInfo['email']; $identity->user_id = $userInfoInDb['id']; } return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity, array()); } } return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $this->consumerKey); }
/** * * Verify we have a facebook session and load the credentials * * @return array List of authentication credentials * */ public function getCredentials() { // We have a possible session lets get our user data if ($this->_facebook->getSession()) { try { $fb_results = $this->_facebook->api('/me'); return array('id' => $fb_results[$this->_config['fb_id']], 'handle' => $fb_results[$this->_config['fb_handle']], 'email' => $fb_results[$this->_config['fb_email']], 'moniker' => $fb_results[$this->_config['fb_moniker']], 'verified' => true); } catch (FacebookApiException $e) { // Session is invalid, login failed } } return false; }
function login() { if ($this->uri->segment(3) == 'twitter') { $twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET); // Requesting authentication tokens, the parameter is the URL we will be redirected to $request_token = $twitteroauth->getRequestToken(site_url() . '/home/twitter'); // Saving them into the session $this->session->set_userdata('oauth_token', $request_token['oauth_token']); $this->session->set_userdata('oauth_token_secret', $request_token['oauth_token_secret']); // If everything goes well.. if ($twitteroauth->http_code == 200) { // Let's generate the URL and redirect $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']); redirect($url, 'refresh'); } } else { if ($this->uri->segment(3) == 'facebook') { $facebook = new Facebook(array('appId' => APP_ID, 'secret' => APP_SECRET, 'cookie' => true)); $session = $facebook->getSession(); if (!empty($session)) { //Active session, let's try getting the user id (getUser()) and user info (api->('/me')) try { $uid = $facebook->getUser(); $user = $facebook->api('/me'); } catch (Exception $e) { } if (!empty($user)) { //User info ok? Let's print it (Here we will be adding the login and registering routines) //print_r($user); $username = $user['name']; $userdata = $this->usermodel->get_user($uid, 'facebook', $username); if (!empty($userdata)) { $this->session->set_userdata('id', $userdata['id']); $this->session->set_userdata('oauth_id', $uid); $this->session->set_userdata('username', $userdata['username']); $this->session->set_userdata('oauth_provider', $userdata['oauth_provider']); redirect(site_url(), 'refresh'); } } } else { # There's no active session, let's generate one $login_url = $facebook->getLoginUrl(); redirect($login_url, 'refresh'); } } else { //redirect 404? } } }
public static function Facebook($user) { $fb = new Facebook(array('appId' => self::$config['appId'], 'secret' => self::$config['secret'], 'cookie' => true)); $api = NULL; $user = NULL; $session = $fb->getSession(); if ($session) { try { $user = $fb->getUser(); $api = $fb->api($user); } catch (FacebookApiException $e) { parent::ErrorException('Facebook', $e, $user); } } return array('fb' => $fb, 'api' => $api, 'session' => $session); }
function beforeFilter() { $this->RequestHandler->setContent('json', 'text/x-json'); $facebook = new Facebook(array('appId' => '175485662472361', 'secret' => '4b66d239e574be89813bba4457b97a36', 'cookie' => true)); $session = $facebook->getSession(); if (empty($session)) { // $this->redirect(array('controller'=>'users','action'=>'login')); } if (!empty($user_record)) { $user_record_1 = array(); $user_record_1['Auth']['username'] = $user_record['User']['username']; $user_record_1['Auth']['password'] = $user_record['User']['password']; $this->Auth->authenticate_from_twitter($user_record_1['Auth']); $this->redirect('/'); } // endif; }
public static function getUid() { $culture = sfContext::getInstance()->getUser()->getCulture(); $facebook_uid = false; $facebook = new Facebook(array('appId' => sfConfig::get("app_facebook_api_id_{$culture}"), 'secret' => sfConfig::get("app_facebook_api_secret_{$culture}"), 'cookie' => true)); $session = $facebook->getSession(); $me = null; if ($session) { try { $uid = $facebook->getUser(); //$me = $facebook->api('/me'); $facebook_uid = $uid; } catch (FacebookApiException $e) { error_log($e); } } return $facebook_uid; }
/** * connect */ public function connect() { $facebook = new Facebook(array('appId' => $this->appId, 'secret' => $this->secret, 'cookie' => true)); $session = $facebook->getSession(); if (!empty($session)) { try { $uid = $facebook->getUser(); $user = $facebook->api('/me'); if (!empty($user['email'])) { return $user; } return false; } catch (Exception $e) { } } else { # There's no active session, let's generate one $login_url = $facebook->getLoginUrl(); header("Location: " . $login_url); } }
public function getSession($redirect_uri = null) { $session = parent::getSession(); if ($session) { return $session; } // oAuth 콜백 처리 if (!isset($_REQUEST['code'])) { return null; } // state 검사 if ($_SESSION['state'] != $_REQUEST['state']) { return null; } // 액세스 토큰 요청 $response = $this->makeRequest($this->getUrl('graph', 'oauth/access_token'), array('client_id' => $this->getAppId(), 'client_secret' => $this->getApiSecret(), 'code' => $_REQUEST['code'], 'redirect_uri' => $redirect_uri)); parse_str($response, $params); $this->setSession($params, true); return $params; }
/** * Authenticates the user passed by the constructor, however in this case we * user the WRAP server variable "WRAP_USERID" to get this appropriate username. * * @return new Zend_Auth_Result object */ public function authenticate() { if (AUTH_FB_APPID == '' || AUTH_FB_SECRET == '') { throw new Exception('Yahoo authentication options must be set in the application configuration.'); } // Create our Application instance (replace this with your appId and secret). $facebook = new Facebook(array('appId' => AUTH_FB_APPID, 'secret' => AUTH_FB_SECRET, 'cookie' => true)); $session = $facebook->getSession(); $username = null; // Session based API call. if ($session) { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); } catch (FacebookApiException $e) { return new Zend_Auth_Result(false, new stdClass(), array($e->getMessage())); } } // login if (!$me) { header('location:' . $facebook->getLoginUrl()); die; } $class = new stdClass(); $class->username = $me['id']; $class->firstName = $me['first_name']; $class->lastName = $me['last_name']; $class->realm = 'facebook'; return new Zend_Auth_Result(true, $class, array()); }
public function testSignedTokenInQuery() { $facebook = new Facebook(array('appId' => self::APP_ID, 'secret' => self::SECRET)); $_REQUEST['signed_request'] = self::$VALID_SIGNED_REQUEST; $this->assertNotNull($facebook->getSession()); unset($_REQUEST['signed_request']); }
<?php require_once '../config.php'; $fbc = new Facebook(array('appId' => FB::$app_id, 'secret' => FB::$secret, 'cookie' => true)); $session = $fbc->getSession(); $writer = new Zend_Log_Writer_Stream(LOG_ROOT . 'user_pop.log'); Logger::registerLogger('user_pop', $writer, null, true); Logger::debug(print_r($_POST, true)); Logger::debug(print_r($_GET, true)); Logger::debug(print_r($session, true));
function fb_connect_post_message($message) { global $config, $db, $plugin_config; $this_config = $plugin_config['protect']['fb_connect']; $testmode = $this_config['testmode']; $publish = $this_config['publish_stream']; if (!$publish) { return; } if (!$message) { return; } $facebook = new Facebook(array('appId' => "{$this_config['appid']}", 'secret' => "{$this_config['appsecret']}", 'cookie' => true)); // Check they are logged into Facebook $session = $facebook->getSession(); if ($session) { $fbuser = $facebook->getUser(); try { $statusupdate = $facebook->api('/me/feed', 'post', array('message' => $message, 'cb' => '')); if ($testmode) { $db->log_error("fb_connect: Updated wall for fbuser ({$fbuser}), message = {$message}"); } } catch (FacebookApiException $e) { if ($testmode) { $db->log_error("fb_connect: Error updating wall for fbuser ({$fbuser}) - {$e}"); } } } }
//Include libraries require 'facebook.php'; //Initializing variables $client_id = '140229329376512'; $display = 'page'; $redirect_url = 'http://nic4eve.appspot.com/authorize/'; //where should Facebook redirect after authorization? $scope = 'publish_stream'; //what permissions does the user need to grant your app? $oauth_url = 'https://graph.facebook.com/oauth/authorize?' . 'client_id=' . $client_id . '&redirect_uri=' . $redirect_url . '&type=' . 'user_agent' . '&display=' . $display . '&scope=' . $scope; //Initializing Facebook's PHP library $config = array('appId' => '140229329376512', 'secret' => '198fb6f72dfb3a029d410d98e3beb203', 'cookie' => true, 'domain' => true); $facebook_client = new Facebook($config); //Grab the user's session $session = $facebook_client->getSession(); /*If session does not exist, the user is not loggedin or hasn't added the app so redirect them to the authorize page.*/ if (!$session) { $text = "<script type=\"text/javascript\">\ntop.location.href = \"{$oauth_url}\";\n</script>"; echo $text; exit; } $access_token = $session['access_token']; $params = array('access_token' => $access_token); try { $me = $facebook_client->api('/me', $params); $friends = $facebook_client->api('/me/friends', $params); $friend = $friends['data']; $random1 = rand(1, count($friend)); $random2 = rand(1, count($friend));
public function getSession() { $session = parent::getSession(); if(!$session && isset($_REQUEST['fb_sig_session_key'])) { if(!$this->tokenSessionLoaded){ $oauth_struct = $this->getAccessTokenFromSessionKey($_REQUEST['fb_sig_session_key']); if(!isset($_REQUEST['fb_sig_user'])){ // After the initial invite is clicked. FB forwards to a page where a user can further invite // more friends via email. When a skip button is clicked. fb_sig_user was not sent back. // TODO: the access token returned by getAccessTokenFromSessionKey is incorrect. $me_json = $this->api('/me', array("access_token"=>$oauth_struct[0]->access_token)); $uid = $me_json['id']; }else{ $uid = $_REQUEST['fb_sig_user']; } $session = array('access_token' => $oauth_struct[0]->access_token, 'session_key' => $_REQUEST['fb_sig_session_key'], 'expires'=> $oauth_struct[0]->expires, 'uid' => $uid); $this->session = $session; $this->tokenSessionLoaded = true; }else{ $session = $this->session; } } return $session; }
public function actionLogout() { // If the user is already logged out send them to returnLogoutUrl if (Yii::app()->user->isGuest) { $this->redirect(Yum::module()->returnLogoutUrl); } //let's delete the login_type cookie $cookie = Yii::app()->request->cookies['login_type']; if ($cookie) { $cookie->expire = time() - 3600 * 72; Yii::app()->request->cookies['login_type'] = $cookie; } if ($user = YumUser::model()->findByPk(Yii::app()->user->id)) { $username = $user->username; $user->logout(); if (Yii::app()->user->name == 'facebook') { if (!Yum::module()->loginType & UserModule::LOGIN_BY_FACEBOOK) { throw new Exception('actionLogout for Facebook was called, but is not activated in main.php'); } Yii::import('application.modules.user.vendors.facebook.*'); require_once 'Facebook.php'; $facebook = new Facebook(Yum::module()->facebookConfig); $fb_cookie = 'fbs_' . Yum::module()->facebookConfig['appId']; $cookie = Yii::app()->request->cookies[$fb_cookie]; if ($cookie) { $cookie->expire = time() - 1 * (3600 * 72); Yii::app()->request->cookies[$cookie->name] = $cookie; $servername = '.' . Yii::app()->request->serverName; setcookie("{$fb_cookie}", "", time() - 3600); setcookie("{$fb_cookie}", "", time() - 3600, "/", "{$servername}", 1); } $session = $facebook->getSession(); Yum::log('Facebook logout from user ' . $username); Yii::app()->user->logout(); $this->redirect($facebook->getLogoutUrl(array('next' => $this->createAbsoluteUrl(Yum::module()->returnLogoutUrl), 'session_key' => $session['session_key']))); } else { Yum::log(Yum::t('User {username} logged off', array('{username}' => $username))); Yii::app()->user->logout(); } } $this->redirect(Yum::module()->returnLogoutUrl); }
function fb_callback() { if (isset($_GET['denied'])) { //session_name('CAKEPHP'); //session_start(); $this->Session->setFlash(__('<font color="red">You denied access to your facebook account.</font>', true)); } else { //import facebook Api App::import('Vendor', 'facebook'); $facebook = new Facebook(array('appId' => '212974112072342', 'secret' => '5d5452c23803f641a7f5487087f917be', 'cookie' => true)); $session = $facebook->getSession(); if (!empty($session)) { try { $responce = json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' . $session['access_token'])); } catch (FacebookApiException $e) { error_log($e); } if (!empty($responce)) { //check user on users table by fb_uid if (!$this->Session->check('User')) { $user = $this->User->find('all', array('conditions' => array('User.email' => '' . $responce->email))); //if empty or not found then insert into table if (empty($user)) { $img = file_get_contents('https://graph.facebook.com/' . $responce->id . '/picture?type=large'); $img_path = '/uploads/profile_img/' . $responce->id . '.jpeg'; file_put_contents($_SERVER['DOCUMENT_ROOT'] . $img_path, $img); //header("Content-type:image/gif"); echo($img); exit; $this->data['User']['email'] = '' . $responce->email; $this->data['User']['password'] = $this->randomString(); #$this->data['User']['group_id'] = '2'; #$this->data['User']['verified'] = 'yes'; $this->data['User']['name'] = $responce->first_name . ' ' . $responce->last_name; $this->data['User']['image'] = $responce->id . '.jpeg'; $this->data['User']['username'] = $responce->id; $this->data['User']['active'] = '1'; $this->data['User']['fbid'] = $responce->id; $this->data['User']['token'] = $session['access_token']; $this->data['User']['facebook_link'] = $session['secret']; $this->User->save($this->data); $user_id = $this->User->getLastInsertId(); // Insert Data to Account Tables $account_arr = array('user_id' => $user_id, 'available_funds' => '0', 'awaiting_funds' => '0', 'upcoming_funds' => '0', 'withdrawn_funds' => '0', 'purchases_funds' => '0'); $this->Account->save($account_arr); // $subject='Account activation email from '.SITE_URL; // $this->_sendUserMail('',$subject,'activate_account',$this->data['email'],'Y'); // Success $this->Session->setFlash("Your Account has been created successfully"); //$this->redirect('/users/nextstep/1'); $u = $this->User->read(); $this->setSession($u['User']); //$this->Session->write('user_id',$this->User->id); //$this->Session->write('email',$responce->email); //$this->Session->write('name', $responce->first_name); $this->redirect('/users/index'); } else { $this->setSession($user[0]['User']); $this->redirect('/users/index'); } } else { if ($this->Session->check('User')) { $fb_user = $this->User->find('first', array('conditions' => array('User.fbid' => $responce->id, 'User.status' => 'Active'))); if (is_array($fb_user)) { $this->setSession($fb_user['User']); $this->redirect('/users/index'); } } } } else { $this->Session->setFlash(__('<font color="red">Sorry, we could not authenticate you.</font>', true)); $this->redirect(array('controller' => 'users', 'action' => 'index'), null, true); } } } }
/** * Process a submitted comment. Redirects to the contents of the RET post var. * @return none */ function submit_comment() { //Get our settings and connect to OGraph API $this->getSettings(); $xid = $_POST['FB-XID']; require_once "facebook.php"; //Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false; //Temporary Hack //Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2; $facebook = new Facebook(array('appId' => $this->settings['appId'], 'secret' => $this->settings['secret'], 'cookie' => true)); //If there is a comment to test.. if (!empty($_POST['fb-commentText'])) { //Test for logged in user $session = $facebook->getSession(); if ($session) { $me; try { $me = $facebook->getUser(); } catch (FacebookApiException $e) { error_log($e); } if ($me) { //Add the comment! try { $facebook->api(array("method" => "comments.add", "xid" => $xid, "text" => $_POST['fb-commentText'])); } catch (FacebookApiException $e) { error_log($e); die("Error submitting comment to facebook."); } } else { echo "ERROR: No Facebook user."; return false; } } else { echo "ERROR: No Facebook Session."; return false; } } else { } //Send it back to the referrering page\ $this->EE->functions->redirect($_POST['RET']); }
/** * Allow the user to login using Facebook */ function action_fb_login() { // Facebook login must be enabled in config/useradmin.php if (!Kohana::config('useradmin')->facebook) { Message::add('error', 'Facebook login is not enabled. Please register below.'); Request::instance()->redirect('user/register'); } include Kohana::find_file('vendor', 'facebook/src/facebook'); // Create our Facebook SDK instance. $facebook = new Facebook(array('appId' => Kohana::config('facebook')->app_id, 'secret' => Kohana::config('facebook')->secret, 'cookie' => true)); $me = null; // Session based API call. if ($facebook->getSession()) { try { $uid = $facebook->getUser(); // read user info as array from Graph API $me = $facebook->api('/me'); } catch (FacebookApiException $e) { // do nothing } } // check if user is logged in $user = ORM::factory('user')->where('facebook_user_id', '=', $facebook->getUser())->find(); if (is_numeric($user->id) && $user->id != '0') { // found, log user in Auth_ORM::instance()->force_login($user); // redirect to the user account Request::instance()->redirect('user/profile'); return; } // associated user not found; register the user // retrieve user email from Facebook if ($me != NULL && Validate::email($me['email'], TRUE)) { // search for existing user using email $user = ORM::factory('user')->where('email', '=', $me['email'])->find(); if (is_numeric($user->id) && $user->id != '0') { // Note: there is minor security issue here - we trust the email supplied by Facebook // They do perform a verification check for email addresses... and the data is signed. // Hence this is not really a problem; I bet most of the implementations do trust Facebook. // If you want, you can ask the user to enter their password to confirm, but it's // a bit clunky - and adds more special cases like what if they don't remember the password? // Then you have to allow them to reset the password using their email .... Message::add('success', __('We found an existing account using your email address.')); // found: "merge" with the existing user $user->facebook_user_id = $facebook->getUser(); $user->save(); // force login Auth_ORM::instance()->force_login($user); // redirect to the user account Request::instance()->redirect('user/profile'); return; } } // not found: create a new user for real if ($me != NULL) { // Instantiate a new user $user = ORM::factory('user'); // fill in values // generate long random password (maximum that passes validation is 42 characters) $password = $user->generate_password(42); $values = array('username' => $user->generate_username($me['first_name'] . '.' . $me['last_name']), 'facebook_user_id' => $facebook->getUser(), 'password' => $password, 'password_confirm' => $password); if (Validate::email($me['email'], TRUE)) { $values['email'] = $me['email']; } $user->values($values); // If the post data validates using the rules setup in the user model if ($user->check()) { // create the account $user->save(); // Add the login role to the user (add a row to the db) $login_role = new Model_Role(array('name' => 'login')); $user->add('roles', $login_role); // sign the user in Auth::instance()->login($values['username'], $password); // redirect to the user account Request::instance()->redirect('user/profile'); } else { // in case the data for some reason fails, the user will still see something sensible: // the normal registration form. // Load the view $view = View::factory('user/register'); // Note how the first param is the path to the message file (e.g. /messages/register.php) $view->errors = $user->validate()->errors('register'); // Pass on the old form values $values['password'] = $values['password_confirm'] = ''; $view->set('defaults', $values); $this->template->content = $view; } } else { Message::add('error', 'Retrieving information from Facebook failed. Please register below.'); Request::instance()->redirect('user/register'); } }
public function processEditUser($user, $data) { if (array_key_exists('remove', $data)) { $user->setFacebookID(null); $user->save(); $user->recordActivity(USERBASE_ACTIVITY_REMOVED_FB); return true; } $facebook = new Facebook(array('appId' => $this->appID, 'secret' => $this->secret, 'cookie' => true)); $session = $facebook->getSession(); if (!$session) { return null; } try { $fbuser = $facebook->getUser(); } catch (FacebookApiException $e) { error_log("Can't get Facebook user"); return null; } $errors = array(); if (is_int($fbuser)) { $errors['fbuserid'][] = 'No Facebook id is passed'; throw new InputValidationException('No facebook user id', 0, $errors); } if (!is_null(User::getUserByFacebookID($fbuser))) { $errors['fbuserid'][] = 'Another user is already associated with your Facebook account.'; } if (count($errors) > 0) { throw new InputValidationException('Validation failed', 0, $errors); } $user->setFacebookID($fbuser); // if user doesn't have email address and we required it for Facebook connection, let's save it if (!$user->getEmail()) { try { $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log("Can't get /me API data"); return null; } if (array_key_exists('email', $me)) { $user->setEmail($me['email']); } } $user->save(); $user->recordActivity(USERBASE_ACTIVITY_ADDED_FB); return true; }
/** * Collback facebook page * @author Oleg D. */ function fb_connect_callback($permissionsType) { set_time_limit(500); $this->noCache(); App::import('Vendor', 'facebook'); $backURL = $this->apiBackURL(); $Facebook = new Facebook(array('appId' => FACEBOOK_API_KEY, 'secret' => FACEBOOK_SECRET_KEY, 'cookie' => true)); $this->User->recursive = -1; $facebook_session = $Facebook->getSession(); $this->Session->write('facebook_session', (array) $facebook_session); $this->Session->write('facebook_session_' . $permissionsType, (array) $facebook_session); $FacebookUser = json_decode($this->file_get_contents_curl('https://graph.facebook.com/me?access_token=' . $facebook_session['access_token'])); if (!empty($facebook_session)) { try { $FacebookUser = json_decode($this->file_get_contents_curl('https://graph.facebook.com/me?access_token=' . $facebook_session['access_token'])); } catch (FacebookApiException $e) { $this->Session->setFlash($e, 'flash_error'); return $this->redirect("/"); } if (!empty($FacebookUser) && $FacebookUser->id && $FacebookUser->email) { $this->User->recursive = -1; $likeUserInfo = array(); // Find User by Facebook ID and login $userInfo = $this->User->find('first', array('conditions' => array('User.facebook_id' => $FacebookUser->id, 'User.is_deleted <> ' => 1))); if (!empty($userInfo['User']['id'])) { $this->Access->loggining($userInfo['User']['id'], 1); $this->Session->write('FacebookUser', (array) $FacebookUser); return $this->redirect($backURL); // There is no Username with such Facebook ID } else { $likeUserInfo = $this->User->find('first', array('conditions' => array('User.email' => $FacebookUser->email, 'User.is_deleted <> ' => 1))); } $this->Session->write('FacebookUser', (array) $FacebookUser); $this->set('likeUserInfo', $likeUserInfo); $this->render(); } else { $this->Session->setFlash('Sorry, we could not authenticate you. Error code: f.2', 'flash_error'); return $this->redirect("/"); } } else { $this->Session->setFlash('Sorry, we could not authenticate you. Error code: f.3', 'flash_error'); return $this->redirect("/"); } }
<?php require_once 'facebook.php'; require_once 'functions.php'; $App = GET_appdetails(); $Urls = GET_urls(); $title = GET_title(); $tel = 'yes'; // check if the app was already accepted $facebook = new Facebook(array('appId' => $App['AppID'], 'secret' => $App['Secret'], 'cookie' => true)); try { $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); } if ($facebook->getSession()) { echo "<script>location.href = 'accepted.php'</script>"; //load accepted } $send = isset($_GET['send']) ? $_GET['send'] : ""; $validation = "non"; $DB = DB_info(); $conn = DB_connection($DB['db_host'], $DB['db_user'], $DB['db_pass'], $DB['db_name']); if ($send == "yes") { $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; if (GET_telephone()) { $telephone = $_POST['telephone']; } $email = $_POST['email']; $error_telephone = false;
public function fbConnect() { $this->objMods = $this->getObject('modules', 'modulecatalogue'); $this->objDbSysconfig = $this->getObject('dbsysconfig', 'sysconfig'); $show = $this->objDbSysconfig->getValue('show_fbconnect_auth', 'security'); if ($this->objMods->checkIfRegistered('facebookapps') && strtolower($show) == 'true') { include $this->getResourcePath('facebook.php', 'facebookapps'); $apikey = $this->objDbSysconfig->getValue('apikey', 'facebookapps'); $secret = $this->objDbSysconfig->getValue('apisecret', 'facebookapps'); $appId = $this->objDbSysconfig->getValue('apid', 'facebookapps'); // Create our Application instance (replace this with your appId and secret). $facebook = new Facebook(array('appId' => $appId, 'secret' => $secret, 'cookie' => true)); // We may or may not have this data based on a $_GET or $_COOKIE based session. // // If we get a session here, it means we found a correctly signed session using // the Application Secret only Facebook and the Application know. We dont know // if it is still valid until we make an API call using the session. A session // can become invalid if it has already expired (should not be getting the // session back in this case) or if the user logged out of Facebook. $session = $facebook->getSession(); $me = NULL; // Session based API call. if ($session) { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); if ($me) { $this->fbAuth($me); } } catch (FacebookApiException $e) { log_debug($e); } } // login or logout url will be needed depending on current user state. if ($me) { $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(array('req_perms' => 'email,read_stream')); } } else { return NULL; } }
public function testIgnoreArgSeparatorForCookie() { $cookieName = 'fbs_' . self::APP_ID; $session = self::$VALID_EXPIRED_SESSION; $_COOKIE[$cookieName] = '"' . http_build_query($session) . '"'; ini_set('arg_separator.output', '&'); // ensure we're testing what we expect $this->assertEquals(http_build_query(array('a' => 1, 'b' => 2)), 'a=1&b=2'); $facebook = new Facebook(array('appId' => self::APP_ID, 'secret' => self::SECRET, 'cookie' => true)); // since we're serializing and deserializing the array, we cannot rely on // positions being the same, so we do a ksort before comparison $loaded_session = $facebook->getSession(); ksort($loaded_session); ksort($session); $this->assertEquals($loaded_session, $session, 'Expect session back.'); unset($_COOKIE[$cookieName]); ini_set('arg_separator.output', '&'); }
function connect_facebook() { $this->load->config('facebook'); include_once APPPATH . 'third_party/facebook.php'; $fbparam = array('appId' => $this->config->item('fb_app_id'), 'secret' => $this->config->item('fb_app_secret'), 'cookie' => true); $facebook = new Facebook($fbparam); $session = $facebook->getSession(); if (!$session) { /* * The parameters: * - next: the url to go to after a successful login * - cancel_url: the url to go to after the user cancels * - req_perms: comma separated list of requested extended perms * - display: can be "page" (default, full page) or "popup" */ $login_param = array('next' => current_url()); $url = $facebook->getLoginUrl($login_param); redirect($url); } else { $fbid = $facebook->getUser(); $fbuser = $this->ion_auth_model->get_user_by_socmed('fb_id', $fbid); if ($fbuser) { $this->tpl['message'] = 'This Facebook Account Already Registered'; $this->tpl['content'] = $this->load->view('profile_connect_facebook', $this->tpl, true); $this->load->view('public/body_member', $this->tpl); } else { $fbdata = array('fb_id' => $session['uid'], 'fb_oauth_token' => $session['access_token']); $this->ion_auth->update_user($this->profile->id, $fbdata); redirect('member/profile'); } } }
$output_array3[] = $output_array2[0]; unset($output_array2); } for ($j = 0; $j <= count($output_array3) - 1; $j++) { $return2 = $facebook->api('/' . $output_array3[$j] . '/feed', 'POST', $data); } unset($output); unset($output_array); unset($output_array3); curl_close($ch); } } global $current_user; wp_get_current_user(); $facebook = new Facebook(array('appId' => 'APP ID', 'secret' => 'APP SECRET', 'cookie' => true)); $session = $facebook->getSession(); $access_token = $session['access_token']; $session = $facebook->getSession(); if ($session) { $result = mysql_num_rows(mysql_query("SELECT FIELD FROM TABLE WHERE username='******'")); if ($result != 0) { mysql_query("DELETE FROM TABLE WHERE username='******'") or die(mysql_error()); mysql_query("INSERT INTO TABLE (FIELD,FIELD) VALUE ('" . $current_user->user_login . "','" . $access_token . "')") or die(mysql_error()); } else { mysql_query("INSERT INTO TABLE (FIELD,FIELD) VALUE ('" . $current_user->user_login . "','" . $access_token . "')") or die(mysql_error()); } } function add_plugin_menu() { add_options_page('hss-notify-fb Settings', 'hss-notify-fb', 8, __FILE__, 'add_settings_page'); }
<?php $fbconfig = Yum::module()->facebookConfig; if(isset($fbconfig)) { Yii::import('application.modules.user.vendors.facebook.*'); require_once('Facebook.php'); $facebook = new Facebook($fbconfig); $fb_session = $facebook->getSession(); if($fb_session && Yii::app()->user->isGuest) if($this->action->id != 'login') $this->redirect($this->createUrl('/user/auth/login')); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="language" content="en" /> <script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl;?>/css/wmd/showdown.js"></script> <script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl;?>/css/wmd/jQuery/jquery-1.2.6.min.js "></script> <script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl;?>/css/custom_js.js "></script> <script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl;?>/css/prettify/src/prettify.js"></script> <!-- blueprint CSS framework --> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" /> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" /> <!--[if lt IE 8]> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" /> <![endif]-->