facebook-opengraph

Provides easy access to Facebook's PHP SDK and JS SDK, Social Plugin widgets and Open Graph meta tags
62 followers

INTRODUCTION:

This is mainly a wrapper for the Facebook PHP SDK class.

You can also use it to include the Facebook JS SDK on your pages, and easily set Open Graph meta tags.

Also included are helper widgets for all of the Facebook Social Plugins.

Facebook PHP SDK: http://developers.facebook.com/docs/reference/php/ https://github.com/facebook/facebook-php-sdk

Facebook JS SDK: http://developers.facebook.com/docs/reference/javascript/

Facebook Social Plugins: http://developers.facebook.com/docs/reference/plugins

Open Graph Protocol: http://developers.facebook.com/docs/opengraph/

A lot of this comes from forking ianare's faceplugs Yii extension: http://www.yiiframework.com/extension/faceplugs https://github.com/digitick/yii-faceplugs


INSTALLATION:

Copy the file "facebook-channel.php" to your project root.

Copy the rest of this extension in to your project's protected/extensions directory.

Include the extension in your Yii config:

'components'=>array(
  'facebook'=>array(
    'class' => 'ext.yii-facebook-opengraph.SFacebook',
    'appId'=>'YOUR_FACEBOOK_APP_ID', // needed for JS SDK, Social Plugins and PHP SDK
    'secret'=>'YOUR_FACEBOOK_APP_SECRET', // needed for the PHP SDK
    //'fileUpload'=>false, // needed to support API POST requests which send files
    //'trustForwarded'=>false, // trust HTTP_X_FORWARDED_* headers ?
    //'locale'=>'en_US', // override locale setting (defaults to en_US)
    //'jsSdk'=>true, // don't include JS SDK
    //'async'=>true, // load JS SDK asynchronously
    //'jsCallback'=>false, // declare if you are going to be inserting any JS callbacks to the async JS SDK loader
    //'status'=>true, // JS SDK - check login status
    //'cookie'=>true, // JS SDK - enable cookies to allow the server to access the session
    //'oauth'=>true,  // JS SDK - enable OAuth 2.0
    //'xfbml'=>true,  // JS SDK - parse XFBML / html5 Social Plugins
    //'frictionlessRequests'=>true, // JS SDK - enable frictionless requests for request dialogs
    //'html5'=>true,  // use html5 Social Plugins instead of XFBML
    //'ogTags'=>array(  // set default OG tags
        //'title'=>'MY_WEBSITE_NAME',
        //'description'=>'MY_WEBSITE_DESCRIPTION',
        //'image'=>'URL_TO_WEBSITE_LOGO',
    //),
  ),
),

Then, in your base Controller, add this function to override the afterRender callback:

protected function afterRender($view, &$output) {
  parent::afterRender($view,$output);
  //Yii::app()->facebook->addJsCallback($js); // use this if you are registering any $js code you want to run asyc
  Yii::app()->facebook->initJs($output); // this initializes the Facebook JS SDK on all pages
  Yii::app()->facebook->renderOGMetaTags(); // this renders the OG tags
  return true;
}

USAGE:

Setting OG tags on a page (in view or action):

<?php Yii::app()->facebook->ogTags['og:title'] = "My Page Title"; ?>

Render Facebook Social Plugins using helper Yii widgets:

<?php $this->widget('ext.yii-facebook-opengraph.plugins.LikeButton', array(
   //'href' => 'YOUR_URL', // if omitted Facebook will use the OG meta tag
   'show_faces'=>true,
   'send' => true
)); ?>

You can, of course, just use the code for this as well if loading the JS SDK on all pages using the initJs() call in afterRender():

<div class="fb-like" data-send="true" data-width="450" data-show-faces="true"></div>

To use the PHP SDK anywhere in your application, just call it like so (there pass-through the Facebook class):

<?php $userid = Yii::app()->facebook->getUser() ?>
<?php $loginUrl = Yii::app()->facebook->getLoginUrl() ?>
<?php $results = Yii::app()->facebook->api('/me') ?>

I also created a couple of little helper functions:

<?php $userinfo = Yii::app()->facebook->getInfo() // gets the Graph info of the current user ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePicture('large') // gets the Facebook picture URL of the current user ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePicture(array('height'=>300,'width'=>300)) // $size can also be specific ?>
<?php $userinfo = Yii::app()->facebook->getInfoById($openGraphId) // gets the Graph info of a given OG entity ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePictureById($openGraphId, $size) // gets the Facebook picture URL of a given OG entity ?>

BREAKING CHANGES:

  • Before version 0.6 you didn't need to include the full OG meta tag (including the "og:" bit). Now you need to, to allow for new custom graph objects and actions. If you were setting OG meta tags like this Yii::app()->facebook->ogTags['title'] it now needs to be like this Yii::app()->facebook->ogTags['og:title'].

CHANGE LOG:

  • 0.6 Added support for custom OG meta tags, upgraded PHP SDK to 3.2, +some bugfixes
  • 0.6.1 Bugfix for the custom OG meta tags, which were overwriting the type, title and url tags
  • 0.7 Upgraded to PHP SDK 3.2.2
  • 0.8 Fixed error with LoginButton plugin where inherited CWidget 'skin' property caused display error, added missing attributes to LoginButton, and added ability to specify custom profile image size
  • 0.8.1 Updated the PHP SDK cert chain bundle which was not update to date for some reason, and copied in a security fix from the PHP SDK as well

I plan on continuing to update and bugfix this extension as needed.

Please log bugs to the GitHub tracker.

Updated Feb 17th 2013 by Evan Johnson http://splashlabsocial.com

Total 20 comments

#13238 report it
Dũng Ninh Bình at 2013/05/17 12:35am
issue logged out from facebook.com too while logging out from the site using facebook-opengraph

You get issue logged out from facebook.com too while logging out from the site using facebook-opengraph It was resolved for me by. In config of extension in file main i edit this line:

//'status'=>true, // JS SDK - check login status

to

'status'=>false, // JS SDK - check login status
#11739 report it
rigel at 2013/01/31 03:27am
Using both PHP and Jssdk

@thaddeusmt Thanks Yii::app()->facebook->addJsCallback() method worked But i am facing similar issue like @Tpoxa.

I have use PHP sdk for login and authentication. Rest of the facebook features I wish to use JSsdk. Though the Js does not work in many pages (sometimes on refresh it does).

In most of the cases I get the following Error /**/ FB._callbacks.__gcb2({"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}});

*update. I guess I found the issue http://freeporoxy.appspot.com/facebook.stackoverflow.com/questions/7338763/facebook-js-sdk-and-php-sdk-access-token-conflict .

Will try and implement it

#11659 report it
schmunk at 2013/01/25 07:19am
Composer Package

This extension is now available for composer from the Phundament package repository

#11557 report it
thaddeusmt at 2013/01/20 04:05pm
Login Button fix, profile picture custom sizes and async JS callback

@Sebastien Thanks or the heads up on the 'skin' bug, the extension was accidentally passing the skin="default" parameter into the Login Button plugin, which was causing it not to show up. It is fixed now. And thanks for the profile picture dimensions suggestion, I will add that to the extension soon.

Anyone else finding bugs or suggesting code enhancements, please file them in GitHub, thanks.

@rigel If you are loading the Facebook JS SDK using this extension's default settings, it is loading asynchronously. This means FB will not be available in $.ready() or onLoad events. You need to put code dependent on FB in the async callback. You can do this with this extension using the Yii::app()->facebook->addJsCallback() method.

#11553 report it
rigel at 2013/01/20 09:04am
Reference Error : FB is not defined

Hi , I am little confused. I am trying to use this custom multi-friend select plugin from here https://github.com/mbrevoort/jquery-facebook-multi-friend-selector.

When I call any function related to FB example FB.api on some event like click even on button the script facebook sdk works fine. But when tryin to call FB related function on event like onLoad I get error

Reference Error : FB is not defined

Is it realted to loading of this script

<

script id="facebook-jssdk" async="" src="//connect.facebook.net/en_US/all.js">

I dont know how to resolve this issue. I want the plugin to showup as page loads

#11528 report it
Sebastian at 2013/01/18 10:21am
Two additions

To use the LoginButton, I had to work out how to use it:

$this->widget('ext.yii-facebook-opengraph.plugins.LoginButton', array(
    'show_faces'=>false,
    'skin'=>'light',));

Setting the skin was crucial, as facebook denies to use the "default" skin. I do miss some documentation.

I also needed to have the profile picture resized. Facebook can do this for us, but we have to change this function in SFacebook.php:

public function getProfilePictureById($id, $size = null) {
    if (is_array($size) && isset($size['height']) && isset($size['width'])) {
      return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture?width='.$size['width'].'&height='.$size['height'];
    } else if ($size && !is_array($size))
      return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture?type='.$size;
    else
      return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture';
  }

It was quite less hassle than I thought before. However, I am missing a "afterLogin"-action somehow. Have to figure out, how to create accounts for the newly logged in users.

#11411 report it
Tpoxa at 2013/01/11 01:53pm
An active access token must be used to query information about current user SOLVED

Hi. Extension works great! But I suppose access token expire to quickly. Couple minutes and my application requires re-login again. Could someone help me with it?

Here is what I have in log

An active access token must be used to query information about about the current user.

(I uncommented

catch (Exception $e) { Yii::log('Failed to make Facebook API call. Exception: ' . $e->getMessage()); }

) to see it

====================== Problem was in my sessions. Ensure that php do not lost sessions on disk and cookie that stores session id has correct lifetime

EXAMPLE: ini_set('session.gc_maxlifetime', 8 * 60 * 60); session_set_cookie_params(8 * 60 * 60); session_save_path(realpath(dirname(FILE) . '/../protected/runtime/'));

#11291 report it
thaddeusmt at 2013/01/03 05:26pm
Updated to include Facebook PHP SDK 3.2.2

I hope this fixes any issues folks have encountered. Updated in GitHub and in the download ZIP, version 0.7.

#11025 report it
hemc at 2012/12/11 12:49am
Valid access token problem

all those are facing this problem, please update php sdk to 3.2.2 . currently no wrapper for Yii is available for this version.Facebook have solved the active token issue on 6th December 2012 including migrations of DEC 5, 2012 changes. I am enhancing the old extension soon it will be available to download.

-----> Wrapper is available to use https://github.com/hemendra619/yii-facebook-opengrpah

#11024 report it
nafa at 2012/12/11 12:39am
help me

can you please help me.. i try to follow all of the step, but i end up facing some problem. when i paste the afterRender function in the controller, the page view gone blank. can you please notified where i go wrong..

#10988 report it
melengo at 2012/12/08 10:51am
An active access token must be used to query information about the current user.

An active access token must be used to query information about the current user. Help My

#10850 report it
thaddeusmt at 2012/11/27 11:38am
Use setExtendedAccessToken() to extend access token in place of offline_access perm

@rigel I have not used the offline_access tokens, but if that is in fact your issue, this extensions wraps the official PHP SDK which has the setExtendedAccessToken() method you can use to request an extended access token, as detailed in the migration info.

#10837 report it
rigel at 2012/11/27 04:23am
offline_access deprecated

Hi My code was working fine till yesderday. Today I started getting error too many redirects. I googled for the solution and I think it is due to deprecation of offline_access. How can I handle the situation here. to get 60 days accesss. Thanks

#10829 report it
thaddeusmt at 2012/11/26 01:04pm
getUser() returning uid even with invalid session?

@hemc The getUser() method in the PHP SDK calls getUserFromAvailableData() to get the user ID. This method checks the signed request first, then the session (getUserFromAvailableData()), then looks for an access token. So it's possible that if the user has logged out Facebook in another window, getUser() might still return the user_id from the Session? I'm not sure though. This StackOverflow answer says he has to put a try/catch around the API call to destroy the session, give this a try: http://stackoverflow.com/a/8829619/164439

#10767 report it
hemc at 2012/11/22 07:13am
when user logout facebbok in other broswer tab.

when user logout from facebook in other tab in that case code

$facebook_id = Yii::app()->facebook->getUser();
if ($facebook_id) { // check that you get a Facebook ID before calling api()
  // now we know we have a Facebook Session,
  $user_info = Yii::app()->facebook->api('/me'); // so it's safe to call api()
  if ($user_info) {
    // ... your code here ...
  }
}

in this case $facebook_id is set but error occurs as valid session required. why this vaariable set?

#10401 report it
thaddeusmt at 2012/10/25 12:00pm
Fixed import path bug in SFacebook

@uvegpohar thanks for finding that bug, my mistake. Yii::import("ext.facebook.SBaseFacebook"); should have been Yii::import("ext.yii-facebook-opengraph.SBaseFacebook");. Although doing what you did fixes it just as well. I updated the download file with the fix.

#10395 report it
uvegpohar at 2012/10/25 10:02am
SBaseFacebook path

I put in the extensions/yii-facebook-opengraph folder but in the SFacebook.php there is a Yii::import("ext.facebook.SBaseFacebook"); it does not works for me (can't find the extensions/facebook/SBaseFacebook.php) I replaced it to require_once('SBaseFacebook.php'); and it works now

#10148 report it
thaddeusmt at 2012/10/07 06:56pm
Errors

@Molinski Not sure what is going on there - file system permissions issue maybe? I have not seen that issue before.

@Polux and Shawn - I'm not sure what the root of your error is, but yes please open bug reports on GitHub. It looks like an issue with the Access Token being cached incorrectly in a cookie? The new PHP SDK 3.2 I included in the new 0.6 version of the extension has some improved cookie/session code, maybe that will fix it? Also, I call destroySession() in the Yii logout action which helps clean things out, worth a try.

#10147 report it
thaddeusmt at 2012/10/07 06:50pm
Custom OG meta tags

@fernandrez I just uploaded a new version which supports custom OG meta tags. It does break backward compatibility: anyone upgrading and using the OG meta tags part will need to now declare the full tag name ("og:title") instead of just the short name ("title").

#10146 report it
thaddeusmt at 2012/10/07 06:12pm
Permissions / scope

@vihuarar This extension does not actually handle login/authentication and permission scope, it just provides access to those functions for you to integrate in to your application. If you want a global set of permissions (scope) just declare that as global Yii param, and use that when calling the PHP getLoginUrl() method or the JS FB.login() method, which both take in 'scope' as a parameter.

Leave a comment

Please to leave your comment.

Create extension