You are here

function _masquerade_drush_start_masquerade in Masquerade Extras 7.2

Same name and namespace in other branches
  1. 6.2 masquerade_drush/masquerade_drush.drush.inc \_masquerade_drush_start_masquerade()

Initializes a masquerade on the user's behalf. This is useful when developing and you want the user to start masquerading as soon as they login to the site.

Parameters

string $account: The (source) username.

string $target: The (target) username.

1 call to _masquerade_drush_start_masquerade()
drush_masquerade_drush_masquerade in masquerade_drush/masquerade_drush.drush.inc
Implements drush_HOOK_COMMAND().

File

masquerade_drush/masquerade_drush.drush.inc, line 227
Provides some drush commands for masquerade.

Code

function _masquerade_drush_start_masquerade($account, $target) {
  drupal_session_initialize();
  $account = _masquerade_drush_get_user($account);
  $target = _masquerade_drush_get_user($target);

  // Ensure the user specified the account they want to begin the masquerade with.
  if (empty($account)) {
    return drush_log("You must specify the source user. You can provide an email address, user ID, or username.", 'error');
  }

  // Ensure the user specified the account they want to masquerade as.
  if (empty($target)) {
    return drush_log("You must specify the target user. You can provide an email address, user ID, or username.", 'error');
  }

  // Lookup the requested account's session.
  $s = db_select('sessions', 's')
    ->fields('s')
    ->condition('s.uid', $account->uid, '=')
    ->execute()
    ->fetchObject();

  // If the requested user doesn't have a session, this won't work...just exit.
  if (empty($s)) {
    return drush_log("The requested masquerader is not currently logged into the site.", 'error');
  }

  // Take over our own session with the session ID of the real user.
  session_id($s->sid);

  // Change ownership of the session to the target user.
  $upd = db_update('sessions')
    ->fields(array(
    'uid' => $target->uid,
    'session' => serialize($_SESSION),
    'cache' => 0,
  ))
    ->condition('uid', $account->uid, '=')
    ->execute();
  if (empty($upd)) {
    return drush_log("Crap");
  }

  // Update the masquerade table.
  $added = db_insert('masquerade')
    ->fields(array(
    'uid_as' => $target->uid,
    'uid_from' => $account->uid,
    'sid' => $s->sid,
  ))
    ->execute();

  // Inform the user the masquerade has begun.
  if (!empty($added)) {
    return drush_log('Initialized masquerade for "' . $account->name . '" as "' . $target->name . '"', 'success');
  }

  // There was a problem initializing the masquerade.
  drush_log('There was a problem initalizing the masquerade.', 'error');
}