You are here

function uc_roles_grant in Ubercart 7.3

Same name and namespace in other branches
  1. 6.2 uc_roles/uc_roles.module \uc_roles_grant()

Grants a role to a given user.

This function grants a given role to a user's list of roles. If there is a previous record of this user/role combination, it is first removed. The function then saves the user (if $user_save is TRUE). Next, a check to verify the role actually exists, if not, no expiration data is stored. The menu cache is flushed, as new menu items may be visible after the new role is granted. The function notifies the user of the role grant.

Parameters

$account: A Drupal user object.

int $rid: A Drupal role ID.

int $timestamp: When this role will expire.

$save_user: Optimization to prevent unnecessary user saving when calling from uc_roles_user_presave().

bool $silent: When set to TRUE will suppress any Drupal messages from this function.

2 calls to uc_roles_grant()
uc_roles_action_order_renew in uc_roles/uc_roles.rules.inc
Renews an order's product roles.
uc_roles_user_presave in uc_roles/uc_roles.module
Implements hook_user_presave().

File

uc_roles/uc_roles.module, line 1089
Grants roles upon accepted payment of products.

Code

function uc_roles_grant(&$account, $rid, $timestamp, $save_user = TRUE, $silent = FALSE) {
  global $user;

  // First, delete any previous record of this user/role association.
  uc_roles_delete($account, $rid, $silent);
  if ($save_user) {

    // Punch the role into the user object.
    $roles_list = $account->roles + array(
      $rid => _uc_roles_get_name($rid),
    );
    $account = user_save($account, array(
      'roles' => $roles_list,
    ));
  }

  // If the role expires, keep a record.
  if (!is_null($timestamp)) {
    db_insert('uc_roles_expirations')
      ->fields(array(
      'uid' => $account->uid,
      'rid' => $rid,
      'expiration' => $timestamp,
    ))
      ->execute();
  }

  // Flush visible menu items, since our permissions could've changed.
  _uc_roles_flush_menu_cache($account);

  // Display the message if appropriate.
  if (!$silent) {
    $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(
      ':rid' => $rid,
    ))
      ->fetchField();
    if ($user->uid == $account->uid) {
      $message = t('You have been granted the %role role.', array(
        '%role' => $role_name,
      ));
    }
    else {
      $message = t('!user has been granted the %role role.', array(
        '!user' => theme('username', array(
          'account' => $account,
          'name' => check_plain(format_username($account)),
          'link_path' => 'user/' . $account->uid,
        )),
        '%role' => $role_name,
      ));
    }
    if ($timestamp) {
      $message .= ' ' . t('It will expire on %date', array(
        '%date' => format_date($timestamp, 'short'),
      ));
    }
    drupal_set_message($message);
  }
}