public function __get($name)
 {
     if ($name == "value") {
         if ($this->fb->getUser()) {
             $this->value = $this->fb->getAccessToken();
         } else {
             $this->value = "NONE";
         }
         return $this->value;
     } else {
         return parent::__get($name);
     }
 }
    /**
     * save social information
     * access token,
     */
    public function saveProfileSystemInfo()
    {
        if ($oProfile = self::getProfileObject()) {
            $sSocialID = (string) $oProfile->id;
            $session = serialize(self::$object->getAccessToken());
            $profileInfo = serialize($oProfile);
            if ($sSocialID && $session && $profileInfo) {
                return SJB_DB::query('INSERT INTO `facebook` SET `facebook_id` = ?s, `access` = ?s, `profile_info` = ?s
					ON DUPLICATE KEY UPDATE `access` = ?s, `profile_info`=?s', $sSocialID, $session, $profileInfo, $session, $profileInfo);
            }
            return false;
        }
        return null;
    }
示例#3
0
 /**
  * Log a user in
  * @return Array Userdata
  * @throws FacebookApiException
  */
 public function login($grabUserImage = false)
 {
     $uid = $this->_client->getUser();
     $accessToken = $this->_client->getAccessToken();
     // If a user is authenticated, $userData will be filled with user data
     $userData = $this->_client->api('/me');
     if ($grabUserImage) {
         $apiUrl = '/' . $this->_client->getUser() . '/picture?redirect=0&type=large';
         $picture = $this->_client->api($apiUrl);
         $userData['imageUrl'] = $picture['data']['url'];
     }
     $userData['access_token'] = $accessToken;
     return $userData;
 }
 public function callback()
 {
     $member = Member::currentUser();
     if ($member) {
         $SiteConfig = SiteConfig::current_site_config();
         $request = $this->getRequest()->requestVars();
         $facebook = new Facebook(array('appId' => $SiteConfig->FBAppID, 'secret' => $SiteConfig->FBSecret, 'code' => $request['code']));
         $facebook->setAccessToken($facebook->getAccessToken());
         if ($facebook->getUser() && $facebook->getAccessToken()) {
             $SiteConfig->FBVerified = $facebook->getAccessToken();
         }
         $SiteConfig->write();
         $this->redirect('/admin/settings');
     }
 }
示例#5
0
 public function testSetSession()
 {
     $facebook = new Facebook(array('appId' => self::APP_ID, 'secret' => self::SECRET, 'cookie' => true));
     $facebook->setSession(self::$VALID_EXPIRED_SESSION);
     $this->assertTrue($facebook->getUser() == self::$VALID_EXPIRED_SESSION['uid'], 'Expect uid back.');
     $this->assertTrue($facebook->getAccessToken() == self::$VALID_EXPIRED_SESSION['access_token'], 'Expect access token back.');
 }
示例#6
0
 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);
 }
 public function doLogin()
 {
     $code = Input::get('code');
     if (strlen($code) == 0) {
         return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
     }
     $facebook = new Facebook(Config::get('facebook'));
     $uid = $facebook->getUser();
     if ($uid == 0) {
         return Redirect::to('/')->with('message', 'There was an error');
     }
     $me = $facebook->api('/me', ['fields' => ['id', 'first_name', 'last_name', 'picture', 'email', 'gender']]);
     $profile = Profile::whereUid($uid)->first();
     if (empty($profile)) {
         $user = new User();
         $user->name = $me['first_name'] . ' ' . $me['last_name'];
         $user->email = $me['email'];
         $user->photo = 'https://graph.facebook.com/' . $me['id'] . '/picture?type=large';
         $user->save();
         $profile = new Profile();
         $profile->uid = $uid;
         $profile->username = $me['id'];
         $profile->gender = $me['gender'];
         $profile = $user->profiles()->save($profile);
     }
     $profile->access_token = $facebook->getAccessToken();
     $profile->save();
     $user = $profile->user;
     Auth::login($user);
     return Redirect::to('/')->with('message', 'Logged in with Facebook');
 }
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     $user = $this->_Collection->Auth->user();
     $service = strtolower($request->params['pass'][0]);
     if ($service !== $this->service) {
         return false;
     }
     try {
         $facebook = new Facebook(array('appId' => $this->myConsumerKey, 'secret' => $this->myConsumerSec, 'cookie' => true));
         $action = $request->params['action'];
         if ($action === 'login') {
             $url = $facebook->getLoginUrl(array('redirect_uri' => Router::url('callback/facebook/', true), 'scope' => 'email,publish_stream'));
             if ($url !== null) {
                 $response->header('Location', $url);
                 $response->send();
             }
         } elseif ($action === 'callback') {
             preg_match('/state=(.*)/', $_REQUEST['url'], $state);
             $_REQUEST['state'] = $state[1];
             $accessToken = $facebook->getAccessToken();
             if ($accessToken != '') {
                 $this->_fetch($facebook, $accessToken, $response);
             } else {
                 //you should throw exception
             }
         }
     } catch (OAuthException $E) {
         //you can catch OAuth exception
     }
 }
示例#9
0
function mx_mntestusers($page, $option, $action)
{
    global $facebook;
    echo 'Disabled.';
    return;
    $fbapp = new Facebook(array('appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET, 'grant_type' => 'client_credentials'));
    $acctok = $fbapp->getAccessToken();
    if ($_REQUEST['createuser']) {
        $newuser = $fbapp->api('/' . FACEBOOK_APP_ID . '/accounts/test-users?installed=true&permissions=&access_token=' . $acctok, 'POST');
    } else {
        if ($_REQUEST['deleteuser']) {
            foreach ($_REQUEST['selected'] as $user) {
                $testusers = $fbapp->api('/' . $user . '?access_token=' . $acctok, 'DELETE');
                mx_deleteuser($user);
                // delete should only be possible for test users!!
            }
        }
    }
    $testusers = $fbapp->api('/' . FACEBOOK_APP_ID . '/accounts/test-users&access_token=' . $acctok, 'GET');
    echo '<form action="' . mx_optionurl($page, $option) . '" method=POST>';
    echo '<table border=1 width=100%><tr><th>Sel</th><th>ID</th><!-- <th>access_token</th> --><th>login_url</th></tr>';
    foreach ($testusers['data'] as $testuser) {
        echo '<tr><td><input type=checkbox name="selected[]" value="' . $testuser['id'] . '"></td>' . '<td>' . $testuser['id'] . '</td>';
        //$user=$facebook->api('/'.$testuser['id']);
        //die(print_r($user));
        //echo '<td>'.$user['name'].'</td>';
        echo '<!-- <td>' . $testuser['access_token'] . '</td> --><td>' . '<a href="' . $testuser['login_url'] . '">' . $testuser['login_url'] . '</a></td></tr>';
    }
    echo '<tr><td colspan=3 align=center><input type=submit name="createuser" value="Create User">' . ' <input type=submit name="deleteuser" value="Delete User(s)"></td></tr>';
    echo '</table></form>';
}
示例#10
0
 /**
  * Overrides Facebook's SDK call to pass it our defined Token and not
  * from a session.
  *
  * Returns regular SDK call if none set
  *
  * @return string
  */
 public function getAccessToken()
 {
     if ($this->accessToken !== null) {
         return $this->accessToken;
     } else {
         return parent::getAccessToken();
     }
 }
 protected function _connectCallback()
 {
     $helper = Mage::helper('social/facebook');
     $storeId = Mage::app()->getStore()->getStoreId();
     $websiteId = Mage::app()->getStore()->getWebsiteId();
     $facebook = new Facebook(array('appId' => $helper->getFacebookConfig('client_id', $storeId), 'secret' => $helper->getFacebookConfig('client_secret', $storeId)));
     $fid = $facebook->getUser();
     $ftoken = $facebook->getAccessToken();
     if ($fid) {
         try {
             $data = $facebook->api('/me');
             $customersByFacebookId = Mage::helper('social/facebook')->getCustomersByFacebookId($fid, $websiteId);
             if (Mage::getSingleton('customer/session')->isLoggedIn()) {
                 if ($customersByFacebookId->getSize()) {
                     Mage::getSingleton('core/session')->addNotice($this->__('Your facebook account is already connected to one of our store accounts.'));
                     return $this;
                 }
                 $customer = Mage::getSingleton('customer/session')->getCustomer();
                 Mage::helper('social/facebook')->connectByFacebookId($customer, $fid, $ftoken);
                 Mage::getSingleton('core/session')->addSuccess($this->__('Your facebook account is now connected to your store account. You can now login using our facebook login button or using store account credentials you will receive to your email address.'));
                 return $this;
             }
             if ($customersByFacebookId->getSize()) {
                 $customer = $customersByFacebookId->getFirstItem();
                 Mage::helper('social/facebook')->loginByCustomer($customer);
                 Mage::getSingleton('core/session')->addSuccess($this->__('You have successfully logged in using your facebook account.'));
                 return $this;
             }
             $customersByEmail = Mage::helper('social/facebook')->getCustomersByEmail($data['email'], $websiteId);
             if ($customersByEmail->getSize()) {
                 $customer = $customersByEmail->getFirstItem();
                 Mage::helper('social/facebook')->connectByFacebookId($customer, $fid, $ftoken);
                 Mage::getSingleton('core/session')->addSuccess($this->__('We have discovered you already have an account at our store. Your facebook account is now connected to your store account.'));
                 return $this;
             }
             $firstName = $data['first_name'];
             if (empty($firstName)) {
                 throw new Exception($this->__('Sorry, could not retrieve your facebook first name. Please try again.'));
             }
             $lastName = $data['last_name'];
             if (empty($lastName)) {
                 throw new Exception($this->__('Sorry, could not retrieve your facebook last name. Please try again.'));
             }
             Mage::helper('social/facebook')->connectByCreatingAccount($data['email'], $data['first_name'], $data['last_name'], $fid, $ftoken);
             Mage::getSingleton('core/session')->addSuccess($this->__('Your facebook account is now connected to your new user account at our store. Now you can login using our facebook login button or using store account credentials you will receive to your email address.'));
             return $this;
         } catch (Exception $e) {
             Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
             return $this;
         }
     } else {
         Mage::getSingleton('core/session')->addError($this->__('Sorry, could not login. Please try again.'));
         return $this;
     }
 }
示例#12
0
 public function callback()
 {
     $facebook = new Facebook(array('appId' => FACEBOOK_APPID, 'secret' => FACEBOOK_SECRET, 'cookie' => true));
     #Recebo o token inicial, short-lived, de 2hrs
     $facebook = new Facebook(array('appId' => FACEBOOK_APPID, 'secret' => FACEBOOK_SECRET, 'cookie' => true));
     $facebook->setAccessToken($facebook->getAccessToken());
     #Trocamos o token short-lived por uma long lived
     $facebook->setExtendedAccessToken();
     $extendedAccessToken = $_SESSION["fb_" . FACEBOOK_APPID . "_access_token"];
     $facebook->setAccessToken($extendedAccessToken);
     $accessToken = $facebook->getAccessToken();
     # agora eu pego uns dados do cara
     $me = $facebook->api('/me');
     # e guardo o token c/ mais uns dados dele
     $o = new stdClass();
     $o->accessToken = $accessToken;
     $o->userID = $me['id'];
     $o->userName = $me['username'];
     SocialNetwork::link_account($this->session->user->id, SocialNetwork::FACEBOOK, $o);
     Request::redirect(HOST . 'perfil/configuracoes');
 }
 function initialize(&$controller, $settings = array())
 {
     global $signed_request;
     $facebook = new Facebook(array('appId' => Configure::read('fbconfig.id'), 'secret' => Configure::read('fbconfig.secret'), 'cookie' => true));
     $access_token = $facebook->getAccessToken();
     if (isset($_REQUEST['signed_request'])) {
         // faster
         $signed_request = $_REQUEST['signed_request'];
     } else {
         // backup via API
         $signed_request = $facebook->getSignedRequest();
     }
     $this->facebook = $facebook;
 }
示例#14
0
function fb_send($appid, $appsecret, $userid, $msg)
{
    try {
        $facebook = new Facebook(array('appId' => $appid, 'secret' => $appsecret, 'cookie' => true));
        $token = $facebook->getAccessToken();
        $post = array('access_token' => $token, 'message' => $msg);
        $res = $facebook->api('/' . $userid . '/feed', 'POST', $post);
        // echo post was sent successfully
        //$global['xajax_res']->addAppend('rezLog', 'innerHTML', '<br>New post was sent to Facebook');
    } catch (Exception $e) {
        // save error
        //em_save_post_error($id, $_SESSION['user'], $e->getMessage());
        // echo the error message
        //$global['xajax_res']->addAppend('rezLog', 'innerHTML', '<br>Facebook error:'.$e->getMessage());
    }
}
示例#15
0
 public function actionFacebook()
 {
     Yii::import('application.vendors.Facebook.*');
     include_once 'facebook.php';
     $facebook = new Facebook(array('appId' => '274957429359215', 'secret' => '2f021bff5939f3ffe097b5e29a1baec4'));
     $params = array('scope' => 'public_profile, email, user_birthday, user_hometown', 'redirect_uri' => Yii::app()->request->hostInfo . Yii::app()->request->url);
     $loginUrl = $facebook->getLoginUrl($params);
     if ($user = $facebook->getUser()) {
         $authkey = $this->registrar_por_red_social('facebook', $facebook->getAccessToken());
         Yii::app()->session['key'] = $authkey;
         $this->redirect(array('/usuario/registro/crearclave'));
     } elseif ($_GET['error']) {
         Yii::app()->user->setFlash('error', "No se autorizó el registro con Facebook");
         $this->redirect(array('/usuario/registro'));
     } else {
         $this->redirect($loginUrl);
     }
 }
示例#16
0
 /**
  * {@inheritdoc}
  */
 function getUserProfile()
 {
     // request user profile from fb api
     try {
         $fields = array('id', 'name', 'first_name', 'last_name', 'link', 'website', 'gender', 'locale', 'about', 'email', 'hometown', 'location');
         $data = $this->api->api('/me?fields=' . implode(',', $fields));
     } catch (FacebookApiException $e) {
         throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e}", 6);
     }
     // if the provider identifier is not received, we assume the auth has failed
     if (!isset($data["id"])) {
         throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response.", 6);
     }
     # store the user profile.
     $this->user->profile->identifier = array_key_exists('id', $data) ? $data['id'] : "";
     $this->user->profile->username = array_key_exists('username', $data) ? $data['username'] : "";
     $this->user->profile->displayName = array_key_exists('name', $data) ? $data['name'] : "";
     $this->user->profile->firstName = array_key_exists('first_name', $data) ? $data['first_name'] : "";
     $this->user->profile->lastName = array_key_exists('last_name', $data) ? $data['last_name'] : "";
     $this->user->profile->photoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150";
     $this->user->profile->coverInfoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "?fields=cover&access_token=" . $this->api->getAccessToken();
     $this->user->profile->profileURL = array_key_exists('link', $data) ? $data['link'] : "";
     $this->user->profile->webSiteURL = array_key_exists('website', $data) ? $data['website'] : "";
     $this->user->profile->gender = array_key_exists('gender', $data) ? $data['gender'] : "";
     $this->user->profile->language = array_key_exists('locale', $data) ? $data['locale'] : "";
     $this->user->profile->description = array_key_exists('about', $data) ? $data['about'] : "";
     $this->user->profile->email = array_key_exists('email', $data) ? $data['email'] : "";
     $this->user->profile->emailVerified = array_key_exists('email', $data) ? $data['email'] : "";
     $this->user->profile->region = array_key_exists("location", $data) && array_key_exists("name", $data['location']) ? $data['location']["name"] : "";
     if (!empty($this->user->profile->region)) {
         $regionArr = explode(',', $this->user->profile->region);
         if (count($regionArr) > 1) {
             $this->user->profile->city = trim($regionArr[0]);
             $this->user->profile->country = trim($regionArr[1]);
         }
     }
     if (array_key_exists('birthday', $data)) {
         list($birthday_month, $birthday_day, $birthday_year) = explode("/", $data['birthday']);
         $this->user->profile->birthDay = (int) $birthday_day;
         $this->user->profile->birthMonth = (int) $birthday_month;
         $this->user->profile->birthYear = (int) $birthday_year;
     }
     return $this->user->profile;
 }
示例#17
0
 /**
  * Render fieldset html
  *
  * @param Varien_Data_Form_Element_Abstract $element
  * @return string
  */
 public function render(Varien_Data_Form_Element_Abstract $element)
 {
     $msg = '<div style="padding-bottom: 1em;max-width: 800px;">';
     $appId = Mage::getStoreConfig('besociable/facebook/appid');
     $appSecret = Mage::getStoreConfig('besociable/facebook/appsecret');
     $currentAccessToken = Mage::getStoreConfig('besociable/facebook/access_token');
     if ($appId != '' && $appSecret != '') {
         $facebook = new Facebook(array('appId' => $appId, 'secret' => $appSecret));
         $merge = $appId . '|' . $appSecret;
         $accessToken = $facebook->getAccessToken();
         if ($accessToken != $merge && $accessToken != $currentAccessToken) {
             Mage::getConfig()->saveConfig('besociable/facebook/access_token', $accessToken);
             $facebook->setAccessToken($accessToken);
         } else {
             $facebook->setAccessToken($currentAccessToken);
         }
         $user = $facebook->getUser();
         if ($user) {
             $loginUrl = $facebook->getLoginUrl(array('scope' => array('manage_pages', 'publish_stream')));
             $msg .= Mage::helper('sociable')->__('<span style="color: green;">You have successfully authorized with facebook.</span>');
             $msg .= Mage::helper('sociable')->__('<br>You can always <a href="%s">click here</a> to re-authorize your access to facebook again.', $loginUrl);
             $msg .= Mage::helper('sociable')->__('<br>If you want to get a list of your pages, you can simply <a href="%s">click here</a>', $this->getUrl('adminhtml/sociable/getPages'));
             $msg .= Mage::helper('sociable')->__('<br>Please <a href="%s">click here</a> to make a test post.', $this->getUrl('adminhtml/sociable/testfacebook'));
             /*
             if(!$user){
             	$loginUrl = $facebook->getLoginUrl(array('scope'=>array('manage_pages','publish_stream')));//, 'publish_actions', 'publish_stream'
             	$msg .= Mage::helper('sociable')->__('<strong style="color:red">Important: </strong>');
             	$msg .= Mage::helper('sociable')->__('You will need to <a href="%s">click here</a> to authorize your access to facebook for the first time.',$loginUrl);
             }else {
             	
             }
             */
         } else {
             $loginUrl = $facebook->getLoginUrl(array('scope' => array('manage_pages', 'publish_stream')));
             //, 'publish_actions', 'publish_stream'
             $msg .= Mage::helper('sociable')->__('<strong style="color:red">Important: </strong>');
             $msg .= Mage::helper('sociable')->__('You will need to <a href="%s">click here</a> to authorize your access to facebook for the first time.', $loginUrl);
         }
     }
     $msg .= '</div>';
     return $msg;
 }
 protected function getUserIdFromApi()
 {
     // Create a Facebook object
     $facebook = new Facebook(array('appId' => FB_APP_ID, 'secret' => FB_SECRET, 'cookie' => true));
     Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
     Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
     // See if there is a Facebook session
     $this->facebookId = $facebook->getUser();
     $this->accessToken = $facebook->getAccessToken();
     if (!empty($this->facebookId)) {
         try {
             $facebookAttemptAPI = $facebook->api('/me');
             $this->name = $facebookAttemptAPI['name'];
         } catch (FacebookApiException $e) {
             $this->exitWithMessage('Error: The user data could not be retrieved from Facebook.');
         }
     } else {
         $this->exitWithMessage('Error: The user ID could not be retrieved from Facebook.');
     }
 }
示例#19
0
function hg_facebook_user_tiles()
{
    $c = new Cache();
    $c->setCachePath(HG_DIR . '/sdk/cache/');
    $c->seed = NONCE_SALT;
    $c->eraseExpired();
    $_template = '<div id="faces-wrap">
		<div class="faces">%s</div>
	</div>';
    $_template_item = sprintf('<img src="%s/sdk/cache/%%s.jpg">', get_bloginfo('template_directory'));
    $output = "";
    if ($c->isCached('attending')) {
        $attending = $c->retrieve('attending');
    } else {
        $facebook = new Facebook(array('appId' => FACEBOOK_EVENT_APP_ID, 'secret' => FACEBOOK_EVENT_APP_KEY));
        $attending = array();
        $access_token = $facebook->getAccessToken();
        $params = array('access_token' => $access_token);
        $objs = $facebook->api(FACEBOOK_EVENT_APP_ID . '/events', 'GET', $params);
        foreach ($objs['data'] as $data) {
            $objs2 = $facebook->api($data['id'] . '/invited', 'GET', $params);
            foreach ($objs2['data'] as $attendee) {
                if ($attendee['rsvp_status'] == 'attending' || $attendee['rsvp_status'] == 'unsure') {
                    if (!is_file(get_stylesheet_directory() . '/sdk/cache/' . $attendee['id'] . '.jpg')) {
                        file_put_contents(get_stylesheet_directory() . '/sdk/cache/' . $attendee['id'] . '.jpg', file_get_contents(get_bloginfo('template_directory') . '/sdk/timthumb.php?src=http://graph.facebook.com/' . $attendee['id'] . '/picture?type=large&w=75&h=75'));
                    }
                    $attending[] = $attendee['id'];
                }
            }
        }
        $c->store('attending', shuffle($attending), 60 * 60 * 24 * 7);
    }
    if (!is_array($attending) || sizeof($attending) < 10) {
        return "";
    }
    foreach ($attending as $id) {
        $output .= sprintf($_template_item, $id);
    }
    return sprintf($_template, $output);
}
 protected function getfbUser()
 {
     $code = Input::get('code');
     if (strlen($code) == 0) {
         return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
     }
     $facebook = new Facebook(Config::get('facebook'));
     $uid = $facebook->getUser();
     if ($uid == 0) {
         return Redirect::to('/')->with('message', 'There was an error');
     }
     $me = $facebook->api('/me');
     // check if that email exists in wordpress database
     //if there is user with that email, log them in
     //otherwise insert that user with dummy password, and alert that to user
     $profile = Profile::whereUid($uid)->first();
     if (empty($profile)) {
         $user = new User();
         $user->user_login = $me['email'];
         $user->user_nicename = $me['first_name'] . ' ' . $me['last_name'];
         $user->user_email = $me['email'];
         //$user->photo = 'https://graph.facebook.com/'.$me['username'].'/picture?type=large';
         $user->save();
         $profile = new Profile();
         $profile->uid = $uid;
         $profile->username = $me['first_name'] . " " . $me['last_name'];
         $profile = $user->profiles()->save($profile);
     }
     $profile->access_token = $facebook->getAccessToken();
     $profile->save();
     $user = $profile->user;
     //dd($user);
     Auth::login($user);
     $username = $me['email'];
     Session::put('username', $username);
     $userId = User::where('user_login', $username)->pluck('ID');
     Session::put('userId', $userId);
     return Redirect::to('/');
     //->with('message', 'Logged in with Facebook');
 }
示例#21
0
function postCheckinToFacebook($appSecret, $userID, $token, $message, $firstAttempt)
{
    // Setup facebook
    $facebook = new Facebook(array('appId' => '400073310043056', 'secret' => $appSecret));
    $facebook->setAccessToken($token);
    // Construct and send the location based post
    try {
        $result = $facebook->api('/' . $userID . '/feed', 'POST', array('access_token' => $facebook->getAccessToken(), 'place' => '246419308104', 'message' => $message, 'coordinates' => json_encode(array('latitude' => '-27.47159234211', 'longitude' => '153.019149383', 'tags' => $userID))));
    } catch (FacebookApiException $e) {
        echo $e->__toString();
        if ($firstAttempt == true) {
            // Having trouble figuring out how to differentiate between the various errors that
            // can be caught here (they don't use unique codes for some reason!?)
            // But it doesn't matter, we can pretty harmlessly just retry with an extended token
            $token = $facebook->getExtendedAccessToken();
            if (isset($token)) {
                postCheckinToFacebook($appSecret, $userID, $token, $message, false);
            }
        }
        // Ignore errors if we've already tried this again
    }
}
示例#22
0
 /**
  * @param $internalAccountId
  * @return string
  */
 public function getAccessToken($internalAccountId)
 {
     // Init PHP Sessions
     if (session_status() == PHP_SESSION_NONE) {
         session_start();
     }
     $fb = new Facebook(['appId' => '585641281593451', 'secret' => '104c6d7f29f24ade25443069032c3320']);
     return $fb->getAccessToken();
     //            $helper = $fb->getRedirectLoginHelper();
     //
     //            if (!isset($_SESSION['facebook_access_token'])) {
     //                $_SESSION['facebook_access_token'] = null;
     //            }
     //
     //            if (!$_SESSION['facebook_access_token']) {
     //                $helper = $fb->getRedirectLoginHelper();
     //                try {
     //                    $_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();
     //                } catch(FacebookResponseException $e) {
     //                    // When Graph returns an error
     //                    echo 'Graph returned an error: ' . $e->getMessage();
     //                    exit;
     //                } catch(FacebookSDKException $e) {
     //                    // When validation fails or other local issues
     //                    echo 'Facebook SDK returned an error: ' . $e->getMessage();
     //                    exit;
     //                }
     //            }
     //
     //            if ($_SESSION['facebook_access_token']) {
     //                echo "You are logged in!";
     //            } else {
     //                $permissions = ['ads_management'];
     //                $loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
     //                echo '<a href="' . $loginUrl . '">Log in with Facebook</a>';
     //            }
     //
     //            return "";
 }
示例#23
0
function getFbToken()
{
    require_once 'fbapp/src/facebook.php';
    // Create our Application instance (replace this with your appId and secret).
    $facebook = new Facebook(array('appId' => '1656109864649862', 'secret' => '30dd5bcdf99df0f6514324d6ffb2c6d9'));
    // Get User ID
    //USER HAS BEEN REDIRECTED HERE AFTER SUCCESSFUL LOGIN
    $fbId = $facebook->getUser();
    if ($fbId == 0) {
        //REDIRECt
        header("Location: login.php");
        exit;
    } else {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $fbToken = $facebook->getAccessToken();
        } catch (FacebookApiException $e) {
            header("Location: " . "index.php?msg=" . urlencode("cannot get fbAccessToken"));
            exit;
        }
    }
    return $fbToken;
}
示例#24
0
function nextend_api_auth_flow()
{
    $api_key = NextendRequest::getVar('api_key');
    $api_secret = NextendRequest::getVar('api_secret');
    $redirect_uri = NextendRequest::getVar('redirect_uri');
    if (session_id() == "") {
        @session_start();
    }
    if (!$api_key || !$api_secret || !$redirect_uri) {
        $api_key = isset($_SESSION['api_key']) ? $_SESSION['api_key'] : null;
        $api_secret = isset($_SESSION['api_secret']) ? $_SESSION['api_secret'] : null;
        $redirect_uri = isset($_SESSION['redirect_uri']) ? $_SESSION['redirect_uri'] : null;
    } else {
        $_SESSION['api_key'] = $api_key;
        $_SESSION['api_secret'] = $api_secret;
        $_SESSION['redirect_uri'] = $redirect_uri;
    }
    if ($api_key && $api_secret) {
        require_once dirname(__FILE__) . "/api/facebook.php";
        $facebook = new Facebook(array('appId' => $api_key, 'secret' => $api_secret));
        $user = $facebook->getUser();
        if (!$user) {
            header('Location: ' . $facebook->getLoginUrl(array('redirect_uri' => $redirect_uri, 'scope' => 'user_photos')));
            exit;
        } else {
            $facebook->setExtendedAccessToken();
            $accessToken = $facebook->getAccessToken();
            $facebook->destroySession();
            unset($_SESSION['api_key']);
            unset($_SESSION['api_secret']);
            unset($_SESSION['redirect_uri']);
            echo '<script type="text/javascript">';
            echo 'window.opener.setToken("' . $accessToken . '");';
            echo '</script>';
        }
    }
}
示例#25
0
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array('appId' => '', 'secret' => ''));
// Get User ID
$user = $facebook->getUser();
echo 'AccessToken:' . $facebook->getAccessToken();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
    try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}
// Login or logout url will be needed depending on current user state.
示例#26
0
    <h3>Your User Object</h3>
    <pre><?php 
    print_r($me);
    ?>
</pre>
    <?php 
    if (true) {
        echo "POSTING TO WALL!<br>\n\n";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/evanhsu/feed");
        curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/116587918401126/feed");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array("access_token" => $facebook->getAccessToken(), 'message' => "Evan is working hard on the siskiyourappellers website!"));
        $response = curl_exec($ch);
    }
    ?>
    <?php 
} else {
    ?>
    <strong><em>You are not Connected.</em></strong>
    <?php 
}
?>

    <h3>Naitik</h3>
    <img src="https://graph.facebook.com/naitik/picture">
    <?php 
echo $naitik['name'];
示例#27
0
<?php

session_start();
# We require the library
include '../include/include.php';
require "facebook.php";
require "facebook_key.php";
# Creating the facebook object
$facebook = new Facebook(array('appId' => $appId, 'secret' => $secret, 'cookie' => true));
# Let's see if we have an active session
$facebook_session = $facebook->getSession();
echo $facebook->getAccessToken();
/*
if(!empty($facebook_session)) 
   {
	try
	{
	 $uid = $facebook_session['uid'];
   	 $fields=array('network_type_id'=>$uid, 'network_type' =>'facebook');
	 $findRow =$db->findCount('compose_networks',$fields);
	 if(!$findRow)
	   {
		$fields=array('userId'=>$_SESSION['sessMemberId'],
				'network_type'=>'facebook',
				'network_type_id'=>$uid,
				'name'=>'',
				'oauth_token' =>$facebook_session['access_token'],
				'oauth_token_secret'=>''
			   );
	   $db->save('compose_networks',$fields);
	   unset($_SESSION['access_token']);
示例#28
0
if (!empty($result)) {
    $facebook->setAccessToken($result['oauth_token']);
}
$user_id = $facebook->getUser();
?>
<!DOCTYPE html>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    </head>
    <body>
    <?php 
if ($user_id) {
    try {
        $facebook->setExtendedAccessToken();
        $access_token = $facebook->getAccessToken();
        $inbox = $facebook->api('/me/inbox', 'GET');
        $me = $facebook->api('/me', 'GET');
        $_SESSION['user_token'] = $access_token;
        facebookMessages($inbox, $me);
        //sleep(5);
        //facebookMessages($inbox,$me);
    } catch (FacebookApiException $e) {
        $params = array('scope' => 'read_mailbox, offline_access', 'redirect_uri' => 'http://localhost/facebook/callback.php');
        $login_url = $facebook->getLoginUrl($params);
        echo 'No Token </br>';
        echo '<a href="' . $login_url . '">Authorize on Facebook</a>';
        error_log($e->getType());
        error_log($e->getMessage());
    }
} else {
require 'facebook.php';
require 'credentials.php';
require 'mysql.php';
$facebook = new Facebook(array('appId' => FB_APP_ID, 'secret' => FB_APP_SECRET));
$userId = $facebook->getUser();
db_connect();
?>

<html>
  <body>
    <?php 
if ($userId) {
    $userInfo = $facebook->api('/' + $userId);
    echo "Welcome " . $userInfo['name'] . "<br>";
    if (db_check_id($userId) == False) {
        db_insert_id($userId, $userInfo['name'], $facebook->getAccessToken());
    } else {
        // Update the access token just in case
        db_update_token($userId, $facebook->getAccessToken());
    }
} else {
    ?>
    <div id="fb-root"></div>
      <div class="fb-login-button" data-scope="email,friends_hometown,offline_access">
        Login with Facebook
      </div>
    <?php 
}
?>
    <script>
      window.fbAsyncInit = function() {
示例#30
0
 public static function try_connect()
 {
     $myparams = JComponentHelper::getParams('com_fbconnct');
     $mainframe = JFactory::getApplication();
     $getappid = $myparams->get('appid');
     $getappsec = $myparams->get('appsecret');
     $fbpermissions = $myparams->get('fbpermissions');
     $facebook = new Facebook(array('appId' => $getappid, 'secret' => $getappsec));
     $fbuser = $facebook->getUser();
     if ($fbuser) {
         try {
             // Proceed knowing you have a logged in user who's authenticated.
             $access_token = $facebook->getAccessToken();
             $me = $facebook->api('/me');
         } catch (FacebookApiException $e) {
             //error_log($e);
             //$mainframe->enqueueMessage('Facebook Says :'. $e->getMessage(), 'error');
         }
     }
     // redirect user to facebook login page if fresh login requires
     if (!$fbuser) {
         $sef_enabled = $mainframe->getCfg('sef');
         //$sef_rewrite = $mainframe->getCfg('sef_rewrite');
         if (!$sef_enabled) {
             $fb_redirect_url = JURI::base() . JRoute::_('index.php?option=com_fbconnct&task=login&view=fbconnct&format=raw');
         } else {
             $fb_redirect_url = JURI::base() . substr(JRoute::_('index.php?option=com_fbconnct&task=login&view=fbconnct&format=raw'), strlen(JURI::base(true)) + 1);
         }
         $loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'scope' => $fbpermissions, 'redirect_uri' => $fb_redirect_url));
         $mainframe->redirect($loginUrl);
     }
     if (!isset($me["email"])) {
         die("Could not get Email address, make sure you are using valid email address at Facebook or have granted the email permission!");
     }
     $fbdata = array('fbid' => $fbuser, 'fbdetails' => $me, 'appid' => $getappid, 'fbtoken' => $access_token, 'fbobject' => $facebook);
     return $fbdata;
 }