You are here

function sess_read in Memcache API and Integration 5.2

Same name in this branch
  1. 5.2 session-memcache.inc \sess_read()
  2. 5.2 session-memcache-db.inc \sess_read()
  3. 5.2 session-memcache.db.inc \sess_read()
Same name and namespace in other branches
  1. 5 memcache-session.inc \sess_read()
  2. 6 memcache-session.inc \sess_read()

File

./session-memcache-db.inc, line 16
User session handling functions.

Code

function sess_read($key) {
  global $user;

  // Write and Close handlers are called after destructing objects since PHP 5.0.5
  // Thus destructors can use sessions but session handler can't use objects.
  // So we are moving session closure before destructing objects.
  register_shutdown_function('session_write_close');

  // Handle the case of first time visitors and clients that don't store cookies (eg. web crawlers).
  if (!isset($_COOKIE[session_name()])) {
    $user = drupal_anonymous_user();
    return '';
  }

  // If user session is in memcache, use it, otherwise load from db.
  $user = dmemcache_get($key, 'session');
  if (!$user) {
    $user = db_fetch_object(db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = '%s'", $key));
  }
  if ($user && $user->uid) {
    if (!isset($user->roles)) {
      $user = drupal_unpack($user);

      // Add roles element to $user
      $user->roles = array();
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      $result = db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d", $user->uid);
      while ($role = db_fetch_object($result)) {
        $user->roles[$role->rid] = $role->name;
      }
    }
  }
  else {
    $session = isset($user->session) ? $user->session : '';
    $user = drupal_anonymous_user($session);
  }
  return $user->session;
}