You are here

fb_autopost.module in Facebook Autopost 7

Module implementation file

File

fb_autopost.module
View source
<?php

/**
 * @file
 * Module implementation file
 */

/**
 * Implements hook_help().
 */
function fb_autopost_help($path, $arg) {
  switch ($path) {

    // Main module help for the block module.
    case 'admin/help#fb_autopost':
      return '<p>' . t('Facebook Autopost allows you to identify a Facebook user, select one of his/her Facebook pages and set autoposting to it. !link.', array(
        '!link' => l(t('Configure Facebook Autopost'), 'admin/config/services/fbautopost'),
      )) . '</p>';
  }
}

/**
 * Implements hook_menu().
 */
function fb_autopost_menu() {
  $items = array();
  $items['admin/config/services/fbautopost'] = array(
    'title' => 'Facebook Autopost',
    'description' => 'Allows you to set your Facebook credentials and select the pages you want to make available to Drupal to post to.',
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'fb_autopost_global_settings',
    ),
    'file' => 'fb_autopost.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/services/fbautopost/settings'] = $items['admin/config/services/fbautopost'];
  $items['admin/config/services/fbautopost/settings']['type'] = MENU_DEFAULT_LOCAL_TASK;
  $items['admin/config/services/fbautopost/login'] = array(
    'title' => 'Facebook Autopost Login',
    'description' => 'Callback that executes right after login in with Facebook.',
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'fb_autopost_facebook_login',
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/fbautopost/logout'] = array(
    'title' => 'Facebook Autopost Logout',
    'description' => 'Callback that executes right after login in from Facebook.',
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'fb_autopost_facebook_logout',
    'type' => MENU_CALLBACK,
  );
  $items['fbautopost/authorization/retry'] = array(
    'title' => 'Post Authorization retry callback',
    'description' => 'Come back here after authorizing the app for publishing on timeline.',
    'access arguments' => array(
      'access content',
    ),
    'page callback' => 'fb_autopost_authorization_retry',
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/fbautopost/session/view'] = array(
    'title' => 'View',
    'description' => 'View the session data.',
    'page arguments' => array(
      5,
    ),
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'fb_autopost_session',
    'type' => MENU_LOCAL_ACTION,
  );
  $items['admin/config/services/fbautopost/session/clear'] = array(
    'title' => 'Clear',
    'description' => 'Clear the session data.',
    'page arguments' => array(
      5,
    ),
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'fb_autopost_session',
    'type' => MENU_LOCAL_ACTION,
  );
  $items['admin/config/services/fbautopost/session'] = array(
    'title' => 'Session handling',
    'description' => 'Perform administrative tasks over the session object.',
    'page arguments' => array(
      'view',
    ),
    'access arguments' => array(
      'administer fb_autopost',
    ),
    'page callback' => 'fb_autopost_session',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function fb_autopost_permission() {
  return array(
    'administer fb_autopost' => array(
      'title' => t('Administer Facebook Autopost'),
      'description' => t('Allows setting default Facebook pages to publish to.'),
    ),
  );
}

/**
 * Helper function to redirect after facebook login.
 */
function fb_autopost_facebook_login() {

  // Show error messages from Facebook.
  if (isset($_GET['error'])) {
    drupal_set_message(t('An error happened while connecting with Facebook. Reason: %reason. Description: %description', array(
      '%reason' => $_GET['error_reason'],
      '%description' => $_GET['error_description'],
    )), 'error');
  }
  else {
    try {
      $fb = facebook_autopost();
      if ($fb_user = $fb
        ->getUser()) {
        $token = $fb
          ->getAccessToken();
        variable_set('fb_autopost_token', $token);
        $user_profile = $fb
          ->api('/me?fields=id');
        variable_set('fb_autopost_account_id', $user_profile['id']);
      }
    } catch (FacebookApiException $e) {

      // Do nothing with the exception.
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }
  drupal_goto('admin/config/services/fbautopost');
}

/**
 * Helper function to redirect after facebook logout.
 */
function fb_autopost_facebook_logout() {
  try {
    $fb = facebook_autopost();

    // Invalidate access_token
    $fb
      ->api('/' . variable_get('fb_autopost_account_id', 'me') . '/permissions', 'DELETE');
  } catch (FacebookApiException $e) {

    // Do nothing with the exception.
    drupal_set_message($e
      ->getMessage(), 'error');
  }
  drupal_set_message(t('Your account has been logged out from Facebook and the permissions for the app have been removed.'));

  // Delete stored variables.
  variable_del('fb_autopost_account_id');
  variable_del('fb_autopost_page');
  drupal_goto('admin/config/services/fbautopost');
}

/**
 * Helper function to publish on user timeline after failing the first time.
 */
function fb_autopost_authorization_retry() {
  try {
    $session = new FBSession();

    // Check if there is all necessary data.
    if ($session
      ->isStored()) {
      $data = $session
        ->getStoredPublication();
      $fb = facebook_autopost($data['publication']['type']);

      // Prevent infinite loop of requesting permissions.
      $fb
        ->setRetry(FALSE);
      $fb
        ->setDestination($data['target']);
      $fb
        ->publish($data['publication']);
    }
  } catch (Exception $e) {

    // Not removing session would lead to be unable to publish until
    // session gets regenerated.
    $session = new FBSession();
    $session
      ->removePublication();
    watchdog_exception('fb_autopost', $e);
    drupal_set_message($e
      ->getMessage(), 'error');
  }

  // This method does not throw anything.
  $destination = isset($data['destination']) ? $data['destination'] : '<front>';
  $session
    ->removePublication();
  drupal_goto($destination);
}

/**
 * Implements hook_theme().
 */
function fb_autopost_theme($existing, $type, $theme, $path) {
  return array(
    'fb_autopost_facebook_profile' => array(
      'render element' => 'fbprofile',
      'file' => 'fb_autopost.theme.inc',
    ),
    'fb_autopost_facebook_page' => array(
      'variables' => array(
        'name' => NULL,
        'id' => 145634995501895,
        'category' => NULL,
      ),
      'file' => 'fb_autopost.theme.inc',
    ),
  );
}

/**
 * Helper function to load the facebook php sdk library.
 *
 * @param string $basename
 *   Optional basename where to find the library
 *
 * @throws Exception
 */
function _load_facebook_sdk($basename = NULL) {
  $lib_path = libraries_get_path('facebook-php-sdk', $basename);
  if (!file_exists($lib_path . '/src/facebook.php')) {

    // In case we cannot find the file display an error and redirect to the
    // report status page (if the user can access it).
    if (user_access('view site reports')) {
      drupal_set_message(t('You need to install the !library to use the Facebook Autopost module. Please download the library to sites/all/libraries/facebook-php-sdk.', array(
        '!library' => l(t('Facebook PHP Library'), 'https://github.com/facebook/facebook-php-sdk', array(
          'attributes' => array(
            'target' => '_blank',
          ),
        )),
      )), 'error');
      drupal_goto('admin/reports/status');
    }
    else {

      // The user cannot see the site reports with further instructions
      // throw an Exception.
      throw new FBAutopostException(t('Facebook Autopost could not be started because the Facebook PHP library is missing. Please contact system administration to communicate this error.'));
    }
  }
  else {
    require_once $lib_path . '/src/facebook.php';
  }
}

/**
 * Page callback to perform an action on the session object.
 *
 * @param string $op
 *   The operation being performed. Supported:
 *     - clear
 *     - view
 */
function fb_autopost_session($op = 'view') {
  $session = new FBSession();
  switch ($op) {
    case 'view':
      if ($session
        ->isStored()) {
        $output = $session
          ->getStoredPublication();

        // Use devel's output if available.
        if (function_exists('dpm')) {
          return dpm($output);
        }
        return '<pre>' . print_r($output, TRUE) . '</pre>';
      }
      else {
        return t('No session data to show.');
      }
    case 'clear':
      $session
        ->removePublication();
      drupal_set_message(t('Session data for Facebook Autopost has been removed.'));
      return fb_autopost_session();
  }
}

/**
 * Factory function.
 *
 * Add here the classes that need to override methods from FBAutopost.
 *
 * @param string $type
 *   The type of Facebook publication to return. Use NULL to not specify a type.
 */
function facebook_autopost($type = NULL) {
  switch ($type) {
    case 'photo':
      $fb = new FBAutopostPhoto();
      break;
    case 'event':
      $fb = new FBAutopostEvent();
      break;
    case 'post':
      $fb = new FBAutopostPost();
      break;
    default:
      $fb = new FBAutopost();
      break;
  }
  if ($type) {
    $fb
      ->setType($type);
  }

  // Allow other modules to alter $fb.Useful for altering the underlying
  // BaseFacebook object for things like adding proxy support to curl options
  drupal_alter('facebook_autopost_fb', $fb);
  return $fb;
}

Functions

Namesort descending Description
facebook_autopost Factory function.
fb_autopost_authorization_retry Helper function to publish on user timeline after failing the first time.
fb_autopost_facebook_login Helper function to redirect after facebook login.
fb_autopost_facebook_logout Helper function to redirect after facebook logout.
fb_autopost_help Implements hook_help().
fb_autopost_menu Implements hook_menu().
fb_autopost_permission Implements hook_permission().
fb_autopost_session Page callback to perform an action on the session object.
fb_autopost_theme Implements hook_theme().
_load_facebook_sdk Helper function to load the facebook php sdk library.