Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Updating master to new cakephp 2.0 branch with new registration helpe…

…r feature. Documentation on new Auth setup added to readme.
  • Loading branch information...
commit 47debb84f8306d04f9e9d9ce5d994239e5e9c91c 2 parents e76480e + 13d7e29
@webtechnick authored
Showing with 751 additions and 1,619 deletions.
  1. +15 −0 Config/facebook.php.example
  2. +3 −3 controllers/components/api.php → Controller/Component/ApiComponent.php
  3. +48 −31 controllers/components/connect.php → Controller/Component/ConnectComponent.php
  4. +1 −1  facebook_app_controller.php → FacebookAppController.php
  5. +1 −1  facebook_app_model.php → FacebookAppModel.php
  6. +3 −2 libs/f_b.php → Lib/FB.php
  7. +1 −1  libs/facebook_api.php → Lib/FacebookApi.php
  8. +6 −1 libs/facebook_info.php → Lib/FacebookInfo.php
  9. +5 −5 tests/cases/components/connect.test.php → Test/Case/Component/ConnectComponentTest.php
  10. +273 −0 Test/Case/View/Helper/FacebookHelperTest.php
  11. 0  vendors/facebook/src/facebook.php → Vendor/Facebook.php
  12. +153 −27 {vendors/facebook/src → Vendor}/base_facebook.php
  13. +7 −0 Vendor/channel.php
  14. 0  {vendors/facebook/src → Vendor}/fb_ca_chain_bundle.crt
  15. BIN  Vendor/img/facebook-logout.png
  16. +172 −86 views/helpers/facebook.php → View/Helper/FacebookHelper.php
  17. +0 −15 config/facebook.php.example
  18. +63 −29 readme.markdown
  19. +0 −226 tests/cases/helpers/facebook.test.php
  20. +0 −28 vendors/facebook/changelog.md
  21. +0 −102 vendors/facebook/examples/example.php
  22. +0 −59 vendors/facebook/examples/with_js_sdk.php
  23. +0 −77 vendors/facebook/readme.md
  24. +0 −5 vendors/facebook/tests/bootstrap.php
  25. +0 −920 vendors/facebook/tests/tests.php
  26. BIN  webroot/img/connectwithfacebook.gif
  27. BIN  webroot/img/facebook-logout.png
  28. BIN  webroot/img/facebook_logout.jpg
View
15 Config/facebook.php.example
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Get an api_key and secret from facebook and fill in this content.
+ * save the file to app/Config/facebook.php
+ */
+ $config = array(
+ 'Facebook' => array(
+ 'appId' => 'YOUR_APP_ID',
+ 'apiKey' => 'YOUR_API_KEY',
+ 'secret' => 'YOUR_SECRET',
+ 'cookie' => true,
+ 'locale' => 'en_US',
+ )
+ );
+?>
View
6 controllers/components/api.php → Controller/Component/ApiComponent.php
@@ -7,7 +7,7 @@
* @link http://www.webtechnick.com
* @license MIT
*/
-App::import('Lib', 'Facebook.FacebookApi');
+App::uses('FacebookApi', 'Facebook.Lib');
class ApiComponent extends Object {
/**
@@ -15,12 +15,12 @@ class ApiComponent extends Object {
* @link http://wiki.developers.facebook.com/index.php/Main_Page
* @access public
*/
- var $FB = null;
+ public $FB = null;
/**
* Load the API into a class property and allow access to it.
*/
- function initialize($controller){
+ public function initialize($controller){
$this->FB = new FacebookApi();
}
View
79 controllers/components/connect.php → Controller/Component/ConnectComponent.php
@@ -10,45 +10,60 @@
* @since 3.1.0
* @license MIT
*/
-App::import('Lib', 'Facebook.FB');
-class ConnectComponent extends Object {
+App::uses('FB', 'Facebook.Lib');
+App::uses('FacebookInfo', 'Facebook.Lib');
+class ConnectComponent extends Component {
/**
* uid is the Facebook ID of the connected Facebook user, or null if not connected
*/
- var $uid = null;
+ public $uid = null;
/**
* me is the Facebook user object for the connected Facebook user
*/
- var $me = null;
+ public $me = null;
/**
* hasAccount is true if the connected Facebook user has an account in your application
*/
- var $hasAccount = false;
+ public $hasAccount = false;
/**
* The authenticated User using Auth
*/
- var $authUser = null;
+ public $authUser = null;
/**
* No Auth, if set to true, syncFacebookUser will NOT be called
*/
- var $noAuth = false;
+ public $noAuth = false;
/**
* Error log
*/
- var $errors = array();
+ public $errors = array();
/**
* createUser is true you want the component to attempt to create a CakePHP Auth user
* account by introspection on the Auth component. If false, you can use $this->hasAccount
* as a reference to decide what to do with that user. (default true)
*/
- var $createUser = true;
+ public $createUser = true;
+
+ /**
+ * name of the authentication model, false by default,
+ * set to model alias to init the model.
+ */
+ public $model = false;
+
+ /**
+ * Fields for the model if you want to save the Auth component.
+ */
+ public $modelFields = array(
+ 'password' => 'password',
+ 'username' => 'username'
+ );
/**
* Initialize, load the api, decide if we're logged in
@@ -58,11 +73,8 @@ class ConnectComponent extends Object {
* @return void
* @access public
*/
- function initialize(&$Controller, $settings = array()){
+ public function initialize(&$Controller, $settings = array()){
$this->Controller = $Controller;
- if (!$this->Controller->Session->started()) {
- $this->Controller->Session->start();
- }
$this->_set($settings);
$this->FB = new FB();
$this->uid = $this->FB->getUser();
@@ -77,7 +89,7 @@ function initialize(&$Controller, $settings = array()){
* @param Controller object to attach to
* @return void
*/
- function startup() {
+ public function startup() {
// Prevent using Auth component only if there is noAuth setting provided
if (!$this->noAuth && !empty($this->uid)) {
$this->__syncFacebookUser();
@@ -89,8 +101,8 @@ function startup() {
* @return associative array of registration data (if there is any)
*/
function registrationData(){
- if(isset($this->Controller->params['form']['signed_request'])){
- return FacebookInfo::parseSignedRequest($this->Controller->params['form']['signed_request']);
+ if(isset($this->Controller->request->data['signed_request'])){
+ return FacebookInfo::parseSignedRequest($this->Controller->request->data['signed_request']);
}
return array();
}
@@ -109,11 +121,11 @@ function registrationData(){
*
* @return boolean True if successful, false otherwise.
*/
- function __syncFacebookUser(){
+ private function __syncFacebookUser(){
if(!isset($this->Controller->Auth)){
return false;
}
- // set Auth to a convenience variable
+ // set Auth to a convenience publiciable
$Auth = $this->Controller->Auth;
if (!$this->__initUserModel()) {
return false;
@@ -126,7 +138,7 @@ function __syncFacebookUser(){
// check if the user already has an account
// User is logged in but doesn't have a
- if($Auth->user()){
+ if($Auth->user('id')){
$this->hasAccount = true;
$this->User->id = $Auth->user($this->User->primaryKey);
if (!$this->User->field('facebook_id')) {
@@ -137,7 +149,6 @@ function __syncFacebookUser(){
else {
// attempt to find the user by their facebook id
$this->authUser = $this->User->findByFacebookId($this->uid);
-
//if we have a user, set hasAccount
if(!empty($this->authUser)){
$this->hasAccount = true;
@@ -145,7 +156,7 @@ function __syncFacebookUser(){
//create the user if we don't have one
elseif(empty($this->authUser) && $this->createUser) {
$this->authUser[$this->User->alias]['facebook_id'] = $this->uid;
- $this->authUser[$this->User->alias][$Auth->fields['password']] = $Auth->password(FacebookInfo::randPass());
+ $this->authUser[$this->User->alias][$this->modelFields['password']] = $Auth->password(FacebookInfo::randPass());
if($this->__runCallback('beforeFacebookSave')){
$this->hasAccount = ($this->User->save($this->authUser, array('validate' => false)));
}
@@ -156,8 +167,12 @@ function __syncFacebookUser(){
//Login user if we have one
if($this->authUser){
$this->__runCallback('beforeFacebookLogin', $this->authUser);
- $Auth->fields = array('username' => 'facebook_id', 'password' => $Auth->fields['password']);
- if($Auth->login($this->authUser)){
+ $Auth->authenticate = array(
+ 'Form' => array(
+ 'fields' => array('username' => 'facebook_id', 'password' => $this->modelFields['password'])
+ )
+ );
+ if($Auth->login($this->authUser[$this->model])){
$this->__runCallback('afterFacebookLogin');
}
}
@@ -170,9 +185,8 @@ function __syncFacebookUser(){
* @param field key to return (xpath without leading slash)
* @param mixed return
*/
- function user($field = null){
+ public function user($field = null){
if(isset($this->uid)){
- $this->uid = $this->uid;
if($this->Controller->Session->read('FB.Me') == null){
$this->Controller->Session->write('FB.Me', $this->FB->api('/me'));
}
@@ -197,10 +211,10 @@ function user($field = null){
/**
* Run the callback if it exists
* @param string callback
- * @param mixed passed in variable (optional)
+ * @param mixed passed in publiciable (optional)
* @return mixed result of the callback function
*/
- function __runCallback($callback, $passedIn = null){
+ private function __runCallback($callback, $passedIn = null){
if(is_callable(array($this->Controller, $callback))){
return call_user_func_array(array($this->Controller, $callback), array($passedIn));
}
@@ -208,12 +222,15 @@ function __runCallback($callback, $passedIn = null){
}
/**
- * Initialize the actual User model object defined by Auth
+ * Initialize the actual User model object defined by the plugin
* @return true if successful
* @access private
*/
- function __initUserModel(){
- $this->User = ClassRegistry::init($this->Controller->Auth->userModel);
+ private function __initUserModel(){
+ if($this->model){
+ App::uses($this->model,'Model');
+ $this->User = ClassRegistry::init($this->model);
+ }
if (isset($this->User)) {
$this->User->recursive = -1;
return true;
@@ -227,7 +244,7 @@ function __initUserModel(){
* @return void
* @access private
*/
- function __error($msg){
+ private function __error($msg){
$this->errors[] = __($msg, true);
}
}
View
2  facebook_app_controller.php → FacebookAppController.php
@@ -1,5 +1,5 @@
<?php
-App::import('Lib', 'Facebook.FacebookInfo');
+App::uses('FacebookInfo', 'Facebook.Lib');
class FacebookAppController extends AppController {
}
View
2  facebook_app_model.php → FacebookAppModel.php
@@ -1,5 +1,5 @@
<?php
-App::import('Lib', 'Facebook.FacebookInfo');
+App::uses('FacebookInfo', 'Facebook.Lib');
class FacebookAppModel extends AppModel {
}
View
5 libs/f_b.php → Lib/FB.php
@@ -7,8 +7,9 @@
* @link http://www.webtechnick.com
* @license MIT
*/
-App::import('Vendor', 'Facebook.facebook/src/facebook');
-App::import('Lib', 'Facebook.FacebookInfo');
+
+App::uses('Facebook', 'Facebook.Vendor');
+App::uses('FacebookInfo', 'Facebook.Lib');
class FB {
/**
View
2  libs/facebook_api.php → Lib/FacebookApi.php
@@ -7,7 +7,7 @@
* @link http://www.webtechnick.com
* @license MIT
*/
-App::import('Vendor', 'Facebook.facebook/src/facebook');
+App::uses('Facebook.Facebook/src/facebook', 'Vendor');
Configure::load('facebook');
class FacebookApi {
View
7 libs/facebook_info.php → Lib/FacebookInfo.php
@@ -98,7 +98,12 @@ static function license(){
* @return string plugin description
*/
static function description(){
- return "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.";
+ return "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.";
}
/**
View
10 tests/cases/components/connect.test.php → Test/Case/Component/ConnectComponentTest.php
@@ -1,9 +1,9 @@
<?php
-App::import('Component', 'Facebook.Connect');
-App::import('Core', 'Controller');
-App::import('Component', 'Auth');
-App::import('Component', 'Session');
-App::import('Lib', 'Facebook.FB');
+App::uses('Facebook.ConnectComponent', 'Controller/Component');
+App::uses('Controller', 'Utility');
+App::uses('AuthComponent', 'Controller/Component');
+App::uses('SessionComponent', 'Controller/Component');
+App::uses('Facebook.FB', 'Lib');
class TestUser extends CakeTestModel {
var $name = 'TestUser';
View
273 Test/Case/View/Helper/FacebookHelperTest.php
@@ -0,0 +1,273 @@
+<?php
+/* Facebook Test cases generated on: 2011-11-22 21:31:37 : 1322022697*/
+App::uses('FacebookHelper', 'Facebook.View/Helper');
+App::uses('HtmlHelper', 'View/Helper');
+App::uses('SessionHelper', 'View/Helper');
+App::uses('View','View');
+/**
+* FacebookHelper Test Case
+*
+*/
+class FacebookHelperTestCase extends CakeTestCase {
+ /**
+ * setUp method
+ *
+ * @return void
+ */
+ public function setUp() {
+ parent::setUp();
+ @$View = new View();
+ $this->Facebook = new FacebookHelper($View);
+ $this->Facebook->Html = new HtmlHelper($View);
+ $this->Facebook->Html->request = new CakeRequest(null, false);
+ $this->Facebook->Html->request->webroot = '';
+ Configure::delete('Facebook.appId');
+ Configure::write('Facebook.appId', '12345');
+ }
+
+ /**
+ * tearDown method
+ *
+ * @return void
+ */
+ public function tearDown() {
+ unset($this->Facebook);
+ parent::tearDown();
+ }
+
+ public function testLocal(){
+ @$View = new View();
+ $this->Facebook->__construct($View, array('locale' => 'es_LA'));
+ $this->assertEqual('es_LA', $this->Facebook->locale);
+ }
+
+ public function testDisconnect(){
+ $results = $this->Facebook->disconnect();
+ $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});">logout</a>', $results);
+
+ $results = $this->Facebook->disconnect(array('label' => 'disconnect'));
+ $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});">disconnect</a>', $results);
+
+ $results = $this->Facebook->disconnect(array('redirect' => array('controller' => 'users', 'action' => 'logout')));
+ $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location = &#039;/users/logout&#039;});">logout</a>', $results);
+
+ $results = $this->Facebook->disconnect(array('confirm' => 'Are you sure?'));
+ $this->assertEqual('<a href="#" onclick="if(confirm(&quot;Are you sure?&quot;)){FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});}">logout</a>', $results);
+ }
+
+ public function testInfo(){
+ $error_text = " is not an available option";
+ $results = $this->Facebook->info();
+ $this->assertNotEqual('version' . $error_text, $results);
+
+ $results = $this->Facebook->info('author');
+ $this->assertNotEqual('author' . $error_text, $results);
+
+ $results = $this->Facebook->info('email');
+ $this->assertNotEqual('email' . $error_text, $results);
+
+ $results = $this->Facebook->info('name');
+ $this->assertNotEqual('name' . $error_text, $results);
+
+ $results = $this->Facebook->info('description');
+ $this->assertNotEqual('description' . $error_text, $results);
+
+ $results = $this->Facebook->info('license');
+ $this->assertNotEqual('license' . $error_text, $results);
+
+ $results = $this->Facebook->info('notvalid');
+ $this->assertEqual('notvalid'. $error_text, $results);
+ }
+
+ public function testHtml(){
+ $results = $this->Facebook->html();
+ $this->assertEqual('<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">', $results);
+ }
+
+ public function testLogin(){
+ $results = $this->Facebook->login();
+ $this->assertEqual("<fb:login-button show-faces='1' width='200' max-rows='1'></fb:login-button>", $results);
+ }
+
+ public function testLogout(){
+ $results = $this->Facebook->logout();
+ $this->assertEqual('<a href="#"><img src="/Facebook/img/facebook-logout.png" alt="Facebook logout" id="" onclick="logout();" /></a>', $results);
+ }
+
+ public function testShare(){
+ $results = $this->Facebook->share('http://www.example.com/some_where');
+ $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="http://www.example.com/some_where" type="button" name="fb_share">share</a><script type="text/javascript" src="http://static.ak.fbcdn.net/connect.php/js/FB.Share"></script>', $results);
+
+ $results = $this->Facebook->share();
+ $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="http://localhost/" type="button" name="fb_share">share</a>', $results);
+
+ //assert the script isn't loaded again on next call
+ $results = $this->Facebook->share('not_here');
+ $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="button" name="fb_share">share</a>', $results);
+
+ $results = $this->Facebook->share('not_here', array('style' => 'link'));
+ $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="icon_link" name="fb_share">share</a>', $results);
+
+ $results = $this->Facebook->share('not_here', array('style' => 'link', 'label' => 'Click'));
+ $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="icon_link" name="fb_share">Click</a>', $results);
+ }
+
+ public function testFanBox(){
+ $results = $this->Facebook->fanbox();
+ $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='0' connections='0'></fb:fan>", $results);
+
+ $results = $this->Facebook->fanbox(array('stream' => true));
+ $this->assertEqual("<fb:fan profile_id='12345' stream='1' logobar='0' connections='0'></fb:fan>", $results);
+
+ $results = $this->Facebook->fanbox(array('connections' => true));
+ $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='0' connections='1'></fb:fan>", $results);
+
+ $results = $this->Facebook->fanbox(array('logobar' => true));
+ $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='1' connections='0'></fb:fan>", $results);
+
+ $results = $this->Facebook->fanbox(array('profile_id' => '789'));
+ $this->assertEqual("<fb:fan profile_id='789' stream='0' logobar='0' connections='0'></fb:fan>", $results);
+ }
+
+ public function testPicture(){
+ $results = $this->Facebook->picture('12345');
+ $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1'></fb:profile-pic>", $results);
+
+ $results = $this->Facebook->picture('12345', array('size' => 'small'));
+ $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1' size='small'></fb:profile-pic>", $results);
+
+ $results = $this->Facebook->picture('12345', array('width' => '150', 'height' => '150'));
+ $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1' width='150' height='150'></fb:profile-pic>", $results);
+
+ $results = $this->Facebook->picture('12345', array('facebook-logo' => false));
+ $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='0'></fb:profile-pic>", $results);
+ }
+
+ public function testLike(){
+ $results = $this->Facebook->like();
+ $this->assertEqual('<fb:like></fb:like>', $results);
+
+ $results = $this->Facebook->like(array('layout' => 'button_count'));
+ $this->assertEqual("<fb:like layout='button_count'></fb:like>", $results);
+ }
+
+ public function testActivity(){
+ $results = $this->Facebook->activity();
+ $this->assertEqual('<fb:activity></fb:activity>', $results);
+
+ $results = $this->Facebook->activity(array('colorscheme' => 'dark'));
+ $this->assertEqual("<fb:activity colorscheme='dark'></fb:activity>", $results);
+ }
+
+ public function testFriendPile(){
+ $results = $this->Facebook->friendpile();
+ $this->assertEqual('<fb:friendpile></fb:friendpile>', $results);
+
+ $results = $this->Facebook->friendpile(array('colorscheme' => 'dark'));
+ $this->assertEqual("<fb:friendpile colorscheme='dark'></fb:friendpile>", $results);
+ }
+
+ public function testRecommendantions(){
+ $results = $this->Facebook->recommendations();
+ $this->assertEqual('<fb:recommendations></fb:recommendations>', $results);
+
+ $results = $this->Facebook->recommendations(array('colorscheme' => 'dark'));
+ $this->assertEqual("<fb:recommendations colorscheme='dark'></fb:recommendations>", $results);
+ }
+
+ public function testLivestream(){
+ $results = $this->Facebook->livestream();
+ $this->assertEqual("<fb:live-stream event_app_id='12345' xid='YOUR_EVENT_XID' width='300' height='500'></fb:live-stream>", $results);
+
+ $results = $this->Facebook->livestream(array('width' => '200', 'height' => '300'));
+ $this->assertEqual("<fb:live-stream event_app_id='12345' xid='YOUR_EVENT_XID' width='200' height='300'></fb:live-stream>", $results);
+ }
+
+ public function testComments(){
+ $results = $this->Facebook->comments();
+ $this->assertEqual("<fb:comments></fb:comments>",$results);
+ }
+
+ public function testInit(){
+ $results = $this->Facebook->init();
+ $expected = <<<EOD
+<div id="fb-root"></div><script src="//connect.facebook.net/en_US/all.js"></script><script type="text/javascript">
+//<![CDATA[
+
+ window.fbAsyncInit = function() {
+ FB.init({
+ appId : '12345', // App ID
+ channelURL : '../../Vendor/channel.php', // Channel File
+ status : true, // check login status
+ cookie : true, // enable cookies to allow the server to access the session
+ oauth : true, // enable OAuth 2.0
+ xfbml : true // parse XFBML
+ });
+
+
+ // Checks whether the user is logged in
+ FB.getLoginStatus(function(response) {
+ if (response.authResponse) {
+ // logged in and connected user, someone you know
+ // alert('You are connected');
+ } else {
+ // no user session available, someone you dont know
+ // alert('You are disconnected');
+ }
+ });
+
+ FB.Event.subscribe('auth.authResponseChange', function(response) {
+ if (response.authResponse) {
+ // the user has just logged in
+ // alert('You just logged in facebook from somewhere');
+ } else {
+ // the user has just logged out
+ // alert('You just logged out from faceboook');
+ }
+ });
+
+ // Other javascript code goes here!
+
+ };
+
+ // logs the user in the application and facebook
+ function login(redirection){
+ FB.login(function (response) {
+ if(response.authResponse) {
+ // user is logged in
+ // console.log('Welcome!');
+ if(redirection != null && redirection != ''){
+ top.location.href = redirection;
+ }
+ } else {
+ // user could not log in
+ console.log('User cancelled login or did not fully authorize.');
+ }
+ }, {scope: 'email'});
+ }
+
+ // logs the user out of the application and facebook
+ function logout(redirection){
+ FB.logout(function(response) {
+ // user is logged out
+ // redirection if any
+ if(redirection != null && redirection != ''){
+ top.location.href = redirection;
+ }
+ });
+ }
+
+ // Load the SDK Asynchronously
+ (function() {
+ var e = document.createElement('script'); e.async = true;
+ e.src = document.location.protocol
+ + '//connect.facebook.net/en_US/all.js';
+ document.getElementById('fb-root').appendChild(e);
+ }());
+//]]>
+</script>
+EOD;
+ $this->assertEqual($expected, $results);
+ }
+}
+?>
View
0  vendors/facebook/src/facebook.php → Vendor/Facebook.php
File renamed without changes
View
180 vendors/facebook/src/base_facebook.php → Vendor/base_facebook.php
@@ -150,6 +150,7 @@ public function __toString() {
'api_video' => 'https://api-video.facebook.com/',
'api_read' => 'https://api-read.facebook.com/',
'graph' => 'https://graph.facebook.com/',
+ 'graph_video' => 'https://graph-video.facebook.com/',
'www' => 'https://www.facebook.com/',
);
@@ -161,11 +162,11 @@ public function __toString() {
protected $appId;
/**
- * The Application API Secret.
+ * The Application App Secret.
*
* @var string
*/
- protected $apiSecret;
+ protected $appSecret;
/**
* The ID of the Facebook user, or 0 if the user is logged out.
@@ -211,7 +212,7 @@ public function __toString() {
*/
public function __construct($config) {
$this->setAppId($config['appId']);
- $this->setApiSecret($config['secret']);
+ $this->setAppSecret($config['secret']);
if (isset($config['fileUpload'])) {
$this->setFileUploadSupport($config['fileUpload']);
}
@@ -243,23 +244,45 @@ public function getAppId() {
}
/**
- * Set the API Secret.
+ * Set the App Secret.
*
- * @param string $apiSecret The API Secret
+ * @param string $apiSecret The App Secret
* @return BaseFacebook
+ * @deprecated
*/
public function setApiSecret($apiSecret) {
- $this->apiSecret = $apiSecret;
+ $this->setAppSecret($apiSecret);
return $this;
}
/**
- * Get the API Secret.
+ * Set the App Secret.
*
- * @return string the API Secret
+ * @param string $appSecret The App Secret
+ * @return BaseFacebook
+ */
+ public function setAppSecret($appSecret) {
+ $this->appSecret = $appSecret;
+ return $this;
+ }
+
+ /**
+ * Get the App Secret.
+ *
+ * @return string the App Secret
+ * @deprecated
*/
public function getApiSecret() {
- return $this->apiSecret;
+ return $this->getAppSecret();
+ }
+
+ /**
+ * Get the App Secret.
+ *
+ * @return string the App Secret
+ */
+ public function getAppSecret() {
+ return $this->appSecret;
}
/**
@@ -278,11 +301,22 @@ public function setFileUploadSupport($fileUploadSupport) {
*
* @return boolean true if and only if the server supports file upload.
*/
- public function useFileUploadSupport() {
+ public function getFileUploadSupport() {
return $this->fileUploadSupport;
}
/**
+ * DEPRECATED! Please use getFileUploadSupport instead.
+ *
+ * Get the file upload support status.
+ *
+ * @return boolean true if and only if the server supports file upload.
+ */
+ public function useFileUploadSupport() {
+ return $this->getFileUploadSupport();
+ }
+
+ /**
* Sets the access token for api calls. Use this if you get
* your access token by other means and just want the SDK
* to use it.
@@ -568,6 +602,17 @@ protected function getSignedRequestCookieName() {
}
/**
+ * Constructs and returns the name of the coookie that potentially contain
+ * metadata. The cookie is not set by the BaseFacebook class, but it may be
+ * set by the JavaScript SDK.
+ *
+ * @return string the name of the cookie that would house metadata.
+ */
+ protected function getMetadataCookieName() {
+ return 'fbm_'.$this->getAppId();
+ }
+
+ /**
* Get the authorization code from the query parameters, if it exists,
* and otherwise return false to signal no authorization code was
* discoverable.
@@ -621,7 +666,7 @@ protected function getUserFromAccessToken() {
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
- return $this->appId.'|'.$this->apiSecret;
+ return $this->appId.'|'.$this->appSecret;
}
/**
@@ -664,7 +709,7 @@ protected function getAccessTokenFromCode($code, $redirect_uri = null) {
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array('client_id' => $this->getAppId(),
- 'client_secret' => $this->getApiSecret(),
+ 'client_secret' => $this->getAppSecret(),
'redirect_uri' => $redirect_uri,
'code' => $code));
} catch (FacebookApiException $e) {
@@ -718,6 +763,21 @@ protected function _restserver($params) {
}
/**
+ * Return true if this is video post.
+ *
+ * @param string $path The path
+ * @param string $method The http method (default 'GET')
+ *
+ * @return boolean true if this is video post
+ */
+ protected function isVideoPost($path, $method = 'GET') {
+ if ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path)) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
* Invoke the Graph API.
*
* @param string $path The path (required)
@@ -734,8 +794,14 @@ protected function _graph($path, $method = 'GET', $params = array()) {
}
$params['method'] = $method; // method override as we always do a POST
+ if ($this->isVideoPost($path, $method)) {
+ $domainKey = 'graph_video';
+ } else {
+ $domainKey = 'graph';
+ }
+
$result = json_decode($this->_oauthRequest(
- $this->getUrl('graph', $path),
+ $this->getUrl($domainKey, $path),
$params
), true);
@@ -788,7 +854,7 @@ protected function makeRequest($url, $params, $ch=null) {
}
$opts = self::$CURL_OPTS;
- if ($this->useFileUploadSupport()) {
+ if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
@@ -851,7 +917,7 @@ protected function parseSignedRequest($signed_request) {
// check sig
$expected_sig = hash_hmac('sha256', $payload,
- $this->getApiSecret(), $raw = true);
+ $this->getAppSecret(), $raw = true);
if ($sig !== $expected_sig) {
self::errorLog('Bad Signed JSON signature!');
return null;
@@ -968,9 +1034,10 @@ protected function getUrl($name, $path='', $params=array()) {
* @return string The current URL
*/
protected function getCurrentUrl() {
- if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
- || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
- ) {
+ if (isset($_SERVER['HTTPS']) &&
+ ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
+ isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
+ $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
@@ -1030,7 +1097,7 @@ protected function shouldRetainParam($param) {
/**
* Analyzes the supplied result to see if it was thrown
* because the access token is no longer valid. If that is
- * the case, then the persistent store is cleared.
+ * the case, then we destroy the session.
*
* @param $result array A record storing the error message returned
* by a failed API call.
@@ -1045,12 +1112,13 @@ protected function throwAPIException($result) {
// REST server errors are just Exceptions
case 'Exception':
$message = $e->getMessage();
- if ((strpos($message, 'Error validating access token') !== false) ||
- (strpos($message, 'Invalid OAuth access token') !== false)) {
- $this->setAccessToken(null);
- $this->user = 0;
- $this->clearAllPersistentData();
- }
+ if ((strpos($message, 'Error validating access token') !== false) ||
+ (strpos($message, 'Invalid OAuth access token') !== false) ||
+ (strpos($message, 'An active access token must be used') !== false)
+ ) {
+ $this->destroySession();
+ }
+ break;
}
throw $e;
@@ -1090,9 +1158,67 @@ protected static function base64UrlDecode($input) {
* Destroy the current session
*/
public function destroySession() {
- $this->setAccessToken(null);
- $this->user = 0;
+ $this->accessToken = null;
+ $this->signedRequest = null;
+ $this->user = null;
$this->clearAllPersistentData();
+
+ // Javascript sets a cookie that will be used in getSignedRequest that we
+ // need to clear if we can
+ $cookie_name = $this->getSignedRequestCookieName();
+ if (array_key_exists($cookie_name, $_COOKIE)) {
+ unset($_COOKIE[$cookie_name]);
+ if (!headers_sent()) {
+ // The base domain is stored in the metadata cookie if not we fallback
+ // to the current hostname
+ $base_domain = '.'. $_SERVER['HTTP_HOST'];
+
+ $metadata = $this->getMetadataCookie();
+ if (array_key_exists('base_domain', $metadata) &&
+ !empty($metadata['base_domain'])) {
+ $base_domain = $metadata['base_domain'];
+ }
+
+ setcookie($cookie_name, '', 0, '/', $base_domain);
+ } else {
+ self::errorLog(
+ 'There exists a cookie that we wanted to clear that we couldn\'t '.
+ 'clear because headers was already sent. Make sure to do the first '.
+ 'API call before outputing anything'
+ );
+ }
+ }
+ }
+
+ /**
+ * Parses the metadata cookie that our Javascript API set
+ *
+ * @return an array mapping key to value
+ */
+ protected function getMetadataCookie() {
+ $cookie_name = $this->getMetadataCookieName();
+ if (!array_key_exists($cookie_name, $_COOKIE)) {
+ return array();
+ }
+
+ // The cookie value can be wrapped in "-characters so remove them
+ $cookie_value = trim($_COOKIE[$cookie_name], '"');
+
+ if (empty($cookie_value)) {
+ return array();
+ }
+
+ $parts = explode('&', $cookie_value);
+ $metadata = array();
+ foreach ($parts as $part) {
+ $pair = explode('=', $part, 2);
+ if (!empty($pair[0])) {
+ $metadata[urldecode($pair[0])] =
+ (count($pair) > 1) ? urldecode($pair[1]) : '';
+ }
+ }
+
+ return $metadata;
}
/**
View
7 Vendor/channel.php
@@ -0,0 +1,7 @@
+<?php
+$cache_expire = 60*60*24*365;
+header("Pragma: public");
+header("Cache-Control: max-age=".$cache_expire);
+header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
+?>
+<script src="//connect.facebook.net/en_US/all.js"></script>
View
0  vendors/facebook/src/fb_ca_chain_bundle.crt → Vendor/fb_ca_chain_bundle.crt
File renamed without changes
View
BIN  Vendor/img/facebook-logout.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
258 views/helpers/facebook.php → View/Helper/FacebookHelper.php 100755 → 100644
@@ -7,31 +7,32 @@
* @license MIT
* @link http://www.webtechnick.com
*/
-App::import('Lib', 'Facebook.FacebookInfo');
+App::uses('FacebookInfo', 'Facebook.Lib');
+App::uses('AppHelper','View/Helper');
class FacebookHelper extends AppHelper {
/**
* Helpers to load with this helper.
*/
- var $helpers = array('Html', 'Session');
+ public $helpers = array('Html', 'Session');
/**
* Default Facebook.Share javascript URL
* @access private
*/
- var $__fbShareScript = 'http://static.ak.fbcdn.net/connect.php/js/FB.Share';
+ public $__fbShareScript = 'http://static.ak.fbcdn.net/connect.php/js/FB.Share';
/**
* locale, settable in the constructor
* @link http://developers.facebook.com/docs/internationalization/
* @access public
*/
- var $locale = null;
+ public $locale = null;
/**
* Loadable construct, pass in locale settings
* Fail safe locale to 'en_US'
*/
- function __construct($settings = array()){
+ public function __construct(View $View, $settings = array()){
$this->_set($settings);
if(!$this->locale){
@@ -40,7 +41,7 @@ function __construct($settings = array()){
if(!$this->locale){
$this->locale = 'en_US';
}
- parent::__construct();
+ parent::__construct($View, $settings);
}
/**
@@ -53,7 +54,7 @@ function __construct($settings = array()){
* - 'license' => License Info
* @return string plugin version
*/
- function info($name = 'version'){
+ public function info($name = 'version'){
if(FacebookInfo::_isAvailable($name)){
return FacebookInfo::$name();
}
@@ -63,20 +64,12 @@ function info($name = 'version'){
}
/**
- * Loaoder is no longer needed and is now deprecated
- * @return null
- */
- function loader(){
- return null;
- }
-
- /**
* HTML XMLNS tag (required)
* @return string of html header
* @access public
*/
- function html(){
- return '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">';
+ public function html(){
+ return '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">';
}
/**
@@ -103,28 +96,58 @@ function registration($options = array(), $label = ''){
* Login Button
* $this->Facebook->init() is required for this
* @param array of options
- * - show-faces bool Show pictures of the user's friends who have joined your application
- * - width int The width of the plugin in pixels
- * - max-rows int The maximum number of rows of profile pictures to show
- * - scope string list of permissions to ask for when logging in separated by commas (eg: 'email,read_stream,publish_stream'). (http://developers.facebook.com/docs/authentication/permissions)
+ * - redirect string: to your app's logout url (default null)
+ * - label string: text to use in link (default logout)
+ * - custom boolean: Used to create custom link instead of standart fbml.
+ if redirect option is set this one is not required.
+ * - img string: Creates fortmatted image tag. 'img' should be
+ relative to /app/webroot/img/
+ * - alt string: Image caption
+ * - id string: Tag CSS id
+ * - show-faces bool: Show pictures of the user's friends who have joined your application
+ * - width int: The width of the plugin in pixels
+ * - max-rows int: The maximum number of rows of profile pictures to show
+ * - perms list: of permissions to ask for when logging in separated by commas (eg: 'email,read_stream,publish_stream'). (http://developers.facebook.com/docs/authentication/permissions)
* @param string label
* @return string XFBML tag
* @access public
*/
- function login($options = array(), $label = ''){
+ public function login($options = array(), $label = ''){
$options = array_merge(
array(
- 'show-faces' => 'false',
- 'width' => '200',
- 'max-rows' => '1',
+ 'label' => '',
+ 'custom' => false,
+ 'redirect' => false,
+ 'img' => false,
+ 'alt' => '',
+ 'id' => '',
+ 'show-faces' => true, // fb button only
+ 'width' => 200, // fb button only
+ 'max-rows' => 1 // fb button only
),
$options
);
- if(isset($options['perms'])){
- $options['scope'] = $options['perms'];
- unset($options['perms']);
+ if((isset($options['redirect']) && $options['redirect']) || $options['custom']){
+ $options['redirect'] = Router::url($options['redirect']);
+ $onclick = "login('".$options['redirect']."');";
+ if($options['img']){
+ $source = '/Facebook/img/'.$options['img'];
+ return $this->Html->image($source, array(
+ 'alt' => $options['alt'],
+ 'id' => $options['id'],
+ 'url' => '#',
+ 'onclick' => $onclick));
+ }
+ else {
+ return $this->Html->link($options['label'], '#', array(
+ 'onclick' => $onclick, 'id' => $options['id']));
+ }
+ }
+ else {
+ if(!$options['id']){ unset($options['id']); }
+ unset($options['label'], $options['custom'], $options['redirect'], $options['img'], $options['alt']);
+ return $this->__fbTag('fb:login-button', $label, $options);
}
- return $this->__fbTag('fb:login-button', $label, $options);
}
@@ -132,41 +155,56 @@ function login($options = array(), $label = ''){
* Logout Button
* $this->Facebook->init() is required for this
* @param array of options
- * - redirect string to your app's logout url (default null)
- * - label string of text to use in link (default logout)
- * - confirm string Alert dialog which will be visible if user clicks on the button/link
- * - custom used to create custom link instead of standard fbml. if redirect option is set this one is not required.
+ * - redirect string: to your app's logout url (default null)
+ * - label string: text to use in link (default logout)
+ * - confirm string: Alert dialog which will be visible if user clicks on the button/link
+ * - custom boolean: Used to create custom link instead of standart fbml.
+ if redirect option is set this one is not required.
+ * - img string: Creates fortmatted image tag. 'img' should be
+ relative to /app/webroot/img/
+ * - alt string: Image caption
+ * - id string: Tag CSS Id
* @param string label
* @return string XFBML tag for logout button
* @access public
*/
- function logout($options = array(), $label = ''){
+ public function logout($options = array(), $label = ''){
$options = array_merge(
array(
- 'autologoutlink' => 'true',
- 'label' => 'logout',
- 'custom' => false
+ 'label' => '',
+ 'custom' => false,
+ 'redirect' => false,
+ 'img' => false,
+ 'alt' => '',
+ 'id' => ''
),
$options
);
- if(isset($options['redirect']) || $options['custom']){
- if(isset($options['redirect']) && $options['redirect']){
- $options['redirect'] = Router::url($options['redirect']);
- $response = "window.location = '{$options['redirect']}';";
- } else {
- $response = "window.location.reload();";
- }
- $onclick = "FB.logout(function(response){".$response."});";
+ if((isset($options['redirect']) && $options['redirect']) || $options['custom']){
+ $options['redirect'] = Router::url($options['redirect']);
+ $onclick = "logout('".$options['redirect']."');";
if(isset($options['confirm'])){
$onclick = 'if(confirm("'.$options['confirm'].'")){'.$onclick.'}';
}
- if(!empty($label)){
- $options['label'] = $label;
+ if($options['img']){
+ $source = '/Facebook/img/'.$options['img'];
+ return $this->Html->image($source, array(
+ 'alt' => $options['alt'],
+ 'id' => $options['id'],
+ 'url' => '#',
+ 'onclick' => $onclick));
+ }
+ else {
+ return $this->Html->link($options['label'], '#', array(
+ 'onclick' => $onclick, 'id' => $options['id']));
}
- return $this->Html->link($options['label'], '#', array('onclick' => $onclick));
} else {
- unset($options['label'], $options['escape'], $options['custom']);
- return $this->__fbTag('fb:login-button', $label, $options);
+ $source = '/Facebook/img/facebook-logout.png';
+ return $this->Html->image($source, array(
+ 'alt' => 'Facebook logout',
+ 'url' => '#',
+ 'id' => $options['id'],
+ 'onclick' => 'logout();'));
}
}
@@ -180,7 +218,7 @@ function logout($options = array(), $label = ''){
* @return string Link for disconnect button
* @access public
*/
- function disconnect($options = array()){
+ public function disconnect($options = array()){
$options = array_merge(
array(
'label' => 'logout'
@@ -211,7 +249,7 @@ function disconnect($options = array()){
* @return string XFBML tag along with shareJs script
* @access public
*/
- function share($url = null, $options = array()){
+ public function share($url = null, $options = array()){
if(empty($url)){
$url = Router::url(null, true);
}
@@ -255,7 +293,7 @@ function share($url = null, $options = array()){
* @return string fb tag for profile picture or empty string if uid is not present
* @access public
*/
- function picture($uid = null, $options = array()){
+ public function picture($uid = null, $options = array()){
$options = array_merge(
array(
'uid' => $uid,
@@ -305,7 +343,7 @@ function sendbutton($url = null, $options = array()){
* - connections : number of connections to show (default 10)
* - colorscheme : dark | light (default light)
*/
- function likebox($url = null, $options = array()){
+ public function likebox($url = null, $options = array()){
$options = array_merge(
array(
'href' => $url,
@@ -330,7 +368,7 @@ function likebox($url = null, $options = array()){
* @return string xfbhtml tag
* @access public
*/
- function fanbox($options = array()){
+ public function fanbox($options = array()){
$options = array_merge(
array(
'profile_id' => FacebookInfo::getConfig('appId'),
@@ -354,7 +392,7 @@ function fanbox($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function livestream($options = array()){
+ public function livestream($options = array()){
$options = array_merge(
array(
'event_app_id' => FacebookInfo::getConfig('appId'),
@@ -376,7 +414,7 @@ function livestream($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function comments($options = array()){
+ public function comments($options = array()){
return $this->__fbTag('fb:comments', '', $options);
}
@@ -393,7 +431,7 @@ function comments($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function recommendations($options = array()){
+ public function recommendations($options = array()){
return $this->__fbTag('fb:recommendations', '', $options);
}
@@ -406,7 +444,7 @@ function recommendations($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function friendpile($options = array()){
+ public function friendpile($options = array()){
return $this->__fbTag('fb:friendpile', '', $options);
}
@@ -424,7 +462,7 @@ function friendpile($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function activity($options = array()){
+ public function activity($options = array()){
return $this->__fbTag('fb:activity', '', $options);
}
@@ -441,48 +479,96 @@ function activity($options = array()){
* @return string xfbhtml tag
* @access public
*/
- function like($options = array()){
+ public function like($options = array()){
return $this->__fbTag('fb:like', '', $options);
}
/**
* HTML XMLNS tag (required)
+ * Facebook Auth 2.0 support
* @param array $options
* @example $this->Facebook->init();
* @return string of scriptBlock for FB.init() or error
*/
- function init($options = null, $reload = true) {
+
+ public function init($options = null, $reload = true) {
if (empty($options)) {
$options = array();
}
if ($appId = FacebookInfo::getConfig('appId')) {
- $session = json_encode($this->Session->read('FB.Session'));
- if ($reload) {
- $callback = "FB.Event.subscribe('auth.login',function(){window.location.reload()});";
+ $init = '<div id="fb-root"></div>';
+ $init .= '<script src="//connect.facebook.net/en_US/all.js"></script>';
+ $init .= $this->Html->scriptBlock("
+ window.fbAsyncInit = function() {
+ FB.init({
+ appId : '$appId', // App ID
+ channelURL : '../../Vendor/channel.php', // Channel File
+ status : true, // check login status
+ cookie : true, // enable cookies to allow the server to access the session
+ oauth : true, // enable OAuth 2.0
+ xfbml : true // parse XFBML
+ });
+
+
+ // Checks whether the user is logged in
+ FB.getLoginStatus(function(response) {
+ if (response.authResponse) {
+ // logged in and connected user, someone you know
+ // alert('You are connected');
} else {
- $callback = "if(typeof(facebookReady)=='function'){facebookReady()}";
+ // no user session available, someone you dont know
+ // alert('You are disconnected');
}
- $init = '<div id="fb-root"></div>';
- $init .= $this->Html->scriptBlock(
-<<<JS
-window.fbAsyncInit = function() {
- FB.init({
- appId : '{$appId}',
- status : true, // check login status
- cookie : true, // enable cookies to allow the server to access the session
- xfbml : true, // parse XFBML
- oauth : true // use Oauth
- });
- {$callback}
-};
-(function() {
- var e = document.createElement('script');
- e.src = document.location.protocol + '//connect.facebook.net/{$this->locale}/all.js';
- e.async = true;
+ });
+
+ FB.Event.subscribe('auth.authResponseChange', function(response) {
+ if (response.authResponse) {
+ // the user has just logged in
+ // alert('You just logged in facebook from somewhere');
+ } else {
+ // the user has just logged out
+ // alert('You just logged out from faceboook');
+ }
+ });
+
+ // Other javascript code goes here!
+
+ };
+
+ // logs the user in the application and facebook
+ function login(redirection){
+ FB.login(function (response) {
+ if(response.authResponse) {
+ // user is logged in
+ // console.log('Welcome!');
+ if(redirection != null && redirection != ''){
+ top.location.href = redirection;
+ }
+ } else {
+ // user could not log in
+ console.log('User cancelled login or did not fully authorize.');
+ }
+ }, {scope: 'email'});
+ }
+
+ // logs the user out of the application and facebook
+ function logout(redirection){
+ FB.logout(function(response) {
+ // user is logged out
+ // redirection if any
+ if(redirection != null && redirection != ''){
+ top.location.href = redirection;
+ }
+ });
+ }
+
+ // Load the SDK Asynchronously
+ (function() {
+ var e = document.createElement('script'); e.async = true;
+ e.src = document.location.protocol
+ + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
-}());
-JS
- , $options);
+ }());");
return $init;
} else {
return "<span class='error'>No Facebook configuration detected. Please add the facebook configuration file to your config folder.</span>";
View
15 config/facebook.php.example
@@ -1,15 +0,0 @@
-<?php
-/**
- * Get an api_key and secret from facebook and fill in this content.
- * save the file to app/config/facebook.php
- */
-$config = array(
- 'Facebook' => array(
- 'appId' => 'YOUR_APP_ID',
- 'apiKey' => 'YOUR_API_KEY',
- 'secret' => 'YOUR_SECRET',
- 'cookie' => true,
- 'locale' => 'en_US',
- )
-);
-?>
View
92 readme.markdown
@@ -1,6 +1,5 @@
# Facebook Plugin
* Author: Nick Baker (nick@webtechnick.com)
-* version 3.1.1
* http://www.webtechnick.com
* license: MIT
@@ -48,12 +47,29 @@ The purpose of the Facebook plugin is to provide a seamless way to connect your
* New callback feature for FacebookHelper::init() (page refresh is still default).
* Nicer FacebookHelper::share() now uses Router instead of environment and $this->here
* Optimization, Moving __syncFacebookUser to after Controller->beforeFilter() so $noAuth can be changed in the beforeFilter if need be.
-* 3.0.0: Updated Facebook PHP SDK 3.1.1. FB->getSession() is no longer available, user FB->getUser() instead.
+* 3.0.0: Upgraded to Facebook PHP SDK v 3.1.1
+* 3.0.1: Added CakePHP 2.0 support
+ * the AuthComponent in 2.0 has been redesigned significantly, making the guesswork done by the FacebookPlugin much harder to acheive
+ * As such, you now have to set the model in which you want the Facebook plugin to interact with if you want User/Auth integration via database
+ * You must set this when defining the Facebook.Connect component
+ * If you do not set a 'model' key, integration with your Auth Model will not happen automatically.
+
+ //Example AppController setup
+ public $components = array('Session',
+ 'Auth' => array(
+ 'authenticate' => array(
+ 'Form' => array(
+ 'fields' => array('username' => 'email')
+ )
+ ),
+ 'authorize' => 'Controller'
+ ),
+ 'Facebook.Connect' => array('model' => 'User')
+ );
* 3.1.0: Added new facebook social features (registration and send)
* FacebookHelper::registration() creates a registration form prepopulated with their facebook information.
* ConnectComponent::registrationData() a useful shortcut to parsing a successful registration post to facebook.
* FacebookHelper::sendbutton() creates a nice send button.
-* 3.1.1: Updated Facebook PHP SDK to latest version.
# About Plugin
* Blog: <http://www.webtechnick.com/blogs/view/229/CakePHP_Facebook_Plugin_Auth_Facebook_and_more>
@@ -82,30 +98,37 @@ The purpose of the Facebook plugin is to provide a seamless way to connect your
# Install and Setup
-First clone the repository into your `app/plugins/facebook` directory
+* First clone the repository into your `app/Plugin/Facebook` directory
- git clone git://github.com/webtechnick/CakePHP-Facebook-Plugin.git app/plugins/facebook
+ git clone git://github.com/webtechnick/CakePHP-Facebook-Plugin.git app/Plugin/Facebook
-Once installed, if you wish to use any other features *other* than the share button you'll need to get an api_key and secret for your application.
-1. Create an app from facebook at this url: <http://www.facebook.com/developers/createapp.php>
-2. Once you generate an api_key and secret you'll need to create a file `app/config/facebook.php` You can find an example of what you'll need and how it is laid out in `/facebook/config/facebook.php.example`
- //app/config/facebook.php
- $config = array(
- 'Facebook' => array(
- 'appId' => 'YOUR_APP_ID',
- 'apiKey' => 'YOUR_API_KEY',
- 'secret' => 'YOUR_SECRET',
- 'cookie' => true,
- 'locale' => 'en_US',
- )
- );
+* Load the plugin in your `app/Config/bootstrap.php` file:
+
+ //app/Config/bootstrap.php
+ CakePlugin::load('Facebook');
+
+### Once installed, if you wish to use any other features *other* than the share button you'll need to get an api_key and secret for your application.
+* Create an app from facebook at this url: <http://www.facebook.com/developers/createapp.php>
+* Once you generate an api_key and secret you'll need to create a file `app/Config/facebook.php` You can find an example of what you'll need and how it is laid out in `/Facebook/Config/facebook.php.example`
+
+ //app/Config/facebook.php
+ $config = array(
+ 'Facebook' => array(
+ 'appId' => 'YOUR_APP_ID',
+ 'apiKey' => 'YOUR_API_KEY',
+ 'secret' => 'YOUR_SECRET',
+ 'cookie' => true,
+ 'locale' => 'en_US',
+ )
+ );
+
# Usage
You can use all or some of the Facebook plugin as you see fit.
At the very least you will probably want to use the Facebook Helper
- var $helpers = array('Facebook.Facebook');
+ public $helpers = array('Facebook.Facebook');
If all you want to use is the share feature of the Facebook plugin you're all done.
@@ -135,7 +158,7 @@ Despite the name, the Facebook Connect component takes immediate advantage of th
To use this feature you will first need to update your facebook application with the connect url of your application's url. This is done on the facebook application settings. <http://www.facebook.com/developers/apps.php>
Now all you need to do is add the `Facebook.Connect` component to your app_controller.
- var $components = array('Facebook.Connect');
+ public $components = array('Facebook.Connect');
That's it. You're now ready to accept facebook authentication.
@@ -177,9 +200,21 @@ To access the registartion data posted by your registration user, use the convie
Use the data in $user to finish the registration process on your own (save a new user, find/update the user, etc..)
## CakePHP Auth + Facebook.Connect
-Facebook.Connect will play nice with a variety of Authentication systesm. It has seamless integration with CakePHP AuthComponent.
-
- var $components = array('Auth', 'Facebook.Connect');
+Facebook.Connect will play nice with a variety of Authentication systems. It has nearly seamless integration with CakePHP AuthComponent.
+
+*note* Since the CakePHP 2.0 AuthComponent revamp, ConnectComponent doesn't have the introspection available anymore. It is necessary to tell Connect what model you store your users data in for the automagic to work like so:
+ //Example AppController.php components settup with FacebookConnect
+ public $components = array('Session',
+ 'Auth' => array(
+ 'authenticate' => array(
+ 'Form' => array(
+ 'fields' => array('username' => 'email')
+ )
+ ),
+ 'authorize' => 'Controller'
+ ),
+ 'Facebook.Connect' => array('model' => 'User')
+ );
To integrate with CakePHP Auth, you'll need to alter your users table (or whatever table your Auth component uses) and add a new field -> `facebook_id`.
@@ -188,7 +223,6 @@ To integrate with CakePHP Auth, you'll need to alter your users table (or whatev
Since you already have an authentication system, the logout step will need to also log out the user from your authentication system.
You do this by passing a redirect to `$facebook->logout()` to your system's logout authentication action.
- <?php echo $this->Facebook->logout(array('redirect' => 'users/logout')); ?>
<?php echo $this->Facebook->logout(array('redirect' => array('controller' => 'users', 'action' => 'logout'))); ?>
This will log out of the facebook authentication and then redirect to your authentication logout for you to finish the logout.
@@ -232,24 +266,24 @@ There are three callbacks available to use, each are defined in the controller a
You can access the Facebook Api from anywhere in your app.
You'll need to include the Api first
- App::import('Lib', 'Facebook.FB');
+ App::uses('FB', 'Facebook.Lib');
Then you can instanciate it or, if you're running PHP 5.3.x you can make static calls on it.
PHP version 5.2.x
- $Facebook = new FB();
- $Facebook->api('/me');
+ $Facebook = new FB();
+ $Facebook->api('/me');
PHP 5.3.x
- FB::api('/me');
+ FB::api('/me');
# Internationalization
You can set the locale of the plugin through the helper declaration or through the `config/facebook.php` configuration file (see top of document).
- var $helpers = array('Facebook.Facebook' => array('locale' => 'en_US'));
+ public $helpers = array('Facebook.Facebook' => array('locale' => 'en_US'));
Facebook locales: <http://developers.facebook.com/docs/internationalization/>
View
226 tests/cases/helpers/facebook.test.php
@@ -1,226 +0,0 @@
-<?php
-App::import('Helper', 'Facebook.Facebook');
-App::import('Helper', 'Html');
-App::import('Helper', 'Session');
-Mock::generate('SessionHelper');
-class FacebookHelperTest extends CakeTestCase {
- var $Facebook = null;
-
- function startTest(){
- $this->Facebook = new FacebookHelper();
- $this->Facebook->Html = new HtmlHelper();
- $this->Facebook->Session = new MockSessionHelper();
- Configure::delete('Facebook.appId');
- Configure::write('Facebook.appId', '12345');
- }
-
- function testLocale(){
- $this->Facebook->__construct(array('locale' => 'es_LA'));
- $this->assertEqual('es_LA', $this->Facebook->locale);
- }
-
- function testDisconnect(){
- $results = $this->Facebook->disconnect();
- $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});">logout</a>', $results);
-
- $results = $this->Facebook->disconnect(array('label' => 'disconnect'));
- $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});">disconnect</a>', $results);
-
- $results = $this->Facebook->disconnect(array('redirect' => array('controller' => 'users', 'action' => 'logout')));
- $this->assertEqual('<a href="#" onclick="FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location = &#039;/users/logout&#039;});">logout</a>', $results);
-
- $results = $this->Facebook->disconnect(array('confirm' => 'Are you sure?'));
- $this->assertEqual('<a href="#" onclick="if(confirm(&quot;Are you sure?&quot;)){FB.api({ method: &#039;Auth.revokeAuthorization&#039; }, function(response) {window.location.reload();});}">logout</a>', $results);
- }
-
- function testInfo(){
- $error_text = " is not an available option";
- $results = $this->Facebook->info();
- $this->assertNotEqual('version' . $error_text, $results);
-
- $results = $this->Facebook->info('author');
- $this->assertNotEqual('author' . $error_text, $results);
-
- $results = $this->Facebook->info('email');
- $this->assertNotEqual('email' . $error_text, $results);
-
- $results = $this->Facebook->info('name');
- $this->assertNotEqual('name' . $error_text, $results);
-
- $results = $this->Facebook->info('description');
- $this->assertNotEqual('description' . $error_text, $results);
-
- $results = $this->Facebook->info('license');
- $this->assertNotEqual('license' . $error_text, $results);
-
- $results = $this->Facebook->info('notvalid');
- $this->assertEqual('notvalid'. $error_text, $results);
- }
-
- function testHtml(){
- $results = $this->Facebook->html();
- $this->assertTrue('<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">', $results);
- }
-
- function testLogin(){
- $results = $this->Facebook->login();
- $this->assertEqual("<fb:login-button></fb:login-button>", $results);
-
- $results = $this->Facebook->login(array('size' => 'small'));
- $this->assertEqual("<fb:login-button size='small'></fb:login-button>", $results);
-
- $results = $this->Facebook->login(array('size' => 'large'));
- $this->assertEqual("<fb:login-button size='large'></fb:login-button>", $results);
-
- $results = $this->Facebook->login(array('background' => 'dark'));
- $this->assertEqual("<fb:login-button background='dark'></fb:login-button>", $results);
-
- $results = $this->Facebook->login(array('onlogin' => 'blah'));
- $this->assertEqual("<fb:login-button onlogin='blah'></fb:login-button>", $results);
- }
-
- function testLogout(){
- $results = $this->Facebook->logout();
- $this->assertEqual("<fb:login-button autologoutlink='true'></fb:login-button>", $results);
-
- $results = $this->Facebook->logout(array('redirect' => 'users/logout'));
- $this->assertEqual('<a href="#" onclick="FB.logout(function(response){window.location = &#039;/users/logout&#039;});">logout</a>', $results);
-
- $results = $this->Facebook->logout(array('redirect' => 'users/logout', 'label' => 'Sign Out'));
- $this->assertEqual('<a href="#" onclick="FB.logout(function(response){window.location = &#039;/users/logout&#039;});">Sign Out</a>', $results);
-
- $results = $this->Facebook->logout(array('redirect' => array('controller' => 'users', 'action' => 'logout'), 'label' => 'Sign Out'));
- $this->assertEqual('<a href="#" onclick="FB.logout(function(response){window.location = &#039;/users/logout&#039;});">Sign Out</a>', $results);
- }
-
- function testShare(){
- $results = $this->Facebook->share('http://www.example.com/some_where');
- $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="http://www.example.com/some_where" type="button" name="fb_share">share</a><script type="text/javascript" src="http://static.ak.fbcdn.net/connect.php/js/FB.Share"></script>', $results);
-
- $results = $this->Facebook->share();
- $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="/" type="button" name="fb_share">share</a>', $results);
-
- //assert the script isn't loaded again on next call
- $results = $this->Facebook->share('not_here');
- $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="button" name="fb_share">share</a>', $results);
-
- $results = $this->Facebook->share('not_here', array('style' => 'link'));
- $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="icon_link" name="fb_share">share</a>', $results);
-
- $results = $this->Facebook->share('not_here', array('style' => 'link', 'label' => 'Click'));
- $this->assertEqual('<a href="http://www.facebook.com/sharer.php" share_url="not_here" type="icon_link" name="fb_share">Click</a>', $results);
- }
-
- function testFanBox(){
- $results = $this->Facebook->fanbox();
- $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='0' connections='0'></fb:fan>", $results);
-
- $results = $this->Facebook->fanbox(array('stream' => true));
- $this->assertEqual("<fb:fan profile_id='12345' stream='1' logobar='0' connections='0'></fb:fan>", $results);
-
- $results = $this->Facebook->fanbox(array('connections' => true));
- $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='0' connections='1'></fb:fan>", $results);
-
- $results = $this->Facebook->fanbox(array('logobar' => true));
- $this->assertEqual("<fb:fan profile_id='12345' stream='0' logobar='1' connections='0'></fb:fan>", $results);
-
- $results = $this->Facebook->fanbox(array('profile_id' => '789'));
- $this->assertEqual("<fb:fan profile_id='789' stream='0' logobar='0' connections='0'></fb:fan>", $results);
- }
-
- function testPicture(){
- $results = $this->Facebook->picture('12345');
- $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1'></fb:profile-pic>", $results);
-
- $results = $this->Facebook->picture('12345', array('size' => 'small'));
- $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1' size='small'></fb:profile-pic>", $results);
-
- $results = $this->Facebook->picture('12345', array('width' => '150', 'height' => '150'));
- $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='1' width='150' height='150'></fb:profile-pic>", $results);
-
- $results = $this->Facebook->picture('12345', array('facebook-logo' => false));
- $this->assertEqual("<fb:profile-pic uid='12345' facebook-logo='0'></fb:profile-pic>", $results);
- }
-
- function testLike(){
- $results = $this->Facebook->like();
- $this->assertEqual('<fb:like></fb:like>', $results);
-
- $results = $this->Facebook->like(array('layout' => 'button_count'));
- $this->assertEqual("<fb:like layout='button_count'></fb:like>", $results);
- }
-
- function testActivity(){
- $results = $this->Facebook->activity();
- $this->assertEqual('<fb:activity></fb:activity>', $results);
-
- $results = $this->Facebook->activity(array('colorscheme' => 'dark'));
- $this->assertEqual("<fb:activity colorscheme='dark'></fb:activity>", $results);
- }
-
- function testFriendPile(){
- $results = $this->Facebook->friendpile();
- $this->assertEqual('<fb:friendpile></fb:friendpile>', $results);
-
- $results = $this->Facebook->friendpile(array('colorscheme' => 'dark'));
- $this->assertEqual("<fb:friendpile colorscheme='dark'></fb:friendpile>", $results);
- }
-
- function testRecommendantions(){
- $results = $this->Facebook->recommendations();
- $this->assertEqual('<fb:recommendations></fb:recommendations>', $results);
-
- $results = $this->Facebook->recommendations(array('colorscheme' => 'dark'));
- $this->assertEqual("<fb:recommendations colorscheme='dark'></fb:recommendations>", $results);
- }
-
- function testLivestream(){
- $results = $this->Facebook->livestream();
- $this->assertEqual("<fb:live-stream event_app_id='12345' xid='YOUR_EVENT_XID' width='300' height='500'></fb:live-stream>", $results);
-
- $results = $this->Facebook->livestream(array('width' => '200', 'height' => '300'));
- $this->assertEqual("<fb:live-stream event_app_id='12345' xid='YOUR_EVENT_XID' width='200' height='300'></fb:live-stream>", $results);
- }
-
- function testComments(){
- $results = $this->Facebook->comments();
- $this->assertEqual("<fb:comments></fb:comments>",$results);
- }
-
- function testInit(){
- $this->Facebook->Session->setReturnValue('read', '4567');
- $locale = $this->Facebook->locale;
- $this->Facebook->locale = 'en_US';
-
- $results = $this->Facebook->init();
- $expected = "<div id=\"fb-root\"></div><script type=\"text/javascript\">
-//<![CDATA[
-window.fbAsyncInit = function() {
- FB.init({
- appId : '12345',
- session : \"4567\", // don't refetch the session when PHP already has it
- status : true, // check login status
- cookie : true, // enable cookies to allow the server to access the session
- xfbml : true, // parse XFBML
- oauth : true // use Oauth
- });
- FB.Event.subscribe('auth.login',function(){window.location.reload()});
-};
-(function() {
- var e = document.createElement('script');
- e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js#appId=12345&xfbml=1';
- e.async = true;
- document.getElementById('fb-root').appendChild(e);
-}());
-//]]>
-</script>";
- $this->assertEqual($expected, $results);
- }
-
- function endTest(){
- unset($this->Facebook);
- FacebookInfo::$configs = null;
- Configure::delete('Facebook');
- }
-}
-?>
View
28 vendors/facebook/changelog.md
@@ -1,28 +0,0 @@
-Facebook PHP SDK (v.3.0.0)
-==========================
-
-The new PHP SDK (v3.0.0) is a major upgrade to the older one (v2.2.x):
-
-- Uses OAuth authentication flows instead of our legacy authentication flow
-- Consists of two classes. The first (class BaseFacebook) maintains the core of the upgrade, and the second one (class Facebook) is a small subclass that uses PHP sessions to store the user id and access token.
-
-If you’re currently using the PHP SDK (v2.2.x) for authentication, you will recall that the login code looked like this:
-
- $facebook = new Facebook(…);
- $session = $facebook->getSession();
- if ($session) {
- // proceed knowing you have a valid user session
- } else {
- // proceed knowing you require user login and/or authentication
- }
-
-The login code is now:
-
- $facebook = new Facebook(…);
- $user = $facebook->getUser();
- if ($user) {
- // proceed knowing you have a logged in user who's authenticated
- } else {
- // proceed knowing you require user login and/or authentication
- }
-
View
102 vendors/facebook/examples/example.php
@@ -1,102 +0,0 @@
-<?php
-/**
- * Copyright 2011 Facebook, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may
- * not use this file except in compliance with the License. You may obtain
- * 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' => '191149314281714',
- 'secret' => '73b67bf1c825fa47efae70a46c18906b',
-));
-
-// Get User ID
-$user = $facebook->getUser();
-
-// 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.
-if ($user) {
- $logoutUrl = $facebook->getLogoutUrl();
-} else {
- $loginUrl = $facebook->getLoginUrl();
-}
-
-// This call will always work since we are fetching public data.
-$naitik = $facebook->api('/naitik');
-
-?>
-<!doctype html>
-<html xmlns:fb="http://www.facebook.com/2008/fbml">
- <head>
- <title>php-sdk</title>
- <style>
- body {
- font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
- }
- h1 a {
- text-decoration: none;
- color: #3b5998;
- }
- h1 a:hover {
- text-decoration: underline;
- }
- </style>
- </head>
- <body>
- <h1>php-sdk</h1>
-
- <?php if ($user): ?>
- <a href="<?php echo $logoutUrl; ?>">Logout</a>
- <?php else: ?>
- <div>
- Login using OAuth 2.0 handled by the PHP SDK:
- <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
- </div>
- <?php endif ?>
-
- <h3>PHP Session</h3>
- <pre><?php print_r($_SESSION); ?></pre>
-
- <?php if ($user): ?>
- <h3>You</h3>
- <img src="https://graph.facebook.com/<?php echo $user; ?>/pictu