Index: modules/user/user.module =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.module,v retrieving revision 1.916 diff -u -p -r1.916 user.module --- modules/user/user.module 17 Aug 2008 10:46:30 -0000 1.916 +++ modules/user/user.module 21 Aug 2008 20:20:40 -0000 @@ -2413,3 +2413,54 @@ function _user_forms(&$edit, $account, $ return empty($groups) ? FALSE : $groups; } + +/** + * Set the current user stored in $GLOBALS['user']. + * + * When this function is called for the first time the user is saved, + * subsequent calls that set a user do not overwrite the value of the + * original user. The user is restored when this function is called with + * a NULL value. + * + * @param $new_user User to switch to, either UID or user object. If + * nothing is provided the user will be reset to the original. + * @return Current user object. + */ +function user_switch_user($new_user = NULL) { + global $user; + static $user_original; + + if (empty($new_user)) { + if (isset($user_original)) { + // Restore the original user. + $user = $user_original; + unset($user_original); + session_save_session(TRUE); + } + return $user; + } + + // Backup the user the first time this is called. + if (!isset($user_original)) { + $user_original = $user; + session_save_session(FALSE); + } + + if (is_int($new_user)) { + $user = user_load(array('uid' => $new_user)); + } + else { + $user = (object) $new_user; + } + + return $user; +} + +/** + * Restore the user that was originally loaded. + * + * @return Current user. + */ +function user_restore_user() { + return user_switch_user(); +} Index: modules/user/user.test =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.test,v retrieving revision 1.10 diff -u -p -r1.10 user.test --- modules/user/user.test 27 Jun 2008 07:25:11 -0000 1.10 +++ modules/user/user.test 21 Aug 2008 20:20:41 -0000 @@ -463,3 +463,40 @@ class UserPermissionsTestCase extends Dr } } + + +class UserSwitchUserTestCase extends DrupalWebTestCase { + protected $original_user; + /** + * Implementation of getInfo(). + */ + function getInfo() { + return array( + 'name' => t('Switch User'), + 'description' => t('Temporarily switch the current user, and then restore the original user.'), + 'group' => t('User'), + ); + } + + function setUp() { + parent::setUp(); + + $this->original_user = $this->drupalCreateUser(); + } + + function testUserSwitchUser() { + global $user; + + $this->drupalLogin($this->original_user); + $this->assertEqual($user->uid, $this->original_user, t('Using original user.')); + + // Create a new user and switch to it. + $new_user = $this->drupalCreateUser(); + user_switch_user($new_user->uid); + + $this->assertEqual($user->uid, $new_user->uid, t('Switched to new user.')); + + user_restore_user(); + $this->assertEqual($user->uid, $this->original_user, t('Switched back to original user.')); + } +}