From 2ff8ef80cd26bbfe154818c12bf953f7d12ef46f Mon Sep 17 00:00:00 2001 From: Yassine Guedidi Date: Mon, 26 Jun 2017 01:15:51 +0200 Subject: [PATCH] Remove helpers --- CHANGELOG.md | 1 + README.md | 6 - docs/README.md | 1 - docs/examples/access_token_from_canvas.md | 33 +- docs/examples/access_token_from_javascript.md | 30 +- docs/examples/access_token_from_page_tab.md | 36 +- docs/examples/facebook_login.md | 101 ------ docs/getting_started.md | 104 +----- docs/reference.md | 6 - docs/reference/Facebook.md | 79 ----- docs/reference/FacebookCanvasHelper.md | 103 ------ docs/reference/FacebookJavaScriptHelper.md | 93 ----- docs/reference/FacebookPageTabHelper.md | 59 ---- docs/reference/FacebookRedirectLoginHelper.md | 134 -------- docs/reference/PersistentDataInterface.md | 70 ---- docs/reference/UrlDetectionInterface.md | 51 --- src/Facebook/Facebook.php | 88 ----- src/Facebook/Helpers/FacebookCanvasHelper.php | 52 --- .../Helpers/FacebookJavaScriptHelper.php | 42 --- .../Helpers/FacebookPageTabHelper.php | 95 ------ .../Helpers/FacebookRedirectLoginHelper.php | 319 ------------------ .../FacebookSignedRequestFromInputHelper.php | 165 --------- .../FacebookMemoryPersistentDataHandler.php | 53 --- .../FacebookSessionPersistentDataHandler.php | 76 ----- .../PersistentData/PersistentDataFactory.php | 65 ---- .../PersistentDataInterface.php | 49 --- .../Url/FacebookUrlDetectionHandler.php | 182 ---------- src/Facebook/Url/UrlDetectionInterface.php | 39 --- .../FooFacebookClientForOAuth2Test.php | 58 ---- tests/Authentication/OAuth2ClientTest.php | 168 --------- tests/FacebookTest.php | 57 ---- tests/Fixtures/FooPersistentDataInterface.php | 38 --- .../Fixtures/FooRedirectLoginOAuth2Client.php | 34 -- tests/Fixtures/FooSignedRequestHelper.php | 34 -- .../FooSignedRequestHelperFacebookClient.php | 41 --- tests/Fixtures/FooUrlDetectionInterface.php | 34 -- tests/Helpers/FacebookCanvasHelperTest.php | 53 --- .../Helpers/FacebookJavaScriptHelperTest.php | 45 --- tests/Helpers/FacebookPageTabHelperTest.php | 46 --- .../FacebookRedirectLoginHelperTest.php | 101 ------ ...cebookSignedRequestFromInputHelperTest.php | 91 ----- ...acebookMemoryPersistentDataHandlerTest.php | 46 --- ...cebookSessionPersistentDataHandlerTest.php | 62 ---- .../PersistentDataFactoryTest.php | 69 ---- tests/Url/FacebookUrlDetectionHandlerTest.php | 134 -------- 45 files changed, 47 insertions(+), 3196 deletions(-) delete mode 100644 docs/examples/facebook_login.md delete mode 100644 docs/reference/FacebookCanvasHelper.md delete mode 100644 docs/reference/FacebookJavaScriptHelper.md delete mode 100644 docs/reference/FacebookPageTabHelper.md delete mode 100644 docs/reference/FacebookRedirectLoginHelper.md delete mode 100644 docs/reference/PersistentDataInterface.md delete mode 100644 docs/reference/UrlDetectionInterface.md delete mode 100644 src/Facebook/Helpers/FacebookCanvasHelper.php delete mode 100644 src/Facebook/Helpers/FacebookJavaScriptHelper.php delete mode 100644 src/Facebook/Helpers/FacebookPageTabHelper.php delete mode 100644 src/Facebook/Helpers/FacebookRedirectLoginHelper.php delete mode 100644 src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php delete mode 100644 src/Facebook/PersistentData/FacebookMemoryPersistentDataHandler.php delete mode 100644 src/Facebook/PersistentData/FacebookSessionPersistentDataHandler.php delete mode 100644 src/Facebook/PersistentData/PersistentDataFactory.php delete mode 100644 src/Facebook/PersistentData/PersistentDataInterface.php delete mode 100644 src/Facebook/Url/FacebookUrlDetectionHandler.php delete mode 100644 src/Facebook/Url/UrlDetectionInterface.php delete mode 100644 tests/Authentication/FooFacebookClientForOAuth2Test.php delete mode 100644 tests/Authentication/OAuth2ClientTest.php delete mode 100644 tests/Fixtures/FooPersistentDataInterface.php delete mode 100644 tests/Fixtures/FooRedirectLoginOAuth2Client.php delete mode 100644 tests/Fixtures/FooSignedRequestHelper.php delete mode 100644 tests/Fixtures/FooSignedRequestHelperFacebookClient.php delete mode 100644 tests/Fixtures/FooUrlDetectionInterface.php delete mode 100644 tests/Helpers/FacebookCanvasHelperTest.php delete mode 100644 tests/Helpers/FacebookJavaScriptHelperTest.php delete mode 100644 tests/Helpers/FacebookPageTabHelperTest.php delete mode 100644 tests/Helpers/FacebookRedirectLoginHelperTest.php delete mode 100644 tests/Helpers/FacebookSignedRequestFromInputHelperTest.php delete mode 100644 tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php delete mode 100644 tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php delete mode 100644 tests/PersistentData/PersistentDataFactoryTest.php delete mode 100644 tests/Url/FacebookUrlDetectionHandlerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d820b9618..fe8ab19a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ Starting with version 5, the Facebook PHP SDK follows [SemVer](http://semver.org - Replace custom CSPRNG implementation with `paragonie/random_compat` (#644) - Removed the built-in autoloader in favor of composer's autoloader (#646) - Big integers in signed requests get decoded as `string` instead of `float` (#699) + - Remove helpers ## 5.x diff --git a/README.md b/README.md index 04939335c..984123604 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,6 @@ $fb = new \Facebook\Facebook([ //'default_access_token' => '{access-token}', // optional ]); -// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity. -// $helper = $fb->getRedirectLoginHelper(); -// $helper = $fb->getJavaScriptHelper(); -// $helper = $fb->getCanvasHelper(); -// $helper = $fb->getPageTabHelper(); - try { // Get the \Facebook\GraphNodes\GraphUser object for the current user. // If you provided a 'default_access_token', the '{access-token}' is optional. diff --git a/docs/README.md b/docs/README.md index 229a2d763..1a359bbc3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,7 +13,6 @@ For installation & implementation instructions, look through the [Getting Starte The following examples demonstrate how you would accomplish common tasks with the Facebook SDK for PHP. - **Authentication & Signed Requests** - - [Facebook Login (OAuth 2.0)](./examples/facebook_login.md) - [Obtaining an access token from the SDK for JavaScript](./examples/access_token_from_javascript.md) - [Obtaining an access token within a Facebook Canvas context](./examples/access_token_from_canvas.md) - [Obtaining an access token within a Facebook Page tab context](./examples/access_token_from_page_tab.md) diff --git a/docs/examples/access_token_from_canvas.md b/docs/examples/access_token_from_canvas.md index 27b655cee..07cbc90a5 100644 --- a/docs/examples/access_token_from_canvas.md +++ b/docs/examples/access_token_from_canvas.md @@ -4,37 +4,32 @@ This example covers obtaining an access token and signed request from within the ## Example -A signed request will be sent to your app via the HTTP POST method within the context of app canvas. The PHP SDK provides a helper to easily obtain, validate & decode the signed request. If the proper OAuth data exists in the signed request payload data, an attempt can be made to obtain an access token from the Graph API. +A signed request will be sent to your app via the HTTP POST method within the context of app canvas. The PHP SDK provides a helper to validate & decode the signed request. ```php $fb = new Facebook\Facebook([ - 'app_id' => '{app-id}', - 'app_secret' => '{app-secret}', - 'default_graph_version' => 'v2.9', - ]); - -$helper = $fb->getCanvasHelper(); + 'app_id' => '{app-id}', + 'app_secret' => '{app-secret}', + 'default_graph_version' => 'v2.9', +]); try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; + $signedRequest = new SignedRequest($fb->getApp(), $_POST['signed_request']) + $accessToken = $signedRequest->getAccessToken(); } catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; + // When validation fails or other local issues + echo 'Facebook SDK returned an error: ' . $e->getMessage(); + exit; } -if (! isset($accessToken)) { - echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.'; - exit; +if (!isset($accessToken)) { + echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.'; + exit; } // Logged in echo '

Signed Request

'; -var_dump($helper->getSignedRequest()); +var_dump($signedRequest->getPayload()); echo '

Access Token

'; var_dump($accessToken->getValue()); diff --git a/docs/examples/access_token_from_javascript.md b/docs/examples/access_token_from_javascript.md index 738c83956..c6bae5134 100644 --- a/docs/examples/access_token_from_javascript.md +++ b/docs/examples/access_token_from_javascript.md @@ -50,28 +50,24 @@ After the user successfully logs in, redirect the user (or make an AJAX request) ```php # /js-login.php $fb = new Facebook\Facebook([ - 'app_id' => '{app-id}', - 'app_secret' => '{app-secret}', - 'default_graph_version' => 'v2.9', - ]); - -$helper = $fb->getJavaScriptHelper(); + 'app_id' => '{app-id}', + 'app_secret' => '{app-secret}', + 'default_graph_version' => 'v2.9', +]); try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; + $fbApp = $fb->getApp(); + $signedRequest = new SignedRequest($fbApp, $_COOKIE['fbsr_' . $fbApp->getId()])) + $accessToken = $signedRequest->getAccessToken(); } catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; + // When validation fails or other local issues + echo 'Facebook SDK returned an error: ' . $e->getMessage(); + exit; } -if (! isset($accessToken)) { - echo 'No cookie set or no OAuth data could be obtained from cookie.'; - exit; +if (!isset($accessToken)) { + echo 'No cookie set or no OAuth data could be obtained from cookie.'; + exit; } // Logged in diff --git a/docs/examples/access_token_from_page_tab.md b/docs/examples/access_token_from_page_tab.md index 0d3936e6d..533c4afb6 100644 --- a/docs/examples/access_token_from_page_tab.md +++ b/docs/examples/access_token_from_page_tab.md @@ -1,3 +1,4 @@ + # Get Access Token From Page Tab Example This example covers obtaining an access token and signed request from within the context of a page tab with the Facebook SDK for PHP. @@ -8,39 +9,34 @@ Page tabs behave much like the app canvas. The PHP SDK provides a helper for pag ```php $fb = new Facebook\Facebook([ - 'app_id' => '{app-id}', - 'app_secret' => '{app-secret}', - 'default_graph_version' => 'v2.9', - ]); - -$helper = $fb->getPageTabHelper(); + 'app_id' => '{app-id}', + 'app_secret' => '{app-secret}', + 'default_graph_version' => 'v2.9', +]); try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; + $signedRequest = new SignedRequest($fb->getApp(), $_POST['signed_request']) + $accessToken = $signedRequest->getAccessToken(); } catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; + // When validation fails or other local issues + echo 'Facebook SDK returned an error: ' . $e->getMessage(); + exit; } -if (! isset($accessToken)) { - echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.'; - exit; +if (!isset($accessToken)) { + echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.'; + exit; } // Logged in echo '

Page ID

'; -var_dump($helper->getPageId()); +var_dump($signedRequest->get('page')['id']); echo '

User is admin of page

'; -var_dump($helper->isAdmin()); +var_dump($signedRequest->get('page')['admin'] === true); echo '

Signed Request

'; -var_dump($helper->getSignedRequest()); +var_dump($signedRequest->getPayload()); echo '

Access Token

'; var_dump($accessToken->getValue()); diff --git a/docs/examples/facebook_login.md b/docs/examples/facebook_login.md deleted file mode 100644 index 86c373b3f..000000000 --- a/docs/examples/facebook_login.md +++ /dev/null @@ -1,101 +0,0 @@ -# Facebook Login Example - -This example covers Facebook Login with the Facebook SDK for PHP. - -## Example - -Although it's common to see examples of Facebook Login being implemented in one PHP script, is best to use two separate PHP scripts for more separation and more control over the responses. - -In this example, the PHP script that generates the login link is called `/login.php`. The callback URL that Facebook redirects the user to after login dialog is called `/fb-callback.php`. - -## /login.php - -```php -$fb = new Facebook\Facebook([ - 'app_id' => '{app-id}', - 'app_secret' => '{app-secret}', - 'default_graph_version' => 'v2.9', - ]); - -$helper = $fb->getRedirectLoginHelper(); - -$permissions = ['email']; // Optional permissions -$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php', $permissions); - -echo 'Log in with Facebook!'; -``` - -## /fb-callback.php - -```php -$fb = new Facebook\Facebook([ - 'app_id' => '{app-id}', - 'app_secret' => '{app-secret}', - 'default_graph_version' => 'v2.9', - ]); - -$helper = $fb->getRedirectLoginHelper(); - -try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; -} - -if (! isset($accessToken)) { - if ($helper->getError()) { - header('HTTP/1.0 401 Unauthorized'); - echo "Error: " . $helper->getError() . "\n"; - echo "Error Code: " . $helper->getErrorCode() . "\n"; - echo "Error Reason: " . $helper->getErrorReason() . "\n"; - echo "Error Description: " . $helper->getErrorDescription() . "\n"; - } else { - header('HTTP/1.0 400 Bad Request'); - echo 'Bad request'; - } - exit; -} - -// Logged in -echo '

Access Token

'; -var_dump($accessToken->getValue()); - -// The OAuth 2.0 client handler helps us manage access tokens -$oAuth2Client = $fb->getOAuth2Client(); - -// Get the access token metadata from /debug_token -$tokenMetadata = $oAuth2Client->debugToken($accessToken); -echo '

Metadata

'; -var_dump($tokenMetadata); - -// Validation (these will throw FacebookSDKException's when they fail) -$tokenMetadata->validateAppId($config['app_id']); -// If you know the user ID this access token belongs to, you can validate it here -//$tokenMetadata->validateUserId('123'); -$tokenMetadata->validateExpiration(); - -if (! $accessToken->isLongLived()) { - // Exchanges a short-lived access token for a long-lived one - try { - $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken); - } catch (Facebook\Exceptions\FacebookSDKException $e) { - echo "

Error getting long-lived access token: " . $e->getMessage() . "

\n\n"; - exit; - } - - echo '

Long-lived

'; - var_dump($accessToken->getValue()); -} - -$_SESSION['fb_access_token'] = (string) $accessToken; - -// User is logged in with a long-lived access token. -// You can redirect them to a members-only page. -//header('Location: https://example.com/members.php'); -``` diff --git a/docs/getting_started.md b/docs/getting_started.md index 982be5ec6..32c874266 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -50,113 +50,15 @@ The `Facebook\Facebook` service ties all the components of the SDK for PHP toget The SDK can be used to support logging a Facebook user into your site using Facebook Login which is based on OAuth 2.0. -Most all request made to the Graph API require an access token. We can obtain user access tokens with the SDK using the [helper classes](reference.md). - - -### Obtaining an access token from redirect - -For most websites, you'll use the [`Facebook\Helpers\FacebookRedirectLoginHelper`](reference/FacebookRedirectLoginHelper.md) to generate a login URL with the `getLoginUrl()` method. The link will take the user to an app authorization screen and upon approval, will redirect them back to a URL that you specified. On the redirect callback page we can obtain the user access token as an [`AccessToken`](reference/AccessToken.md) entity. - -> For this example we'll assume `login.php` will present the login link and the user will be redirected to `login-callback.php` where we will obtain the access token. - -```php -# login.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getRedirectLoginHelper(); -$permissions = ['email', 'user_likes']; // optional -$loginUrl = $helper->getLoginUrl('http://{your-website}/login-callback.php', $permissions); - -echo 'Log in with Facebook!'; -``` - -> **Warning:** The `FacebookRedirectLoginHelper` makes use of sessions to store a [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) value. You need to make sure you have sessions enabled before invoking the `getLoginUrl()` method. This is usually done automatically in most web frameworks, but if you're not using a web framework you can add [`session_start();`](http://php.net/session_start) to the top of your `login.php` & `login-callback.php` scripts. - -```php -# login-callback.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getRedirectLoginHelper(); -try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; -} - -if (isset($accessToken)) { - // Logged in! - $_SESSION['facebook_access_token'] = (string) $accessToken; - - // Now you can redirect to another page and use the - // access token from $_SESSION['facebook_access_token'] -} -``` - +Most all request made to the Graph API require an access token. We can obtain user access tokens with libraries dedicated to OAuth 2.0. ### Obtaining an access token from a Facebook Canvas context -If your app is on Facebook Canvas, use the `getAccessToken()` method on [`Facebook\Helpers\FacebookCanvasHelper`](reference/FacebookCanvasHelper.md) to get an [`AccessToken`](reference/AccessToken.md) entity for the user. - -> **Warning:** The `FacebookCanvasHelper` will detect a [signed request](reference.md#signed-requests) for you and attempt to obtain an access token using the payload data from the signed request. The signed request will only contain the data needed to obtain an access token if the user has already authorized your app sometime in the past. If they have not yet authorized your app the `getAccessToken()` will return `null` and you will need to log the user in with either the [redirect method](#obtaining-an-access-token-from-redirect) or by using the [SDK for JavaScript](https://developers.facebook.com/docs/javascript) and then use the SDK for PHP to [obtain the access token from the cookie](#obtaining-an-access-token-from-the-sdk-for-javascript) the SDK for JavaScript set. - -```php -# example-canvas-app.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getCanvasHelper(); -try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; -} - -if (isset($accessToken)) { - // Logged in. -} -``` - -> If your app exists within the context of a Page tab, you can obtain an access token using the example above since a Page tab is very similar to a Facebook Canvas app. But if you'd like to use a Page-tab-specific helper, you can use the [`Facebook\Helpers\FacebookPageTabHelper`](reference/FacebookPageTabHelper.md) - +**TODO**: Rewrite ### Obtaining an access token from the SDK for JavaScript -If you're already using the Facebook SDK for JavaScript to authenticate users, you can obtain the access token with PHP by using the [FacebookJavaScriptHelper](reference/FacebookJavaScriptHelper.md). The `getAccessToken()` method will return an [`AccessToken`](reference/AccessToken.md) entity. - -```php -# example-obtain-from-js-cookie-app.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getJavaScriptHelper(); -try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; -} - -if (isset($accessToken)) { - // Logged in -} -``` - -> **Warning:** Make sure you set the `{cookie:true}` option when you [initialize the SDK for JavaScript](https://developers.facebook.com/docs/javascript/reference/FB.init/v2.9). This will make the SDK for JavaScript set a cookie on your domain containing information about the user in the form of a signed request. +**TODO**: Rewrite ## Extending the access token diff --git a/docs/reference.md b/docs/reference.md index b8d75b756..c578da607 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -17,7 +17,6 @@ These classes facilitate authenticating a Facebook user with OAuth 2.0. | Class name | Description | | ------------- | ------------- | -| [`Facebook\Helpers\FacebookRedirectLoginHelper`](reference/FacebookRedirectLoginHelper.md) | An OAuth 2.0 service to obtain a user access token from a redirect using a "Log in with Facebook" link. | | [`Facebook\Authentication\AccessToken`](reference/AccessToken.md) | An entity that represents an access token. | | `Facebook\Authentication\AccessTokenMetadata` | An entity that represents metadata from an access token. | | `Facebook\Authentication\OAuth2Client` | An OAuth 2.0 client that sends and receives HTTP requests related to user authentication. | @@ -41,9 +40,6 @@ Classes to help obtain and manage signed requests. | Class name | Description | | ------------- | ------------- | -| [`Facebook\Helpers\FacebookJavaScriptHelper`](reference/FacebookJavaScriptHelper.md) | Used to obtain an access token or signed request from the cookie set by the JavaScript SDK. | -| [`Facebook\Helpers\FacebookCanvasHelper`](reference/FacebookCanvasHelper.md) | Used to obtain an access token or signed request from within the context of an app canvas. | -| [`Facebook\Helpers\FacebookPageTabHelper`](reference/FacebookPageTabHelper.md) | Used to obtain an access token or signed request from within the context of a page tab. | | [`Facebook\SignedRequest`](reference/SignedRequest.md) | An entity that represents a signed request. | # Core Exceptions @@ -89,5 +85,3 @@ You can overwrite certain functionality of the SDK by coding to an interface and | ------------- | ------------- | | `Facebook\HttpClients\ FacebookHttpClientInterface` | An interface to code your own HTTP client implementation. | | `Facebook\Http\GraphRawResponse` | An entity that is returned from an instance of a `FacebookHttpClientInterface` that represents a raw HTTP response from the Graph API. | -| [`Facebook\PersistentData\PersistentDataInterface`](reference/PersistentDataInterface.md) | An interface to code your own persistent data storage implementation. | -| [`Facebook\Url\UrlDetectionInterface`](reference/UrlDetectionInterface.md) | An interface to code your own URL detection logic. | diff --git a/docs/reference/Facebook.md b/docs/reference/Facebook.md index a14aef47f..1947446ee 100644 --- a/docs/reference/Facebook.md +++ b/docs/reference/Facebook.md @@ -50,8 +50,6 @@ $fb = new Facebook\Facebook([ 'enable_beta_mode' => true, 'default_graph_version' => 'v2.9', 'http_client_handler' => 'guzzle', - 'persistent_data_handler' => 'memory', - 'url_detection_handler' => new MyUrlDetectionHandler(), ]); ``` @@ -87,34 +85,6 @@ $fb = new Facebook([ If any other value is provided an `InvalidArgumentException` will be thrown. -### `persistent_data_handler` -Allows you to overwrite the default persistent data store. - -By default, the SDK will try to use the native PHP session for the persistent data store. There is also an in-memory persistent data handler which is useful when running your script from the command line for example. You can force either implementation by setting this value to `session` or `memory`. - -If you wish to write your own persistent data handler, you can code your persistent data handler to the [`Facebook\PersistentData\PersistentDataInterface`](PersistentDataInterface.md) and set the value of `persistent_data_handler` to an instance of your custom handler. - -```php -$fb = new Facebook([ - 'persistent_data_handler' => new MyCustomPersistentDataHandler(), -]); -``` - -If any other value is provided an `InvalidArgumentException` will be thrown. - -### `url_detection_handler` -Allows you to overwrite the default URL detection logic. - -The SDK will do its best to detect the proper current URL but this can sometimes get tricky if you have a very customized environment. You can write your own URL detection logic that implements the ['Facebook\Url\UrlDetectionInterface'](UrlDetectionInterface.md)` and set the value of `url_detection_handler` to an instance of your custom URL detector. - -```php -$fb = new Facebook([ - 'url_detection_handler' => new MyUrlDetectionHandler(), -]); -``` - -If any other value is provided an `InvalidArgumentException` will be thrown. - ## Environment variables fallback The only required configuration options are `app_id`, `app_secret` and `default_graph_version`. However, the SDK will look to environment variables for the app ID and app secret. @@ -153,12 +123,6 @@ public Facebook\FacebookResponse|Facebook\FacebookBatchResponse|null getLastResp ``` Returns the last response received from the Graph API in the form of a `Facebook\FacebookResponse` or `Facebook\FacebookBatchResponse`. -## getUrlDetectionHandler() -```php -public Facebook\Url\UrlDetectionInterface getUrlDetectionHandler() -``` -Returns an instance of [`Facebook\Url\UrlDetectionInterface`](UrlDetectionInterface.md). - ## getDefaultAccessToken() ```php public Facebook\Authentication\AccessToken|null getDefaultAccessToken() @@ -327,49 +291,6 @@ $batchResponse = $fb->sendBatchRequest($requests); [See a full batch example](../examples/batch_request.md). -## getRedirectLoginHelper() -```php -public Facebook\Helpers\FacebookRedirectLoginHelper getRedirectLoginHelper() -``` - -Returns a [`Facebook\Helpers\FacebookRedirectLoginHelper`](FacebookRedirectLoginHelper.md) which is used to generate a "Login with Facebook" link and obtain an access token from a redirect. - -```php -$helper = $fb->getRedirectLoginHelper(); -``` - -## getJavaScriptHelper() -```php -public Facebook\Helpers\FacebookJavaScriptHelper getJavaScriptHelper() -``` - -Returns a [`Facebook\Helpers\FacebookJavaScriptHelper`](FacebookJavaScriptHelper.md) which is used to access the signed request stored in the cookie set by the SDK for JavaScript. - -```php -$helper = $fb->getJavaScriptHelper(); -``` - -## getCanvasHelper() -```php -public Facebook\Helpers\FacebookCanvasHelper getCanvasHelper() -``` - -Returns a [`Facebook\Helpers\FacebookCanvasHelper`](FacebookCanvasHelper.md) which is used to access the signed request that is `POST`ed to canvas apps. - -```php -$helper = $fb->getCanvasHelper(); -``` - -## getPageTabHelper() -```php -public Facebook\Helpers\FacebookPageTabHelper getPageTabHelper() -``` - -Returns a [`Facebook\Helpers\FacebookPageTabHelper`](FacebookPageTabHelper.md) which is used to access the signed request that is `POST`ed to canvas apps and provides a number of helper methods useful for apps living in a page tab context. - -```php -$helper = $fb->getPageTabHelper(); -``` ## next() ```php diff --git a/docs/reference/FacebookCanvasHelper.md b/docs/reference/FacebookCanvasHelper.md deleted file mode 100644 index 18624574c..000000000 --- a/docs/reference/FacebookCanvasHelper.md +++ /dev/null @@ -1,103 +0,0 @@ -# Facebook\Helpers\FacebookCanvasHelper - -The `FacebookCanvasHelper` is used to obtain an access token or signed request when working within the context of an [app canvas](https://developers.facebook.com/docs/games/canvas). - -```php -Facebook\Helpers\FacebookCanvasHelper( Facebook\FacebookApp $facebookApp ) -``` - -## Usage - -If your app is loaded through Canvas, Facebook sends a POST request to your app with a signed request. This helper will handle validating and decrypting the signed request. - -```php -$fb = new Facebook\Facebook([/* */]); -$canvasHelper = $fb->getCanvasHelper(); -$signedRequest = $canvasHelper->getSignedRequest(); - -if ($signedRequest) { - $payload = $signedRequest->getPayload(); - var_dump($payload); -} -``` - -If a user has already authenticated your app, you can also obtain an access token. - -```php -$fb = new Facebook\Facebook([/* */]); -$canvasHelper = $fb->getCanvasHelper(); - -try { - $accessToken = $canvasHelper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); -} - -if (isset($accessToken)) { - // Logged in. -} -``` - -The `$accessToken` will be `null` if the signed request did not contain any OAuth 2.0 data to obtain the access token. - -## Instance Methods - -### __construct() -```php -public FacebookCanvasHelper __construct(FacebookApp $app, FacebookClient $client, $graphVersion = null) -``` -Upon instantiation, `FacebookCanvasHelper` validates and decrypts the signed request that was sent via POST if present. - -### getAccessToken() -```php -public Facebook\AccessToken|null getAccessToken() -``` -Checks the signed request for authentication data and tries to obtain an access token access token. - -### getUserId() -```php -public string|null getUserId() -``` -A convenience method for obtaining a user's ID from the signed request if present. This will only return the user's ID if a valid signed request can be obtained and decrypted and the user has already authorized the app. - -```php -$userId = $canvasHelper->getUserId(); - -if ($userId) { - // User is logged in -} -``` - -This is equivalent to accessing the user ID from the signed request entity. - -```php -$signedRequest = $canvasHelper->getSignedRequest(); - -if ($signedRequest) { - $userId = $signedRequest->getUserId(); - // OR - $userId = $signedRequest->get('user_id'); -} -``` - -### getAppData() -```php -public string|null getAppData() -``` -Gets the value that is set in the `app_data` property if present. - -### getSignedRequest() -```php -public Facebook\SignedRequest|null getSignedRequest() -``` -Returns the signed request as an instance of [`Facebook\SignedRequest`](SignedRequest.md) if present. - -### getRawSignedRequest() -```php -public string|null getRawSignedRequest() -``` -Returns the raw encoded signed request as a `string` if present in the POST variables or `null`. diff --git a/docs/reference/FacebookJavaScriptHelper.md b/docs/reference/FacebookJavaScriptHelper.md deleted file mode 100644 index d9520c779..000000000 --- a/docs/reference/FacebookJavaScriptHelper.md +++ /dev/null @@ -1,93 +0,0 @@ -# Facebook\Helpers\FacebookJavaScriptHelper - -If you're using the [JavaScript SDK](https://developers.facebook.com/docs/javascript) on your site, information on the logged in user is stored in a cookie. Use the `FacebookJavaScriptHelper` to obtain an access token or signed request from the cookie. - -## Usage - -This helper will handle validating and decode the signed request from the cookie set by the JavaScript SDK. - -```php -$fb = new Facebook\Facebook([/* */]); -$jsHelper = $fb->getJavaScriptHelper(); -$signedRequest = $jsHelper->getSignedRequest(); - -if ($signedRequest) { - $payload = $signedRequest->getPayload(); - var_dump($payload); -} -``` - -If a user has already authenticated your app, you can also obtain an access token. - -```php -$fb = new Facebook\Facebook([/* */]); -$jsHelper = $fb->getJavaScriptHelper(); - -try { - $accessToken = $jsHelper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); -} - -if (isset($accessToken)) { - // Logged in. -} -``` - -You will likely want to make an Ajax request when the login state changes in the Facebook SDK for JavaScript. Information about that here: [FB.event.subscribe](https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/#events) - -## Instance Methods - -### __construct() -```php -public FacebookJavaScriptHelper __construct(FacebookApp $app, FacebookClient $client, $graphVersion = null) -``` -Upon instantiation, `FacebookJavaScriptHelper` validates and decodes the signed request that exists in the cookie set by the JavaScript SDK if present. - -### getAccessToken() -```php -public Facebook\AccessToken|null getAccessToken( Facebook\FacebookClient $client ) -``` -Checks the signed request for authentication data and tries to obtain an access token access token. - -### getUserId() -```php -public string|null getUserId() -``` -A convenience method for obtaining a user's ID from the signed request if present. This will only return the user's ID if a valid signed request can be obtained and decoded and the user has already authorized the app. - -```php -$userId = $jsHelper->getUserId(); - -if ($userId) { - // User is logged in -} -``` - -This is equivalent to accessing the user ID from the signed request entity. - -```php -$signedRequest = $jsHelper->getSignedRequest(); - -if ($signedRequest) { - $userId = $signedRequest->getUserId(); - // OR - $userId = $signedRequest->get('user_id'); -} -``` - -### getSignedRequest() -```php -public Facebook\SignedRequest|null getSignedRequest() -``` -Returns the signed request as a [`Facebook\SignedRequest`](SignedRequest.md) entity if present. - -### getRawSignedRequest() -```php -public string|null getRawSignedRequest() -``` -Returns the raw encoded signed request as a `string` or `null`. diff --git a/docs/reference/FacebookPageTabHelper.md b/docs/reference/FacebookPageTabHelper.md deleted file mode 100644 index 3666a8cc6..000000000 --- a/docs/reference/FacebookPageTabHelper.md +++ /dev/null @@ -1,59 +0,0 @@ -# Facebook\Helpers\FacebookPageTabHelper - -Page tabs are similar to the context to app canvases but are treated slightly differently. Use the `FacebookPageTabHelper` to obtain an access token or signed request within the context of a page tab. - -## Usage - -The usage of the `FacebookPageTabHelper` is exactly the same as [`FacebookCanvasHelper`](FacebookCanvasHelper.md) with additional methods to obtain the `page` data from the signed request. - -```php -$fb = new Facebook\Facebook([/* */]); -$pageHelper = $fb->getPageTabHelper(); -$signedRequest = $pageHelper->getSignedRequest(); - -if ($signedRequest) { - $payload = $signedRequest->getPayload(); - var_dump($payload); -} -``` - -If a user has already authenticated your app, you can also obtain an access token. - -```php -$fb = new Facebook\Facebook([/* */]); -$pageHelper = $fb->getPageTabHelper(); - -try { - $accessToken = $pageHelper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); -} - -if (isset($accessToken)) { - // Logged in. -} -``` - -## Instance Methods - -### getPageData() -```php -public string|null getPageData($key, $default = null) -``` -Gets a value from the `page` property if present. - -### isAdmin() -```php -public boolean isAdmin() -``` -Returns `true` is the user has authenticated your app and is an admin of the parent page. - -### getPageId() -```php -public string|null getPageId() -``` -Returns the ID of the parent page if it can be obtained from the `page` property in the signed request. diff --git a/docs/reference/FacebookRedirectLoginHelper.md b/docs/reference/FacebookRedirectLoginHelper.md deleted file mode 100644 index 367ab3765..000000000 --- a/docs/reference/FacebookRedirectLoginHelper.md +++ /dev/null @@ -1,134 +0,0 @@ -# Facebook\Helpers\FacebookRedirectLoginHelper - -The most commonly used helper is the `FacebookRedirectLoginHelper` which allows you to obtain a user access token from a redirect using a "Log in with Facebook" link. - -## Usage - -Facebook Login is achieved via OAuth 2.0. But you don't really have to know much about OAuth 2.0 since the SDK for PHP does all the heavy lifting for you. - - -### Obtaining an instance of FacebookRedirectLoginHelper - -You can obtain an instance of the `FacebookRedirectLoginHelper` from the `getRedirectLoginHelper()` method on the `Facebook\Facebook` service. - -```php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getRedirectLoginHelper(); -``` - -### Login with Facebook - -The basic login flow goes like this: - -1. A user is presented with a unique "log in with Facebook" link that was generated by the `FacebookRedirectLoginHelper`. -2. Once the user clicks on the link they will be taken to Facebook's website and presented with an app authorization modal. -3. After the user confirms or denies the app authorization, they will be redirected to a specific callback URL on your website. -4. In your callback URL you can analyse the response to obtain a user access token or display an error if the user denied the request. - -```php -# login.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getRedirectLoginHelper(); -$permissions = ['email', 'user_likes']; // optional -$loginUrl = $helper->getLoginUrl('http://{your-website}/login-callback.php', $permissions); - -echo 'Log in with Facebook!'; -``` - -> **Warning:** The `FacebookRedirectLoginHelper` makes use of sessions to store a [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) value. You need to make sure you have sessions enabled before invoking the `getLoginUrl()` method. This is usually done automatically in most web frameworks, but if you're not using a web framework you can add [`session_start();`](http://php.net/session_start) to the top of your `login.php` & `login-callback.php` scripts. You can overwrite the default session handling - see [extensibility points](#extensibility-points) below. - -Then, in your callback page (at the redirect url) when Facebook sends the user back: - -```php -# login-callback.php -$fb = new Facebook\Facebook([/* . . . */]); - -$helper = $fb->getRedirectLoginHelper(); -try { - $accessToken = $helper->getAccessToken(); -} catch(Facebook\Exceptions\FacebookResponseException $e) { - // When Graph returns an error - echo 'Graph returned an error: ' . $e->getMessage(); - exit; -} catch(Facebook\Exceptions\FacebookSDKException $e) { - // When validation fails or other local issues - echo 'Facebook SDK returned an error: ' . $e->getMessage(); - exit; -} - -if (isset($accessToken)) { - // Logged in! - $_SESSION['facebook_access_token'] = (string) $accessToken; - - // Now you can redirect to another page and use the - // access token from $_SESSION['facebook_access_token'] -} elseif ($helper->getError()) { - // The user denied the request - exit; -} -``` - -## Instance Methods - -### getLoginUrl() -```php -public string getLoginUrl(string $redirectUrl, array $scope = [], string $separator = '&') -``` -Generates an authorization URL to ask a user for access to their profile on behalf of your app. - -#### Arguments -- `$redirectUrl` (_Required_) The callback URL that the user will be redirected to after being presented with the app authorization modal. -- `$scope` (_Optional_) A numeric array of permissions to ask the user for. -- `$separator` (_Optional_) The URL parameter separator. When working with XML documents, you can set this to `&` for example. - -### getReRequestUrl() -```php -public string getReRequestUrl(string $redirectUrl, array $scope = [], string $separator = '&') -``` -Generates a URL to rerequest permissions from a user. The arguments are the same as the `getLoginUrl()` method above. - -### getReAuthenticationUrl() -```php -public string getReAuthenticationUrl(string $redirectUrl, array $scope = [], string $separator = '&') -``` -Generates a URL to ask the user to reauthenticate. The arguments are the same as the `getLoginUrl()` method above. - -### getLogoutUrl() -```php -public string getLogoutUrl(string $accessToken, string $next, string $separator = '&') -``` -Generates the URL log a user out of Facebook. This will throw an `FacebookSDKException` if you try to use an app access token. - -### getAccessToken() -```php -public Facebook\Authentication\AccessToken|null getAccessToken(string $redirectUrl = null) -``` -Attempts to obtain an access token from an authorization code. This method will make a request to the Graph API and return a response. If there was an error in that process a `FacebookSDKException` will be thrown. A `FacebookSDKException` will also be thrown if the CSRF validation fails. - -If no authorization code could be found from the `code` param in the URL, this method will return `null`. - -#### Arguments -- `$redirectUrl` (_Optional_) The URL of the callback that the user is currently on. This should be the same as the one used when creating the login URL. If no URL is provided, it will be detected automatically. - -## Extensibility Points - -The `FacebookRedirectLoginHelper` has to orchestrate a number of components from the hosting environment to make the OAuth 2.0 authorization process as easy as possible to integrate. Out of the box it auto-detects all the things it needs, but sometimes you'll want to control these components. - - -### Sessions (persistent data) - -In order to prevent [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)'s, a unique value is generated with each login link and stored in a session. - -Most modern web frameworks have custom session handlers that allow you to manage your sessions with something other than the default flat-file storage. You can integrate your framework's custom session handling by coding to the [`PersistentDataInterface`](PersistentDataInterface.md). - - -### CSPRNG - -The CSRF value that the `getLoginUrl()`, `getReRequestUrl()`, and `getReAuthenticationUrl()` methods generate are all _cryptographically secure_ random strings. To generate these tokens the PHP SDK uses the [CSPRNG functions in PHP 7](http://php.net/csprng) and the [paragonie/random_compat](https://github.com/paragonie/random_compat) polyfill for PHP 5.6. - - -### URL detection - -In order to not make you pass the callback URL to the `getAccessToken()` method, the SDK will do its best to detect the callback's URL for you. Most modern web frameworks have URL detection built-in. You can code your specific web framework's URL detection logic by coding to the [`UrlDetectionInterface`](UrlDetectionInterface.md). diff --git a/docs/reference/PersistentDataInterface.md b/docs/reference/PersistentDataInterface.md deleted file mode 100644 index 9f2283981..000000000 --- a/docs/reference/PersistentDataInterface.md +++ /dev/null @@ -1,70 +0,0 @@ -# The persistent data handler interface for the Facebook SDK for PHP - -The persistent data handler interface stores values in a persistent data store. By default the SDK for PHP uses native PHP sessions to store the persistent data. You can overwrite this behavior by coding to the `Facebook\PersistentData\PersistentDataInterface`. - -## Facebook\PersistentData\PersistentDataInterface - -If you're using a web framework that handles persistent data for you, you might want to code a custom persistent data handler to ensure that your persistent storage is being handled consistently. - -For example if you are using Laravel, a custom handler might look like this: - -```php -use Facebook\PersistentData\PersistentDataInterface; - -class MyLaravelPersistentDataHandler implements PersistentDataInterface -{ - /** - * @var string Prefix to use for session variables. - */ - protected $sessionPrefix = 'FBRLH_'; - - /** - * @inheritdoc - */ - public function get($key) - { - return \Session::get($this->sessionPrefix . $key); - } - - /** - * @inheritdoc - */ - public function set($key, $value) - { - \Session::put($this->sessionPrefix . $key, $value); - } -} -``` - -To enable your custom persistent data handler implementation in the SDK, you can set an instance of the handler to the `persistent_data_handler` config of the `Facebook\Facebook` super service. - -```php -$fb = new Facebook\Facebook([ - // . . . - 'persistent_data_handler' => new MyLaravelPersistentDataHandler(), - // . . . - ]); -``` - -Alternatively, if you're working with the `Facebook\Helpers\FacebookRedirectLoginHelper` directly, you can inject your custom handler via the constructor. - -```php -use Facebook\Helpers\FacebookRedirectLoginHelper; - -$myPersistentDataHandler = new MyLaravelPersistentDataHandler(); -$helper = new FacebookRedirectLoginHelper($fbApp, $myPersistentDataHandler); -``` - -## Method Reference - -### get() -```php -public mixed get(string $key) -``` -Returns a value from the persistent data store or `null` if the value does not exist. - -### set() -```php -public void set(string $key, mixed $value) -``` -Sets a value to the persistent data store. diff --git a/docs/reference/UrlDetectionInterface.md b/docs/reference/UrlDetectionInterface.md deleted file mode 100644 index 7e14b2445..000000000 --- a/docs/reference/UrlDetectionInterface.md +++ /dev/null @@ -1,51 +0,0 @@ -# The URL detection interface for the Facebook SDK for PHP - -The URL detection interface allows you to overwrite the default URL detection logic by coding to the `Facebook\Url\UrlDetectionInterface`. - -## Facebook\Url\UrlDetectionInterface - -If you're using a web framework that handles routes and URL generation for you, you might want to code a custom URL detection handler to ensure that your URL's are being generated consistently. - -For example if you are using Laravel, a custom handler might look like this: - -```php -use Facebook\Url\UrlDetectionInterface; - -class MyLaravelUrlDetectionHandler implements UrlDetectionInterface -{ - /** - * @inheritdoc - */ - public function getCurrentUrl() - { - return \Request::url(); - } -} -``` - -To enable your custom URL detection implementation in the SDK, you can set an instance of the handler to the `url_detection_handler` config of the `Facebook\Facebook` super service. - -```php -$fb = new Facebook\Facebook([ - // . . . - 'url_detection_handler' => new MyLaravelUrlDetectionHandler(), - // . . . - ]); -``` - -Alternatively, if you're working with the `Facebook\Helpers\FacebookRedirectLoginHelper` directly, you can inject your custom handler via the constructor. - -```php -use Facebook\Helpers\FacebookRedirectLoginHelper; - -$myUrlDetectionHandler = new MyLaravelUrlDetectionHandler(); -$helper = new FacebookRedirectLoginHelper($fbApp, null, $myUrlDetectionHandler); -``` - -## Method Reference - -### getCurrentUrl() -```php -public string getCurrentUrl() -``` -Returns the full and currently active URL. diff --git a/src/Facebook/Facebook.php b/src/Facebook/Facebook.php index 7df2005d7..8bf94c15d 100644 --- a/src/Facebook/Facebook.php +++ b/src/Facebook/Facebook.php @@ -30,15 +30,7 @@ use Facebook\FileUpload\FacebookTransferChunk; use Facebook\FileUpload\FacebookVideo; use Facebook\GraphNodes\GraphEdge; -use Facebook\Url\UrlDetectionInterface; -use Facebook\Url\FacebookUrlDetectionHandler; use Facebook\HttpClients\HttpClientsFactory; -use Facebook\PersistentData\PersistentDataFactory; -use Facebook\PersistentData\PersistentDataInterface; -use Facebook\Helpers\FacebookCanvasHelper; -use Facebook\Helpers\FacebookJavaScriptHelper; -use Facebook\Helpers\FacebookPageTabHelper; -use Facebook\Helpers\FacebookRedirectLoginHelper; use Facebook\Exceptions\FacebookSDKException; /** @@ -78,11 +70,6 @@ class Facebook */ protected $oAuth2Client; - /** - * @var UrlDetectionInterface|null The URL detection handler. - */ - protected $urlDetectionHandler; - /** * @var AccessToken|null The default access token to use with requests. */ @@ -93,11 +80,6 @@ class Facebook */ protected $defaultGraphVersion; - /** - * @var PersistentDataInterface|null The persistent data handler. - */ - protected $persistentDataHandler; - /** * @var FacebookResponse|FacebookBatchResponse|null Stores the last request made to Graph. */ @@ -118,8 +100,6 @@ public function __construct(array $config = []) 'default_graph_version' => null, 'enable_beta_mode' => false, 'http_client_handler' => null, - 'persistent_data_handler' => null, - 'url_detection_handler' => null, ], $config); if (!$config['app_id']) { @@ -137,10 +117,6 @@ public function __construct(array $config = []) HttpClientsFactory::createHttpClient($config['http_client_handler']), $config['enable_beta_mode'] ); - $this->setUrlDetectionHandler($config['url_detection_handler'] ?: new FacebookUrlDetectionHandler()); - $this->persistentDataHandler = PersistentDataFactory::createPersistentDataHandler( - $config['persistent_data_handler'] - ); if (isset($config['default_access_token'])) { $this->setDefaultAccessToken($config['default_access_token']); @@ -195,26 +171,6 @@ public function getLastResponse() return $this->lastResponse; } - /** - * Returns the URL detection handler. - * - * @return UrlDetectionInterface - */ - public function getUrlDetectionHandler() - { - return $this->urlDetectionHandler; - } - - /** - * Changes the URL detection handler. - * - * @param UrlDetectionInterface $urlDetectionHandler - */ - private function setUrlDetectionHandler(UrlDetectionInterface $urlDetectionHandler) - { - $this->urlDetectionHandler = $urlDetectionHandler; - } - /** * Returns the default AccessToken entity. * @@ -259,50 +215,6 @@ public function getDefaultGraphVersion() return $this->defaultGraphVersion; } - /** - * Returns the redirect login helper. - * - * @return FacebookRedirectLoginHelper - */ - public function getRedirectLoginHelper() - { - return new FacebookRedirectLoginHelper( - $this->getOAuth2Client(), - $this->persistentDataHandler, - $this->urlDetectionHandler - ); - } - - /** - * Returns the JavaScript helper. - * - * @return FacebookJavaScriptHelper - */ - public function getJavaScriptHelper() - { - return new FacebookJavaScriptHelper($this->app, $this->client, $this->defaultGraphVersion); - } - - /** - * Returns the canvas helper. - * - * @return FacebookCanvasHelper - */ - public function getCanvasHelper() - { - return new FacebookCanvasHelper($this->app, $this->client, $this->defaultGraphVersion); - } - - /** - * Returns the page tab helper. - * - * @return FacebookPageTabHelper - */ - public function getPageTabHelper() - { - return new FacebookPageTabHelper($this->app, $this->client, $this->defaultGraphVersion); - } - /** * Sends a GET request to Graph and returns the result. * diff --git a/src/Facebook/Helpers/FacebookCanvasHelper.php b/src/Facebook/Helpers/FacebookCanvasHelper.php deleted file mode 100644 index 7f3466ff7..000000000 --- a/src/Facebook/Helpers/FacebookCanvasHelper.php +++ /dev/null @@ -1,52 +0,0 @@ -signedRequest ? $this->signedRequest->get('app_data') : null; - } - - /** - * Get raw signed request from POST. - * - * @return string|null - */ - public function getRawSignedRequest() - { - return $this->getRawSignedRequestFromPost() ?: null; - } -} diff --git a/src/Facebook/Helpers/FacebookJavaScriptHelper.php b/src/Facebook/Helpers/FacebookJavaScriptHelper.php deleted file mode 100644 index 01a76b8b2..000000000 --- a/src/Facebook/Helpers/FacebookJavaScriptHelper.php +++ /dev/null @@ -1,42 +0,0 @@ -getRawSignedRequestFromCookie(); - } -} diff --git a/src/Facebook/Helpers/FacebookPageTabHelper.php b/src/Facebook/Helpers/FacebookPageTabHelper.php deleted file mode 100644 index c87d0c9ab..000000000 --- a/src/Facebook/Helpers/FacebookPageTabHelper.php +++ /dev/null @@ -1,95 +0,0 @@ -signedRequest) { - return; - } - - $this->pageData = $this->signedRequest->get('page'); - } - - /** - * Returns a value from the page data. - * - * @param string $key - * @param mixed|null $default - * - * @return mixed|null - */ - public function getPageData($key, $default = null) - { - if (isset($this->pageData[$key])) { - return $this->pageData[$key]; - } - - return $default; - } - - /** - * Returns true if the user is an admin. - * - * @return boolean - */ - public function isAdmin() - { - return $this->getPageData('admin') === true; - } - - /** - * Returns the page id if available. - * - * @return string|null - */ - public function getPageId() - { - return $this->getPageData('id'); - } -} diff --git a/src/Facebook/Helpers/FacebookRedirectLoginHelper.php b/src/Facebook/Helpers/FacebookRedirectLoginHelper.php deleted file mode 100644 index d55c52616..000000000 --- a/src/Facebook/Helpers/FacebookRedirectLoginHelper.php +++ /dev/null @@ -1,319 +0,0 @@ -oAuth2Client = $oAuth2Client; - $this->persistentDataHandler = $persistentDataHandler ?: new FacebookSessionPersistentDataHandler(); - $this->urlDetectionHandler = $urlHandler ?: new FacebookUrlDetectionHandler(); - } - - /** - * Returns the persistent data handler. - * - * @return PersistentDataInterface - */ - public function getPersistentDataHandler() - { - return $this->persistentDataHandler; - } - - /** - * Returns the URL detection handler. - * - * @return UrlDetectionInterface - */ - public function getUrlDetectionHandler() - { - return $this->urlDetectionHandler; - } - - /** - * Stores CSRF state and returns a URL to which the user should be sent to in order to continue the login process with Facebook. - * - * @param string $redirectUrl The URL Facebook should redirect users to after login. - * @param array $scope List of permissions to request during login. - * @param array $params An array of parameters to generate URL. - * @param string $separator The separator to use in http_build_query(). - * - * @return string - */ - private function makeUrl($redirectUrl, array $scope, array $params = [], $separator = '&') - { - $state = $this->persistentDataHandler->get('state') ?: $this->getPseudoRandomString(); - $this->persistentDataHandler->set('state', $state); - - return $this->oAuth2Client->getAuthorizationUrl($redirectUrl, $state, $scope, $params, $separator); - } - - private function getPseudoRandomString() - { - return bin2hex(random_bytes(static::CSRF_LENGTH)); - } - - /** - * Returns the URL to send the user in order to login to Facebook. - * - * @param string $redirectUrl The URL Facebook should redirect users to after login. - * @param array $scope List of permissions to request during login. - * @param string $separator The separator to use in http_build_query(). - * - * @return string - */ - public function getLoginUrl($redirectUrl, array $scope = [], $separator = '&') - { - return $this->makeUrl($redirectUrl, $scope, [], $separator); - } - - /** - * Returns the URL to send the user in order to log out of Facebook. - * - * @param AccessToken|string $accessToken The access token that will be logged out. - * @param string $next The url Facebook should redirect the user to after a successful logout. - * @param string $separator The separator to use in http_build_query(). - * - * @return string - * - * @throws FacebookSDKException - */ - public function getLogoutUrl($accessToken, $next, $separator = '&') - { - if (!$accessToken instanceof AccessToken) { - $accessToken = new AccessToken($accessToken); - } - - if ($accessToken->isAppAccessToken()) { - throw new FacebookSDKException('Cannot generate a logout URL with an app access token.', 722); - } - - $params = [ - 'next' => $next, - 'access_token' => $accessToken->getValue(), - ]; - - return 'https://www.facebook.com/logout.php?' . http_build_query($params, null, $separator); - } - - /** - * Returns the URL to send the user in order to login to Facebook with permission(s) to be re-asked. - * - * @param string $redirectUrl The URL Facebook should redirect users to after login. - * @param array $scope List of permissions to request during login. - * @param string $separator The separator to use in http_build_query(). - * - * @return string - */ - public function getReRequestUrl($redirectUrl, array $scope = [], $separator = '&') - { - $params = ['auth_type' => 'rerequest']; - - return $this->makeUrl($redirectUrl, $scope, $params, $separator); - } - - /** - * Returns the URL to send the user in order to login to Facebook with user to be re-authenticated. - * - * @param string $redirectUrl The URL Facebook should redirect users to after login. - * @param array $scope List of permissions to request during login. - * @param string $separator The separator to use in http_build_query(). - * - * @return string - */ - public function getReAuthenticationUrl($redirectUrl, array $scope = [], $separator = '&') - { - $params = ['auth_type' => 'reauthenticate']; - - return $this->makeUrl($redirectUrl, $scope, $params, $separator); - } - - /** - * Takes a valid code from a login redirect, and returns an AccessToken entity. - * - * @param string|null $redirectUrl The redirect URL. - * - * @return AccessToken|null - * - * @throws FacebookSDKException - */ - public function getAccessToken($redirectUrl = null) - { - if (!$code = $this->getCode()) { - return null; - } - - $this->validateCsrf(); - $this->resetCsrf(); - - $redirectUrl = $redirectUrl ?: $this->urlDetectionHandler->getCurrentUrl(); - // At minimum we need to remove the state param - $redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl, ['state']); - - return $this->oAuth2Client->getAccessTokenFromCode($code, $redirectUrl); - } - - /** - * Validate the request against a cross-site request forgery. - * - * @throws FacebookSDKException - */ - protected function validateCsrf() - { - $state = $this->getState(); - if (!$state) { - throw new FacebookSDKException('Cross-site request forgery validation failed. Required GET param "state" missing.'); - } - $savedState = $this->persistentDataHandler->get('state'); - if (!$savedState) { - throw new FacebookSDKException('Cross-site request forgery validation failed. Required param "state" missing from persistent data.'); - } - - if (\hash_equals($savedState, $state)) { - return; - } - - throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.'); - } - - /** - * Resets the CSRF so that it doesn't get reused. - */ - private function resetCsrf() - { - $this->persistentDataHandler->set('state', null); - } - - /** - * Return the code. - * - * @return string|null - */ - protected function getCode() - { - return $this->getInput('code'); - } - - /** - * Return the state. - * - * @return string|null - */ - protected function getState() - { - return $this->getInput('state'); - } - - /** - * Return the error code. - * - * @return string|null - */ - public function getErrorCode() - { - return $this->getInput('error_code'); - } - - /** - * Returns the error. - * - * @return string|null - */ - public function getError() - { - return $this->getInput('error'); - } - - /** - * Returns the error reason. - * - * @return string|null - */ - public function getErrorReason() - { - return $this->getInput('error_reason'); - } - - /** - * Returns the error description. - * - * @return string|null - */ - public function getErrorDescription() - { - return $this->getInput('error_description'); - } - - /** - * Returns a value from a GET param. - * - * @param string $key - * - * @return string|null - */ - private function getInput($key) - { - return isset($_GET[$key]) ? $_GET[$key] : null; - } -} diff --git a/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php b/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php deleted file mode 100644 index 0e4feafe6..000000000 --- a/src/Facebook/Helpers/FacebookSignedRequestFromInputHelper.php +++ /dev/null @@ -1,165 +0,0 @@ -app = $app; - $this->oAuth2Client = new OAuth2Client($this->app, $client, $graphVersion); - - $this->instantiateSignedRequest(); - } - - /** - * Instantiates a new SignedRequest entity. - * - * @param string|null - */ - public function instantiateSignedRequest($rawSignedRequest = null) - { - $rawSignedRequest = $rawSignedRequest ?: $this->getRawSignedRequest(); - - if (!$rawSignedRequest) { - return; - } - - $this->signedRequest = new SignedRequest($this->app, $rawSignedRequest); - } - - /** - * Returns an AccessToken entity from the signed request. - * - * @return AccessToken|null - * - * @throws \Facebook\Exceptions\FacebookSDKException - */ - public function getAccessToken() - { - if ($this->signedRequest && $this->signedRequest->hasOAuthData()) { - $code = $this->signedRequest->get('code'); - $accessToken = $this->signedRequest->get('oauth_token'); - - if ($code && !$accessToken) { - return $this->oAuth2Client->getAccessTokenFromCode($code); - } - - $expiresAt = $this->signedRequest->get('expires', 0); - - return new AccessToken($accessToken, $expiresAt); - } - - return null; - } - - /** - * Returns the SignedRequest entity. - * - * @return SignedRequest|null - */ - public function getSignedRequest() - { - return $this->signedRequest; - } - - /** - * Returns the user_id if available. - * - * @return string|null - */ - public function getUserId() - { - return $this->signedRequest ? $this->signedRequest->getUserId() : null; - } - - /** - * Get raw signed request from input. - * - * @return string|null - */ - abstract public function getRawSignedRequest(); - - /** - * Get raw signed request from POST input. - * - * @return string|null - */ - public function getRawSignedRequestFromPost() - { - if (isset($_POST['signed_request'])) { - return $_POST['signed_request']; - } - - return null; - } - - /** - * Get raw signed request from cookie set from the Javascript SDK. - * - * @return string|null - */ - public function getRawSignedRequestFromCookie() - { - if (isset($_COOKIE['fbsr_' . $this->app->getId()])) { - return $_COOKIE['fbsr_' . $this->app->getId()]; - } - - return null; - } -} diff --git a/src/Facebook/PersistentData/FacebookMemoryPersistentDataHandler.php b/src/Facebook/PersistentData/FacebookMemoryPersistentDataHandler.php deleted file mode 100644 index 4b7c87ea9..000000000 --- a/src/Facebook/PersistentData/FacebookMemoryPersistentDataHandler.php +++ /dev/null @@ -1,53 +0,0 @@ -sessionData[$key]) ? $this->sessionData[$key] : null; - } - - /** - * @inheritdoc - */ - public function set($key, $value) - { - $this->sessionData[$key] = $value; - } -} diff --git a/src/Facebook/PersistentData/FacebookSessionPersistentDataHandler.php b/src/Facebook/PersistentData/FacebookSessionPersistentDataHandler.php deleted file mode 100644 index 9123e3dc7..000000000 --- a/src/Facebook/PersistentData/FacebookSessionPersistentDataHandler.php +++ /dev/null @@ -1,76 +0,0 @@ -sessionPrefix . $key])) { - return $_SESSION[$this->sessionPrefix . $key]; - } - - return null; - } - - /** - * @inheritdoc - */ - public function set($key, $value) - { - $_SESSION[$this->sessionPrefix . $key] = $value; - } -} diff --git a/src/Facebook/PersistentData/PersistentDataFactory.php b/src/Facebook/PersistentData/PersistentDataFactory.php deleted file mode 100644 index 18fb8fd5b..000000000 --- a/src/Facebook/PersistentData/PersistentDataFactory.php +++ /dev/null @@ -1,65 +0,0 @@ -getHttpScheme() . '://' . $this->getHostName() . $this->getServerVar('REQUEST_URI'); - } - - /** - * Get the currently active URL scheme. - * - * @return string - */ - protected function getHttpScheme() - { - return $this->isBehindSsl() ? 'https' : 'http'; - } - - /** - * Tries to detect if the server is running behind an SSL. - * - * @return boolean - */ - protected function isBehindSsl() - { - // Check for proxy first - $protocol = $this->getHeader('X_FORWARDED_PROTO'); - if ($protocol) { - return $this->protocolWithActiveSsl($protocol); - } - - $protocol = $this->getServerVar('HTTPS'); - if ($protocol) { - return $this->protocolWithActiveSsl($protocol); - } - - return (string)$this->getServerVar('SERVER_PORT') === '443'; - } - - /** - * Detects an active SSL protocol value. - * - * @param string $protocol - * - * @return boolean - */ - protected function protocolWithActiveSsl($protocol) - { - $protocol = strtolower((string)$protocol); - - return in_array($protocol, ['on', '1', 'https', 'ssl'], true); - } - - /** - * Tries to detect the host name of the server. - * - * Some elements adapted from - * - * @see https://github.com/symfony/HttpFoundation/blob/master/Request.php - * - * @return string - */ - protected function getHostName() - { - // Check for proxy first - $header = $this->getHeader('X_FORWARDED_HOST'); - if ($header && $this->isValidForwardedHost($header)) { - $elements = explode(',', $header); - $host = $elements[count($elements) - 1]; - } elseif (!$host = $this->getHeader('HOST')) { - if (!$host = $this->getServerVar('SERVER_NAME')) { - $host = $this->getServerVar('SERVER_ADDR'); - } - } - - // trim and remove port number from host - // host is lowercase as per RFC 952/2181 - $host = strtolower(preg_replace('/:\d+$/', '', trim($host))); - - // Port number - $scheme = $this->getHttpScheme(); - $port = $this->getCurrentPort(); - $appendPort = ':' . $port; - - // Don't append port number if a normal port. - if (($scheme == 'http' && $port == '80') || ($scheme == 'https' && $port == '443')) { - $appendPort = ''; - } - - return $host . $appendPort; - } - - protected function getCurrentPort() - { - // Check for proxy first - $port = $this->getHeader('X_FORWARDED_PORT'); - if ($port) { - return (string)$port; - } - - $protocol = (string)$this->getHeader('X_FORWARDED_PROTO'); - if ($protocol === 'https') { - return '443'; - } - - return (string)$this->getServerVar('SERVER_PORT'); - } - - /** - * Returns the a value from the $_SERVER super global. - * - * @param string $key - * - * @return string - */ - protected function getServerVar($key) - { - return isset($_SERVER[$key]) ? $_SERVER[$key] : ''; - } - - /** - * Gets a value from the HTTP request headers. - * - * @param string $key - * - * @return string - */ - protected function getHeader($key) - { - return $this->getServerVar('HTTP_' . $key); - } - - /** - * Checks if the value in X_FORWARDED_HOST is a valid hostname - * Could prevent unintended redirections - * - * @param string $header - * - * @return boolean - */ - protected function isValidForwardedHost($header) - { - $elements = explode(',', $header); - $host = $elements[count($elements) - 1]; - - return preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $host) //valid chars check - && 0 < strlen($host) && strlen($host) < 254 //overall length check - && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $host); //length of each label - } -} diff --git a/src/Facebook/Url/UrlDetectionInterface.php b/src/Facebook/Url/UrlDetectionInterface.php deleted file mode 100644 index dca38a0c3..000000000 --- a/src/Facebook/Url/UrlDetectionInterface.php +++ /dev/null @@ -1,39 +0,0 @@ -response = '{"data":{"user_id":"444"}}'; - } - - public function setAccessTokenResponse() - { - $this->response = '{"access_token":"my_access_token","expires":"1422115200"}'; - } - - public function setCodeResponse() - { - $this->response = '{"code":"my_neat_code"}'; - } - - public function sendRequest(FacebookRequest $request) - { - return new FacebookResponse( - $request, - $this->response, - 200, - [] - ); - } -} diff --git a/tests/Authentication/OAuth2ClientTest.php b/tests/Authentication/OAuth2ClientTest.php deleted file mode 100644 index e52846a16..000000000 --- a/tests/Authentication/OAuth2ClientTest.php +++ /dev/null @@ -1,168 +0,0 @@ -client = new FooFacebookClientForOAuth2Test(); - $this->oauth = new OAuth2Client($app, $this->client, static::TESTING_GRAPH_VERSION); - } - - public function testCanGetMetadataFromAnAccessToken() - { - $this->client->setMetadataResponse(); - - $metadata = $this->oauth->debugToken('baz_token'); - - $this->assertInstanceOf(AccessTokenMetadata::class, $metadata); - $this->assertEquals('444', $metadata->getUserId()); - - $expectedParams = [ - 'input_token' => 'baz_token', - 'access_token' => '123|foo_secret', - 'appsecret_proof' => 'de753c58fd58b03afca2340bbaeb4ecf987b5de4c09e39a63c944dd25efbc234', - ]; - - $request = $this->oauth->getLastRequest(); - $this->assertEquals('GET', $request->getMethod()); - $this->assertEquals('/debug_token', $request->getEndpoint()); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); - } - - public function testCanBuildAuthorizationUrl() - { - $scope = ['email', 'base_foo']; - $authUrl = $this->oauth->getAuthorizationUrl('https://foo.bar', 'foo_state', $scope, ['foo' => 'bar'], '*'); - - $this->assertContains('*', $authUrl); - - $expectedUrl = 'https://www.facebook.com/' . static::TESTING_GRAPH_VERSION . '/dialog/oauth?'; - $this->assertStringStartsWith($expectedUrl, $authUrl, 'Unexpected base authorization URL returned from getAuthorizationUrl().'); - - $params = [ - 'client_id' => '123', - 'redirect_uri' => 'https://foo.bar', - 'state' => 'foo_state', - 'sdk' => 'php-sdk-' . Facebook::VERSION, - 'scope' => implode(',', $scope), - 'foo' => 'bar', - ]; - foreach ($params as $key => $value) { - $this->assertContains($key . '=' . urlencode($value), $authUrl); - } - } - - public function testCanGetAccessTokenFromCode() - { - $this->client->setAccessTokenResponse(); - - $accessToken = $this->oauth->getAccessTokenFromCode('bar_code', 'foo_uri'); - - $this->assertInstanceOf(AccessToken::class, $accessToken); - $this->assertEquals('my_access_token', $accessToken->getValue()); - - $expectedParams = [ - 'code' => 'bar_code', - 'redirect_uri' => 'foo_uri', - 'client_id' => '123', - 'client_secret' => 'foo_secret', - 'access_token' => '123|foo_secret', - 'appsecret_proof' => 'de753c58fd58b03afca2340bbaeb4ecf987b5de4c09e39a63c944dd25efbc234', - ]; - - $request = $this->oauth->getLastRequest(); - $this->assertEquals('GET', $request->getMethod()); - $this->assertEquals('/oauth/access_token', $request->getEndpoint()); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals(static::TESTING_GRAPH_VERSION, $request->getGraphVersion()); - } - - public function testCanGetLongLivedAccessToken() - { - $this->client->setAccessTokenResponse(); - - $accessToken = $this->oauth->getLongLivedAccessToken('short_token'); - - $this->assertEquals('my_access_token', $accessToken->getValue()); - - $expectedParams = [ - 'grant_type' => 'fb_exchange_token', - 'fb_exchange_token' => 'short_token', - 'client_id' => '123', - 'client_secret' => 'foo_secret', - 'access_token' => '123|foo_secret', - 'appsecret_proof' => 'de753c58fd58b03afca2340bbaeb4ecf987b5de4c09e39a63c944dd25efbc234', - ]; - - $request = $this->oauth->getLastRequest(); - $this->assertEquals($expectedParams, $request->getParams()); - } - - public function testCanGetCodeFromLongLivedAccessToken() - { - $this->client->setCodeResponse(); - - $code = $this->oauth->getCodeFromLongLivedAccessToken('long_token', 'foo_uri'); - - $this->assertEquals('my_neat_code', $code); - - $expectedParams = [ - 'access_token' => 'long_token', - 'redirect_uri' => 'foo_uri', - 'client_id' => '123', - 'client_secret' => 'foo_secret', - 'appsecret_proof' => '7e91300ea91be4166282611d4fc700b473466f3ea2981dafbf492fc096995bf1', - ]; - - $request = $this->oauth->getLastRequest(); - $this->assertEquals($expectedParams, $request->getParams()); - $this->assertEquals('/oauth/client_code', $request->getEndpoint()); - } -} diff --git a/tests/FacebookTest.php b/tests/FacebookTest.php index 82406a824..cd285d0fa 100644 --- a/tests/FacebookTest.php +++ b/tests/FacebookTest.php @@ -30,13 +30,9 @@ use Facebook\GraphNodes\GraphEdge; use Facebook\Tests\Fixtures\FakeGraphApiForResumableUpload; use Facebook\Tests\Fixtures\FooClientInterface; -use Facebook\Tests\Fixtures\FooPersistentDataInterface; -use Facebook\Tests\Fixtures\FooUrlDetectionInterface; use Facebook\HttpClients\FacebookCurlHttpClient; use Facebook\HttpClients\FacebookStreamHttpClient; use Facebook\HttpClients\FacebookGuzzleHttpClient; -use Facebook\PersistentData\FacebookMemoryPersistentDataHandler; -use Facebook\Url\FacebookUrlDetectionHandler; use Facebook\FacebookResponse; use Facebook\GraphNodes\GraphUser; @@ -138,49 +134,6 @@ public function testGuzzleHttpClientHandlerCanBeForced() ); } - /** - * @expectedException \InvalidArgumentException - */ - public function testSettingAnInvalidPersistentDataHandlerThrows() - { - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'foo_handler', - ]); - new Facebook($config); - } - - public function testPersistentDataHandlerCanBeForced() - { - $config = array_merge($this->config, [ - 'persistent_data_handler' => 'memory' - ]); - $fb = new Facebook($config); - $this->assertInstanceOf( - FacebookMemoryPersistentDataHandler::class, - $fb->getRedirectLoginHelper()->getPersistentDataHandler() - ); - } - - public function testSettingAnInvalidUrlHandlerThrows() - { - $expectedException = (PHP_MAJOR_VERSION > 5 && class_exists('TypeError')) - ? 'TypeError' - : \PHPUnit_Framework_Error::class; - - $this->setExpectedException($expectedException); - - $config = array_merge($this->config, [ - 'url_detection_handler' => 'foo_handler', - ]); - new Facebook($config); - } - - public function testTheUrlHandlerWillDefaultToTheFacebookImplementation() - { - $fb = new Facebook($this->config); - $this->assertInstanceOf(FacebookUrlDetectionHandler::class, $fb->getUrlDetectionHandler()); - } - public function testAnAccessTokenCanBeSetAsAString() { $fb = new Facebook($this->config); @@ -236,8 +189,6 @@ public function testCanInjectCustomHandlers() { $config = array_merge($this->config, [ 'http_client_handler' => new FooClientInterface(), - 'persistent_data_handler' => new FooPersistentDataInterface(), - 'url_detection_handler' => new FooUrlDetectionInterface(), ]); $fb = new Facebook($config); @@ -245,14 +196,6 @@ public function testCanInjectCustomHandlers() FooClientInterface::class, $fb->getClient()->getHttpClientHandler() ); - $this->assertInstanceOf( - FooPersistentDataInterface::class, - $fb->getRedirectLoginHelper()->getPersistentDataHandler() - ); - $this->assertInstanceOf( - FooUrlDetectionInterface::class, - $fb->getRedirectLoginHelper()->getUrlDetectionHandler() - ); } public function testPaginationReturnsProperResponse() diff --git a/tests/Fixtures/FooPersistentDataInterface.php b/tests/Fixtures/FooPersistentDataInterface.php deleted file mode 100644 index 5ff57938b..000000000 --- a/tests/Fixtures/FooPersistentDataInterface.php +++ /dev/null @@ -1,38 +0,0 @@ -getParams(); - $rawResponse = json_encode([ - 'access_token' => 'foo_access_token_from:' . $params['code'], - ]); - - return new FacebookResponse($request, $rawResponse, 200); - } -} diff --git a/tests/Fixtures/FooUrlDetectionInterface.php b/tests/Fixtures/FooUrlDetectionInterface.php deleted file mode 100644 index 8ee70c303..000000000 --- a/tests/Fixtures/FooUrlDetectionInterface.php +++ /dev/null @@ -1,34 +0,0 @@ -helper = new FacebookCanvasHelper($app, new FacebookClient(), 'v0.0'); - } - - public function testSignedRequestDataCanBeRetrievedFromPostData() - { - $_POST['signed_request'] = $this->rawSignedRequestAuthorized; - - $rawSignedRequest = $this->helper->getRawSignedRequest(); - - $this->assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); - } -} diff --git a/tests/Helpers/FacebookJavaScriptHelperTest.php b/tests/Helpers/FacebookJavaScriptHelperTest.php deleted file mode 100644 index d96590145..000000000 --- a/tests/Helpers/FacebookJavaScriptHelperTest.php +++ /dev/null @@ -1,45 +0,0 @@ -rawSignedRequestAuthorized; - - $app = new FacebookApp('123', 'foo_app_secret'); - $helper = new FacebookJavaScriptHelper($app, new FacebookClient(), 'v0.0'); - - $rawSignedRequest = $helper->getRawSignedRequest(); - - $this->assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); - } -} diff --git a/tests/Helpers/FacebookPageTabHelperTest.php b/tests/Helpers/FacebookPageTabHelperTest.php deleted file mode 100644 index 0fd37de78..000000000 --- a/tests/Helpers/FacebookPageTabHelperTest.php +++ /dev/null @@ -1,46 +0,0 @@ -rawSignedRequestAuthorized; - - $app = new FacebookApp('123', 'foo_app_secret'); - $helper = new FacebookPageTabHelper($app, new FacebookClient(), 'v0.0'); - - $this->assertFalse($helper->isAdmin()); - $this->assertEquals('42', $helper->getPageId()); - $this->assertEquals('42', $helper->getPageData('id')); - $this->assertEquals('default', $helper->getPageData('foo', 'default')); - } -} diff --git a/tests/Helpers/FacebookRedirectLoginHelperTest.php b/tests/Helpers/FacebookRedirectLoginHelperTest.php deleted file mode 100644 index 1a429551d..000000000 --- a/tests/Helpers/FacebookRedirectLoginHelperTest.php +++ /dev/null @@ -1,101 +0,0 @@ -persistentDataHandler = new FacebookMemoryPersistentDataHandler(); - - $app = new FacebookApp('123', 'foo_app_secret'); - $oAuth2Client = new FooRedirectLoginOAuth2Client($app, new FacebookClient(), 'v1337'); - $this->redirectLoginHelper = new FacebookRedirectLoginHelper($oAuth2Client, $this->persistentDataHandler); - } - - public function testLoginURL() - { - $scope = ['foo', 'bar']; - $loginUrl = $this->redirectLoginHelper->getLoginUrl(self::REDIRECT_URL, $scope); - - $expectedUrl = 'https://www.facebook.com/v1337/dialog/oauth?'; - $this->assertStringStartsWith($expectedUrl, $loginUrl, 'Unexpected base login URL returned from getLoginUrl().'); - - $params = [ - 'client_id' => '123', - 'redirect_uri' => self::REDIRECT_URL, - 'state' => $this->persistentDataHandler->get('state'), - 'sdk' => 'php-sdk-' . Facebook::VERSION, - 'scope' => implode(',', $scope), - ]; - foreach ($params as $key => $value) { - $this->assertContains($key . '=' . urlencode($value), $loginUrl); - } - } - - public function testLogoutURL() - { - $logoutUrl = $this->redirectLoginHelper->getLogoutUrl('foo_token', self::REDIRECT_URL); - $expectedUrl = 'https://www.facebook.com/logout.php?'; - $this->assertStringStartsWith($expectedUrl, $logoutUrl, 'Unexpected base logout URL returned from getLogoutUrl().'); - - $params = [ - 'next' => self::REDIRECT_URL, - 'access_token' => 'foo_token', - ]; - foreach ($params as $key => $value) { - $this->assertContains($key . '=' . urlencode($value), $logoutUrl); - } - } - - public function testAnAccessTokenCanBeObtainedFromRedirect() - { - $this->persistentDataHandler->set('state', 'foo_state'); - $_GET['state'] = 'foo_state'; - $_GET['code'] = 'foo_code'; - - $accessToken = $this->redirectLoginHelper->getAccessToken(self::REDIRECT_URL); - - $this->assertEquals('foo_token_from_code|foo_code|' . self::REDIRECT_URL, (string)$accessToken); - } -} diff --git a/tests/Helpers/FacebookSignedRequestFromInputHelperTest.php b/tests/Helpers/FacebookSignedRequestFromInputHelperTest.php deleted file mode 100644 index e3f6f82b9..000000000 --- a/tests/Helpers/FacebookSignedRequestFromInputHelperTest.php +++ /dev/null @@ -1,91 +0,0 @@ -helper = new FooSignedRequestHelper($app, new FooSignedRequestHelperFacebookClient(), 'v0.0'); - } - - public function testSignedRequestDataCanBeRetrievedFromPostData() - { - $_POST['signed_request'] = 'foo_signed_request'; - - $rawSignedRequest = $this->helper->getRawSignedRequestFromPost(); - - $this->assertEquals('foo_signed_request', $rawSignedRequest); - } - - public function testSignedRequestDataCanBeRetrievedFromCookieData() - { - $_COOKIE['fbsr_123'] = 'foo_signed_request'; - - $rawSignedRequest = $this->helper->getRawSignedRequestFromCookie(); - - $this->assertEquals('foo_signed_request', $rawSignedRequest); - } - - public function testAccessTokenWillBeNullWhenAUserHasNotYetAuthorizedTheApp() - { - $this->helper->instantiateSignedRequest($this->rawSignedRequestUnauthorized); - $accessToken = $this->helper->getAccessToken(); - - $this->assertNull($accessToken); - } - - public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsAnAccessToken() - { - $this->helper->instantiateSignedRequest($this->rawSignedRequestAuthorizedWithAccessToken); - $accessToken = $this->helper->getAccessToken(); - - $this->assertInstanceOf(AccessToken::class, $accessToken); - $this->assertEquals('foo_token', $accessToken->getValue()); - } - - public function testAnAccessTokenCanBeInstantiatedWhenRedirectReturnsACode() - { - $this->helper->instantiateSignedRequest($this->rawSignedRequestAuthorizedWithCode); - $accessToken = $this->helper->getAccessToken(); - - $this->assertInstanceOf(AccessToken::class, $accessToken); - $this->assertEquals('foo_access_token_from:foo_code', $accessToken->getValue()); - } -} diff --git a/tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php b/tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php deleted file mode 100644 index 89717f831..000000000 --- a/tests/PersistentData/FacebookMemoryPersistentDataHandlerTest.php +++ /dev/null @@ -1,46 +0,0 @@ -set('foo', 'bar'); - $value = $handler->get('foo'); - - $this->assertEquals('bar', $value); - } - - public function testGettingAValueThatDoesntExistWillReturnNull() - { - $handler = new FacebookMemoryPersistentDataHandler(); - $value = $handler->get('does_not_exist'); - - $this->assertNull($value); - } -} diff --git a/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php b/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php deleted file mode 100644 index 752d275de..000000000 --- a/tests/PersistentData/FacebookSessionPersistentDataHandlerTest.php +++ /dev/null @@ -1,62 +0,0 @@ -set('foo', 'bar'); - - $this->assertEquals('bar', $_SESSION['FBRLH_foo']); - } - - public function testCanGetAValue() - { - $_SESSION['FBRLH_faz'] = 'baz'; - $handler = new FacebookSessionPersistentDataHandler($enableSessionCheck = false); - $value = $handler->get('faz'); - - $this->assertEquals('baz', $value); - } - - public function testGettingAValueThatDoesntExistWillReturnNull() - { - $handler = new FacebookSessionPersistentDataHandler($enableSessionCheck = false); - $value = $handler->get('does_not_exist'); - - $this->assertNull($value); - } -} diff --git a/tests/PersistentData/PersistentDataFactoryTest.php b/tests/PersistentData/PersistentDataFactoryTest.php deleted file mode 100644 index c79c76b73..000000000 --- a/tests/PersistentData/PersistentDataFactoryTest.php +++ /dev/null @@ -1,69 +0,0 @@ -assertInstanceOf(self::COMMON_INTERFACE, $persistentDataHandler); - $this->assertInstanceOf($expected, $persistentDataHandler); - } - - /** - * @return array - */ - public function persistentDataHandlerProviders() - { - $handlers = [ - ['memory', self::COMMON_NAMESPACE . 'FacebookMemoryPersistentDataHandler'], - [new FacebookMemoryPersistentDataHandler(), self::COMMON_NAMESPACE . 'FacebookMemoryPersistentDataHandler'], - [new FacebookSessionPersistentDataHandler(false), self::COMMON_NAMESPACE . 'FacebookSessionPersistentDataHandler'], - [null, self::COMMON_INTERFACE], - ]; - - if (session_status() === PHP_SESSION_ACTIVE) { - $handlers[] = ['session', self::COMMON_NAMESPACE . 'FacebookSessionPersistentDataHandler']; - } - - return $handlers; - } -} diff --git a/tests/Url/FacebookUrlDetectionHandlerTest.php b/tests/Url/FacebookUrlDetectionHandlerTest.php deleted file mode 100644 index b623c0524..000000000 --- a/tests/Url/FacebookUrlDetectionHandlerTest.php +++ /dev/null @@ -1,134 +0,0 @@ - 'foo.bar', - 'SERVER_PORT' => '80', - 'REQUEST_URI' => '/baz?foo=123', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('http://foo.bar/baz?foo=123', $currentUri); - } - - public function testProperlyGeneratesSecureUrlFromCommonScenario() - { - $_SERVER = [ - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '443', - 'REQUEST_URI' => '/baz?foo=123', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('https://foo.bar/baz?foo=123', $currentUri); - } - - public function testProperlyGeneratesUrlFromProxy() - { - $_SERVER = [ - 'HTTP_X_FORWARDED_PORT' => '80', - 'HTTP_X_FORWARDED_PROTO' => 'http', - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '80', - 'REQUEST_URI' => '/baz?foo=123', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('http://foo.bar/baz?foo=123', $currentUri); - } - - public function testProperlyGeneratesSecureUrlFromProxy() - { - $_SERVER = [ - 'HTTP_X_FORWARDED_PORT' => '443', - 'HTTP_X_FORWARDED_PROTO' => 'https', - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '80', - 'REQUEST_URI' => '/baz?foo=123', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('https://foo.bar/baz?foo=123', $currentUri); - } - - public function testProperlyGeneratesUrlWithCustomPort() - { - $_SERVER = [ - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '1337', - 'REQUEST_URI' => '/foo.php', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('http://foo.bar:1337/foo.php', $currentUri); - } - - public function testProperlyGeneratesSecureUrlWithCustomPort() - { - $_SERVER = [ - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '1337', - 'REQUEST_URI' => '/foo.php', - 'HTTPS' => 'On', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('https://foo.bar:1337/foo.php', $currentUri); - } - - public function testProperlyGeneratesUrlWithCustomPortFromProxy() - { - $_SERVER = [ - 'HTTP_X_FORWARDED_PORT' => '8888', - 'HTTP_X_FORWARDED_PROTO' => 'http', - 'HTTP_HOST' => 'foo.bar', - 'SERVER_PORT' => '80', - 'REQUEST_URI' => '/foo.php', - ]; - - $urlHandler = new FacebookUrlDetectionHandler(); - $currentUri = $urlHandler->getCurrentUrl(); - - $this->assertEquals('http://foo.bar:8888/foo.php', $currentUri); - } -}