Start to rebrand it as Diaspora

This commit is contained in:
Phyks 2015-01-17 23:21:25 +01:00
parent 3205f6049b
commit 1238e052ff
80 changed files with 46 additions and 11773 deletions

View File

@ -1,6 +1,6 @@
<?php
namespace IdnoPlugins\Facebook {
namespace IdnoPlugins\Diaspora {
class Main extends \Idno\Common\Plugin
{

View File

@ -1,13 +1,13 @@
<?php
/**
* Facebook pages
* Diaspora pages
*/
namespace IdnoPlugins\Facebook\Pages {
namespace IdnoPlugins\Diaspora\Pages {
/**
* Default class to serve Facebook-related account settings
* Default class to serve Diaspora-related account settings
*/
class Account extends \Idno\Common\Page
{
@ -15,25 +15,25 @@
function getContent()
{
$this->gatekeeper(); // Logged-in users only
if ($facebook = \Idno\Core\site()->plugins()->get('Facebook')) {
$login_url = $facebook->getAuthURL();
if ($diaspora = \Idno\Core\site()->plugins()->get('Diaspora')) {
$login_url = $diaspora->getAuthURL();
}
$t = \Idno\Core\site()->template();
$body = $t->__(array('login_url' => $login_url))->draw('account/facebook');
$t->__(array('title' => 'Facebook', 'body' => $body))->drawPage();
$body = $t->__(array('login_url' => $login_url))->draw('account/diaspora');
$t->__(array('title' => 'Diaspora', 'body' => $body))->drawPage();
}
function postContent() {
$this->gatekeeper(); // Logged-in users only
if (($this->getInput('remove'))) {
$user = \Idno\Core\site()->session()->currentUser();
$user->facebook = array();
$user->diaspora = array();
$user->save();
\Idno\Core\site()->session()->addMessage('Your Facebook settings have been removed from your account.');
\Idno\Core\site()->session()->addMessage('Your Diaspora settings have been removed from your account.');
}
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/facebook/');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/');
}
}
}
}

View File

@ -1,13 +1,13 @@
<?php
/**
* Facebook pages
* Diaspora pages
*/
namespace IdnoPlugins\Facebook\Pages {
namespace IdnoPlugins\Diaspora\Pages {
/**
* Default class to serve Facebook settings in administration
* Default class to serve Diaspora settings in administration
*/
class Admin extends \Idno\Common\Page
{
@ -16,23 +16,23 @@
{
$this->adminGatekeeper(); // Admins only
$t = \Idno\Core\site()->template();
$body = $t->draw('admin/facebook');
$t->__(array('title' => 'Facebook', 'body' => $body))->drawPage();
$body = $t->draw('admin/diaspora');
$t->__(array('title' => 'Diaspora', 'body' => $body))->drawPage();
}
function postContent() {
$this->adminGatekeeper(); // Admins only
$appId = $this->getInput('appId');
$secret = $this->getInput('secret');
\Idno\Core\site()->config->config['facebook'] = array(
\Idno\Core\site()->config->config['diaspora'] = array(
'appId' => $appId,
'secret' => $secret
);
\Idno\Core\site()->config()->save();
\Idno\Core\site()->session()->addMessage('Your Facebook application details were saved.');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'admin/facebook/');
\Idno\Core\site()->session()->addMessage('Your Diaspora application details were saved.');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'admin/diaspora/');
}
}
}
}

View File

@ -1,13 +1,13 @@
<?php
/**
* Facebook pages
* Diaspora pages
*/
namespace IdnoPlugins\Facebook\Pages {
namespace IdnoPlugins\Diaspora\Pages {
/**
* Default class to serve the Facebook callback
* Default class to serve the Diaspora callback
*/
class Callback extends \Idno\Common\Page
{
@ -15,20 +15,20 @@
function getContent()
{
$this->gatekeeper(); // Logged-in users only
if ($facebook = \Idno\Core\site()->plugins()->get('Facebook')) {
if ($facebookAPI = $facebook->connect()) {
/* @var \IdnoPlugins\Facebook\FacebookAPI $facebookAPI */
if ($session = $facebookAPI->getSessionOnLogin()) {
if ($diaspora = \Idno\Core\site()->plugins()->get('Diaspora')) {
if ($diasporaAPI = $diaspora->connect()) {
/* @var \IdnoPlugins\diaspora\diasporaAPI $diasporaAPI */
if ($session = $diasporaAPI->getSessionOnLogin()) {
$user = \Idno\Core\site()->session()->currentUser();
$access_token = $session->getToken();
$facebookAPI->setAccessToken($access_token);
if ($person = $facebookAPI->api('/me','GET')) {
$diasporaAPI->setAccessToken($access_token);
if ($person = $diasporaAPI->api('/me','GET')) {
$name = $person['response']->getProperty('name');
$id = $person['response']->getProperty('id');
$user->facebook[$id] = ['id' => $id, 'access_token' => $access_token, 'name' => $name];
\Idno\Core\site()->syndication()->registerServiceAccount('facebook', $id, $name);
$user->diaspora[$id] = ['id' => $id, 'access_token' => $access_token, 'name' => $name];
\Idno\Core\site()->syndication()->registerServiceAccount('diaspora', $id, $name);
if (\Idno\Core\site()->config()->multipleSyndicationAccounts()) {
if ($companies = $facebookAPI->api('/me/accounts','GET')) {
if ($companies = $diasporaAPI->api('/me/accounts','GET')) {
if (!empty($companies['response'])) {
foreach($companies['response']->asArray() as $company_container) {
foreach($company_container as $company) {
@ -38,8 +38,8 @@
$id = $company['id'];
$name = $company['name'];
$access_token = $company['access_token'];
$user->facebook[$id] = ['id' => $id, 'access_token' => $access_token, 'name' => $name, 'page' => true];
\Idno\Core\site()->syndication()->registerServiceAccount('facebook', $id, $name);
$user->diaspora[$id] = ['id' => $id, 'access_token' => $access_token, 'name' => $name, 'page' => true];
\Idno\Core\site()->syndication()->registerServiceAccount('diaspora', $id, $name);
}
}
}
@ -48,7 +48,7 @@
}
}
} else {
$user->facebook = array('access_token' => $access_token);
$user->diaspora = array('access_token' => $access_token);
}
$user->save();
}
@ -58,9 +58,9 @@
unset($_SESSION['onboarding_passthrough']);
$this->forward(\Idno\Core\site()->config()->getURL() . 'begin/connect-forwarder');
}
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/facebook/');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/');
}
}
}
}

View File

@ -1,40 +0,0 @@
<?php
/**
* Plugin administration
*/
namespace IdnoPlugins\Facebook\Pages {
class Deauth extends \Idno\Common\Page
{
function getContent()
{
$this->gatekeeper(); // Logged-in users only
if ($twitter = \Idno\Core\site()->plugins()->get('Facebook')) {
if ($user = \Idno\Core\site()->session()->currentUser()) {
if ($account = $this->getInput('remove')) {
if (array_key_exists($account, $user->facebook)) {
unset($user->facebook[$account]);
} else {
$user->facebook = false;
}
}
$user->save();
\Idno\Core\site()->session()->refreshSessionUser($user);
if (!empty($user->link_callback)) {
$this->forward($user->link_callback); exit;
}
}
}
$this->forward($_SERVER['HTTP_REFERER']);
}
function postContent() {
$this->getContent();
}
}
}

View File

@ -1,4 +1,4 @@
Facebook for Known
Diaspora for Known
==================
This plugin provides POSSE support for Known.
@ -6,16 +6,11 @@ This plugin provides POSSE support for Known.
Installation
------------
* Drop the Facebook folder into the IdnoPlugins folder of your idno installation.
* Drop the Diaspora folder into the IdnoPlugins folder of your idno installation.
* Log into Known and click on Administration.
* Click "install" next to Facebook.
* Click "install" next to Diaspora.
License
-------
Released under the Apache 2.0 license: http://www.apache.org/licenses/LICENSE-2.0.html
Contains
--------
Also contains the official PHP Facebook SDK.

View File

@ -1,13 +0,0 @@
Contributing
------------
For us to accept contributions you will have to first have signed the
[Contributor License Agreement](https://developers.facebook.com/opensource/cla).
When committing, keep all lines to less than 80 characters, and try to
follow the existing style.
Before creating a pull request, squash your commits into a single commit.
Add the comments where needed, and provide ample explanation in the
commit message.

View File

@ -1,19 +0,0 @@
Copyright 2014 Facebook, Inc.
You are hereby granted a non-exclusive, worldwide, royalty-free license to
use, copy, modify, and distribute this software in source code or binary
form for use in connection with the web services and APIs provided by
Facebook.
As with any software that integrates with the Facebook platform, your use
of this software is subject to the Facebook Developer Principles and
Policies [http://developers.facebook.com/policy/]. This copyright notice
shall be included in all copies or substantial portions of the software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,84 +0,0 @@
Facebook SDK for PHP
====================
[![Latest Stable Version](http://img.shields.io/badge/Latest%20Stable-4.0.12-blue.svg)](https://packagist.org/packages/facebook/php-sdk-v4)
This repository contains the open source PHP SDK that allows you to access Facebook
Platform from your PHP app.
Usage
-----
This version of the Facebook SDK for PHP requires PHP 5.4 or greater.
Minimal example:
```php
<?php
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('YOUR_APP_ID','YOUR_APP_SECRET');
// Use one of the helper classes to get a FacebookSession object.
// FacebookRedirectLoginHelper
// FacebookCanvasLoginHelper
// FacebookJavaScriptLoginHelper
// or create a FacebookSession with a valid access token:
$session = new FacebookSession('access-token-here');
// Get the GraphUser object for the current user:
try {
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo $me->getName();
} catch (FacebookRequestException $e) {
// The Graph API returned an error
} catch (\Exception $e) {
// Some other error occurred
}
```
Complete documentation, installation instructions, and examples are available at:
[https://developers.facebook.com/docs/php](https://developers.facebook.com/docs/php)
Tests
-----
1) [Composer](https://getcomposer.org/) is a prerequisite for running the tests.
Install composer globally, then run `composer install` to install required files.
2) Create a test app on [Facebook Developers](https://developers.facebook.com), then
create `tests/FacebookTestCredentials.php` from `tests/FacebookTestCredentials.php.dist`
and edit it to add your credentials.
3) The tests can be executed by running this command from the root directory:
```bash
./vendor/bin/phpunit
```
Contributing
------------
For us to accept contributions you will have to first have signed the
[Contributor License Agreement](https://developers.facebook.com/opensource/cla).
When committing, keep all lines to less than 80 characters, and try to
follow the existing style.
Before creating a pull request, squash your commits into a single commit.
Add the comments where needed, and provide ample explanation in the
commit message.

View File

@ -1,70 +0,0 @@
<?php
/**
* Copyright 2014 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/**
* You only need this file if you are not using composer.
* Why are you not using composer?
* https://getcomposer.org/
*/
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
throw new Exception('The Facebook SDK v4 requires PHP version 5.4 or higher.');
}
/**
* Register the autoloader for the Facebook SDK classes.
* Based off the official PSR-4 autoloader example found here:
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class)
{
// project-specific namespace prefix
$prefix = 'Facebook\\';
// base directory for the namespace prefix
$base_dir = defined('FACEBOOK_SDK_V4_SRC_DIR') ? FACEBOOK_SDK_V4_SRC_DIR : __DIR__ . '/src/Facebook/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});

View File

@ -1,30 +0,0 @@
{
"name": "facebook/php-sdk-v4",
"description": "Facebook SDK for PHP",
"keywords": ["facebook", "sdk"],
"type": "library",
"homepage": "https://github.com/facebook/facebook-php-sdk-v4",
"license": "Facebook Platform",
"authors": [
{
"name": "Facebook",
"homepage": "https://github.com/facebook/facebook-php-sdk-v4/contributors"
}
],
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"mockery/mockery": "dev-master",
"guzzlehttp/guzzle": "~4.0"
},
"suggest": {
"guzzlehttp/guzzle": "Allows for implementation of the Guzzle HTTP client"
},
"autoload": {
"psr-4": {
"Facebook\\": "src/Facebook/"
}
}
}

View File

@ -1,37 +0,0 @@
<card>
# FacebookCanvasLoginHelper for the Facebook SDK for PHP
A helper class for getting a FacebookSession in a Canvas app
</card>
<card>
## Facebook\FacebookCanvasLoginHelper {#overview}
If your app is loaded through Canvas, Facebook sends a POST request with a signed request. This helper class will handle processing and validating that information with Facebook, and returns a `FacebookSession`.
Usage:
~~~~
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in.
}
~~~~
</card>
<card>
## Instance Methods {#instance-methods}
### getSession {#getsession}
`getSession()`
Processes the POST request from Facebook, if present. Returns a `FacebookSession` or `null`.
</card>

View File

@ -1,39 +0,0 @@
<card>
# FacebookJavaScriptLoginHelper for the Facebook SDK for PHP
A helper class for getting a FacebookSession using the session from the Facebook SDK for JavaScript.
</card>
<card>
## Facebook\FacebookJavaScriptLoginHelper {#overview}
If your web app uses the Facebook SDK for JavaScript, you can access that in your PHP code as well. This helper class will process and validate the cookie data used by the Facebook SDK for JavaScript, returning a `FacebookSession` on success.
Usage:
~~~~
$helper = new FacebookJavaScriptLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in.
}
~~~~
It's important to note that on first access, or if a session has since expired, these methods will operate on data that is one request-cycle stale. 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]
</card>
<card>
## Instance Methods {#instance-methods}
### getSession {#getsession}
`getSession()`
Processes the data available from the Facebook SDK for JavaScript, if present. Returns a `FacebookSession` or `null`.
</card>

View File

@ -1,54 +0,0 @@
<card>
# FacebookRedirectLoginHelper for the Facebook SDK for PHP
A helper class for getting a FacebookSession using the OAuth protocol.
</card>
<card>
## Facebook\FacebookRedirectLoginHelper {#overview}
If your web app uses Facebook Login on the back-end, you'll need to redirect your visitors to a URL at Facebook to initiate a login request. Facebook then redirects the user to your apps callback URL, providing session data. This helper class will generate the login URL for you, and can process and validate the data from Facebook, returning a `FacebookSession` on success.
This class can be extended, and the `storeState($state)` and `loadState()` methods overridden, to store the state check using another method besides the default `$_SESSION`.
Usage:
~~~~
$helper = new FacebookRedirectLoginHelper($redirect_url, $appId = NULL, $appSecret = NULL);
echo '<a href="' . $helper->getLoginUrl() . '">Login with Facebook</a>';
~~~~
Then, in your callback page (at the redirect url) when Facebook sends the user back:
~~~~
$helper = new FacebookRedirectLoginHelper($redirect_url);
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in.
}
~~~~
</card>
<card>
## Instance Methods {#instance-methods}
### getLoginUrl {#getloginurl}
`getLoginUrl()`
Generates the URL to redirect a web visitor to Facebook to login to your app.
### getLogoutUrl {#getlogouturl}
`getLogoutUrl($next_url)`
Generates the URL to redirect a web visitor to Facebook to logout, with a url to redirect to after.
### getSessionFromRedirect {#getsessionfromredirect}
`getSessionFromRedirect()`
Processes the redirect data from Facebook, if present. Returns a `FacebookSession` or `null`.
</card>

View File

@ -1,59 +0,0 @@
<card>
# FacebookRequest for the Facebook SDK for PHP
Represents a request that will be made against the Graph API.
</card>
<card>
## Facebook\FacebookRequest {#overview}
Constructor:
~~~~
$request = new FacebookRequest(
FacebookSession $session,
string $httpMethod,
string $path,
array $params = NULL,
string $version = NULL
);
~~~~
Usage:
~~~~
// Make a new request and execute it.
try {
$response = (new FacebookRequest($session, 'GET', '/me'))->execute();
$object = $response->getGraphObject();
echo $object->getProperty('name');
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
// You can chain methods together and get a strongly typed GraphUser
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className);
echo $me->getName();
~~~~
</card>
<card>
## Instance Methods {#instance-methods}
### execute {#execute}
`execute()`
Returns a `Facebook\FacebookResponse` from this request, from which a strongly-typed result can be retrieved. Throws an exception if the request fails. If the error is returned from Facebook, as opposed to a networking issue, a `Facebook\FacebookRequestException` is thrown.
### getPath {#getpath}
`getPath()`
Returns a copy of the path for the request, not including the version.
### getParameters {#getparams}
`getParameters()`
Returns a copy of the parameters array for the request.
### getSession {#getsession}
`getSession()`
Returns the `Facebook\FacebookSession` object associated with this request.
</card>

View File

@ -1,43 +0,0 @@
<card>
# FacebookRequestException for the Facebook SDK for PHP
Represents an exception thrown by executing a Facebook request.
</card>
<card>
## Facebook\FacebookRequestException {#overview}
This base class has several subclasses:
`FacebookAuthorizationException`
`FacebookClientException`
`FacebookPermissionException`
`FacebookServerException`
`FacebookThrottleException`
`FacebookOtherException`
Whenever a FacebookRequestException is thrown, it will be one of these types.
They are derived from the error information here: https://developers.facebook.com/docs/graph-api/using-graph-api/#errors
</card>
<card>
## Instance Methods {#instance-methods}
`FacebookRequestException` extends from the base `\Exception` class, so `getCode()` and `getMessage()` are available by default.
### getHttpStatusCode {#gethttpstatus}
`getHttpStatusCode()`
Returns the HTTP status code returned with this exception.
### getSubErrorCode {#getsuberrorcode}
`getSubErrorCode()`
Returns the numeric sub-error code returned from Facebook.
### getErrorType {#geterrortype}
`getErrorType()`
Returns the type of error as a string.
### getResponse {#getresponse}
`getResponse()`
Returns the decoded response used to create the exception.
### getRawResponse {#getrawresponse}
`getRawResponse()`
Returns the raw response used to create the exception.
</card>

View File

@ -1,57 +0,0 @@
<card>
# FacebookResponse for the Facebook SDK for PHP
Represents a response from the Graph API.
</card>
<card>
## Facebook\FacebookResponse {#overview}
Usage:
~~~~
// A FacebookResponse is returned from an executed FacebookRequest
try {
$response = (new FacebookRequest($session, 'GET', '/me'))->execute();
// You can get the request back:
$request = $response->getRequest();
// You can get the response as a GraphObject:
$object = $response->getGraphObject();
// You can get the response as a subclass of GraphObject:
$me = $response->getGraphObject(GraphUser::className());
// If this response has multiple pages, you can get a request for the next or previous pages:
$nextPageRequest = $response->getRequestForNextPage();
$previousPageRequest = $response->getRequestForPreviousPage();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
// You can also chain the methods together:
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className);
echo $me->getName();
~~~~
</card>
<card>
## Instance Methods {#instance-methods}
### getGraphObject {#getgraphobject}
`getGraphObject(string $type = 'Facebook\GraphObject')`
Returns the result as a `GraphObject`. If specified, a strongly-typed subclass of `GraphObject` is returned.
### getGraphObjectList {#getgraphobjectlist}
`getGraphObjectList(string $type = 'Facebook\GraphObject')`
Returns an array of `GraphObject` returned by this request. If specified, a strongly-typed subclass of `GraphObject` is returned.
### getRequest {#getrequest}
`getRequest()`
Returns the `FacebookRequest` that produced this response.
### getRequestForNextPage {#getnextpage}
`getRequestForNextPage()`
If the response has paginated data, produces a `FacebookRequest` for the next pge of data.
### getRequestForPreviousPage {#getpreviouspage}
`getRequestForPreviousPage()`
If the response has paginated data, produces a `FacebookRequest` for the previous page of data.
</card>

View File

@ -1,71 +0,0 @@
<card>
# FacebookSession for the Facebook SDK for PHP
Represents a Facebook Session, which is used when making requests to the Graph API.
</card>
<card>
## Facebook\FacebookSession {#overview}
Usage:
~~~~
use Facebook\FacebookSession;
FacebookSession::setDefaultApplication('app-id', 'app-secret');
// If you already have a valid access token:
$session = new FacebookSession('access-token');
// If you're making app-level requests:
$session = FacebookSession::newAppSession();
// To validate the session:
try {
$session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
~~~~
</card>
<card>
## Static Methods {#static-methods}
### setDefaultApplication {#setdefaultapp}
`setDefaultApplication(string $appId, string $appSecret)`
Configures and app ID and secret that will be used by default throughout the SDK (but can be overridden whenever necessary using parameters to other methods.
### validate {#validate}
`validate(Facebook\GraphSessionInfo $sessionInfo, string $appId = NULL, string $appSecret = NULL)`
Ensures that the provided GraphSessionInfo is valid, throwing an exception if not. It does this by ensuring the app ID in the token info matches the given (or default) app ID, ensuring the token itself is valid, and ensuring that the expiration time has not passed.
### newAppSession {#newappsession}
`newAppSession(string $appId = NULL, string $appSecret = NULL)`
Returns a `Facebook\FacebookSession` configured with a token for the app which can be used for publishing and for requesting app-level information.
### newSessionFromSignedRequest {#newsessionfromsr}
`newSessionFromSignedRequest(string $signedRequest)`
Returns a `Facebook\FacebookSession` for the given signed request.
</card>
<card>
## Instance Methods {#instance-methods}
### getToken {#gettoken}
`getToken()`
Returns the token string for the session.
### getSessionInfo {#getsessioninfo}
`getSessionInfo(string $appId = NULL, string $appSecret = NULL)`
Equivalent to calling the /debug_token endpoint of the Graph API to get the details for the access token for this session. Returns a `Facebook\GraphSessionInfo` object.
### getLongLivedSession {#getlonglivedsession}
`getLongLivedSession(string $appId = NULL, string $appSecret = NULL)`
Returns a new `Facebook\FacebookSession` resulting from extending a short-lived access token. This method will make a network request. If you know you already have a long-lived session, you do not need to call this. The only time you get a short-lived session as of March 2014 is from the Facebook SDK for JavaScript. If this session is not short-lived, this method will return `$this`. A long-lived session is on the order of months. A short-lived session is on the order of hours. You can figure out whether a session is short-lived or long-lived by checking the expiration date in the session info, but it's not a precise thing.
### getExchangeToken {#getexchangetoken}
`getExchangeToken(string $appId = NULL, string $appSecret = NULL)`
Returns an exchange token string which can be sent back to clients and exchanged for a device-linked access token. You need this when your user did not log in on a particular device, but you want to be able to make Graph API calls from that device as this user.
### validate {#validatei}
`validate(string $appId = NULL, string $appSecret = NULL)`
Ensures that a session is valid, throwing an exception if not. It does this by fetching the token info, ensuring the app ID in the token info matches the given (or default) app ID, ensuring the token itself is valid, and ensuring that the expiration time has not passed.
</card>

View File

@ -1,155 +0,0 @@
<card>
# GraphObject for the Facebook SDK for PHP
Represents an object returned by the Graph API.
</card>
<card>
## Facebook\GraphObject {#overview}
This base class has several subclasses, some are provided by default:
[__GraphUser__](#user-instance-methods)
[__GraphLocation__](#location-instance-methods)
[__GraphSessionInfo__](#sessioninfo-instance-methods)
Usage:
~~~~
// Get the base class GraphObject from the response
$object = $response->getGraphObject();
// Get the response typed as a GraphUser
$user = $response->getGraphObject(GraphUser::className());
// or convert the base object previously accessed
// $user = $object->cast(GraphUser::className());
// Get the response typed as a GraphLocation
$loc = $response->getGraphObject(GraphLocation::className());
// or convert the base object previously accessed
// $loc = $object->cast(GraphLocation::className());
// User example
echo $object->getProperty('name');
echo $user->getName();
// Location example
echo $object->getProperty('country');
echo $loc->getCountry();
// SessionInfo example
$info = $session->getSessionInfo());
echo $info->getxpiresAt();
~~~~
</card>
<card>
## GraphObject Instance Methods {#instance-methods}
### cast {#cast}
`cast(string $type)`
Returns a new instance of a GraphObject subclass with this objects underlying data.
### asArray {#asarray}
`asArray()`
Returns the raw representation (associative arrays, nested) of this objects underlying data.
### getProperty {#getproperty}
`getProperty(string $name, string $type = 'Facebook\GraphObject')`
Gets the value of a named key for this graph object. If the value is a scalar (string, number, etc.) it will be returned. If it's an associative array, it will be returned as a GraphObject cast to the appropriate subclass type if provided.
### getPropertyAsArray {#getproparray}
`getPropertyAsArray()`
Gets the contents of a named array property on this graph object. If the values are scalar (strings, numbers, etc.) they will be returned as-is. If the values are associative arrays, they will be returned as GraphObjects cast to the appropriate subclass type if provided.
### getPropertyNames
`getPropertyNames()`
Returns an array with the names of all properties present on this graph object.
</card>
<card>
## GraphUser Instance Methods {#user-instance-methods}
### getId {#getid}
`getId()`
Returns the `id` property for the user as a string if present.
### getName {#getname}
`getName()`
Returns the `name` property for the user as a string if present.
### getFirstName {#getfirstname}
`getFirstName()`
Returns the `first_name` property for the user as a string if present.
### getMiddleName {#getmiddlename}
`getMiddleName()`
Returns the `middle_name` property for the user as a string if present.
### getLastName {#getlastname}
`getLastName()`
Returns the `last_name` property for the user as a string if present.
### getLink {#getlink}
`getLink()`
Returns the `link` property for the user as a string if present.
### getUsername {#getusername}
`getUsername()`
Returns the `username` property for the user as a string if present.
### getBirthday {#getbirthday}
`getBirthday()`
Returns the `birthday` property for the user as a `\DateTime` if present.
### getLocation {#getlocation}
`getLocation()`
Returns the `location` property for the user as a `Facebook\GraphLocation` if present.'
</card>
<card>
## GraphLocation Instance Methods {#location-instance-methods}
### getStreet {#getstreet}
`getStreet()`
Returns the `street` property for the location as a string if present.
### getCity {#getcity}
`getCity()`
Returns the `city` property for the location as a string if present.
### getState {#getstate}
`getState()`
Returns the `state` property for the location as a string if present.
### getCountry {#getcountry}
`getCountry()`
Returns the `country` property for the location as a string if present.
### getZip {#getzip}
`getZip()`
Returns the `zip` property for the user as a location if present.
### getLatitude {#getlat}
`getLatitude()`
Returns the `latitude` property for the location as a float if present.
### getLongitude {#getlon}
`getLongitude()`
Returns the `latitude` property for the location as a float if present.
</card>
<card>
## GraphSessionInfo Instance Methods {#sessioninfo-instance-methods}
### getAppId {#getappid}
`getAppId()`
Returns the `app_id` property for the session as a string if present.
### getApplication {#getapp}
`getApplication()`
Returns the `application` property for the session as a string if present.
### getExpiresAt {#getexpires}
`getExpiresAt()`
Returns the `expires_at` property for the session as a \DateTime if present.
### getIsValid {#getvalid}
`getIsValid()`
Returns the `is_valid` property for the session as a boolean if present.
### getIssuedAt {#getissued}
`getIssuedAt()`
Returns the `issued_at` property for the session as a \DateTime if present.
### getScopes {#getscopes}
`getScopes()`
Returns the `scopes` property for the session as an array if present.
### getId {#getuid}
`getId()`
Returns the `user_id` property for the session as a string if present.
</card>

View File

@ -1,44 +0,0 @@
<card>
# Post Links Using the Graph API
This example covers posting a link to the current user's timeline using the Graph API and Facebook SDK for PHP.
It assumes that you've already set your default app id and secret, and acquired a `FacebookSession` using an access token or one of the login helper classes found [here](/docs/php). You must have requested the `publish_actions` scope when logging in the user for this to work.
For more information, see the documentation for [`GraphObject`](/docs/php/GraphObject), [`FacebookRequest`](/docs/php/FacebookRequest), and [`FacebookRequestException`](/docs/php/FacebookRequestException).
</card>
<card>
~~~~
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
if($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'www.example.com',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
~~~~
Note that the 'message' field must come from the user, as pre-filled content is forbidden by the [Platform Policies](https://developers.intern.facebook.com/policy/#control) (2.3).
</card>

View File

@ -1,38 +0,0 @@
<card>
# Retrieve User Profile via the Graph API
This example covers getting profile information for the current user and printing their name, using the Graph API and the Facebook SDK for PHP.
It assumes that you've already set your default app id and secret, and acquired a `FacebookSession` using an access token or one of the login helper classes found [here](/docs/php).
For more information, see the documentation for [`GraphObject`](/docs/php/GraphObject), [`GraphUser`](/docs/php/GraphObject/#user-instance-methods), [`FacebookRequest`](/docs/php/FacebookRequest), and [`FacebookRequestException`](/docs/php/FacebookRequestException).
</card>
<card>
~~~~
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
~~~~
</card>

View File

@ -1,136 +0,0 @@
<card>
# Getting started with the Facebook SDK for PHP
The Facebook SDK for PHP provides developers with a modern, native library for accessing the Graph API and taking advantage of Facebook Login. Usually this means you're developing with PHP for a Facebook Canvas app, building your own website, or adding server-side functionality to an app that already uses the [Facebook SDK for JavaScript](/docs/reference/javascript/).
</card>
<card>
## Download the SDK {#download}
%FB(devsite:markdown-wiki:info-card {
content: "The Facebook SDK for PHP v4 requires PHP 5.4 or greater.",
type: 'warning',
})
If you're using [Composer](https://getcomposer.org/) as a package manager for PHP, which we recommend, installing the SDK is as easy as adding a require entry for the Facebook SDK for PHP to the composer.json file in the root of your project:
~~~~
{
"require" : {
"facebook/php-sdk-v4" : "~4.0.12"
}
}
~~~~
Then run composer with the install parameter, and it will download the newest version. If you're using the autoloader as part of Composer, the Facebook namespace will be available for use without adding require statements for all of the files.
If you're not using Composer, you can download the SDK from our GitHub:
%FB(devsite:markdown-wiki:button {
text: 'Download the PHP SDK',
href: 'https://github.com/facebook/facebook-php-sdk-v4/archive/4.0-dev.zip',
size: 'large',
use: 'special',
})
</card>
<card>
## Initializing {#init}
You will need to have configured a Facebook App, which you can obtain from the [App Dashboard](http://developers.facebook.com/apps).
Then, initialize the SDK with your app ID and secret:
~~~
session_start(); // For the Facebook SDK to work correctly, you need to start a PHP session
FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');
~~~
</card>
<card>
## Authentication and authorization {#authentication}
The SDK can be used to support login your site using a Facebook account. On the server-side, the SDK provides helper classes for the most common scenarios.
For most websites, you'll use the [FacebookRedirectLoginHelper](/docs/php/FacebookRedirectLoginHelper). Generate the login URL to redirect visitors to with the `getLoginUrl()` method, redirect them, and then process the response from Facebook with the `getSessionFromRedirect()` method, which returns a `FacebookSession`.
~~~~
$helper = new FacebookRedirectLoginHelper('your redirect URL here');
$loginUrl = $helper->getLoginUrl();
// Use the login url on a link or button to redirect to Facebook for authentication
~~~~
~~~~
$helper = new FacebookRedirectLoginHelper();
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in
}
~~~~
If your app is on Facebook Canvas, use the `getSession()` method on [FacebookCanvasLoginHelper](/docs/php/FacebookCanvasLoginHelper) to get a `FacebookSession` for the user.
~~~~
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in
}
~~~~
If you're already using the Facebook SDK for JavaScript to authenticate users, you can also log them in on the server side with the [FacebookJavaScriptLoginHelper](/docs/php/FacebookJavaScriptLoginHelper). The `getSession()` method will return a `FacebookSession`.
~~~~
$helper = new FacebookJavaScriptLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in
}
~~~~
You can also create a `FacebookSession` with an access token you've acquired through some other means, by passing it to the constructor.
~~~~
$session = new FacebookSession('access token here');
~~~~
</card>
<card>
## Making Requests to the Graph API {#making-requests}
Once you have a `FacebookSession` you can begin making calls to the Graph API with [FacebookRequest](/docs/php/FacebookRequest).
~~~~
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
~~~~
You can also chain these methods:
~~~~
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
~~~~
For more details, see the examples and API reference for all of these classes listed on the [landing page for the Facebook SDK for PHP](/docs/reference/php).
</card>

View File

@ -1,45 +0,0 @@
<card>
# Facebook SDK for PHP
The Facebook SDK for PHP provides developers with a modern, native library for accessing the Graph API and taking advantage of Facebook Login. Usually this means you're developing with PHP for a Facebook Canvas app, building your own website, or adding server-side functionality to an app that already uses the [Facebook SDK for JavaScript](/docs/reference/javascript/).
Take a look through our guide, [Getting Started with the Facebook SDK for PHP](/docs/php/gettingstarted), and then check out some of the examples below.
</card>
<card>
## Examples {#examples}
* [Retrieve a users profile](/docs/php/howto/profilewithgraphapi)
* [Post a link to a users feed](/docs/php/howto/postwithgraphapi)
* [Upload a photo to a users profile](/docs/php/howto/uploadphoto)
</card>
<card>
## API Reference - Facebook namespace {#reference}
[Facebook\FacebookSession](/docs/php/FacebookSession)
An access token backed session used when making requests against the Graph API.
[Facebook\FacebookRequest](/docs/php/FacebookRequest)
Makes requests against the Graph API.
[Facebook\FacebookResponse](/docs/php/FacebookResponse)
A successful response from the Graph API resulting from a FacebookRequest.
[Facebook\FacebookRequestException](/docs/php/FacebookRequestException)
An error returned by the Graph API during a FacebookRequest. Subclasses: FacebookClientException, FacebookServerException, FacebookAuthorizationException, FacebookPermissionException, FacebookThrottleException, FacebookOtherException.
[Facebook\GraphObject](/docs/php/GraphObject)
Represents an object returned by the Graph API. Subclasses: GraphUser, GraphLocation, GraphSessionInfo
[Facebook\FacebookRedirectLoginHelper](/docs/php/FacebookRedirectLoginHelper)
A helper class for getting a FacebookSession using the OAuth protocol.
[Facebook\FacebookCanvasLoginHelper](/docs/php/FacebookCanvasLoginHelper)
A helper class for getting a FacebookSession from Facebook Canvas.
[Facebook\FacebookJavaScriptLoginHelper](/docs/php/FacebookJavaScriptLoginHelper)
A helper class for getting a FacebookSession from the Facebook SDK for JavaScript.
</card>

View File

@ -1,49 +0,0 @@
<card>
# Upload Photos to a User's Profile
This example covers uploading a photo to the current User's profile using the Graph API and the Facebook SDK for PHP.
It assumes that you've already set your default app id and secret, and acquired a `FacebookSession` using an access token or one of the login helper classes found [here](/docs/php). You must have requested the `publish_actions` scope when logging in the user for this to work.
For more information, see the documentation for [`GraphObject`](/docs/php/GraphObject), [`FacebookRequest`](/docs/php/FacebookRequest), and [`FacebookRequestException`](/docs/php/FacebookRequestException).
</card>
<card>
~~~~
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
if($session) {
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => new CURLFile('path/to/file.name', 'image/png'),
'message' => 'User provided message'
)
))->execute()->getGraphObject();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '@/path/to/file.name'
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
~~~~
Note that the 'message' field must come from the user, as pre-filled content is forbidden by the [Platform Policies](https://developers.intern.facebook.com/policy/#control) (2.3).
</card>

View File

@ -1,19 +0,0 @@
<phpunit
colors="true"
stderr="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false"
bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Facebook PHP SDK v4 Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/Facebook</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -1,370 +0,0 @@
<?php
/**
* Copyright 2014 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace Facebook\Entities;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookSession;
use Facebook\GraphSessionInfo;
/**
* Class AccessToken
* @package Facebook
*/
class AccessToken
{
/**
* The access token.
*
* @var string
*/
protected $accessToken;
/**
* A unique ID to identify a client.
*
* @var string
*/
protected $machineId;
/**
* Date when token expires.
*
* @var \DateTime|null
*/
protected $expiresAt;
/**
* Create a new access token entity.
*
* @param string $accessToken
* @param int $expiresAt
* @param string|null machineId
*/
public function __construct($accessToken, $expiresAt = 0, $machineId = null)
{
$this->accessToken = $accessToken;
if ($expiresAt) {
$this->setExpiresAtFromTimeStamp($expiresAt);
}
$this->machineId = $machineId;
}
/**
* Setter for expires_at.
*
* @param int $timeStamp
*/
protected function setExpiresAtFromTimeStamp($timeStamp)
{
$dt = new \DateTime();
$dt->setTimestamp($timeStamp);
$this->expiresAt = $dt;
}
/**
* Getter for expiresAt.
*
* @return \DateTime|null
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Getter for machineId.
*
* @return string|null
*/
public function getMachineId()
{
return $this->machineId;
}
/**
* Determines whether or not this is a long-lived token.
*
* @return bool
*/
public function isLongLived()
{
if ($this->expiresAt) {
return $this->expiresAt->getTimestamp() > time() + (60 * 60 * 2);
}
return false;
}
/**
* Checks the validity of the access token.
*
* @param string|null $appId Application ID to use
* @param string|null $appSecret App secret value to use
* @param string|null $machineId
*
* @return boolean
*/
public function isValid($appId = null, $appSecret = null, $machineId = null)
{
$accessTokenInfo = $this->getInfo($appId, $appSecret);
$machineId = $machineId ?: $this->machineId;
return static::validateAccessToken($accessTokenInfo, $appId, $machineId);
}
/**
* Ensures the provided GraphSessionInfo object is valid,
* throwing an exception if not. Ensures the appId matches,
* that the machineId matches if it's being used,
* that the token is valid and has not expired.
*
* @param GraphSessionInfo $tokenInfo
* @param string|null $appId Application ID to use
* @param string|null $machineId
*
* @return boolean
*/
public static function validateAccessToken(GraphSessionInfo $tokenInfo,
$appId = null, $machineId = null)
{
$targetAppId = FacebookSession::_getTargetAppId($appId);
$appIdIsValid = $tokenInfo->getAppId() == $targetAppId;
$machineIdIsValid = $tokenInfo->getProperty('machine_id') == $machineId;
$accessTokenIsValid = $tokenInfo->isValid();
// Not all access tokens return an expiration. E.g. an app access token.
if ($tokenInfo->getExpiresAt() instanceof \DateTime) {
$accessTokenIsStillAlive = $tokenInfo->getExpiresAt()->getTimestamp() >= time();
} else {
$accessTokenIsStillAlive = true;
}
return $appIdIsValid && $machineIdIsValid && $accessTokenIsValid && $accessTokenIsStillAlive;
}
/**
* Get a valid access token from a code.
*
* @param string $code
* @param string|null $appId
* @param string|null $appSecret
* @param string|null $machineId
*
* @return AccessToken
*/
public static function getAccessTokenFromCode($code, $appId = null, $appSecret = null, $machineId = null)
{
$params = array(
'code' => $code,
'redirect_uri' => '',
);
if ($machineId) {
$params['machine_id'] = $machineId;
}
return static::requestAccessToken($params, $appId, $appSecret);
}
/**
* Get a valid code from an access token.
*
* @param AccessToken|string $accessToken
* @param string|null $appId
* @param string|null $appSecret
*
* @return AccessToken
*/
public static function getCodeFromAccessToken($accessToken, $appId = null, $appSecret = null)
{
$accessToken = (string) $accessToken;
$params = array(
'access_token' => $accessToken,
'redirect_uri' => '',
);
return static::requestCode($params, $appId, $appSecret);
}
/**
*