You are here

function cas_attributes_map_roles in CAS Attributes 7

Map roles to the pre-defined CAS or LDAP attributes.

1 call to cas_attributes_map_roles()
cas_attributes_cas_user_presave in ./cas_attributes.module
Implements hook_cas_user_presave().

File

./cas_attributes.module, line 90
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_attributes_map_roles(&$edit, $account) {
  $data = array(
    'cas' => $edit['cas_user']['name'],
  );

  // Make sure there are attributes to check.
  $mapping = variable_get('cas_attributes_roles_mapping', '');
  if (!empty($mapping)) {

    // Get the users attributes, either via CAS or LDAP
    $attribute_matching_type = variable_get('cas_attributes_roles_cas_or_ldap', 'cas');
    if (module_exists('cas_ldap') && $attribute_matching_type == 'ldap') {
      $user_attributes = cas_ldap_attributes($data['cas']);
    }
    else {

      // If nothing has been specified (e.g. because of a module upgrade) use CAS.
      $user_attributes = cas_phpcas_attributes($data['cas']);
    }

    // Allow other modules to manipulate the attribute values.
    // Can't use module_invoke_all() because we need to pass byref.
    $arguments = array(
      &$user_attributes,
    );
    foreach (module_implements('cas_attributes_roles_modify') as $module) {
      $function = $module . '_cas_attributes_roles_modify';
      call_user_func_array($function, $arguments);
    }

    // Build all the attributes to check.
    $attributes_to_check = preg_split("#\r\n|\n|\r#", $mapping);
    $cas_user_roles = array();
    foreach ($attributes_to_check as $attribute) {
      $attribute = trim($attribute);
      if (!empty($user_attributes[$attribute])) {
        if (is_array($user_attributes[$attribute])) {
          $cas_user_roles = array_merge($cas_user_roles, $user_attributes[$attribute]);
        }
        else {
          $cas_user_roles[] = $user_attributes[$attribute];
        }
      }
    }

    // Loop through all the managed roles and see if the user has access to them
    // and set accordingly.
    $roles = user_roles();
    foreach (variable_get('cas_attributes_roles_manage', array()) as $rid) {
      if (!empty($rid)) {
        if (in_array($roles[$rid], $cas_user_roles)) {
          $edit['roles'][$rid] = $roles[$rid];
        }
        else {
          unset($edit['roles'][$rid]);
        }
      }
    }
  }
}