code:
<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

if (!function_exists('curl_init')) {
  throw new Exception('Facebook needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
  throw new Exception('Facebook needs the JSON PHP extension.');
}

/**
 * Thrown when an API call returns an exception.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
class FacebookApiException extends Exception
{
  /**
   * The result from the API server that represents the exception information.
   */
  protected $result;

  /**
   * Make a new API Exception with the given result.
   *
   * @param array $result The result from the API server
   */
  public function __construct($result) {
    $this->result = $result;

    $code = isset($result['error_code']) ? $result['error_code'] : 0;

    if (isset($result['error_description'])) {
      // OAuth 2.0 Draft 10 style
      $msg = $result['error_description'];
    } else if (isset($result['error']) && is_array($result['error'])) {
      // OAuth 2.0 Draft 00 style
      $msg = $result['error']['message'];
    } else if (isset($result['error_msg'])) {
      // Rest server style
      $msg = $result['error_msg'];
    } else {
      $msg = 'Unknown Error. Check getResult()';
    }

    parent::__construct($msg, $code);
  }

  /**
   * Return the associated result object returned by the API server.
   *
   * @return array The result from the API server
   */
  public function getResult() {
    return $this->result;
  }

  /**
   * Returns the associated type for the error. This will default to
   * 'Exception' when a type is not available.
   *
   * @return string
   */
  public function getType() {
    if (isset($this->result['error'])) {
      $error = $this->result['error'];
      if (is_string($error)) {
        // OAuth 2.0 Draft 10 style
        return $error;
      } else if (is_array($error)) {
        // OAuth 2.0 Draft 00 style
        if (isset($error['type'])) {
          return $error['type'];
        }
      }
    }

    return 'Exception';
  }

  /**
   * To make debugging easier.
   *
   * @return string The string representation of the error
   */
  public function __toString() {
    $str = $this->getType() . ': ';
    if ($this->code != 0) {
      $str .= $this->code . ': ';
    }
    return $str . $this->message;
  }
}

/**
 * Provides access to the Facebook Platform.  This class provides
 * a majority of the functionality needed, but the class is abstract
 * because it is designed to be sub-classed.  The subclass must
 * implement the four abstract methods listed at the bottom of
 * the file.
 *
 * @author Naitik Shah <naitik@facebook.com>
 */
abstract class BaseFacebook
{
  /**
   * Version.
   */
  const VERSION = '3.1.1';

  /**
   * Default options for curl.
   */
  public static $CURL_OPTS = array(
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_USERAGENT      => 'facebook-php-3.1',
  );

  /**
   * List of query parameters that get automatically dropped when rebuilding
   * the current URL.
   */
  protected static $DROP_QUERY_PARAMS = array(
    'code',
    'state',
    'signed_request',
  );

  /**
   * Maps aliases to Facebook domains.
   */
  public static $DOMAIN_MAP = array(
    'api'       => 'https://api.facebook.com/',
    'api_video' => 'https://api-video.facebook.com/',
    'api_read'  => 'https://api-read.facebook.com/',
    'graph'     => 'https://graph.facebook.com/',
    'www'       => 'https://www.facebook.com/',
  );

  /**
   * The Application ID.
   *
   * @var string
   */
  protected $appId;

  /**
   * The Application API Secret.
   *
   * @var string
   */
  protected $apiSecret;

  /**
   * The ID of the Facebook user, or 0 if the user is logged out.
   *
   * @var integer
   */
  protected $user;

  /**
   * The data from the signed_request token.
   */
  protected $signedRequest;

  /**
   * A CSRF state variable to assist in the defense against CSRF attacks.
   */
  protected $state;

  /**
   * The OAuth access token received in exchange for a valid authorization
   * code.  null means the access token has yet to be determined.
   *
   * @var string
   */
  protected $accessToken = null;

  /**
   * Indicates if the CURL based @ syntax for file uploads is enabled.
   *
   * @var boolean
   */
  protected $fileUploadSupport = false;

  /**
   * Initialize a Facebook Application.
   *
   * The configuration:
   * - appId: the application ID
   * - secret: the application secret
   * - fileUpload: (optional) boolean indicating if file uploads are enabled
   *
   * @param array $config The application configuration
   */
  public function __construct($config) {
    $this->setAppId($config['appId']);
    $this->setApiSecret($config['secret']);
    if (isset($config['fileUpload'])) {
      $this->setFileUploadSupport($config['fileUpload']);
    }

    $state = $this->getPersistentData('state');
    if (!empty($state)) {
      $this->state = $this->getPersistentData('state');
    }
  }

  /**
   * Set the Application ID.
   *
   * @param string $appId The Application ID
   * @return BaseFacebook
   */
  public function setAppId($appId) {
    $this->appId = $appId;
    return $this;
  }

  /**
   * Get the Application ID.
   *
   * @return string the Application ID
   */
  public function getAppId() {
    return $this->appId;
  }

  /**
   * Set the API Secret.
   *
   * @param string $apiSecret The API Secret
   * @return BaseFacebook
   */
  public function setApiSecret($apiSecret) {
    $this->apiSecret = $apiSecret;
    return $this;
  }

  /**
   * Get the API Secret.
   *
   * @return string the API Secret
   */
  public function getApiSecret() {
    return $this->apiSecret;
  }

  /**
   * Set the file upload support status.
   *
   * @param boolean $fileUploadSupport The file upload support status.
   * @return BaseFacebook
   */
  public function setFileUploadSupport($fileUploadSupport) {
    $this->fileUploadSupport = $fileUploadSupport;
    return $this;
  }

  /**
   * Get the file upload support status.
   *
   * @return boolean true if and only if the server supports file upload.
   */
  public function useFileUploadSupport() {
    return $this->fileUploadSupport;
  }

  /**
   * Sets the access token for api calls.  Use this if you get
   * your access token by other means and just want the SDK
   * to use it.
   *
   * @param string $access_token an access token.
   * @return BaseFacebook
   */
  public function setAccessToken($access_token) {
    $this->accessToken = $access_token;
    return $this;
  }

  /**
   * Determines the access token that should be used for API calls.
   * The first time this is called, $this->accessToken is set equal
   * to either a valid user access token, or it's set to the application
   * access token if a valid user access token wasn't available.  Subsequent
   * calls return whatever the first call returned.
   *
   * @return string The access token
   */
  public function getAccessToken() {
    if ($this->accessToken !== null) {
      // we've done this already and cached it.  Just return.
      return $this->accessToken;
    }

    // first establish access token to be the application
    // access token, in case we navigate to the /oauth/access_token
    // endpoint, where SOME access token is required.
    $this->setAccessToken($this->getApplicationAccessToken());
    if ($user_access_token = $this->getUserAccessToken()) {
      $this->setAccessToken($user_access_token);
    }

    return $this->accessToken;
  }

  /**
   * Determines and returns the user access token, first using
   * the signed request if present, and then falling back on
   * the authorization code if present.  The intent is to
   * return a valid user access token, or false if one is determined
   * to not be available.
   *
   * @return string A valid user access token, or false if one
   *                could not be determined.
   */
  protected function getUserAccessToken() {
    // first, consider a signed request if it's supplied.
    // if there is a signed request, then it alone determines
    // the access token.
    $signed_request = $this->getSignedRequest();
    if ($signed_request) {
      // apps.facebook.com hands the access_token in the signed_request
      if (array_key_exists('oauth_token', $signed_request)) {
        $access_token = $signed_request['oauth_token'];
        $this->setPersistentData('access_token', $access_token);
        return $access_token;
      }

      // the JS SDK puts a code in with the redirect_uri of ''
      if (array_key_exists('code', $signed_request)) {
        $code = $signed_request['code'];
        $access_token = $this->getAccessTokenFromCode($code, '');
        if ($access_token) {
          $this->setPersistentData('code', $code);
          $this->setPersistentData('access_token', $access_token);
          return $access_token;
        }
      }

      // signed request states there's no access token, so anything
      // stored should be cleared.
      $this->clearAllPersistentData();
      return false; // respect the signed request's data, even
                    // if there's an authorization code or something else
    }

    $code = $this->getCode();
    if ($code && $code != $this->getPersistentData('code')) {
      $access_token = $this->getAccessTokenFromCode($code);
      if ($access_token) {
        $this->setPersistentData('code', $code);
        $this->setPersistentData('access_token', $access_token);
        return $access_token;
      }

      // code was bogus, so everything based on it should be invalidated.
      $this->clearAllPersistentData();
      return false;
    }

    // as a fallback, just return whatever is in the persistent
    // store, knowing nothing explicit (signed request, authorization
    // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
    // but it's the same as what's in the persistent store)
    return $this->getPersistentData('access_token');
  }

  /**
   * Retrieve the signed request, either from a request parameter or,
   * if not present, from a cookie.
   *
   * @return string the signed request, if available, or null otherwise.
   */
  public function getSignedRequest() {
    if (!$this->signedRequest) {
      if (isset($_REQUEST['signed_request'])) {
        $this->signedRequest = $this->parseSignedRequest(
          $_REQUEST['signed_request']);
      } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
        $this->signedRequest = $this->parseSignedRequest(
          $_COOKIE[$this->getSignedRequestCookieName()]);
      }
    }
    return $this->signedRequest;
  }

  /**
   * Get the UID of the connected user, or 0
   * if the Facebook user is not connected.
   *
   * @return string the UID if available.
   */
  public function getUser() {
    if ($this->user !== null) {
      // we've already determined this and cached the value.
      return $this->user;
    }

    return $this->user = $this->getUserFromAvailableData();
  }

  /**
   * Determines the connected user by first examining any signed
   * requests, then considering an authorization code, and then
   * falling back to any persistent store storing the user.
   *
   * @return integer The id of the connected Facebook user,
   *                 or 0 if no such user exists.
   */
  protected function getUserFromAvailableData() {
    // if a signed request is supplied, then it solely determines
    // who the user is.
    $signed_request = $this->getSignedRequest();
    if ($signed_request) {
      if (array_key_exists('user_id', $signed_request)) {
        $user = $signed_request['user_id'];
        $this->setPersistentData('user_id', $signed_request['user_id']);
        return $user;
      }

      // if the signed request didn't present a user id, then invalidate
      // all entries in any persistent store.
      $this->clearAllPersistentData();
      return 0;
    }

    $user = $this->getPersistentData('user_id', $default = 0);
    $persisted_access_token = $this->getPersistentData('access_token');

    // use access_token to fetch user id if we have a user access_token, or if
    // the cached access token has changed.
    $access_token = $this->getAccessToken();
    if ($access_token &&
        $access_token != $this->getApplicationAccessToken() &&
        !($user && $persisted_access_token == $access_token)) {
      $user = $this->getUserFromAccessToken();
      if ($user) {
        $this->setPersistentData('user_id', $user);
      } else {
        $this->clearAllPersistentData();
      }
    }

    return $user;
  }

  /**
   * Get a Login URL for use with redirects. By default, full page redirect is
   * assumed. If you are using the generated URL with a window.open() call in
   * JavaScript, you can pass in display=popup as part of the $params.
   *
   * The parameters:
   * - redirect_uri: the url to go to after a successful login
   * - scope: comma separated list of requested extended perms
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the login flow
   */
  public function getLoginUrl($params=array()) {
    $this->establishCSRFTokenState();
    $currentUrl = $this->getCurrentUrl();

    // if 'scope' is passed as an array, convert to comma separated list
    $scopeParams = isset($params['scope']) ? $params['scope'] : null;
    if ($scopeParams && is_array($scopeParams)) {
      $params['scope'] = implode(',', $scopeParams);
    }

    return $this->getUrl(
      'www',
      'dialog/oauth',
      array_merge(array(
                    'client_id' => $this->getAppId(),
                    'redirect_uri' => $currentUrl, // possibly overwritten
                    'state' => $this->state),
                  $params));
  }

  /**
   * Get a Logout URL suitable for use with redirects.
   *
   * The parameters:
   * - next: the url to go to after a successful logout
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the logout flow
   */
  public function getLogoutUrl($params=array()) {
    return $this->getUrl(
      'www',
      'logout.php',
      array_merge(array(
        'next' => $this->getCurrentUrl(),
        'access_token' => $this->getAccessToken(),
      ), $params)
    );
  }

  /**
   * Get a login status URL to fetch the status from Facebook.
   *
   * The parameters:
   * - ok_session: the URL to go to if a session is found
   * - no_session: the URL to go to if the user is not connected
   * - no_user: the URL to go to if the user is not signed into facebook
   *
   * @param array $params Provide custom parameters
   * @return string The URL for the logout flow
   */
  public function getLoginStatusUrl($params=array()) {
    return $this->getUrl(
      'www',
      'extern/login_status.php',
      array_merge(array(
        'api_key' => $this->getAppId(),
        'no_session' => $this->getCurrentUrl(),
        'no_user' => $this->getCurrentUrl(),
        'ok_session' => $this->getCurrentUrl(),
        'session_version' => 3,
      ), $params)
    );
  }

  /**
   * Make an API call.
   *
   * @return mixed The decoded response
   */
  public function api(/* polymorphic */) {
    $args = func_get_args();
    if (is_array($args[0])) {
      return $this->_restserver($args[0]);
    } else {
      return call_user_func_array(array($this, '_graph'), $args);
    }
  }

  /**
   * Constructs and returns the name of the cookie that
   * potentially houses the signed request for the app user.
   * The cookie is not set by the BaseFacebook class, but
   * it may be set by the JavaScript SDK.
   *
   * @return string the name of the cookie that would house
   *         the signed request value.
   */
  protected function getSignedRequestCookieName() {
    return 'fbsr_'.$this->getAppId();
  }

  /**
   * Get the authorization code from the query parameters, if it exists,
   * and otherwise return false to signal no authorization code was
   * discoverable.
   *
   * @return mixed The authorization code, or false if the authorization
   *               code could not be determined.
   */
  protected function getCode() {
    if (isset($_REQUEST['code'])) {
      if ($this->state !== null &&
          isset($_REQUEST['state']) &&
          $this->state === $_REQUEST['state']) {

        // CSRF state has done its job, so clear it
        $this->state = null;
        $this->clearPersistentData('state');
        return $_REQUEST['code'];
      } else {
        self::errorLog('CSRF state token does not match one provided.');
        return false;
      }
    }

    return false;
  }

  /**
   * Retrieves the UID with the understanding that
   * $this->accessToken has already been set and is
   * seemingly legitimate.  It relies on Facebook's Graph API
   * to retrieve user information and then extract
   * the user ID.
   *
   * @return integer Returns the UID of the Facebook user, or 0
   *                 if the Facebook user could not be determined.
   */
  protected function getUserFromAccessToken() {
    try {
      $user_info = $this->api('/me');
      return $user_info['id'];
    } catch (FacebookApiException $e) {
      return 0;
    }
  }

  /**
   * Returns the access token that should be used for logged out
   * users when no authorization code is available.
   *
   * @return string The application access token, useful for gathering
   *                public information about users and applications.
   */
  protected function getApplicationAccessToken() {
    return $this->appId.'|'.$this->apiSecret;
  }

  /**
   * Lays down a CSRF state token for this process.
   *
   * @return void
   */
  protected function establishCSRFTokenState() {
    if ($this->state === null) {
      $this->state = md5(uniqid(mt_rand(), true));
      $this->setPersistentData('state', $this->state);
    }
  }

  /**
   * Retrieves an access token for the given authorization code
   * (previously generated from www.facebook.com on behalf of
   * a specific user).  The authorization code is sent to graph.facebook.com
   * and a legitimate access token is generated provided the access token
   * and the user for which it was generated all match, and the user is
   * either logged in to Facebook or has granted an offline access permission.
   *
   * @param string $code An authorization code.
   * @return mixed An access token exchanged for the authorization code, or
   *               false if an access token could not be generated.
   */
  protected function getAccessTokenFromCode($code, $redirect_uri = null) {
    if (empty($code)) {
      return false;
    }

    if ($redirect_uri === null) {
      $redirect_uri = $this->getCurrentUrl();
    }

    try {
      // need to circumvent json_decode by calling _oauthRequest
      // directly, since response isn't JSON format.
      $access_token_response =
        $this->_oauthRequest(
          $this->getUrl('graph', '/oauth/access_token'),
          $params = array('client_id' => $this->getAppId(),
                          'client_secret' => $this->getApiSecret(),
                          'redirect_uri' => $redirect_uri,
                          'code' => $code));
    } catch (FacebookApiException $e) {
      // most likely that user very recently revoked authorization.
      // In any event, we don't have an access token, so say so.
      return false;
    }

    if (empty($access_token_response)) {
      return false;
    }

    $response_params = array();
    parse_str($access_token_response, $response_params);
    if (!isset($response_params['access_token'])) {
      return false;
    }

    return $response_params['access_token'];
  }

  /**
   * Invoke the old restserver.php endpoint.
   *
   * @param array $params Method call object
   *
   * @return mixed The decoded response object
   * @throws FacebookApiException
   */
  protected function _restserver($params) {
    // generic application level parameters
    $params['api_key'] = $this->getAppId();
    $params['format'] = 'json-strings';

    $result = json_decode($this->_oauthRequest(
      $this->getApiUrl($params['method']),
      $params
    ), true);

    // results are returned, errors are thrown
    if (is_array($result) && isset($result['error_code'])) {
      throw new FacebookApiException($result);
    }

    return $result;
  }

  /**
   * Invoke the Graph API.
   *
   * @param string $path The path (required)
   * @param string $method The http method (default 'GET')
   * @param array $params The query/post data
   *
   * @return mixed The decoded response object
   * @throws FacebookApiException
   */
  protected function _graph($path, $method = 'GET', $params = array()) {
    if (is_array($method) && empty($params)) {
      $params = $method;
      $method = 'GET';
    }
    $params['method'] = $method; // method override as we always do a POST

    $result = json_decode($this->_oauthRequest(
      $this->getUrl('graph', $path),
      $params
    ), true);

    // results are returned, errors are thrown
    if (is_array($result) && isset($result['error'])) {
      $this->throwAPIException($result);
    }

    return $result;
  }

  /**
   * Make a OAuth Request.
   *
   * @param string $url The path (required)
   * @param array $params The query/post data
   *
   * @return string The decoded response object
   * @throws FacebookApiException
   */
  protected function _oauthRequest($url, $params) {
    if (!isset($params['access_token'])) {
      $params['access_token'] = $this->getAccessToken();
    }

    // json_encode all params values that are not strings
    foreach ($params as $key => $value) {
      if (!is_string($value)) {
        $params[$key] = json_encode($value);
      }
    }

    return $this->makeRequest($url, $params);
  }

  /**
   * Makes an HTTP request. This method can be overridden by subclasses if
   * developers want to do fancier things or use something other than curl to
   * make the request.
   *
   * @param string $url The URL to make the request to
   * @param array $params The parameters to use for the POST body
   * @param CurlHandler $ch Initialized curl handle
   *
   * @return string The response text
   */
  protected function makeRequest($url, $params, $ch=null) {
    if (!$ch) {
      $ch = curl_init();
    }

    $opts = self::$CURL_OPTS;
    if ($this->useFileUploadSupport()) {
      $opts[CURLOPT_POSTFIELDS] = $params;
    } else {
      $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
    }
    $opts[CURLOPT_URL] = $url;

    // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
    // for 2 seconds if the server does not support this header.
    if (isset($opts[CURLOPT_HTTPHEADER])) {
      $existing_headers = $opts[CURLOPT_HTTPHEADER];
      $existing_headers[] = 'Expect:';
      $opts[CURLOPT_HTTPHEADER] = $existing_headers;
    } else {
      $opts[CURLOPT_HTTPHEADER] = array('Expect:');
    }

    curl_setopt_array($ch, $opts);
    $result = curl_exec($ch);

    if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
      self::errorLog('Invalid or no certificate authority found, '.
                     'using bundled information');
      curl_setopt($ch, CURLOPT_CAINFO,
                  dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
      $result = curl_exec($ch);
    }

    if ($result === false) {
      $e = new FacebookApiException(array(
        'error_code' => curl_errno($ch),
        'error' => array(
        'message' => curl_error($ch),
        'type' => 'CurlException',
        ),
      ));
      curl_close($ch);
      throw $e;
    }
    curl_close($ch);
    return $result;
  }

  /**
   * Parses a signed_request and validates the signature.
   *
   * @param string $signed_request A signed token
   * @return array The payload inside it or null if the sig is wrong
   */
  protected function parseSignedRequest($signed_request) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = self::base64UrlDecode($encoded_sig);
    $data = json_decode(self::base64UrlDecode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
      self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
      return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload,
                              $this->getApiSecret(), $raw = true);
    if ($sig !== $expected_sig) {
      self::errorLog('Bad Signed JSON signature!');
      return null;
    }

    return $data;
  }

  /**
   * Build the URL for api given parameters.
   *
   * @param $method String the method name.
   * @return string The URL for the given parameters
   */
  protected function getApiUrl($method) {
    static $READ_ONLY_CALLS =
      array('admin.getallocation' => 1,
            'admin.getappproperties' => 1,
            'admin.getbannedusers' => 1,
            'admin.getlivestreamvialink' => 1,
            'admin.getmetrics' => 1,
            'admin.getrestrictioninfo' => 1,
            'application.getpublicinfo' => 1,
            'auth.getapppublickey' => 1,
            'auth.getsession' => 1,
            'auth.getsignedpublicsessiondata' => 1,
            'comments.get' => 1,
            'connect.getunconnectedfriendscount' => 1,
            'dashboard.getactivity' => 1,
            'dashboard.getcount' => 1,
            'dashboard.getglobalnews' => 1,
            'dashboard.getnews' => 1,
            'dashboard.multigetcount' => 1,
            'dashboard.multigetnews' => 1,
            'data.getcookies' => 1,
            'events.get' => 1,
            'events.getmembers' => 1,
            'fbml.getcustomtags' => 1,
            'feed.getappfriendstories' => 1,
            'feed.getregisteredtemplatebundlebyid' => 1,
            'feed.getregisteredtemplatebundles' => 1,
            'fql.multiquery' => 1,
            'fql.query' => 1,
            'friends.arefriends' => 1,
            'friends.get' => 1,
            'friends.getappusers' => 1,
            'friends.getlists' => 1,
            'friends.getmutualfriends' => 1,
            'gifts.get' => 1,
            'groups.get' => 1,
            'groups.getmembers' => 1,
            'intl.gettranslations' => 1,
            'links.get' => 1,
            'notes.get' => 1,
            'notifications.get' => 1,
            'pages.getinfo' => 1,
            'pages.isadmin' => 1,
            'pages.isappadded' => 1,
            'pages.isfan' => 1,
            'permissions.checkavailableapiaccess' => 1,
            'permissions.checkgrantedapiaccess' => 1,
            'photos.get' => 1,
            'photos.getalbums' => 1,
            'photos.gettags' => 1,
            'profile.getinfo' => 1,
            'profile.getinfooptions' => 1,
            'stream.get' => 1,
            'stream.getcomments' => 1,
            'stream.getfilters' => 1,
            'users.getinfo' => 1,
            'users.getloggedinuser' => 1,
            'users.getstandardinfo' => 1,
            'users.hasapppermission' => 1,
            'users.isappuser' => 1,
            'users.isverified' => 1,
            'video.getuploadlimits' => 1);
    $name = 'api';
    if (isset($READ_ONLY_CALLS[strtolower($method)])) {
      $name = 'api_read';
    } else if (strtolower($method) == 'video.upload') {
      $name = 'api_video';
    }
    return self::getUrl($name, 'restserver.php');
  }

  /**
   * Build the URL for given domain alias, path and parameters.
   *
   * @param $name string The name of the domain
   * @param $path string Optional path (without a leading slash)
   * @param $params array Optional query parameters
   *
   * @return string The URL for the given parameters
   */
  protected function getUrl($name, $path='', $params=array()) {
    $url = self::$DOMAIN_MAP[$name];
    if ($path) {
      if ($path[0] === '/') {
        $path = substr($path, 1);
      }
      $url .= $path;
    }
    if ($params) {
      $url .= '?' . http_build_query($params, null, '&');
    }

    return $url;
  }

  /**
   * Returns the Current URL, stripping it of known FB parameters that should
   * not persist.
   *
   * @return string The current URL
   */
  protected function getCurrentUrl() {
    if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
      || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
    ) {
      $protocol = 'https://';
    }
    else {
      $protocol = 'http://';
    }
    $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $parts = parse_url($currentUrl);

    $query = '';
    if (!empty($parts['query'])) {
      // drop known fb params
      $params = explode('&', $parts['query']);
      $retained_params = array();
      foreach ($params as $param) {
        if ($this->shouldRetainParam($param)) {
          $retained_params[] = $param;
        }
      }

      if (!empty($retained_params)) {
        $query = '?'.implode($retained_params, '&');
      }
    }

    // use port if non default
    $port =
      isset($parts['port']) &&
      (($protocol === 'http://' && $parts['port'] !== 80) ||
       ($protocol === 'https://' && $parts['port'] !== 443))
      ? ':' . $parts['port'] : '';

    // rebuild
    return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  }

  /**
   * Returns true if and only if the key or key/value pair should
   * be retained as part of the query string.  This amounts to
   * a brute-force search of the very small list of Facebook-specific
   * params that should be stripped out.
   *
   * @param string $param A key or key/value pair within a URL's query (e.g.
   *                     'foo=a', 'foo=', or 'foo'.
   *
   * @return boolean
   */
  protected function shouldRetainParam($param) {
    foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
      if (strpos($param, $drop_query_param.'=') === 0) {
        return false;
      }
    }

    return true;
  }

  /**
   * Analyzes the supplied result to see if it was thrown
   * because the access token is no longer valid.  If that is
   * the case, then the persistent store is cleared.
   *
   * @param $result array A record storing the error message returned
   *                      by a failed API call.
   */
  protected function throwAPIException($result) {
    $e = new FacebookApiException($result);
    switch ($e->getType()) {
      // OAuth 2.0 Draft 00 style
      case 'OAuthException':
        // OAuth 2.0 Draft 10 style
      case 'invalid_token':
        $message = $e->getMessage();
      if ((strpos($message, 'Error validating access token') !== false) ||
          (strpos($message, 'Invalid OAuth access token') !== false)) {
        $this->setAccessToken(null);
        $this->user = 0;
        $this->clearAllPersistentData();
      }
    }

    throw $e;
  }

  /**
   * Prints to the error log if you aren't in command line mode.
   *
   * @param string $msg Log message
   */
  protected static function errorLog($msg) {
    // disable error log if we are running in a CLI environment
    // @codeCoverageIgnoreStart
    if (php_sapi_name() != 'cli') {
      error_log($msg);
    }
    // uncomment this if you want to see the errors on the page
    // print 'error_log: '.$msg."\n";
    // @codeCoverageIgnoreEnd
  }

  /**
   * Base64 encoding that doesn't need to be urlencode()ed.
   * Exactly the same as base64_encode except it uses
   *   - instead of +
   *   _ instead of /
   *
   * @param string $input base64UrlEncoded string
   * @return string
   */
  protected static function base64UrlDecode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
  }

  /**
   * Each of the following four methods should be overridden in
   * a concrete subclass, as they are in the provided Facebook class.
   * The Facebook class uses PHP sessions to provide a primitive
   * persistent store, but another subclass--one that you implement--
   * might use a database, memcache, or an in-memory cache.
   *
   * @see Facebook
   */

  /**
   * Stores the given ($key, $value) pair, so that future calls to
   * getPersistentData($key) return $value. This call may be in another request.
   *
   * @param string $key
   * @param array $value
   *
   * @return void
   */
  abstract protected function setPersistentData($key, $value);

  /**
   * Get the data for $key, persisted by BaseFacebook::setPersistentData()
   *
   * @param string $key The key of the data to retrieve
   * @param boolean $default The default value to return if $key is not found
   *
   * @return mixed
   */
  abstract protected function getPersistentData($key, $default = false);

  /**
   * Clear the data with $key from the persistent storage
   *
   * @param string $key
   * @return void
   */
  abstract protected function clearPersistentData($key);

  /**
   * Clear all data from the persistent storage
   *
   * @return void
   */
  abstract protected function clearAllPersistentData();
}


code:
<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

require_once "base_facebook.php";

/**
 * Extends the BaseFacebook class with the intent of using
 * PHP sessions to store user ids and access tokens.
 */
class Facebook extends BaseFacebook
{
  /**
   * Identical to the parent constructor, except that
   * we start a PHP session to store the user ID and
   * access token if during the course of execution
   * we discover them.
   *
   * @param Array $config the application configuration.
   * @see BaseFacebook::__construct in facebook.php
   */
  public function __construct($config) {
    if (!session_id()) {
      session_start();
    }
    parent::__construct($config);
  }

  protected static $kSupportedKeys =
    array('state', 'code', 'access_token', 'user_id');

  /**
   * Provides the implementations of the inherited abstract
   * methods.  The implementation uses PHP sessions to maintain
   * a store for authorization codes, user ids, CSRF states, and
   * access tokens.
   */
  protected function setPersistentData($key, $value) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to setPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    $_SESSION[$session_var_name] = $value;
  }

  protected function getPersistentData($key, $default = false) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to getPersistentData.');
      return $default;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    return isset($_SESSION[$session_var_name]) ?
      $_SESSION[$session_var_name] : $default;
  }

  protected function clearPersistentData($key) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to clearPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    unset($_SESSION[$session_var_name]);
  }

  protected function clearAllPersistentData() {
    foreach (self::$kSupportedKeys as $key) {
      $this->clearPersistentData($key);
    }
  }

  protected function constructSessionVariableName($key) {
    return implode('_', array('fb',
                              $this->getAppId(),
                              $key));
  }
}

repo_name: piratas/tortuga

license: mit


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for communicating with Facebook
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Craig Andrews <candrews@integralblue.com>
 * @author    Zach Copley <zach@status.net>
 * @copyright 2009-2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Class for communication with Facebook
 *
 * @category Plugin
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
class Facebookclient
{
    protected $facebook      = null; // Facebook Graph client obj
    protected $flink         = null; // Foreign_link StatusNet -> Facebook
    protected $notice        = null; // The user's notice
    protected $user          = null; // Sender of the notice

    /**
     *
     * @param Notice $notice the notice to manipulate
     * @param Profile $profile local user to act as; if left empty, the notice's poster will be used.
     */
    function __construct($notice, $profile=null)
    {
        $this->facebook = self::getFacebook();

        if (empty($this->facebook)) {
            throw new FacebookApiException(
                "Could not create Facebook client! Bad application ID or secret?"
            );
        }

        $this->notice = $notice;

        $profile_id = $profile ? $profile->id : $notice->profile_id;
        $this->flink = Foreign_link::getByUserID(
            $profile_id,
            FACEBOOK_SERVICE
        );

        if (!empty($this->flink)) {
            $this->user = $this->flink->getUser();
        }
    }

    /*
     * Get an instance of the Facebook Graph SDK object
     *
     * @param string $appId     Application
     * @param string $secret    Facebook API secret
     *
     * @return Facebook A Facebook SDK obj
     */
    static function getFacebook($appId = null, $secret = null)
    {
        // Check defaults and configuration for application ID and secret
        if (empty($appId)) {
            $appId = common_config('facebook', 'appid');
        }

        if (empty($secret)) {
            $secret = common_config('facebook', 'secret');
        }

        // If there's no app ID and secret set in the local config, look
        // for a global one
        if (empty($appId) || empty($secret)) {
            $appId  = common_config('facebook', 'global_appid');
            $secret = common_config('facebook', 'global_secret');
        }

        if (empty($appId)) {
            common_log(
                LOG_WARNING,
                "Couldn't find Facebook application ID!",
                __FILE__
            );
        }

        if (empty($secret)) {
            common_log(
                LOG_WARNING,
                "Couldn't find Facebook application ID!",
                __FILE__
            );
        }

        return new Facebook(
            array(
               'appId'  => $appId,
               'secret' => $secret,
               'cookie' => true
            )
        );
    }

    /*
     * Broadcast a notice to Facebook
     *
     * @param Notice $notice    the notice to send
     */
    static function facebookBroadcastNotice($notice)
    {
        $client = new Facebookclient($notice);
        return $client->sendNotice();
    }

    /*
     * Should the notice go to Facebook?
     */
    function isFacebookBound() {

        if (empty($this->flink)) {
            // User hasn't setup bridging
            return false;
        }

        // Avoid a loop
        if ($this->notice->source == 'Facebook') {
            common_log(
                LOG_INFO,
                sprintf(
                    'Skipping notice %d because its source is Facebook.',
                    $this->notice->id
                ),
                __FILE__
            );
            return false;
        }

        // If the user does not want to broadcast to Facebook, move along
        if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
            common_log(
                LOG_INFO,
                sprintf(
                    'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
                    $this->notice->id
                ),
                __FILE__
            );
            return false;
        }

        // If it's not a reply, or if the user WANTS to send @-replies,
        // then, yeah, it can go to Facebook.

        if (empty($this->notice->reply_to) ||
            ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
            return true;
        }

        return false;
    }

    /*
     * Determine whether we should send this notice using the Graph API or the
     * old REST API and then dispatch
     */
    function sendNotice()
    {
        // If there's nothing in the credentials field try to send via
        // the Old Rest API

        if ($this->isFacebookBound()) {
            common_debug("notice is facebook bound", __FILE__);
            if (empty($this->flink->credentials)) {
                return $this->sendOldRest();
            } else {

                // Otherwise we most likely have an access token
                return $this->sendGraph();
            }
        }

        // dequeue
        return true;
    }

    /*
     * Send a notice to Facebook using the Graph API
     */
    function sendGraph()
    {
        try {

            $fbuid = $this->flink->foreign_id;

            common_debug(
                sprintf(
                    "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
                    $this->notice->id,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );

            $params = array(
                'access_token' => $this->flink->credentials,
                // XXX: Need to worrry about length of the message?
                'message'      => $this->notice->content
            );

            $attachments = $this->notice->attachments();

            if (!empty($attachments)) {

                // We can only send one attachment with the Graph API :(

                $first = array_shift($attachments);

                if (substr($first->mimetype, 0, 6) == 'image/'
                    || in_array(
                        $first->mimetype,
                        array('application/x-shockwave-flash', 'audio/mpeg' ))) {

                   $params['picture'] = $first->url;
                   $params['caption'] = 'Click for full size';
                   $params['source']  = $first->url;
                }

            }

            $result = $this->facebook->api(
                sprintf('/%s/feed', $fbuid), 'post', $params
            );

            // Save a mapping
            Notice_to_item::saveNew($this->notice->id, $result['id']);

            common_log(
                LOG_INFO,
                sprintf(
                    "Posted notice %d as a stream item for %s (%d), fbuid %d",
                    $this->notice->id,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );

        } catch (FacebookApiException $e) {
            return $this->handleFacebookError($e);
        }

        return true;
    }

    /*
     * Send a notice to Facebook using the deprecated Old REST API. We need this
     * for backwards compatibility. Users who signed up for Facebook bridging
     * using the old Facebook Canvas application do not have an OAuth 2.0
     * access token.
     */
    function sendOldRest()
    {
        try {

            $canPublish = $this->checkPermission('publish_stream');
            $canUpdate  = $this->checkPermission('status_update');

            // We prefer to use stream.publish, because it can handle
            // attachments and returns the ID of the published item

            if ($canPublish == 1) {
                $this->restPublishStream();
            } else if ($canUpdate == 1) {
                // as a last resort we can just update the user's "status"
                $this->restStatusUpdate();
            } else {

                $msg = 'Not sending notice %d to Facebook because user %s '
                     . '(%d), fbuid %d,  does not have \'status_update\' '
                     . 'or \'publish_stream\' permission.';

                common_log(
                    LOG_WARNING,
                    sprintf(
                        $msg,
                        $this->notice->id,
                        $this->user->nickname,
                        $this->user->id,
                        $this->flink->foreign_id
                    ),
                    __FILE__
                );
            }

        } catch (FacebookApiException $e) {
            return $this->handleFacebookError($e);
        }

        return true;
    }

    /*
     * Query Facebook to to see if a user has permission
     *
     *
     *
     * @param $permission the permission to check for - must be either
     *                    public_stream or status_update
     *
     * @return boolean result
     */
    function checkPermission($permission)
    {
        if (!in_array($permission, array('publish_stream', 'status_update'))) {
             // TRANS: Server exception thrown when permission check fails.
             throw new ServerException(_('No such permission!'));
        }

        $fbuid = $this->flink->foreign_id;

        common_debug(
            sprintf(
                'Checking for %s permission for user %s (%d), fbuid %d',
                $permission,
                $this->user->nickname,
                $this->user->id,
                $fbuid
            ),
            __FILE__
        );

        $hasPermission = $this->facebook->api(
            array(
                'method'   => 'users.hasAppPermission',
                'ext_perm' => $permission,
                'uid'      => $fbuid
            )
        );

        if ($hasPermission == 1) {

            common_debug(
                sprintf(
                    '%s (%d), fbuid %d has %s permission',
                    $permission,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );

            return true;

        } else {

            $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
                    . 'Facebook returned: %s';

            common_debug(
                sprintf(
                    $logMsg,
                    $this->user->nickname,
                    $this->user->id,
                    $permission,
                    $fbuid,
                    var_export($result, true)
                ),
                __FILE__
            );

            return false;
        }
    }

    /*
     * Handle a Facebook API Exception
     *
     * @param FacebookApiException $e the exception
     *
     */
    function handleFacebookError($e)
    {
        $fbuid  = $this->flink->foreign_id;
        $errmsg = $e->getMessage();
        $code   = $e->getCode();

        // The Facebook PHP SDK seems to always set the code attribute
        // of the Exception to 0; they put the real error code in
        // the message. Gar!
        if ($code == 0) {
            preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
            $code = $matches['code'];
        }

        // XXX: Check for any others?
        switch($code) {
         case 100: // Invalid parameter
            $msg = 'Facebook claims notice %d was posted with an invalid '
                 . 'parameter (error code 100 - %s) Notice details: '
                 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
                 . 'Dequeing.';
            common_log(
                LOG_ERR, sprintf(
                    $msg,
                    $this->notice->id,
                    $errmsg,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid,
                    $this->notice->content
                ),
                __FILE__
            );
            return true;
            break;
         case 200: // Permissions error
         case 250: // Updating status requires the extended permission status_update
            $this->disconnect();
            return true; // dequeue
            break;
         case 341: // Feed action request limit reached
                $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
                     . 'for posting notices to Facebook today. Dequeuing '
                     . 'notice %d';
                common_log(
                    LOG_INFO, sprintf(
                        $msg,
                        $user->nickname,
                        $user->id,
                        $fbuid,
                        $this->notice->id
                    ),
                    __FILE__
                );
            // @todo FIXME: We want to rety at a later time when the throttling has expired
            // instead of just giving up.
            return true;
            break;
         default:
            $msg = 'Facebook returned an error we don\'t know how to deal with '
                 . 'when posting notice %d. Error code: %d, error message: "%s"'
                 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
                 . 'notice content="%s"]. Dequeing.';
            common_log(
                LOG_ERR, sprintf(
                    $msg,
                    $this->notice->id,
                    $code,
                    $errmsg,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid,
                    $this->notice->content
                ),
                __FILE__
            );
            return true; // dequeue
            break;
        }
    }

    /*
     * Publish a notice to Facebook as a status update
     *
     * This is the least preferable way to send a notice to Facebook because
     * it doesn't support attachments and the API method doesn't return
     * the ID of the post on Facebook.
     *
     */
    function restStatusUpdate()
    {
        $fbuid = $this->flink->foreign_id;

        common_debug(
            sprintf(
                "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
                $this->notice->id,
                $this->user->nickname,
                $this->user->id,
                $fbuid
            ),
            __FILE__
        );

        $result = $this->facebook->api(
            array(
                'method'               => 'users.setStatus',
                'status'               => $this->formatMessage(),
                'status_includes_verb' => true,
                'uid'                  => $fbuid
            )
        );

        if ($result == 1) { // 1 is success

            common_log(
                LOG_INFO,
                sprintf(
                    "Posted notice %s as a status update for %s (%d), fbuid %d",
                    $this->notice->id,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );

            // There is no item ID returned for status update so we can't
            // save a Notice_to_item mapping

        } else {

            $msg = sprintf(
                "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
                $this->notice->id,
                $this->user->nickname,
                $this->user->id,
                $fbuid,
                $result // will contain 0, or an error
            );

            throw new FacebookApiException($msg, $result);
        }
    }

    /*
     * Publish a notice to a Facebook user's stream using the old REST API
     */
    function restPublishStream()
    {
        $fbuid = $this->flink->foreign_id;

        common_debug(
            sprintf(
                'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
                $this->notice->id,
                $this->user->nickname,
                $this->user->id,
                $fbuid
            ),
            __FILE__
        );

        $fbattachment = $this->formatAttachments();

        $result = $this->facebook->api(
            array(
                'method'     => 'stream.publish',
                'message'    => $this->formatMessage(),
                'attachment' => $fbattachment,
                'uid'        => $fbuid
            )
        );

        if (!empty($result)) { // result will contain the item ID
            // Save a mapping
            Notice_to_item::saveNew($this->notice->id, $result);

            common_log(
                LOG_INFO,
                sprintf(
                    'Posted notice %d as a %s for %s (%d), fbuid %d',
                    $this->notice->id,
                    empty($fbattachment) ? 'stream item' : 'stream item with attachment',
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );
        } else {

            $msg = sprintf(
                'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
                $this->notice->id,
                empty($fbattachment) ? 'stream item' : 'stream item with attachment',
                $this->user->nickname,
                $this->user->id,
                $result, // result will contain an error code
                $fbuid
            );

            throw new FacebookApiException($msg, $result);
        }
    }

    /*
     * Format the text message of a stream item so it's appropriate for
     * sending to Facebook. If the notice is too long, truncate it, and
     * add a linkback to the original notice at the end.
     *
     * @return String $txt the formated message
     */
    function formatMessage()
    {
        // Start with the plaintext source of this notice...
        $txt = $this->notice->content;

        // Facebook has a 420-char hardcoded max.
        if (mb_strlen($statustxt) > 420) {
            $noticeUrl = common_shorten_url($this->notice->getUrl());
            $urlLen = mb_strlen($noticeUrl);
            $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
        }

        return $txt;
    }

    /*
     * Format attachments for the old REST API stream.publish method
     *
     * Note: Old REST API supports multiple attachments per post
     *
     */
    function formatAttachments()
    {
        $attachments = $this->notice->attachments();

        $fbattachment          = array();
        $fbattachment['media'] = array();

        foreach($attachments as $attachment)
        {
            try {
                $enclosure = $attachment->getEnclosure();
                $fbmedia = $this->getFacebookMedia($enclosure);
            } catch (ServerException $e) {
                $fbmedia = $this->getFacebookMedia($attachment);
            }
            if($fbmedia){
                $fbattachment['media'][]=$fbmedia;
            }else{
                $fbattachment['name'] = ($attachment->title ?
                                      $attachment->title : $attachment->url);
                $fbattachment['href'] = $attachment->url;
            }
        }
        if(count($fbattachment['media'])>0){
            unset($fbattachment['name']);
            unset($fbattachment['href']);
        }
        return $fbattachment;
    }

    /**
     * given a File objects, returns an associative array suitable for Facebook media
     */
    function getFacebookMedia($attachment)
    {
        $fbmedia    = array();

        if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
            $fbmedia['type']         = 'image';
            $fbmedia['src']          = $attachment->url;
            $fbmedia['href']         = $attachment->url;
        } else if ($attachment->mimetype == 'audio/mpeg') {
            $fbmedia['type']         = 'mp3';
            $fbmedia['src']          = $attachment->url;
        }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
            $fbmedia['type']         = 'flash';

            // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
            // says that imgsrc is required... but we have no value to put in it
            // $fbmedia['imgsrc']='';

            $fbmedia['swfsrc']       = $attachment->url;
        }else{
            return false;
        }
        return $fbmedia;
    }

    /*
     * Disconnect a user from Facebook by deleting his Foreign_link.
     * Notifies the user his account has been disconnected by email.
     */
    function disconnect()
    {
        $fbuid = $this->flink->foreign_id;

        common_log(
            LOG_INFO,
            sprintf(
                'Removing Facebook link for %s (%d), fbuid %d',
                $this->user->nickname,
                $this->user->id,
                $fbuid
            ),
            __FILE__
        );

        $result = $this->flink->delete();

        if (empty($result)) {
            common_log(
                LOG_ERR,
                sprintf(
                    'Could not remove Facebook link for %s (%d), fbuid %d',
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );
            common_log_db_error($flink, 'DELETE', __FILE__);
        }

        // Notify the user that we are removing their Facebook link
        if (!empty($this->user->email)) {
            $result = $this->mailFacebookDisconnect();

            if (!$result) {
                $msg = 'Unable to send email to notify %s (%d), fbuid %d '
                     . 'about his/her Facebook link being removed.';

                common_log(
                    LOG_WARNING,
                    sprintf(
                        $msg,
                        $this->user->nickname,
                        $this->user->id,
                        $fbuid
                    ),
                    __FILE__
                );
            }
        } else {
            $msg = 'Unable to send email to notify %s (%d), fbuid %d '
                 . 'about his/her Facebook link being removed because the '
                 . 'user has not set an email address.';

            common_log(
                LOG_WARNING,
                sprintf(
                    $msg,
                    $this->user->nickname,
                    $this->user->id,
                    $fbuid
                ),
                __FILE__
            );
        }
    }

    /**
     * Send a mail message to notify a user that her Facebook link
     * has been terminated.
     *
     * @return boolean success flag
     */
    function mailFacebookDisconnect()
    {
        $profile = $this->user->getProfile();

        $siteName = common_config('site', 'name');

        common_switch_locale($this->user->language);

        // TRANS: E-mail subject.
        $subject = _m('Your Facebook connection has been removed');

        // TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
        $msg = _m("Hi %1\$s,\n\n".
                  "We are sorry to inform you we are unable to publish your notice to\n".
                  "Facebook, and have removed the connection between your %2\$s account and\n".
                  "Facebook.\n\n".
                  "This may have happened because you have removed permission for %2\$s\n".
                  "to post on your behalf, or perhaps you have deactivated your Facebook\n".
                  "account. You can reconnect your %2\$s account to Facebook at any time by\n".
                  "logging in with Facebook again.\n\n".
                  "Sincerely,\n\n".
                  "%2\$s\n");

        $body = sprintf(
            $msg,
            $this->user->nickname,
            $siteName
        );

        common_switch_locale();

        $result = mail_to_user($this->user, $subject, $body);

        if (empty($this->user->password)) {
            $result = self::emailWarn($this->user);
        }

        return $result;
    }

    /*
     * Send the user an email warning that their account has been
     * disconnected and he/she has no way to login and must contact
     * the site administrator for help.
     *
     * @param User $user the deauthorizing user
     *
     */
    static function emailWarn($user)
    {
        $profile = $user->getProfile();

        $siteName  = common_config('site', 'name');
        $siteEmail = common_config('site', 'email');

        if (empty($siteEmail)) {
            common_log(
                LOG_WARNING,
                    "No site email address configured. Please set one."
            );
        }

        common_switch_locale($user->language);

        // TRANS: E-mail subject. %s is the StatusNet sitename.
        $subject = _m('Contact the %s administrator to retrieve your account');

        // TRANS: E-mail body. %1$s is a username,
        // TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail address.
        $msg = _m("Hi %1\$s,\n\n".
                  "We have noticed you have deauthorized the Facebook connection for your\n".
                  "%2\$s account.  You have not set a password for your %2\$s account yet, so\n".
                  "you will not be able to login. If you wish to continue using your %2\$s\n".
                  "account, please contact the site administrator (%3\$s) to set a password.\n\n".
                  "Sincerely,\n\n".
                  "%2\$s\n");

        $body = sprintf(
            $msg,
            $user->nickname,
            $siteName,
            $siteEmail
        );

        common_switch_locale();

        if (mail_to_user($user, $subject, $body)) {
            common_log(
                LOG_INFO,
                sprintf(
                    'Sent account lockout warning to %s (%d)',
                    $user->nickname,
                    $user->id
                ),
                __FILE__
            );
        } else {
            common_log(
                LOG_WARNING,
                sprintf(
                    'Unable to send account lockout warning to %s (%d)',
                    $user->nickname,
                    $user->id
                ),
                __FILE__
            );
        }
    }

    /*
     * Check to see if we have a mapping to a copy of this notice
     * on Facebook
     *
     * @param Notice $notice the notice to check
     *
     * @return mixed null if it can't find one, or the id of the Facebook
     *               stream item
     */
    static function facebookStatusId($notice)
    {
        $n2i = Notice_to_item::getKV('notice_id', $notice->id);

        if (empty($n2i)) {
            return null;
        } else {
            return $n2i->item_id;
        }
    }

    /*
     * Save a Foreign_user record of a Facebook user
     *
     * @param object $fbuser a Facebook Graph API user obj
     *                       See: http://developers.facebook.com/docs/reference/api/user
     * @return mixed $result Id or key
     *
     */
    static function addFacebookUser($fbuser)
    {
        // remove any existing, possibly outdated, record
        $luser = Foreign_user::getForeignUser($fbuser->id, FACEBOOK_SERVICE);

        if (!empty($luser)) {

            $result = $luser->delete();

            if ($result != false) {
                common_log(
                    LOG_INFO,
                    sprintf(
                        'Removed old Facebook user: %s, fbuid %d',
                        $fbuid->name,
                        $fbuid->id
                    ),
                    __FILE__
                );
            }
        }

        $fuser = new Foreign_user();

        $fuser->nickname = $fbuser->username;
        $fuser->uri      = $fbuser->link;
        $fuser->id       = $fbuser->id;
        $fuser->service  = FACEBOOK_SERVICE;
        $fuser->created  = common_sql_now();

        $result = $fuser->insert();

        if (empty($result)) {
            common_log(
                LOG_WARNING,
                    sprintf(
                        'Failed to add new Facebook user: %s, fbuid %d',
                        $fbuser->username,
                        $fbuser->id
                    ),
                    __FILE__
            );

            common_log_db_error($fuser, 'INSERT', __FILE__);
        } else {
            common_log(
                LOG_INFO,
                sprintf(
                    'Added new Facebook user: %s, fbuid %d',
                    $fbuser->name,
                    $fbuser->id
                ),
                __FILE__
            );
        }

        return $result;
    }

    /*
     * Remove an item from a Facebook user's feed if we have a mapping
     * for it.
     */
    function streamRemove()
    {
        $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);

        if (!empty($this->flink) && !empty($n2i)) {
            try {
                $result = $this->facebook->api(
                    array(
                        'method'  => 'stream.remove',
                        'post_id' => $n2i->item_id,
                        'uid'     => $this->flink->foreign_id
                    )
                );

                if (!empty($result) && result == true) {
                    common_log(
                      LOG_INFO,
                        sprintf(
                            'Deleted Facebook item: %s for %s (%d), fbuid %d',
                            $n2i->item_id,
                            $this->user->nickname,
                            $this->user->id,
                            $this->flink->foreign_id
                        ),
                        __FILE__
                    );

                    $n2i->delete();

                } else {
                    throw new FaceboookApiException(var_export($result, true));
                }
            } catch (FacebookApiException $e) {
                common_log(
                  LOG_WARNING,
                    sprintf(
                        'Could not deleted Facebook item: %s for %s (%d), '
                            . 'fbuid %d - (API error: %s) item already deleted '
                            . 'on Facebook? ',
                        $n2i->item_id,
                        $this->user->nickname,
                        $this->user->id,
                        $this->flink->foreign_id,
                        $e
                    ),
                    __FILE__
                );
            }
        }
    }

    /*
     * Like an item in a Facebook user's feed if we have a mapping
     * for it.
     */
    function like()
    {
        $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);

        if (!empty($this->flink) && !empty($n2i)) {
            try {
                $result = $this->facebook->api(
                    array(
                        'method'  => 'stream.addlike',
                        'post_id' => $n2i->item_id,
                        'uid'     => $this->flink->foreign_id
                    )
                );

                if (!empty($result) && result == true) {
                    common_log(
                      LOG_INFO,
                        sprintf(
                            'Added like for item: %s for %s (%d), fbuid %d',
                            $n2i->item_id,
                            $this->user->nickname,
                            $this->user->id,
                            $this->flink->foreign_id
                        ),
                        __FILE__
                    );
                } else {
                    throw new FacebookApiException(var_export($result, true));
                }
            } catch (FacebookApiException $e) {
                common_log(
                  LOG_WARNING,
                    sprintf(
                        'Could not like Facebook item: %s for %s (%d), '
                            . 'fbuid %d (API error: %s)',
                        $n2i->item_id,
                        $this->user->nickname,
                        $this->user->id,
                        $this->flink->foreign_id,
                        $e
                    ),
                    __FILE__
                );
            }
        }
    }

    /*
     * Unlike an item in a Facebook user's feed if we have a mapping
     * for it.
     */
    function unLike()
    {
        $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);

        if (!empty($this->flink) && !empty($n2i)) {
            try {
                $result = $this->facebook->api(
                    array(
                        'method'  => 'stream.removeLike',
                        'post_id' => $n2i->item_id,
                        'uid'     => $this->flink->foreign_id
                    )
                );

                if (!empty($result) && result == true) {
                    common_log(
                      LOG_INFO,
                        sprintf(
                            'Removed like for item: %s for %s (%d), fbuid %d',
                            $n2i->item_id,
                            $this->user->nickname,
                            $this->user->id,
                            $this->flink->foreign_id
                        ),
                        __FILE__
                    );

                } else {
                    throw new FacebookApiException(var_export($result, true));
                }
            } catch (FacebookApiException $e) {
                  common_log(
                  LOG_WARNING,
                    sprintf(
                        'Could not remove like for Facebook item: %s for %s '
                          . '(%d), fbuid %d (API error: %s)',
                        $n2i->item_id,
                        $this->user->nickname,
                        $this->user->id,
                        $this->flink->foreign_id,
                        $e
                    ),
                    __FILE__
                );
            }
        }
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Queuehandler for Facebook transport
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

class FacebookQueueHandler extends QueueHandler
{
    function transport()
    {
        return 'facebook';
    }

    function handle($notice)
    {
        if ($this->_isLocal($notice)) {
            return Facebookclient::facebookBroadcastNotice($notice);
        }
        return true;
    }

    /**
     * Determine whether the notice was locally created
     *
     * @param Notice $notice the notice
     *
     * @return boolean locality
     */
    function _isLocal($notice)
    {
        return ($notice->is_local == Notice::LOCAL_PUBLIC ||
                $notice->is_local == Notice::LOCAL_NONPUBLIC);
    }
}


code:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-27 16:31+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#. TRANS: Title for Facebook administration panel.
#: actions/facebookadminpanel.php:53
msgctxt "TITLE"
msgid "Facebook integration settings"
msgstr ""

#. TRANS: Instruction for Facebook administration panel.
#: actions/facebookadminpanel.php:64
msgid "Facebook integration settings"
msgstr ""

#. TRANS: Client error displayed when providing too long a Facebook application ID.
#: actions/facebookadminpanel.php:126
msgid "Invalid Facebook ID. Maximum length is 255 characters."
msgstr ""

#. TRANS: Client error displayed when providing too long a Facebook secret key.
#: actions/facebookadminpanel.php:133
msgid "Invalid Facebook secret. Maximum length is 255 characters."
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookadminpanel.php:183
msgid "Facebook application settings"
msgstr ""

#. TRANS: Field label for Facebook application ID.
#: actions/facebookadminpanel.php:190
msgid "Application ID"
msgstr ""

#. TRANS: Field title for Facebook application ID.
#: actions/facebookadminpanel.php:192
msgid "ID of your Facebook application."
msgstr ""

#. TRANS: Field label for Facebook secret key.
#: actions/facebookadminpanel.php:201
msgid "Secret"
msgstr ""

#. TRANS: Field title for Facebook secret key.
#: actions/facebookadminpanel.php:203
msgid "Application secret."
msgstr ""

#. TRANS: Button text to save Facebook integration settings.
#. TRANS: Submit button to save synchronisation settings.
#: actions/facebookadminpanel.php:220 actions/facebooksettings.php:188
msgctxt "BUTTON"
msgid "Save"
msgstr ""

#. TRANS: Button title to save Facebook integration settings.
#: actions/facebookadminpanel.php:222
msgid "Save Facebook settings."
msgstr ""

#. TRANS: Client error displayed when trying to login while already logged in.
#: actions/facebooklogin.php:43
msgid "Already logged in."
msgstr ""

#. TRANS: Form instructions.
#: actions/facebooklogin.php:52
msgid "Login with your Facebook Account"
msgstr ""

#. TRANS: Page title.
#. TRANS: Alt text for "Login with Facebook" image.
#: actions/facebooklogin.php:67 actions/facebooklogin.php:92
msgid "Login with Facebook"
msgstr ""

#. TRANS: Title for "Login with Facebook" image.
#: actions/facebooklogin.php:94
msgid "Login with Facebook."
msgstr ""

#: actions/facebookfinishlogin.php:50
msgid "Unable to authenticate you with Facebook."
msgstr ""

#. TRANS: Client error displayed when trying to connect to Facebook while not logged in.
#: actions/facebookfinishlogin.php:73
msgid ""
"You must be logged into Facebook to register a local account using Facebook."
msgstr ""

#. TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
#. TRANS: in the same StatusNet site.
#: actions/facebookfinishlogin.php:117 actions/facebookfinishlogin.php:131
msgid "There is already a local account linked with that Facebook account."
msgstr ""

#. TRANS: Client error displayed when the session token does not match or is not given.
#: actions/facebookfinishlogin.php:144 actions/facebooksettings.php:87
msgid "There was a problem with your session token. Try again, please."
msgstr ""

#. TRANS: Form validation error displayed when user has not agreed to the license.
#: actions/facebookfinishlogin.php:154
msgid "You cannot register if you do not agree to the license."
msgstr ""

#. TRANS: Form validation error displayed when an unhandled error occurs.
#: actions/facebookfinishlogin.php:172
msgid "An unknown error has occured."
msgstr ""

#. TRANS: Form instructions for connecting to Facebook.
#. TRANS: %s is the site name.
#: actions/facebookfinishlogin.php:191
#, php-format
msgid ""
"This is the first time you have logged into %s so we must connect your "
"Facebook to a local account. You can either create a new local account, or "
"connect with an existing local account."
msgstr ""

#. TRANS: Page title.
#: actions/facebookfinishlogin.php:201
msgid "Facebook Setup"
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:235
msgid "Connection options"
msgstr ""

#. TRANS: %s is the name of the license used by the user for their status updates.
#: actions/facebookfinishlogin.php:245
#, php-format
msgid ""
"My text and files are available under %s except this private data: password, "
"email address, IM address, and phone number."
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:262
msgid "Create new account"
msgstr ""

#. TRANS: Form instructions.
#: actions/facebookfinishlogin.php:265
msgid "Create a new user with this nickname."
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:273
msgid "New nickname"
msgstr ""

#. TRANS: Field title.
#: actions/facebookfinishlogin.php:276
msgid "1-64 lowercase letters or numbers, no punctuation or spaces."
msgstr ""

#. TRANS: Submit button to create a new account.
#: actions/facebookfinishlogin.php:284
msgctxt "BUTTON"
msgid "Create"
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:290
msgid "Connect existing account"
msgstr ""

#. TRANS: Form instructions.
#: actions/facebookfinishlogin.php:293
msgid ""
"If you already have an account, login with your username and password to "
"connect it to your Facebook."
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:297
msgid "Existing nickname"
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:301
msgid "Password"
msgstr ""

#. TRANS: Submit button to connect a Facebook account to an existing StatusNet account.
#: actions/facebookfinishlogin.php:305
msgctxt "BUTTON"
msgid "Connect"
msgstr ""

#. TRANS: Client error trying to register with registrations not allowed.
#. TRANS: Client error trying to register with registrations 'invite only'.
#: actions/facebookfinishlogin.php:326 actions/facebookfinishlogin.php:335
msgid "Registration not allowed."
msgstr ""

#. TRANS: Client error trying to register with an invalid invitation code.
#: actions/facebookfinishlogin.php:342
msgid "Not a valid invitation code."
msgstr ""

#. TRANS: Server error displayed when connecting to Facebook fails.
#: actions/facebookfinishlogin.php:378 actions/facebookfinishlogin.php:511
msgid "Error connecting user to Facebook."
msgstr ""

#. TRANS: Form validation error displayed when username/password combination is incorrect.
#: actions/facebookfinishlogin.php:478
msgid "Invalid username or password."
msgstr ""

#. TRANS: Page title for Facebook settings.
#: actions/facebooksettings.php:106
msgctxt "TITLE"
msgid "Facebook settings"
msgstr ""

#. TRANS: Instructions for Facebook settings.
#: actions/facebooksettings.php:116
msgid "Facebook settings"
msgstr ""

#. TRANS: Form note. User is connected to facebook.
#: actions/facebooksettings.php:140
msgid "Connected Facebook user"
msgstr ""

#. TRANS: Checkbox label in Facebook settings.
#: actions/facebooksettings.php:168
msgid "Publish my notices to Facebook."
msgstr ""

#. TRANS: Checkbox label in Facebook settings.
#: actions/facebooksettings.php:179
msgid "Send \"@\" replies to Facebook."
msgstr ""

#. TRANS: Fieldset legend for form to disconnect from Facebook.
#: actions/facebooksettings.php:197
msgid "Disconnect my account from Facebook"
msgstr ""

#. TRANS: Notice in disconnect from Facebook form if user has no local StatusNet password.
#: actions/facebooksettings.php:204
#, php-format
msgid ""
"Disconnecting your Faceboook would make it impossible to log in! Please [set "
"a password](%s) first."
msgstr ""

#. TRANS: Message displayed when initiating disconnect of a StatusNet user
#. TRANS: from a Facebook account. %1$s is the StatusNet site name.
#: actions/facebooksettings.php:215
#, php-format
msgid ""
"Keep your %1$s account but disconnect from Facebook. You'll use your %1$s "
"password to log in."
msgstr ""

#. TRANS: Submit button.
#: actions/facebooksettings.php:221
msgctxt "BUTTON"
msgid "Disconnect"
msgstr ""

#. TRANS: Notice in case saving of synchronisation preferences fail.
#: actions/facebooksettings.php:245
msgid "There was a problem saving your sync preferences."
msgstr ""

#. TRANS: Confirmation that synchronisation settings have been saved into the system.
#: actions/facebooksettings.php:248
msgid "Sync preferences saved."
msgstr ""

#. TRANS: Server error displayed when deleting the link to a Facebook account fails.
#: actions/facebooksettings.php:263
msgid "Could not delete link to Facebook."
msgstr ""

#. TRANS: Confirmation message. StatusNet account was unlinked from Facebook.
#: actions/facebooksettings.php:267
msgid "You have disconnected from Facebook."
msgstr ""

#. TRANS: Menu item for "Facebook" in administration panel.
#. TRANS: Menu item for "Facebook" in user settings.
#: FacebookBridgePlugin.php:202 FacebookBridgePlugin.php:241
#: FacebookBridgePlugin.php:281
msgctxt "MENU"
msgid "Facebook"
msgstr ""

#. TRANS: Menu title for "Facebook" login.
#: FacebookBridgePlugin.php:204
msgid "Login or register using Facebook."
msgstr ""

#. TRANS: Menu title for "Facebook" in administration panel.
#: FacebookBridgePlugin.php:243
msgid "Facebook integration configuration."
msgstr ""

#. TRANS: Menu title for "Facebook" in user settings.
#: FacebookBridgePlugin.php:283
msgid "Facebook settings."
msgstr ""

#. TRANS: Plugin description.
#: FacebookBridgePlugin.php:624
msgid "A plugin for integrating StatusNet with Facebook."
msgstr ""

#. TRANS: E-mail subject.
#: lib/facebookclient.php:790
msgid "Your Facebook connection has been removed"
msgstr ""

#. TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
#: lib/facebookclient.php:793
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We are sorry to inform you we are unable to publish your notice to\n"
"Facebook, and have removed the connection between your %2$s account and\n"
"Facebook.\n"
"\n"
"This may have happened because you have removed permission for %2$s\n"
"to post on your behalf, or perhaps you have deactivated your Facebook\n"
"account. You can reconnect your %2$s account to Facebook at any time by\n"
"logging in with Facebook again.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""

#. TRANS: E-mail subject. %s is the StatusNet sitename.
#: lib/facebookclient.php:846
#, php-format
msgid "Contact the %s administrator to retrieve your account"
msgstr ""

#. TRANS: E-mail body. %1$s is a username,
#. TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail address.
#: lib/facebookclient.php:850
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We have noticed you have deauthorized the Facebook connection for your\n"
"%2$s account.  You have not set a password for your %2$s account yet, so\n"
"you will not be able to login. If you wish to continue using your %2$s\n"
"account, please contact the site administrator (%3$s) to set a password.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""


code:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-02-02 17:47+0100\n"
"PO-Revision-Date: 2015-02-06 16:16+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Afrikaans (http://www.transifex.com/projects/p/gnu-social/language/af/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: af\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#. TRANS: Title for Facebook administration panel.
#: actions/facebookadminpanel.php:53
msgctxt "TITLE"
msgid "Facebook integration settings"
msgstr ""

#. TRANS: Instruction for Facebook administration panel.
#: actions/facebookadminpanel.php:64
msgid "Facebook integration settings"
msgstr ""

#. TRANS: Client error displayed when providing too long a Facebook
#. application ID.
#: actions/facebookadminpanel.php:126
msgid "Invalid Facebook ID. Maximum length is 255 characters."
msgstr ""

#. TRANS: Client error displayed when providing too long a Facebook secret
#. key.
#: actions/facebookadminpanel.php:133
msgid "Invalid Facebook secret. Maximum length is 255 characters."
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookadminpanel.php:183
msgid "Facebook application settings"
msgstr ""

#. TRANS: Field label for Facebook application ID.
#: actions/facebookadminpanel.php:190
msgid "Application ID"
msgstr ""

#. TRANS: Field title for Facebook application ID.
#: actions/facebookadminpanel.php:192
msgid "ID of your Facebook application."
msgstr ""

#. TRANS: Field label for Facebook secret key.
#: actions/facebookadminpanel.php:201
msgid "Secret"
msgstr ""

#. TRANS: Field title for Facebook secret key.
#: actions/facebookadminpanel.php:203
msgid "Application secret."
msgstr ""

#. TRANS: Button text to save Facebook integration settings.
#. TRANS: Submit button to save synchronisation settings.
#: actions/facebookadminpanel.php:220 actions/facebooksettings.php:188
msgctxt "BUTTON"
msgid "Save"
msgstr "Stoor"

#. TRANS: Button title to save Facebook integration settings.
#: actions/facebookadminpanel.php:222
msgid "Save Facebook settings."
msgstr ""

#. TRANS: Client error displayed when trying to login while already logged in.
#: actions/facebooklogin.php:43
msgid "Already logged in."
msgstr "U is reeds aangeteken."

#. TRANS: Form instructions.
#: actions/facebooklogin.php:52
msgid "Login with your Facebook Account"
msgstr ""

#. TRANS: Page title.
#. TRANS: Alt text for "Login with Facebook" image.
#: actions/facebooklogin.php:67 actions/facebooklogin.php:92
msgid "Login with Facebook"
msgstr ""

#. TRANS: Title for "Login with Facebook" image.
#: actions/facebooklogin.php:94
msgid "Login with Facebook."
msgstr ""

#: actions/facebookfinishlogin.php:50
msgid "Unable to authenticate you with Facebook."
msgstr ""

#. TRANS: Client error displayed when trying to connect to Facebook while not
#. logged in.
#: actions/facebookfinishlogin.php:73
msgid ""
"You must be logged into Facebook to register a local account using Facebook."
msgstr ""

#. TRANS: Client error displayed when trying to connect to a Facebook account
#. that is already linked
#. TRANS: in the same StatusNet site.
#: actions/facebookfinishlogin.php:117 actions/facebookfinishlogin.php:131
msgid "There is already a local account linked with that Facebook account."
msgstr ""

#. TRANS: Client error displayed when the session token does not match or is
#. not given.
#: actions/facebookfinishlogin.php:144 actions/facebooksettings.php:87
msgid "There was a problem with your session token. Try again, please."
msgstr ""

#. TRANS: Form validation error displayed when user has not agreed to the
#. license.
#: actions/facebookfinishlogin.php:154
msgid "You cannot register if you do not agree to the license."
msgstr ""

#. TRANS: Form validation error displayed when an unhandled error occurs.
#: actions/facebookfinishlogin.php:172
msgid "An unknown error has occured."
msgstr ""

#. TRANS: Form instructions for connecting to Facebook.
#. TRANS: %s is the site name.
#: actions/facebookfinishlogin.php:191
#, php-format
msgid ""
"This is the first time you have logged into %s so we must connect your "
"Facebook to a local account. You can either create a new local account, or "
"connect with an existing local account."
msgstr ""

#. TRANS: Page title.
#: actions/facebookfinishlogin.php:201
msgid "Facebook Setup"
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:235
msgid "Connection options"
msgstr ""

#. TRANS: %s is the name of the license used by the user for their status
#. updates.
#: actions/facebookfinishlogin.php:245
#, php-format
msgid ""
"My text and files are available under %s except this private data: password,"
" email address, IM address, and phone number."
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:262
msgid "Create new account"
msgstr ""

#. TRANS: Form instructions.
#: actions/facebookfinishlogin.php:265
msgid "Create a new user with this nickname."
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:273
msgid "New nickname"
msgstr ""

#. TRANS: Field title.
#: actions/facebookfinishlogin.php:276
msgid "1-64 lowercase letters or numbers, no punctuation or spaces."
msgstr ""

#. TRANS: Submit button to create a new account.
#: actions/facebookfinishlogin.php:284
msgctxt "BUTTON"
msgid "Create"
msgstr ""

#. TRANS: Fieldset legend.
#: actions/facebookfinishlogin.php:290
msgid "Connect existing account"
msgstr ""

#. TRANS: Form instructions.
#: actions/facebookfinishlogin.php:293
msgid ""
"If you already have an account, login with your username and password to "
"connect it to your Facebook."
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:297
msgid "Existing nickname"
msgstr ""

#. TRANS: Field label.
#: actions/facebookfinishlogin.php:301
msgid "Password"
msgstr "Wagwoord"

#. TRANS: Submit button to connect a Facebook account to an existing StatusNet
#. account.
#: actions/facebookfinishlogin.php:305
msgctxt "BUTTON"
msgid "Connect"
msgstr ""

#. TRANS: Client error trying to register with registrations not allowed.
#. TRANS: Client error trying to register with registrations 'invite only'.
#: actions/facebookfinishlogin.php:326 actions/facebookfinishlogin.php:335
msgid "Registration not allowed."
msgstr "Registrasie nie toegelaat nie."

#. TRANS: Client error trying to register with an invalid invitation code.
#: actions/facebookfinishlogin.php:342
msgid "Not a valid invitation code."
msgstr ""

#. TRANS: Server error displayed when connecting to Facebook fails.
#: actions/facebookfinishlogin.php:378 actions/facebookfinishlogin.php:511
msgid "Error connecting user to Facebook."
msgstr ""

#. TRANS: Form validation error displayed when username/password combination
#. is incorrect.
#: actions/facebookfinishlogin.php:478
msgid "Invalid username or password."
msgstr "Ongeldige gebruikersnaam of wagwoord."

#. TRANS: Page title for Facebook settings.
#: actions/facebooksettings.php:106
msgctxt "TITLE"
msgid "Facebook settings"
msgstr ""

#. TRANS: Instructions for Facebook settings.
#: actions/facebooksettings.php:116
msgid "Facebook settings"
msgstr ""

#. TRANS: Form note. User is connected to facebook.
#: actions/facebooksettings.php:140
msgid "Connected Facebook user"
msgstr ""

#. TRANS: Checkbox label in Facebook settings.
#: actions/facebooksettings.php:168
msgid "Publish my notices to Facebook."
msgstr ""

#. TRANS: Checkbox label in Facebook settings.
#: actions/facebooksettings.php:179
msgid "Send \"@\" replies to Facebook."
msgstr ""

#. TRANS: Fieldset legend for form to disconnect from Facebook.
#: actions/facebooksettings.php:197
msgid "Disconnect my account from Facebook"
msgstr ""

#. TRANS: Notice in disconnect from Facebook form if user has no local
#. StatusNet password.
#: actions/facebooksettings.php:204
#, php-format
msgid ""
"Disconnecting your Faceboook would make it impossible to log in! Please [set"
" a password](%s) first."
msgstr ""

#. TRANS: Message displayed when initiating disconnect of a StatusNet user
#. TRANS: from a Facebook account. %1$s is the StatusNet site name.
#: actions/facebooksettings.php:215
#, php-format
msgid ""
"Keep your %1$s account but disconnect from Facebook. You'll use your %1$s "
"password to log in."
msgstr ""

#. TRANS: Submit button.
#: actions/facebooksettings.php:221
msgctxt "BUTTON"
msgid "Disconnect"
msgstr ""

#. TRANS: Notice in case saving of synchronisation preferences fail.
#: actions/facebooksettings.php:245
msgid "There was a problem saving your sync preferences."
msgstr ""

#. TRANS: Confirmation that synchronisation settings have been saved into the
#. system.
#: actions/facebooksettings.php:248
msgid "Sync preferences saved."
msgstr ""

#. TRANS: Server error displayed when deleting the link to a Facebook account
#. fails.
#: actions/facebooksettings.php:263
msgid "Could not delete link to Facebook."
msgstr ""

#. TRANS: Confirmation message. StatusNet account was unlinked from Facebook.
#: actions/facebooksettings.php:267
msgid "You have disconnected from Facebook."
msgstr ""

#. TRANS: Menu item for "Facebook" in administration panel.
#. TRANS: Menu item for "Facebook" in user settings.
#: FacebookBridgePlugin.php:202 FacebookBridgePlugin.php:241
#: FacebookBridgePlugin.php:281
msgctxt "MENU"
msgid "Facebook"
msgstr ""

#. TRANS: Menu title for "Facebook" login.
#: FacebookBridgePlugin.php:204
msgid "Login or register using Facebook."
msgstr ""

#. TRANS: Menu title for "Facebook" in administration panel.
#: FacebookBridgePlugin.php:243
msgid "Facebook integration configuration."
msgstr ""

#. TRANS: Menu title for "Facebook" in user settings.
#: FacebookBridgePlugin.php:283
msgid "Facebook settings."
msgstr ""

#. TRANS: Plugin description.
#: FacebookBridgePlugin.php:624
msgid "A plugin for integrating StatusNet with Facebook."
msgstr ""

#. TRANS: E-mail subject.
#: lib/facebookclient.php:790
msgid "Your Facebook connection has been removed"
msgstr ""

#. TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
#: lib/facebookclient.php:793
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We are sorry to inform you we are unable to publish your notice to\n"
"Facebook, and have removed the connection between your %2$s account and\n"
"Facebook.\n"
"\n"
"This may have happened because you have removed permission for %2$s\n"
"to post on your behalf, or perhaps you have deactivated your Facebook\n"
"account. You can reconnect your %2$s account to Facebook at any time by\n"
"logging in with Facebook again.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""

#. TRANS: E-mail subject. %s is the StatusNet sitename.
#: lib/facebookclient.php:846
#, php-format
msgid "Contact the %s administrator to retrieve your account"
msgstr ""

#. TRANS: E-mail body. %1$s is a username,
#. TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail
#. address.
#: lib/facebookclient.php:850
#, php-format
msgid ""
"Hi %1$s,\n"
"\n"
"We have noticed you have deauthorized the Facebook connection for your\n"
"%2$s account.  You have not set a password for your %2$s account yet, so\n"
"you will not be able to login. If you wish to continue using your %2$s\n"
"account, please contact the site administrator (%3$s) to set a password.\n"
"\n"
"Sincerely,\n"
"\n"
"%2$s\n"
msgstr ""