CakePHP Facebook Plugin -- Auth+Facebook and more
Date: Tue, Feb 9th 2010, 06:44 Author: nick Views: 7098 Comments: 62 share
Please Support:
CakePHP Facebook Plugin
Info:
- Version: 2.0.2
- Requirements: CakePHP 1.3, PHP5.1+
- Docs: CakePHP Facebook Plugin API
- Article: CakePHP Facebook Plugin Discussion and Examples
Get it:
Download Now
- svn co http://svn.github.com/webtechnick/CakePHP-Facebook-Plugin facebook
The purpose of the Facebook plugin is to provide a seamless way to connect your cakePHP app to everyone's favorite social networking site -- Facebook. The goal for this plugin is to not only provide extremely useful dynamic features but to also provide a complete interface to the Facebook API.
This plugin is specifically for CakePHP 1.3
Example App: http://facebook.webtechnick.com
Example App Source: http://svn.xp-dev.com/svn/facebook_example_app/
Version 2.0 Update (Graph System):
http://www.webtechnick.com/wtn/blogs/view/238/Facebook_Plugin_v2_0_Graph_System
To get started you'll first need to download and unpack the Facebook Plugin into your app/plugins/facebook directory. If you plan on using any features mentioned above (except the share feature, which will work with no further configuration), you will need to get an api_key and secret from Facebook.
Once you have your api_key, secret, and app_id from Facebook, you'll need to create a configuration file named 'facebook.php' within your app/config directory with this information.
You'll more than likely at least want to use the bundled FacebookHelper.
If all you want to use is the 'share' feature skip ahead to Usage Examples as there is no further setup required for 'share' to work. However, if you wish to use some of the more advanced features you will need to alter your layout a little to accommodate the fbxml (facebook-xml).
Replace:
with
Add at bottom of your page:
Your layout should look something like this:
Now you're ready to start using the more advanced features included in the Facebook plugin.
UPDATE: Facebook.Connect now uses the new graph system. Extended permissions are now asked on the fly.
The Plugin comes with a whole slew of neat dynamic content from Facebook.
Share feature:
Fanbox feature (app_id required):
Live Stream feature:
Comments feature:
Profile Pictures feature:
Recommendations:
You can use the Facebook Plugin as your primary user authentication system or along side your current authentication system (currently only supports CakePHP's AuthComponent).
Setup is extremely simple. Just drop in Facebook.Connect into your app_controller's components array.
And add facebook_id to your user table (or the table you use for your Auth Component).
That's it! You're now ready to accept Facebook Login/Logout with your Authentication system.
Login Buttons
To add a Facebook Connect login button use:
Logout Buttons
To add a Facebook Connect logout button use:
If you already have a built in Authentication system you will need to redirect to your apps logout action. Do this by adding a redirect to the logout button.
While using the Facebook.Connect you can obtain more detailed information about your logged in user via the user() function. The result will return an array of useful information for your user. By default, only last_name, first_name, and email are returned. However, you can request anything you want that is an available option via facebook API: http://wiki.developers.facebook.com/index.php/Users.getInfo#Response
Example:
Access the Facebook API by importing Facebook.FB anywhere in your app then calling it to do various custom things. Depending on what version of PHP you're running you can make requests in a number of ways.
The reason for the difference is the introduction of __callstatic() in PHP 5.3 that prior to 5.3 there's no way to overwrite the _call of a static method.
Take a look at all the available options and features you can use via the Facebook API here http://wiki.developers.facebook.com/index.php/Main_Page
If you have a feature request post a comment!
I hope you enjoy the work I put into this plugin. I encourage you to look at the API documentation for an in-depth look at all the available options for each feature.
As always, if you like the plugin, find a bug, or have a feature request post a comment. =) If you really like the plugin and want to help keep it maintained please consider a donation. It really does help!
Thanks,
Nick
This plugin is specifically for CakePHP 1.3
Example App: http://facebook.webtechnick.com
Example App Source: http://svn.xp-dev.com/svn/facebook_example_app/
Version 2.0 Update (Graph System):
http://www.webtechnick.com/wtn/blogs/view/238/Facebook_Plugin_v2_0_Graph_System
Feature List
- Full featured authentication via Facebook Connect. Facebook Authentication will work with or without a user login system already in place on your site. Works seamlessly with your already built in user authentication system via AuthComponent -OR- Facebook Connect can work as your primary authentication system.
- Setup is as easy as dropping Facebook.Connect into your components array.
- Retrieve Detailed User Information and gain access to protected data via extended permissions (user prompted to allowed)
- Easily create dynamic and customizable Facebook content
- Share (let your users share what they find on your site with their friends)
- Like (let your users like what they find on your site with their friends)
- Login/Logout (Facebook users can login and logout of your site with a single click.. no registration required)
- 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)
- Fan Boxes (Allow users to become facebook fans of your site)
- Profile Pictures (Display a facebook profile picture)
- Live Streams (Create dynamic live stream events)
- Comments (Connect with your users by allowing them to comment on any part of your site through Facebook
- Status (Display the status of the logged in user)
- Access to Facebook API anywhere in your app. Build custom content with direct access to the full Facebook API.
- Everything is included. No need to download the Facebook API files or create Facebook specific files (xd_receiver.htm and the like). Everything is included in the plugin and will be maintained.
Configuration
To get started you'll first need to download and unpack the Facebook Plugin into your app/plugins/facebook directory. If you plan on using any features mentioned above (except the share feature, which will work with no further configuration), you will need to get an api_key and secret from Facebook.
Once you have your api_key, secret, and app_id from Facebook, you'll need to create a configuration file named 'facebook.php' within your app/config directory with this information.
- app/config/facebook.php
- 'appId' => 'YOUR_APP_ID',
- 'apiKey' => 'YOUR_API_KEY',
- 'secret' => 'YOUR_SECRET',
- 'cookie' =>true,
- )
- );
Setup
You'll more than likely at least want to use the bundled FacebookHelper.
- //app_controller.php
If all you want to use is the 'share' feature skip ahead to Usage Examples as there is no further setup required for 'share' to work. However, if you wish to use some of the more advanced features you will need to alter your layout a little to accommodate the fbxml (facebook-xml).
Alter your views/layouts/default.ctp
Replace:
- <html>
with
- <?= $facebook->html(); ?>
Add at bottom of your page:
- <?= $facebook->init(); ?>
Your layout should look something like this:
- <?= $facebook->html(); ?>
- <head>
- <title>Facebook Plugin Example</title>
- </head>
- <body>
- <?php echo $content_for_layout ?>
- <?= $facebook->init(); ?>
- </body>
- </html>
Now you're ready to start using the more advanced features included in the Facebook plugin.
Extended Permissions
UPDATE: Facebook.Connect now uses the new graph system. Extended permissions are now asked on the fly.
Usage Examples
The Plugin comes with a whole slew of neat dynamic content from Facebook.
Share feature:
- //Create a share button
- $facebook->share(); //defaults to current page
- //Share button with a different url
- $facebook->share('http://www.webtechnick.com');
- //Share button with url and options
- $facebook->share('http://www.webtechnick.com', array('style' => 'link', 'label' => 'Check it out!'));
- //Like button with url and options
- $facebook->like();
- //Like button with options
- 'font' => 'veranda',
- 'layout' => 'button_count',
- 'action' => 'recommend',
- 'colorscheme' => 'dark'));
Fanbox feature (app_id required):
- //Display Fan Box with minimal options
- $facebook->fanbox();
- //Display fanbox with all the whistles and bells
Live Stream feature:
- //Display livestream event
- $facebook->livestream();
- //Display livestream event with all whistles and bells
- $facebook->livestream(array('width' => '300', 'height' => '500', 'xid' => 'YOUR_EVENT_XID', 'event_app_id' => 'CUSTOM_APP_ID'));
Comments feature:
- //Display comments section
- $facebook->comments();
- //Display comments with all whistles and bells
Profile Pictures feature:
- //Display picture of facebook user
- $facebook->picture($facebook_id);
- /** Hint: if you're using the Facebook.Connect feature, set the Auth->user() to a variable and use that to show the logged in user's profile
- */
- $facebook->picture($user['User']['facebook_id']);
- //Display picture of facebook user with all a size
- //options: thumb, small, normal, square (default thumb)
- //Or set your own size
- //Show a generic facebook logo until the picture is loaded
Recommendations:
- //Display Facebook Recommendations based on the current page
- $facebook->recommendations();
- //Recommendations with some whistles and bells
- 'colorscheme' => 'dark',
- 'bordercolor' => 'black',
- 'width' => '100',
- 'height' => '100',
- 'header' => 'false'));
Facebook Connect (Authentication)
You can use the Facebook Plugin as your primary user authentication system or along side your current authentication system (currently only supports CakePHP's AuthComponent).
Setup is extremely simple. Just drop in Facebook.Connect into your app_controller's components array.
- //app_controller.php
And add facebook_id to your user table (or the table you use for your Auth Component).
- ALTER TABLE `users` ADD `facebook_id` BIGINT UNSIGNED NOT NULL
That's it! You're now ready to accept Facebook Login/Logout with your Authentication system.
Login Buttons
To add a Facebook Connect login button use:
- //Display login button medium size button
- $facebook->login();
- //Display a small button
- //options: small, medium, large, or xlarge
- //Display a login button with a different background
- //options: white, dark, light (default light)
Logout Buttons
To add a Facebook Connect logout button use:
- //Display a logout button medium size
- $facebook->logout();
- //Display a logout button small size
- //Display a logout link with a redirect
- //label is 'logout' by default.
- 'label' => 'Sign Out'));
If you already have a built in Authentication system you will need to redirect to your apps logout action. Do this by adding a redirect to the logout button.
- //Logout from facebook and then redirect to logout from app
- //NOTE: redirect can be CakePHP array based url
- //Change logout text ('logout' by default)
Facebook Connect User Information
While using the Facebook.Connect you can obtain more detailed information about your logged in user via the user() function. The result will return an array of useful information for your user. By default, only last_name, first_name, and email are returned. However, you can request anything you want that is an available option via facebook API: http://wiki.developers.facebook.com/index.php/Users.getInfo#Response
Example:
- function beforeFilter(){
- //Get all the details on the facebook user
- $this->set('facebookUser', $this->Connect->user());
- //retrieve only the id from the facebook user
- $this->set('facebook_id', $this->Connect->user('id'));
- //retrieve only the email from the facebook user
- $this->set('facebook_email', $this->Connect->user('email'));
- }
Full Facebook API access
Access the Facebook API by importing Facebook.FB anywhere in your app then calling it to do various custom things. Depending on what version of PHP you're running you can make requests in a number of ways.
- App::import('Lib', 'Facebook.FB');
- //PHP 5.3
- FB::api('/me'); //graph system call to /me
- //PHP < 5.3
- $FacebookApi = new FB();
- $FacebookApi->api('/me');
The reason for the difference is the introduction of __callstatic() in PHP 5.3 that prior to 5.3 there's no way to overwrite the _call of a static method.
Take a look at all the available options and features you can use via the Facebook API here http://wiki.developers.facebook.com/index.php/Main_Page
If you have a feature request post a comment!
Enjoy
I hope you enjoy the work I put into this plugin. I encourage you to look at the API documentation for an in-depth look at all the available options for each feature.
As always, if you like the plugin, find a bug, or have a feature request post a comment. =) If you really like the plugin and want to help keep it maintained please consider a donation. It really does help!
Thanks,
Nick

here is cakephp plugin im waiting for
Facebook Example App
http://facebook.webtechnick.com
Version 1.4.0 Update
Version 1.5.2 Update
Version 1.5.4 Update
facebook.php not found
I've followed the instructions up until the point where you need to add the line to the footer of your page, but I'm getting an error show up saying:
Login
Enter your details
Username:
Password:
Login Register for free
No Facebook.api_key detected. Please add Configure::write('Facebook.api_key', YOUR_API_KEY_HERE) somewhere in your application.
I'm assuming this is because the plugin isn't finding the facebook.php file in the /app/config folder, but I don't know how to make it do this.
I don't know if this makes any difference or not, but I'm using Cake 1.3. Thank you.
whoops
No Facebook.api_key detected. Please add Configure::write('Facebook.api_key', YOUR_API_KEY_HERE) somewhere in your application.
Thanks
1.5.5 fixes that issue.
Thanks for catching that,
Nick
Thank you
I'm going to spend some more time developing my site locally, getting my own auth system in place, and then look into adding this to it.
Thank you so much for this however, I look forward to using it fully soon :)
Helper
I'm using the latest 1.3 from github
Can you describe what isn't working? Is nothing being outputted? What does your layout look like? Does any of the helper function work? How are you calling the helper? What have you tried to debug it?
Session error
Great plugin but I get this error when resuming a session.
Fatal error: Uncaught exception 'FacebookRestClientException' with message 'Session key invalid or no longer valid' in /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/vendors/facebook/php/facebookapi_php5_restlib.php:3065 Stack trace: #0 /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/vendors/facebook/php/facebookapi_php5_restlib.php(1717): FacebookRestClient->call_method('facebook.users....', Array) #1 /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/controllers/components/connect.php(72): FacebookRestClient->users_getInfo('610926696', Array) #2 /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/controllers/components/connect.php(119): ConnectComponent->getUserInfo(Array) #3 /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/controllers/components/connect.php(58): ConnectComponent->_handleFacebookUser() #4 /var/www/vhosts/mysite.com/httpdocs/cake/cake/libs/controller/component.php(98): ConnectComponent->initialize(Object(EventsController), Array) #5 /va in /var/www/vhosts/mysite.com/httpdocs/cake/app/plugins/facebook/vendors/facebook/php/facebookapi_php5_restlib.php on line 3065
Exception error fixed in 1.5.5
Hope that helps,
Nick
thanks so much
however A) is stored in my users.facebook_id for that auth'd user
but B) $this->Connect->getUserInfo() in the controller returns the correct authd user. I assume it's using the cookie facebook stores.
Can you help me out with this?
edit
What's the order of your components?
Otherwise Facebook.Connect assumes you're not using the Auth component and are using Facebook.Connect as your primary authentication system (ie no save/update is attempted).
Hope that helps,
Nick
facebook_id only saved if its a new user
The facebook_id is only saved to the user table if it's a new record, it won't update an already created user record.
I envisioned if a user decided to use Facebook.Connect they would have to continue to use that for future logins. I imagine it would be nice to have the option to do either your basic Auth login OR Facebook.Connect.
I'll add that as a feature in the next release.
Thanks for the suggestion,
Nick
Version 1.6 update
Let me know if you have any issues, and thanks for the feature request,
Nick
more.
Given your 1.6 update:
I actually changed it so in connect.php, additionally check for $Auth->user instead of !$Auth->user (since i am allready logged in, it wasn't falling into this if statement)
and changed $user to search the User model by the ID specified by the Auth component (since facebook_id is null at this point).
Also, to my taste: I made it so that the plugin doesn't overwrite the Auth component username field. It was preventing me from being able to logout
thanks for your help with this plugin.
download contains svn directories
for anyone who did need to remove it on *nix you can
find . -type -d -name .svn -exec rm -rf {} \;
from within the facebook plugin directory
Thanks, i cant tell you how much i love this plugin.
findByFacebookId()
In looking through your code I can see what looks to be a "fat model" style call to findByFacebookId() in _handleFacebookUser() in the ConnectComponent class which I can't actually locate anywhere even with a recursive grep.
Am I missing the point here?
N
findBy___ is a function given to you by CakePHP
You can read about it here:
http://book.cakephp.org/view/451/findBy
Hope that helps,
Nick
Auth problem
logging in but pop up window doesnt close
my pop-up window doesnt close after authentication...instead my connect url is displayed in this child window while parent window remains unchanged....am i missing something here? help would be greatly appreciated....
logging issue (contd.)
Indeed, you are correct
Are you using the helper for your login button? Make sure you don't overwrite the onlogin key as it sets 'window.location.reload()' as its return function by default.
Hope that helps,
Nick
Facebook connect discontinued
http://mashable.com/2010/04/21/facebook-kills-facebook-connect/
Indeed, just read the news
Good news is the graph API looks extremely powerful and less "spammy" to the user who needs certain permissions from the facebook user (which is a great change, it was always a pain to obtain permissions from the user to retrieve or do certain things).
In regards to this project, there is no need to worry. I will be maintaining the plugin through the transition. It is possible I will fork the project and refactor so that I could include any other OAuth enabled service (twitter, etc..), but either way, I will keep everyone who currently uses this plugin informed via this site.
what do i write in the helpers array?
i put the helpers for form
i dint get you clearly...
Need more information...
logged into pop-up window
once the facebook connect is clicked a pop-up window opens...i login with my facebook credentials....i get logged into my website, i.e. correct login occurs but in the pop-up window only....i am expecting the child window to close and my parent window to show my website after login...
HtmlHelper::script Error
Warning (512): Method HtmlHelper::script does not exist [CORE/cake/libs/view/helper.php, line 143]
Sorry I've only been using cakephp for a few months so I'm still getting used to it. Do you have any idea why this error would occur? It seemed to be coming from ..
Helper::call__() - CORE/cake/libs/view/helper.php, line 143
Overloadable::__call() - CORE/cake/libs/overloadable_php5.php, line 52
HtmlHelper::script() - [internal], line ??
FacebookHelper::loader() - APP/plugins/facebook/views/helpers/facebook.php, line 299
include - APP/views/layouts/default.ctp, line 23
Line 299 of facebook.php:
return $this->Html->script($this->_fbFeatureLoaderScript . $locale['locale'], $options);
Thanks!
Andrew
p.s. Your plugin rocks. Just cause Facebook Connect is being killed doesn't mean it's stopped just yet!!!
Facebook Plugin requires the CakePHP 1.3
Thanks for the compliments. The error you're running into is due to you trying to get this plugin to run in cakephp 1.2.x. The plugin requires cakephp 1.3. That HtmlHelper::script is new in 1.3. Make sure you're using the latest version of CakePHP.
Hope that helps,
Nick
Gigya & Anticipated Date?
Any anticipated date on completion for the Open Graph API?
Working in 1.2
Graph ETA + Gigya
@Facebook Plugin in 1.2
There is no doubt its possible to port to 1.2, and I'm glad you got it working the way you want. However I still suggest upgrading to 1.3, its stable now, and awesome. In fact, if they bottled CakePHP 1.3 and sold it in grocery stores, they would label it AwesomeSauce. :)
Comments integration
@Comment integration
The comments helper does take in many other options as specified by http://wiki.developers.facebook.com/index.php/Fb:comments_%28XFBML%29
Off the top of my head, I might do something like preform a javascript call that catches the submit button, decides and depending on a flag the user selects submit the form to the appropriate place. But again, that's just off the top of my head and might not be what you want.
I hope that at least helps point you in the right direction,
Nick
Fanbox - Number of people
first, thank you for this great plugin
second, just a little tip that wasn't initially obvious for me, maybe it can be useful for others.
About:
$facebook->fanbox(array('stream' => true, 'logobar' => true, 'connections' => true));
the 'connections' parameter accepts the number of avatars to display in the box; true is translated to 1.
Set
'connections' => 10
(or whatever you like, where whatever < 100)
to display 10 (/ whatever) fans.
Stefano
Fanbox stopped working on firefox 3.6.3?
Is maybe something that breaks it in my page? yesterday it was fine, now it shows only a blank box.
Same problem in the demo, it seems:
http://facebook.webtechnick.com/fanbox
/>
i don't get why, the javascript seems fine, it works on IE8
small update on empty fax box
The problem only happens if a logged in user info box (using the facebook connect plugin feature) is on the same page.
ok, last update - it seems a facebook problem
See
http://developers.facebook.com/blog/post/262
/>
i get the fan box only when logged out of facebook.
Awesome plugin
great job!
Fanbox works fine for me loggedin or out
@Graph, Graph is coming soon, very soon. Look forward to a new post coming in the next few days.
resolved
Sorry for the false warning :)
I'll try to track it down if it happens again.
I'm looking forward for graph too!
Friends
One question:
How can I access the friends of the logged in user?
Friends
In the next release I will be giving you all a way to access the graph system and in that system you have a whole slew of things you can do easier than using the FacebookAPI class.
I have some final tests for the new graph system and I'll make it public. I think you'll be pleased with what I've come up with.
Hope all is well,
Nick
New release
I am very excited to hear about your further effort to update your plugin to connect to Facebooks social graph! I can't wait for the new release :-)
If you need beta tester - here I am :-)
Thanks again!
Hi, Problem using Login button plz help.
I am trying to build my first cakephp app with cake1.3, I want set up simple facebook connect.. I want first name and user's id.. I dont know how to retrieve the user data after i create the login button.
Please help me.
Carol
email no longer available?
The problem might be that I don't understand the extended permissions example -- into what file should I add $facebook->init(...?
fixed!
@Carol please read the documentation
Please read the documentation on how to retrieve user data after a valid facebook connect. The method you'll want to use is $this->Facebook->userData(); in a controller.
For everyone else, I've made the example app: http://facebook.webtechnick.com available to the public via svn.
http://svn.xp-dev.com/svn/facebook_example_app/
Feel free to browse the source to give you an idea of how it all works.
Hope that helps,
Nick
Just released Gigya Plugin
Gigya works with all major social networks including: Facebook, Twitter, Google, Linkedin, OpenID, Myspace, and many more...
Read more about it now: http://www.webtechnick.com/blogs/view/235/Gigya_Social_Network_CakePHP_Plugin
Thank you all for your support!
iPad
Version 2.0 Update
Read about it here:
http://www.webtechnick.com/wtn/blogs/view/238/Facebook_Plugin_v2_0_Graph_System
Enjoy,
Nick
Error
"Facebook configuration detected. Please add the facebook configuration file to your config folder."
The configuration file is present as /app/config/facebook.php
Please let me know if you don't mind.
Thanks.
JM
Error
Version 2.0.2 fixes that issue.
best way to implement this ...
Check download link