You are here

twitter_signin.module in Twitter 7.6

Hook implementations for Twitter Signin module.

File

twitter_signin/twitter_signin.module
View source
<?php

/**
 * @file
 * Hook implementations for Twitter Signin module.
 */

/**
 * Implements hook_menu().
 */
function twitter_signin_menu() {
  $items['twitter/redirect'] = array(
    'title' => 'Twitter Redirect',
    'page callback' => 'twitter_signin_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/twitter/signin'] = array(
    'title' => 'Sign-in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'twitter_signin_admin_settings',
    ),
    'access arguments' => array(
      'administer twitter',
    ),
    'file' => 'twitter_signin.pages.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
  );
  return $items;
}

/**
 * Implements hook_block_info().
 */
function twitter_signin_block_info() {
  $block[0]['info'] = t('Sign in with Twitter');
  return $block;
}

/**
 * Implements hook_block_view().
 */
function twitter_signin_block_view($delta) {

  // Don't do anything if the credentials haven't been set up yet.
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  if (empty($key) || empty($secret)) {
    return;
  }
  global $user;
  if (!$user->uid) {
    $block['subject'] = t('Sign in with Twitter');
    $block['content'] = twitter_signin_button();
    return $block;
  }
}

/**
 * Returns an image link for signing in with Twitter.
 */
function twitter_signin_button() {
  return theme('twitter_signin_button');
}

/**
 * Implements hook_theme().
 */
function twitter_signin_theme() {
  return array(
    'twitter_signin_button' => array(),
  );
}

/**
 * Themable function for an image link for signing in with Twitter.
 */
function theme_twitter_signin_button() {
  $button = variable_get('twitter_signin_button', 'Sign-in-with-Twitter-lighter-small.png');
  $class = array(
    'twitter-signin-menuitem',
  );
  if ($button == 'just-text') {
    $item = t('Sign in with Twitter');
    $class[] = 'twitter-signin-menuitem-just-text';
    $link = l($item, 'twitter/redirect', array(
      'attributes' => array(
        'class' => $class,
      ),
    ));
  }
  else {
    $img = drupal_get_path('module', 'twitter_signin') . '/images/' . $button;
    $item = theme('image', array(
      'path' => $img,
      'alt' => t('Sign in with Twitter'),
    ));
    $class[] = 'twitter-signin-menuitem-image';
    $link = l($item, 'twitter/redirect', array(
      'html' => TRUE,
      'attributes' => array(
        'class' => $class,
      ),
    ));
  }
  return $link;
}

/**
 * Submit handler for Twitter signin.
 */
function twitter_signin_redirect() {
  module_load_include('inc', 'twitter');
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  $twitter = new Twitter($key, $secret);

  // Specify a callback_url when generating our token that will match the
  // current domain.
  $oauth_callback = variable_get('twitter_oauth_callback_url', TWITTER_OAUTH_CALLBACK_URL);
  $callback_url = url($oauth_callback, array(
    'absolute' => TRUE,
  ));
  $params = array(
    'oauth_callback' => $callback_url,
  );
  $token = $twitter
    ->get_request_token($params);
  $_SESSION['twitter_oauth']['token'] = $token;
  $_SESSION['twitter_oauth']['destination'] = $_SERVER['HTTP_REFERER'];
  $_SESSION['twitter_oauth']['signin'] = TRUE;
  drupal_goto($twitter
    ->get_authenticate_url($token));
}

/**
 * Implements hook_form_alter().
 */
function twitter_signin_form_alter(&$form, $form_state, $form_id) {

  // By default don't do anything when the site is in maintenance mode, but
  // allow this to be changed so that admins can still login.
  if (defined('MAINTENANCE_MODE') && !variable_get('twitter_signin_maintenance_mode', FALSE)) {
    return;
  }
  if ($form_id == 'twitter_oauth_callback_form' && isset($_SESSION['twitter_oauth']['signin'])) {
    $form['#submit'] = array_merge(array(
      'twitter_signin_oauth_callback_submit',
    ), $form['#submit']);
  }

  // Don't do anything else if the credentials haven't been set up yet.
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  if (empty($key) || empty($secret)) {
    return;
  }

  // Login forms.
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    if (variable_get('twitter_signin_login', TRUE)) {
      $items = array();
      $items[] = twitter_signin_button();
      $form['twitter_signin'] = array(
        '#theme' => 'item_list',
        '#items' => $items,
        '#attributes' => array(
          'class' => array(
            'twitter_signin',
          ),
        ),
      );
    }
  }
  elseif ($form_id == 'user_register_form' && isset($_SESSION['twitter']['values'])) {
    $form['account']['name']['#default_value'] = $_SESSION['twitter']['values']['screen_name'];
    $form['auth_twitter'] = array(
      '#type' => 'hidden',
      '#value' => $_SESSION['twitter']['values']['user_id'],
    );
  }
}

/**
 * Form submit for the OAuth callback. Here we add in sign-in specific handling.
 */
function twitter_signin_oauth_callback_submit(&$form, &$form_state) {
  global $user;
  $success = FALSE;
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  $response = $form_state['twitter_oauth']['response'];
  $account = user_external_load($response['user_id']);
  if (!empty($account)) {
    $account = array(
      'uid' => $account->uid,
    );
    user_login_submit(array(), $account);
    $success = TRUE;
  }
  else {
    $uid = db_query("SELECT uid FROM {twitter_account} WHERE twitter_uid = :twitter_uid", array(
      ':twitter_uid' => $response['user_id'],
    ))
      ->fetchField();

    // We have an existing Twitter account - set it up for login.
    if (!empty($uid)) {
      $account = user_load($uid);
      $edit["authname_twitter"] = $response['user_id'];
      user_save($account, $edit);
      $success = TRUE;
    }
    elseif (variable_get('twitter_signin_register', 0)) {

      // Check for a nickname collision.
      $users = user_load_multiple(array(), array(
        'name' => $response['screen_name'],
      ));
      $account = array_shift($users);
      if (empty($account->uid)) {

        // Generate a random password.
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $password = user_password();

        // Create a new user account object.
        $account = new stdClass();
        $account->name = $response['screen_name'];
        $account->pass = $password;
        $account->init = $response['screen_name'];
        $account->status = 1;
        $account->authname_twitter = $response['user_id'];
        $account->access = REQUEST_TIME;
        $account->is_new = TRUE;

        // Try saving the new user account.
        try {
          $account = user_save($account);
        } catch (Exception $e) {
          watchdog('oauth_login', "Exception saving new account: " . $e
            ->getMessage(), '', WATCHDOG_WARNING);
          return FALSE;
        }

        // Reload the user's account object.
        $account = user_load($account->uid);
        $args = array(
          '!password' => $password,
          '!url' => url('user/' . $account->uid . '/edit'),
        );
        if (variable_get('twitter_signin_show_password', TRUE)) {
          drupal_set_message(t('You have been automatically registered with the password !password. Copy it to <a href="!url">set your account settings</a>.', $args));
        }
        $success = TRUE;
      }
      else {
        $args = array(
          '%name' => $response['screen_name'],
          '@login' => url('user/login'),
        );
        drupal_set_message(t('The nickname %name is already in use on this site, please register below with a new nick name, or @login to continue.', $args), 'warning');
      }
    }
    else {
      drupal_set_message(t('Please log in or register to relate your Twitter account with a user.'));
    }
  }

  // If there was a problem, return to the login screen.
  if (!$success) {
    $_SESSION['twitter']['values'] = $response;
    drupal_goto('user/login');
  }
  else {

    // Log the user into their account.
    $user = $account;

    // Connect the Drupal user account and the Twitter account together.
    $form_state['twitter_oauth']['account'] = $account;

    // Finish the login process.
    $form_state['uid'] = $user->uid;
    user_login_finalize($form_state);
  }
}

/**
 * Implements hook_user_insert().
 *
 * Relates a Twitter account with a just created user account if the user
 * signed in with Twitter but did not have an account in the site yet.
 */
function twitter_signin_user_insert(&$edit, $account, $category) {
  _twitter_signin_add_account($edit, $account);
}

/**
 * Implements hook_user_login().
 *
 * Relates a Twitter account with an existing user account if the user
 * signed in with Twitter.
 */
function twitter_signin_user_login(&$edit, $account) {
  _twitter_signin_add_account($edit, $account);
}

/**
 * Relates a user account with a Twitter account.
 *
 * @param $account
 *   The Drupal user account.
 */
function _twitter_signin_add_account($edit, $account) {
  if (isset($_SESSION['twitter']['values'])) {
    module_load_include('inc', 'twitter');
    $key = variable_get('twitter_consumer_key', '');
    $secret = variable_get('twitter_consumer_secret', '');
    $response = $_SESSION['twitter']['values'];
    $twitter = new Twitter($key, $secret, $response['oauth_token'], $response['oauth_token_secret']);
    try {
      $twitter_account = $twitter
        ->users_show($response['screen_name']);
    } catch (TwitterException $e) {
      drupal_set_message(t('Request failed: @message.', array(
        '@message' => $e
          ->getMessage(),
      )), 'error');
      return;
    }
    $twitter_account
      ->set_auth($response);
    $twitter_account->uid = $account->uid;
    twitter_account_save($twitter_account);
    unset($_SESSION['twitter']);
    drupal_set_message(t('You have related a Twitter account with your user. Next time you can sign in with Twitter.'));
  }
}

Functions

Namesort descending Description
theme_twitter_signin_button Themable function for an image link for signing in with Twitter.
twitter_signin_block_info Implements hook_block_info().
twitter_signin_block_view Implements hook_block_view().
twitter_signin_button Returns an image link for signing in with Twitter.
twitter_signin_form_alter Implements hook_form_alter().
twitter_signin_menu Implements hook_menu().
twitter_signin_oauth_callback_submit Form submit for the OAuth callback. Here we add in sign-in specific handling.
twitter_signin_redirect Submit handler for Twitter signin.
twitter_signin_theme Implements hook_theme().
twitter_signin_user_insert Implements hook_user_insert().
twitter_signin_user_login Implements hook_user_login().
_twitter_signin_add_account Relates a user account with a Twitter account.