You are here

function cas_roles_cas_user_presave in CAS roles 7

Same name and namespace in other branches
  1. 8 cas_roles.module \cas_roles_cas_user_presave()
  2. 6 cas_roles.module \cas_roles_cas_user_presave()
  3. 7.2 cas_roles.module \cas_roles_cas_user_presave()

Implements hook_cas_user_presave().

File

./cas_roles.module, line 52
Allows user account and profile attributes to be automatically populated using tokens. Provides basic tokens for attributes returned by the CAS server.

Code

function cas_roles_cas_user_presave(&$edit, $account) {
  $sync_every_login = variable_get('cas_roles_sync_every_login');
  $behavior = variable_get('cas_roles_behavior');
  $relations = variable_get('cas_roles_relations', array(
    '2' => NULL,
  ));

  // We synchronize on the first login (always) & on future logins (if chosen).
  if ($account->login && !$sync_every_login) {

    // The user has logged in before and we are not set to always synchronize.
    return;
  }
  $role_candidates = cas_roles_candidates($edit['cas_user']);
  if ($behavior == CAS_ROLES_CREATE_NEW_ROLES) {
    $new_roles = array_diff($role_candidates, user_roles());

    // Create new roles.
    foreach ($new_roles as $new) {
      $role = (object) array(
        'name' => $new,
      );
      user_role_save($role);
    }
  }
  if ($behavior == CAS_ROLES_MATCH_REGEX) {

    // Do regexp matching!
    $custom_roles = cas_roles_cutsom_user_roles();
    $new_user_roles = $edit['roles'];
    foreach ($custom_roles as $rid => $role) {
      if (array_key_exists($role, $relations) && $relations[$role]) {
        $matches = preg_grep($relations[$role], $role_candidates);
        if (!empty($matches)) {
          $new_user_roles[$rid] = $role;
        }
        else {
          unset($new_user_roles[$rid]);
        }
      }
    }
  }
  else {

    // Just assign the roles!
    // Add the authenticated user role.
    $new_user_roles = array_intersect(cas_roles_cutsom_user_roles(), $role_candidates);
  }
  $new_user_roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';

  // Set the (new) roles.
  $edit['roles'] = $new_user_roles;
}