Recent Thoughts

Downloads

Contact Us

Email:
Topic:
Message:

Google Ad

Facebook Plugin v2.0 -- Graph System!

Date: Mon, Jul 19th 2010, 02:20 Author: nick Views: 1776 Comments: 48 share

CakePHP Facebook Plugin

Info:
Get it:
  • Download Now
  • svn co http://svn.github.com/webtechnick/CakePHP-Facebook-Plugin facebook
CakePHP Facebook Plugin v2.0 is here! With the help from Theaxiom (https://github.com/theaxiom) the popular CakePHP Facebook plugin is now updated to the newest PHP SDK which features among other things full access to the much anticipated Facebook Graph System.

New Features


Along with access to the new SDK, I've implemented some great new fbxml features
  • Like (let your users like what they find on your site with their friends)
  • Activity Feed (Display your application's and friends activity)
  • Friend Pile (Display your application's friends)
  • Recommendations (Display your recommendations based on your current url)


Some Examples of the newest features are:
  1. //Like Button
  2. $facebook->like(); // => standard like button
  3. $facebook->like(array(
  4.   'font' => 'veranda',
  5.   'layout' => 'button_count',
  6.   'action' => 'recommend',
  7.   'colorscheme' => 'dark'
  8. )); // => customized like button
  9.  
  10. //Activity Feed
  11. $facebook->activity(); // => app activity widget
  12. $facebook->activity(array(
  13.   'colorscheme' => 'dark',
  14.   'bordercolor' => 'black',
  15.   'font' => 'arial',
  16.   'width' => '250',
  17.   'height' => '200',
  18.   'header' => 'false',
  19.   'recommendations' => 'true'
  20. )); // => customzied activity widget including recommendations
  21.  
  22. //Recommendations Widget
  23. $facebook->recommendations(); // => recommendations of current page
  24. $facebook->recommendations(array(
  25.   'colorscheme' => 'dark',
  26.   'bordercolor' => 'black',
  27.   'width' => '250',
  28.   'height' => '200',
  29.   'header' => 'false'
  30. )); // => customized recommendations widget
  31.  
  32. //Friend Pile Widget
  33. $facebook->friendpile(); // => standard friend pile
  34. $facebook->friendpiile(array(
  35.   'width' => 200,
  36.   'numrows' => 3
  37. )); // => customized friend pile


Feature Improvements


Along with the newest Helper features there is an feature enhancement as well.
  • FacebookHelper::logout() Now accepts CakePHP array urls as valid redirect options


Example:
  1. //Normal logout
  2. $facebook->logout(array(
  3.   'redirect' => 'users/logout'
  4. ));
  5.  
  6. //Same as above
  7. $facebook->logout(array(
  8.   'redirect' => array('controller' => 'users', 'action' => 'logout')
  9. ));


1.x to 2.x Migration Guide


There are a few changes you should be aware of before upgrading your application to the newest version 2.0.
  • FacebookHelper::loader() is now deprecated. Remove it from your layout.
  • ConnectComponent::getUserInfo() is no longer available, use ConnectComponent::user() instead.
  • config/facebook.php needs to be updated.
  • FacebookHelper::init() no longer takes in extended permission options, remove any of these extended options from your $facebook->init() call in your layout.
  • FacebookApi class is now FB for short use App::import('Lib','Facebook.FB'); for easy access to the full Facebook API.


New Configuration File Example:
  1. app/config/facebook.php
  2. $config = array(
  3.   'Facebook' => array(
  4.     'appId' => 'YOUR_APP_ID',
  5.     'apiKey' => 'YOUR_API_KEY',
  6.     'secret' => 'YOUR_SECRET',
  7.     'cookie' => true,
  8.   )
  9. );


New ConnectComponent::user() Examples:
  1. var $components = array('Auth','Facebook.Connect');
  2.  
  3. function beforeFilter(){
  4.   //Get all the details on the facebook user
  5.   $this->set('facebookUser', $this->Connect->user());
  6.  
  7.   //retrieve only the id from the facebook user
  8.   $this->set('facebook_id', $this->Connect->user('id'));
  9.  
  10.   //retrieve only the email from the facebook user
  11.   $this->set('facebook_email', $this->Connect->user('email'));
  12. }



New Layout Example:
  1. <?= $facebook->html(); ?>
  2.   <head>
  3.     <title>Facebook Plugin Example</title>
  4.   </head>
  5.   <body>
  6.     <?php echo $content_for_layout ?>
  7.     <?= $facebook->init(); ?>
  8.   </body>
  9. </html>


New API Examples:
  1. App::import('Lib', 'Facebook.FB');
  2.  
  3. //PHP 5.3
  4. FB::api('/me'); //graph system call to /me
  5.  
  6. //PHP < 5.3
  7. $FacebookApi = new FB();
  8. $FacebookApi->api('/me');


Enjoy v2.0


I hope you all enjoy version 2.0. As always, if you like the plugin, have a question, concern, or feature request please post a comment.

If you use the plugin and want to help maintain it please consider a donation.

Enjoy!
Nick

Comments

07/20/2010 8:31 am

V2.0.1

Hi !
what's new in version 2.0.1 VS 2.0 ?

Thx ^^
07/20/2010 1:17 pm

2.0.1 Change Log in README.txt

2.0.1: New Setting ConnectComponent::createUser boolean.

If set to true (default) upon a successful facebook login, and the facebook_id is not found in the User table, the component will attempt to create a new user from introspection on the Auth component. Turn this feature off by passing in 'createUser' => false when setting up the Connect component.

Example usage:
  1. var $components = array(
  2.   'Auth',
  3.   'Facebook.Connect' => array(
  4.     'createUser' => false
  5.   )
  6. );
  7.  
  8. /**
  9.    * Based on Facebook.Connect status, create a user
  10.    */
  11. function beforeFilter(){
  12.   if($this->Connect->me && !$this->Connect->hasAccount){
  13.     //TODO create the user based on the logged in facebook user
  14.   }
  15. }
07/21/2010 7:07 am

Great Plugin

Thanks for the awesome plugin, I will try migrating from the 1.x plugin.
07/26/2010 9:39 am

Retrieve & Insert Email & info

Hello,
Great plugin. I've gotten pretty far developing my app. I am having one issue. I've read the documentation and your comments on the forum multiple times and I am still stuck.

Would it be possible to provide detailed instructions on how to retrieve the user info using the graph system? I seem to be having a problem figuring out how to access the facebook user info array.

I'd be willing to throw you some $$ for support as well.

Thanks in advance.

JM
07/26/2010 11:45 am

Hi JM

I'm happy to help.

So you can get your users information a number of ways. Each way requires your user to give your application rights to retrieve that information. You get those rights by getting the user to click the "Login" button. You can display this at anytime in your views with the facebook helper.

  1. $facebook->login();


By clicking that button, your user is granting your application access to their facebook profile. Upon a successful Facebook.Connect login the $me property of the Facebook.Connect component will be populated with all the relative information for that logged in user.

It is then you can store whatever information you want/need from that user's profile and save it to your database.

The logged in facebook user is also set to the session variable FB which you can access anywhere within your application (model/view/controller).

Or you can use the built in FB class and access the graph system directly.

  1. App::import('Lib','Facebook.FB');
  2. $fb_user = $FB::api('/me'); //php 5.3 only
  3. //or
  4. $fb_user = $FB::api($facebook_id); //php 5.3 only.


A simple example using the component would be something like this:

  1. //app_controller.php
  2. var $components = array('Facebook.Connect');
  3. function beforeFilter(){
  4.   if($this->Connect->me){
  5.     debug($this->Connect->me);
  6.     $profile_data = array(
  7.        'Profile' => array(
  8.          'email' => $this->Connect->user('email'),
  9.          'facebook_id' => $this->Connect->user('id'),
  10.          //.....
  11.        )
  12.     );
  13.     //TODO save the profile
  14.   }
  15. }


Hope that helps,
Nick
07/28/2010 11:46 am

Get access token

Thanks for you work on this Nick. I had started to use your Gigya plugin, but soon ran into issues with inviting friends and creating events...not currently possible. Gigya also wanted to get $1700/month for their service which isn't possible for this side project I'm working on.

Anyways, so I'm back to just using Facebook now.

I'm using your plugin to allow the user to login. What I'm trying to do now is create an event for one of the users groups.

The user selects a group that their are an admin of, and then my app attempts to create the group. The problem is the event is not getting created for the group, just the user.

I'm posting to path //events.

I'm wondering if the issue is because the auth token I have is for the logged in user and I need to get an auth token for my app?

If that is the case, how do I handle logging in the user via the plugin and then also creating events?
08/01/2010 10:44 am

fbxml not working anymore after update from 1.x to 2.0.2

Hi,

First I would like to thank you for the work you did coding this really usefull cake component, it just rocks.

I tried today to update it to the latest version that uses the Graph API and everything seems to work well except that no fbxml is being interpreted anymore.

I followed the upgrade guide.

According to the error log on firefox, it seems to be javascript related.

I have this error:

  1. Error: FB.provide is not a function
  2. Source File: [url=http://connect.facebook.net/en_US/all.js<br]http://connect.facebook.net/en_US/all.js<br />
  3. Line: 10


The code generated by $facebook->init(); is :

  1. <div id="fb-root"></div><script type="text/javascript">
  2. //<![CDATA[
  3.  
  4.           window.fbAsyncInit = function() {
  5.             FB.init({
  6.               appId   : 'my_app_id',
  7.               session : {"removed for post"}, // don't refetch the session when PHP already has it
  8.               status  : true, // check login status
  9.               cookie  : true, // enable cookies to allow the server to access the session
  10.               xfbml   : true // parse XFBML
  11.             });
  12.             // whenever the user logs in, we refresh the page
  13.             FB.Event.subscribe('auth.login', function() {
  14.               window.location.reload();
  15.             });
  16.           };
  17.           (function() {
  18.             var e = document.createElement('script');
  19.             e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
  20.             e.async = true;
  21.             document.getElementById('fb-root').appendChild(e);
  22.           }());
  23.        
  24. //]]>
  25. </script>
  26.   </body>


I try to figure it out but i'm stuck. Any idea ?

Thanks
Madjik
08/01/2010 10:49 am

urgl

Damn sorry I don't know which tag to use to quote code :)

Madjik
08/01/2010 11:23 am

fbxml not working anymore after update from 1.x to 2.0.2

Ok sorry, it's me again :)

I found the problem. It seems that the $facebook->share() fuction is broken in version 2.0.2.

When I use it on a page it brokes all other fbxml tags. Seems to be related to the javascript the share function generates.

If I replace de $facebook->share() with the fb:share-button, it works and the rest also works.

Strange :)
08/01/2010 1:11 pm

Interesting

Thanks for the heads up on the share issue. I'll be sure to look into that and verify. The problem with using fb:share-button as the default is the $facebook->init() is not required for the share feature to work. However, that said, if we're already using the other facebook elements it makes sense to use the fbxml instead of inline javascript. I'll work on a patch for this.

By the way, the bbcode to use for code styling is:

geshi=php
code goes here.
/geshi

With brackets results in:

  1. code goes here.


Thanks again,
Nick
08/01/2010 1:39 pm

Question :)

Hi thanks for your answer. Yes If the only function usable without calling init() is the share, that might be a good idea to set it as mandatory for everything.

I''m getting into another "issue", talking about the init().
We could set the extended attributes we want to access on facebook when calling the init() function. But now it is not allowed anymore on v2.0.2.
How can we set those extended attributes with the new version ?
If i'm not wrong, I saw on the facebook developper that those parameters can be passed to the login button now ?
08/01/2010 2:34 pm

Updated 2.0.3 share

2.0.3 Changes:

Facebook::share now takes in fbxml boolean option (default false). if true, Facebook::share will use the fbxml version of the share button instead of the default javascript version. The fbxml version will only work if Facebook::init() is called on the same page.

Extended Permissions:
You can ask for extended permissions through the Facebook API (Auth Token required) or you can ask through the Facebook::login() function (recommended).

Example:
  1. //Upon login, ask for email and ability to write to wall
  2. $facebook->login(array(
  3.   'perms' => 'email,publish_stream'
  4. ));


For a full list of extended permissions, look here:
http://developers.facebook.com/docs/authentication/permissions

Hope that helps,
Nick
08/01/2010 3:05 pm

2.0.3 test

Hi Nick,

thank you for the changes in the 2.0.3.

It now works well with the fbxml share option.

There's just something that might be enhanced. The fbxml share tag supports many different forms of buttons. The helper is only accepting button or link.

But there are several others:
http://wiki.developers.facebook.com/index.php/Fb:share-button />
As for exemple i use button_count.

:)
08/01/2010 3:15 pm

quickfix

Fixed it, remplacing

  1. switch($options['style']){
  2.       case 'link': $options['type'] = 'icon_link'; break;
  3.       default: $options['type'] = 'button'; break;
  4.     }


with

  1. if (!$options['fbxml']) {
  2.     switch($options['style']){
  3.       case 'link': $options['type'] = 'icon_link'; break;
  4.       default: $options['type'] = 'button'; break;
  5.     }
  6.   }


in the helper share function, so that it doesn't alter the option 'type' when using fbxml.

08/01/2010 4:59 pm

Error...

Okay, so I'm new to both CakePHP and Facebook development. I basically have a vanilla install of CakePHP 1.3.0 and I installed the facebook plugin, but I am getting this error:


Fatal error: Call to a member function delete() on a non-object in /home/.../app/plugins/facebook/controllers/components/connect.php on line 68


It only happens if I have 'Facebook.Connect' as a component in app_controller.
08/01/2010 8:41 pm

Requires Session Component

The Facebook plugin takes advantage of the session component. The session component is no longer auto loaded by default in cakephp 1.3. Be sure to load the session component before the connect component.

Hope that helps,
Nick
08/02/2010 9:33 am

Session login-logout loop

Hi
I meet a problem with fb login, when I using application outside facebook, login work but each action lost cookies and make logout. Inside facebook application make infinite loop login-logout. Someone meeet same problem?


Thanks
Stefano
08/06/2010 2:20 am

about FBML tags

Can u plz tell me how to use fbml tages in your plugin.Xfbml tags are working good but i want my friends's list so i have to use FBML tag so plz tell me how to use FBML tags..
08/06/2010 7:31 am

about FBML tags

Please help me out.i have a upload tomorrow and i got a stuck here plz i need ur help...give me reply..
Thanks for consideration....
08/08/2010 4:15 am

connect/authorization url

login does not work.. what should be the connect/authorization url of the application on facebook??
08/08/2010 9:35 pm

Some answers.

@Stefano the login-logout issue is most likely a misconfiguration of your facebook application on facebook itself. Make sure you have the right domain and connect URL setup.

@about FBML tags: For more on FBML tags, please refer to the facebook documentation:
http://developers.facebook.com/docs/reference/fbml/

@connect/authorize url: The connect/authorization url should be the base of your CakePHP Application.
08/08/2010 11:13 pm

not getting about fbml tags

Hi,
i m still confused how to use fbml tags in our connect.ctp file.you have used all tags related to xfbml but in my application i have to use FQL query:

In my facebook app i used to fire this type of query:

$user = $facebook->require_login();
$fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$user.') AND is_app_user = 1';
$_friends = $facebook->api_client->fql_query($fql);

so how can we use this type of queries in this plugin..Because i have tried this query but it didnt work..plz help me. thank you.
08/09/2010 1:01 am

Use graph system.

That type of query is deprecated. You'll need to use the graph system instead. Take a look at this:

http://developers.facebook.com/docs/api

At first glance it looks like you're trying to get the friends of a logged in user. First, on your login you'll need to ask for the friends permission and then you can preform the graph call to me/friends.

  1. App::import('lib', 'Facebook.FB');
  2. FB::api('/me/friends'); //PHP 5.3 only


Alternatively you can always install the old deprecated version of the facebook plugin, although Facebook has announced those type of queries will not work eventually. Just FYI.

Download latest release of deprecated API: http://github.com/webtechnick/CakePHP-Facebook-Plugin/tarball/v1.6.1

Hope that helps,
Nick
08/09/2010 1:17 am

FQL

Here is some documentation on the FQL. Hope that helps.

http://developers.facebook.com/docs/reference/fql/

You can make a restful apicall with the plugin like so.
  1. App::import('Lib','Facebook.FB');
  2. FB::api(array(
  3.   'method' => 'friends.get',
  4.   array(/* options go here */)
  5. ));


This is straight out of the facebook PHP SDK (vendors/facebook/php/facebook.php) included in the plugin.

This is still deprecated, use with caution.

Hope that helps,
Nick
08/09/2010 1:23 am

Thanx a lot.

Thank you..
08/10/2010 10:28 am

Logout?

I'm a little lost on how to do a logout, without displaying the FB logout button. It's a little unsightly in the design to have two separate logouts (since I merge users or create new users if they have Facebook).
08/10/2010 10:34 am

Custom Button

Just FYI. Not sure if it is good practice but I have a very picky client that can't live with the way the Facebook Buttons look. I used Firebug to identify where the image was being pulled from and then I was able to hack the way the button looks by adding CSS and using !important to override the button being called from the facebook server.

CSS is as follows:

.fb_button.fb_button_medium {
background-color:transparent !important;
background-image:url("PATH_TO_IMAGE") !important;
background-position:left top !important;
background-repeat:no-repeat !important;
height:40px !important;
text-indent:-5000px;
width:300px !important;
08/10/2010 10:40 am

Re: Custom Button

Yep, I know I can style it, but the problem is having two separate "logout" links. I can see the "login with username/password OR facebook", but then it becomes "logout" then "Facebook logout" - and when a user has tied their account to Facebook - it's a bit annoying.

I'd rather have one logout link (text, my own). Or maybe there is something the Graph API for that which I can work around.

Thanks
08/10/2010 10:44 am

Logout Response

In regards to Logout styling. Have you thought of using an if statement to control which button shows? Also, in the documentation at the top of this blog there are some instructions on how to re-direct users upon logout.

The "Custom Button" entry was in response to a question I posted a few days ago. I know some people are probably stuck like me on obvious questions so I thought I would share. Hopefully it helps someone in the future.
08/10/2010 12:13 pm

Re:

Yeah, I'm looking at the helper code right now, I might just manually put in that javascript in an onClick() and swap it if they're not logged in through FB.
08/11/2010 8:35 am

Local development

Any ideas how to get this to work for development? On a local machine? Thanks...
08/11/2010 9:55 am

localhost

The javascript stuff works fine locally, but the PHP calls are returning nothing. Does it still have to use the xd_receiver file maybe? Thanks
08/12/2010 11:33 pm

regarding Friends's list

Hi,
Plz help me.
I have tried out but i m not getting any of my facebook friends

In my users_controller:

var $name = 'Users';
var $helpers = array('Html','Form','Javascript','Ajax','RfRating','Session');
var $components = array('Auth','RfRating', 'RequestHandler','Session');
var $uses = array('User','Databasebkup','Article', 'Vote');

function inde)
{

App::import('Lib','Facebook.FB');

$Facebook = new FB();

$results = $Facebook->api('/me/friends');

print_r($results);

}


function login() {

if ($this->Auth->user())
{


$this->redirect($this->Auth->redirect('users/index'));
}
}

if you feel then plz give me your example and then i will try with that.
plz guide me.
I want to use now facebook graph system only and i have put the code as you have said but still not working..plz give me with working example might be that helps me..
08/18/2010 10:06 am

function logout

i use this code to have a logout botton
logout(array( 'redirect' => '/users/logout' ));
this generate FB.Connect.logoutAndRedirect(/users/logout)
When i click on this link, it doesn't work. This is the error message from firebug
"invalid regular expression flag l"
08/18/2010 7:27 pm

re:function logout

Make sure you're running the latest version. Fb.Connect.logoutAndRedirect() is deprecated.

It should be:
  1. FB.logout(function(response){ window.location = 'users/logout'});


Make sure you're using the most recent facebook plugin 2.0.3.
08/19/2010 4:31 am

helper modified

ok, i've changed the logout function in the helper. It work's, but not everytime.
  1. if(isset($options['redirect']) && $options['redirect']){
  2.       return $this->Html->link($options['label'], '#', array('onclick' => "FB.logout(function(response){ window.location = {$options['redirect']}})"));
  3.     }

It works only if you make a page refresh after the login. If you don't make it, when i click in the logout button i've the following error in firebug console "users it's not defined", and in google chrome inspect the error is
"Uncaught ReferenceError: users is not defined"
"FB.logout() called without a session."
But there is a session. Any idea?
08/19/2010 12:17 pm

re:helper modified

You shouldn't have to modify the helper. You must be running an older version of the plugin. Please update your plugin to the latest version 2.0.3.

By the way, your modifications have a mistake, you have to wrap the redirect in ticks, as right now you're assigning

window.location = /users/logout

which doesn't make sense. It should be:

window.location = '/users/logout'

But this is all done for you with the latest Facebook helper. So upgrading is the best solution to this problem.

Thanks,
Nick
08/20/2010 4:24 am

ok.

Hey Nick,it works. Thanks for your help.
Now I'm trying to find a way to set up the cancel_url parameter if a user don't allow my application.
Also, it would be good to add some function in the connect component, for example simples functions to post on the wall, or to update the status of the user.
But... great work, your plugin rocks!
08/23/2010 1:59 pm

Development Environment

Hi Nick... thanks so much for this great plug-in. I'm new to Cake but worked with the FB api before. When I use your demo app on my production server it works fine, but using MAMP at home with a locally mapped domain name I can't log-in. The XFBML stuff works fine, but cake doesn't log me in. The login button just continues to appear, even after login, and my Firebug console gives a Javascript error of : FB.login() called when user is already connected. Any ideas?
08/23/2010 2:26 pm

Development Environment - More Info

It looks like this may be a known issue when working with MAMP. Here's more information. Do you know where I would modify the line shown here in this post?

http://forum.developers.facebook.net/viewtopic.php?id=57205

I found a fix for this. It is to do with the SSL certificate on a mamp/wamp setup. See this update for the fix:

http://github.com/facebook/php-sdk/issues#issue/7

basically you want to add CURLOPT_SSL_VERIFYPEER => false to line 94 of the facebook.php in the sdk.

Hope that helps someone else!
Rob.
08/23/2010 2:37 pm

Development Environment - Solved

I added that CURL option line to the facebook.php file and it worked to solve this issue. Thank you. You can delete these posts or leave them for others with the same issue.
08/24/2010 12:30 am

Problem with logout

Hello Nick,

I'm trying to do the simple app and using your component. Everything works well. But I got one problem: if you got user logged in Cake using FB and then this user is logged out of FB (for example, session timeout), logout link doesn't work anymore, because it uses some JS related to current FB session I guess. How to do logout in that case? Oh how to determine that FB session is unavailable and change logout link to simple users/logout without any JS.

Thanks.
08/29/2010 7:55 am

Facebook authentication

Where can I get exaustive documentation about setting up Facebook authentication system?

On facebook developer homepage there is no more Connect section, so where I have to put URL. And... what URL i've to use?

Help!
08/30/2010 9:54 am

settings

Hi Nick!
What is your facebook settings (http://www.facebook.com/developers/apps.php)
for your demo application (http://facebook.webtechnick.com/) ?
09/03/2010 12:27 am

Cant have $facebook->share() on same page as other facebook elements

There is an issue with facebook share and having other facebook elements on the same page. It throws a javascript error. Any workarounds for this?
09/03/2010 2:21 pm

re: facebook share conflicts

Yes, pass in 'fbxml' => true as an option to the Facebook::share() and instead of loading javascript, it will use what is available through the other elements in the page.

Example:
  1. $facebook->share('some_url', array('fbxml' => true));


Hope that helps,
Nick
09/03/2010 6:35 pm

XHTML Valid

As soon $facebook->init(); is added XHTML will be invalid (even as transational even is strict).
Any ideas?
09/07/2010 3:37 am

settings

HI! I'm meet some trouble with facebook cookie reject. If you can, can tell me you settings in:
web site -> Site URL
facebook integration -> canvas page
facebook integration -> canvas url
advanced -> JSON Encoding
advanced -> Stream post URL security
advanced -> Canvas Session Parameter
advanced -> OAuth 2.0 for Canvas (beta)

Add Comment

Please login or register to submit a comment.