<?php

/**
 * Implement hook_menu()
 *
 * @return multitype:string
 */

function groups_auth_menu() {
  $items['login'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'groups_auth_login',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implement hook_menu_alter
 *
 * Disable "Request new password" tab on user profile page.
 * Override /user callback.
 * Set administrator role only access to openid tab of user profile.
 *
 * @param unknown &$items
 *  menu items to alter.
 */

function groups_auth_menu_alter(&$items) {
  $items['user/password']['access callback'] = FALSE;
  // Uncomment this to restrict access to standard Drupal
  // login page and redirect to openid provider.
  // $items['user']['page callback'] = 'groups_auth_user_page';
  // unset($items['user']['file']);
  $items['user/%user/openid']['page callback'] = 'groups_auth_user_identities';
  $items['user/%user/openid']['access callback'] = 'groups_auth_role_access';
  $items['user/%user/openid']['access arguments'] = array('administrator');
  $items['user/%user/edit-profile']['access arguments'] = array('administrator');
  $items['user/%user/edit-profile']['access callback'] = 'groups_auth_role_access';
  $items['user/%user/edit']['access arguments'] = array('administrator');
  $items['user/%user/edit']['access callback'] = 'groups_auth_role_access';
}

/**
 * Returns TRUE if the actual user have the speicified
 * role.
 */
function groups_auth_role_access($role) {
  global $user;
  return in_array($role, array_values($user->roles));
}

/**
 * Implements hook_module_implements_alter().
 *
 * Move groups_auth_XXX_form_alter() to the end of the list to access
 * openid form elements from groups_auth module.
 *
 * @param $implementations
 *   All implementations of the given hook.
 * @param $hook
 *   Name of the hook.
 */
function groups_auth_module_implements_alter(&$implementations, $hook) {
  if (($hook == 'form_alter') &&
      (isset($implementations['groups_auth']))) {
    $group = $implementations['groups_auth'];
    unset($implementations['groups_auth']);
    $implementations['groups_auth'] = $group;
  }
}

/**
 * Override user module's page callback
 *
 * Enforce openid authentication for unauthenticated users, otherwise
 * display the profile page.
 *
 * @return
 *   A render array for a user profile
 */

function groups_auth_user_page() {
  global $user;
  if ($user->uid) {
    menu_set_active_item('user/' . $user->uid);
    return menu_execute_active_handler(NULL, FALSE);
  }
  else {
    groups_auth_login();
  }
}

/**
 * hook_FORM_ID_alter()
 *
 * Remove openid links form element.
 * Remove alternate openid login form element.
 */
function groups_auth_form_user_login_alter(&$form, &$form_state) {
  if (isset($form['openid_links'])) {
    unset($form['openid_links']);
  }
  if (isset($form['openid_identifier'])) {
    unset($form['openid_identifier']);
  }
}

/**
 * Implement hook_FORM_ID_form_alter.
 *
 * Restrict registration form to openid authentication, by default
 * redirect to openstack.org profile registration page.
 *
 */

function groups_auth_form_user_register_form_alter(&$form, &$form_state) {
  if (isset($_SESSION['openid']['response'])) {
    module_load_include('inc', 'openid');
    $response = $_SESSION['openid']['response'];
    if (!empty($response['openid.sreg.nickname'])) {
      $form['account']['name']['#default_value'] = $response['openid.sreg.nickname'];
    }
    if (!empty($response['openid.sreg.email'])) {
      // Use the email returned by Simple Registration if available.
      $form['account']['mail']['#default_value'] = $response['openid.sreg.email'];
    }
    if (isset($form['group_access'])) {
       // set default to: Public - accessible to all site users
      $form['group_access'][LANGUAGE_NONE]['#default_value'] = array(0 => 0);
    }
  } else {
    // Redirect to openstack.org profile registration page
    drupal_goto("https://www.openstack.org/join/register");
  }
}

/**
 * Openid login callback.
 *
 */

function groups_auth_login() {
  if (module_exists('groups_oauth2')) {
    groups_oauth2_user_login_submit();
  } else {
    $return_to = url('openid/authenticate',
      array('absolute' => TRUE, 'query' => array('destination' => '<front>')));
    $openid_url = variable_get('groups_openid_provider', 'https://openstackid-dev.openstack.org');
    openid_begin($openid_url, $return_to, array());
  }
}

/**
 * Implement hook_form_user_profile_form_alter
 *
 * Disable password and email address override on user profile.
 *
 * @param unknown $form
 * @param unknown $form_state
 */

function groups_auth_form_user_profile_form_alter( &$form, $form_state ) {
  $form['account']['name']['#disabled'] = TRUE;
  $form['account']['name']['#description'] = t('The username for this account cannot be changed');
  $form['account']['mail']['#disabled'] = TRUE;
  $form['account']['mail']['#description'] = t('This e-mail address for this account cannot be changed.');
  $form['account']['current_pass']['#disabled'] = TRUE;
  $form['account']['current_pass']['#description'] = t('Neither the email address or password for this account can be changed.');
  $form['account']['pass']['#disabled'] = TRUE;
  $form['account']['pass']['#description'] = t('The password for this account cannot be changed.');
}

/**
 * Implement hook_commons_utility_links_alter()
 *
 * Override login href to provide openid one.
 */

function groups_auth_commons_utility_links_alter(&$links) {
  if (isset($links['login'])) {
    unset($links['login']);
  }
  if (isset($links['signup'])) {
    $links['signup']['href'] = 'login';
  }
  if (isset($links['name'])) {
    $links['name']['title'] = t('View profile');
  }
  if (isset($links['logout'])) {
    $links['logout']['weight'] = 1000;
  }
  if (isset($links['settings'])) {
    unset($links['settings']);
  }
}

/**
 * Remove the Add OpenID feature from OpenID identities tab
 * of user profile.
 *
 * @see openid_user_identities()
 */
function groups_auth_user_identities($account) {
  drupal_set_title(format_username($account));
  drupal_add_css(drupal_get_path('module', 'openid') . '/openid.css');
  $header = array(t('OpenID'), t('Operations'));
  $rows = array();

  $result = db_query("SELECT * FROM {authmap} WHERE module='openid' AND uid=:uid", array(':uid' => $account->uid));
  foreach ($result as $identity) {
    $rows[] = array(check_plain($identity->authname), l(t('Delete'), 'user/' . $account->uid . '/openid/delete/' . $identity->aid));
  }

  $build['openid_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No OpenID identities available for this account.'),
  );
  return $build;
}