You are here

function _memcache_storage_session_user_load in Memcache Storage 7

Load user by his session. Recieve user object from memcached. If unable to load from memcached it gets user from the database.

1 call to _memcache_storage_session_user_load()
_drupal_session_read in includes/session.inc
Reads an entire session from the memcached.

File

includes/session.inc, line 549
User session handling functions.

Code

function _memcache_storage_session_user_load($session) {

  // If session is not started return anonymous user.
  if (!$session) {
    $user = drupal_anonymous_user();
    $user->session = '';
    return $user;
  }

  // Try to load user from memcache.
  $user = MemcacheStorageAPI::get($session->uid, 'users');

  // User was successfully loaded.
  if ($user && !empty($user->uid) && !empty($user->status)) {
    _memcache_storage_session_user_add_session($user, $session);
  }
  elseif ($user) {

    // The user is anonymous or blocked. Only preserve two fields from the
    // {sessions} table.
    $account = drupal_anonymous_user();
    $account->session = $session->session;
    $account->timestamp = $session->timestamp;
    $user = $account;
  }
  else {

    // Load user from database.
    $user = db_query('SELECT * FROM {users} WHERE uid = :uid', array(
      ':uid' => $session->uid,
    ))
      ->fetchObject();
    if ($user && !empty($user->uid) && !empty($user->status)) {

      // This is done to unserialize the data member of $user.
      $user->data = unserialize($user->data);

      // Add roles element to $user.
      $user->roles = array();
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      $user->roles += db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid', array(
        ':uid' => $user->uid,
      ))
        ->fetchAllKeyed(0, 1);

      // Save user in memcache. Next time he will be loaded from there.
      MemcacheStorageAPI::set($user->uid, $user, 0, 'users');

      // Add session params to the user object.
      _memcache_storage_session_user_add_session($user, $session);
    }
    elseif ($user) {

      // The user is anonymous or blocked. Only preserve two fields from the
      // {sessions} table.
      $account = drupal_anonymous_user();
      MemcacheStorageAPI::set($account->uid, $account, 0, 'users');
      $account->session = $session->session;
      $account->timestamp = $session->timestamp;
      $user = $account;
    }
    else {
      $user = drupal_anonymous_user();
      $user->session = '';
    }
  }
  return $user;
}