You are here

function user_permissions_profile_permissions_form_submit in User Permissions 7

Same name and namespace in other branches
  1. 5 user_permissions.module \user_permissions_profile_permissions_form_submit()
  2. 6 user_permissions.module \user_permissions_profile_permissions_form_submit()

Handles submission of user_permissions_profile_permissions_form

If the user has a role created by this module, this updates the permissions for this role. Otherwise it creates the new role with the new permissions if any permissions were given.

File

./user_permissions.module, line 114

Code

function user_permissions_profile_permissions_form_submit($form, &$form_state) {
  $perms = array();
  $uid = (int) $form_state['values']['uid'];
  $rid = (int) $form_state['values']['rid'];
  $role_name = $form_state['values']['role_name'];
  if (array_key_exists($rid, $form_state['input'])) {
    $perms = $form_state['input'][$rid];
  }
  if ($role_name == USER_PERMISSIONS_NO_ROLE) {
    if (!empty($perms)) {

      // Creates a new role with the name $role_name
      $role_name = '_user_role_' . $uid;
      $role = new stdClass();
      $role->name = $role_name;
      $role_saved = user_role_save($role);
      if ($role_saved == SAVED_NEW || $role_saved == SAVED_UPDATED) {
        $role = user_role_load_by_name($role_name);
        $rid = $role->rid;
        $account = user_load($uid);
        $account->roles[$rid] = $role_name;
        user_save($account);
        user_role_grant_permissions($rid, $perms);
      }
      else {
        drupal_set_message('User role was not saved.', 'error');
      }
    }

    // else $perms has no permissions for the user, so no user role is created.
  }
  else {

    // Modifying existing user permissions
    if (empty($perms)) {

      // If $perms has no permissions for the user, this deletes all permission/role
      // information related to this role to reduce database clutter
      user_role_delete($rid);
    }
    else {

      // Updating the user's permissions
      $old_perms = user_role_permissions(array(
        $rid => $role_name,
      ));
      user_role_revoke_permissions($rid, array_keys($old_perms[$rid]));
      user_role_grant_permissions($rid, $perms);
    }
  }
}