csna_weibo.module 2.38 KB
<?php
/**
 * @file
 * The CSNA Weibo module is a sub-module of the Chinese Social Networks
 * Authentication (CSNA) framework allowing integration with the Weibo OAuth
 * protocol for Authentication/Login.
 */

/**
 * Implements hook_csna_provider_info().
 */
function csna_weibo_csna_provider_info() {
  $providers = array();

  $providers['weibo'] = array(
    'title' => t('Weibo Sina'),
    'description' => t('Set your <strong>Sina Weibo authorized KEY</strong> and <strong>SECRET</strong> below.<br/>If you want to use an API key, you can get one at the !keylink.', array('!keylink' => l(t('Sina Weibo API website'), 'http://open.weibo.com/', array('attributes' => array('target' => '_blank'))))),
    'display_title' => csna_get_weibo_button_image(),
    'type' => CSNA_OAUTH2,
    'authorize_uri' => 'https://api.weibo.com/oauth2/authorize',
    'access_token_uri' => 'https://api.weibo.com/oauth2/access_token',
    'info_uri' => 'https://api.weibo.com/2/users/show.json',
  );

  return $providers;
}

/**
 * Helper function for returning a themed image for the Weibo display title.
 */
function csna_get_weibo_button_image() {
  $image_arr = array(
    'path' => drupal_get_path('module', 'csna_weibo') . '/weibo_126x24.png',
    'title' => t('Sign in with Weibo'),
    'alt' => t('Sign in with Weibo'),
  );
  return theme('image', $image_arr);
}

/**
 * Implements hook_csna_provider_callback().
 */
function csna_weibo_csna_provider_callback($provider, $request) {
  if (isset($request['code'])) {
    $parameters = array(
      'client_id' => $provider['key'],
      'client_secret' => $provider['secret'],
      'grant_type' => 'authorization_code',
      'redirect_uri' => $provider['callback'],
      'code' => $request['code'],
    );

    $param_data = array(
      'method' => 'POST',
      'data' => drupal_http_build_query($parameters),
    );

    $http = drupal_http_request(url($provider['access_token_uri'], array('query' => $parameters)), $param_data);
    $data = json_decode($http->data);
    $http = drupal_http_request(url($provider['info_uri'], array('query' => array('access_token' => $data->access_token, 'uid' => $data->uid))));
    $info = json_decode($http->data);
    if (!isset($info->id)) {
      return FALSE;
    }
    return array(
      'access_token' => $data->access_token,
      'uid' => $info->id,
      'name' => $info->name,
      'avatar_link' => $info->avatar_large,
    );
  }
}