Completed
Push — 8.x-2.x ( 0cda8a...8af97d )
by Frédéric G.
02:15
created

modules/mongodb_session/mongodb_session.inc::drupal_session_regenerate()   D

Complexity

Conditions 10
Paths 60

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 24
c 1
b 0
f 0
nc 60
nop 0
dl 0
loc 38
rs 4.8196

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
if (!function_exists('_drupal_session_open')) {
3
  include_once dirname(__FILE__) . '/../mongodb_module.php';
4
5
/**
6
 * @file
7
 * User session handling functions.
8
 *
9
 * The user-level session storage handlers:
10
 * - _drupal_session_open()
11
 * - _drupal_session_close()
12
 * - _drupal_session_read()
13
 * - _drupal_session_write()
14
 * - _drupal_session_destroy()
15
 * - _drupal_session_garbage_collection()
16
 * are assigned by session_set_save_handler() in bootstrap.inc and are called
17
 * automatically by PHP. These functions should not be called directly. Session
18
 * data should instead be accessed via the $_SESSION superglobal.
19
 */
20
21
22
/**
23
 * Session handler assigned by session_set_save_handler().
24
 *
25
 * This function is used to handle any initialization, such as file paths or
26
 * database connections, that is needed before accessing session data. Drupal
27
 * does not need to initialize anything in this function.
28
 *
29
 * This function should not be called directly.
30
 *
31
 * @return boolean
32
 *   This function will always return TRUE.
33
 */
34
function _drupal_session_open() {
35
  return TRUE;
36
}
37
38
/**
39
 * Session handler assigned by session_set_save_handler().
40
 *
41
 * This function is used to close the current session. Because Drupal stores
42
 * session data in the database immediately on write, this function does
43
 * not need to do anything.
44
 *
45
 * This function should not be called directly.
46
 *
47
 * @return boolean
48
 *   This function will always return TRUE.
49
 */
50
function _drupal_session_close() {
51
  return TRUE;
52
}
53
54
/**
55
 * Session handler assigned by session_set_save_handler().
56
 *
57
 * This function will be called by PHP to retrieve the current user's
58
 * session data, which is stored in the database. It also loads the
59
 * current user's appropriate roles into the user object.
60
 *
61
 * This function should not be called directly. Session data should
62
 * instead be accessed via the $_SESSION superglobal.
63
 *
64
 * @param string $sid
65
 *   Session ID.
66
 *
67
 * @return array|string
68
 *   Either an array of the session data, or an empty string, if no data
69
 *   was found or the user is anonymous.
70
 */
71
function _drupal_session_read($sid) {
72
  global $user, $is_https;
73
74
  // Write and Close handlers are called after destructing objects
75
  // since PHP 5.0.5.
76
  // Thus destructors can use sessions but session handler can't use objects.
77
  // So we are moving session closure before destructing objects.
78
  register_shutdown_function('session_write_close');
79
80
  // Handle the case of first time visitors and clients that don't store
81
  // cookies (eg. web crawlers).
82
  $insecure_session_name = substr(session_name(), 1);
83
  if (empty($sid) || (!isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name]))) {
84
    $user = drupal_anonymous_user();
85
    return '';
86
  }
87
88
  // Otherwise, if the session is still active, we have a record of the
89
  // client's session in the database. If it's HTTPS then we are either have
90
  // a HTTPS session or we are about to log in so we check the sessions table
91
  // for an anonymous session wth the non-HTTPS-only cookie.
92
  $collection = mongodb_collection(variable_get('mongodb_session', 'session'));
93
  if ($is_https) {
94
    $session = $collection->findOne(array('ssid' => $sid));
95
    if (!$session) {
96
      if (isset($_COOKIE[$insecure_session_name])) {
97
        $session = $collection->findOne(array('sid' => $_COOKIE[$insecure_session_name], 'uid' => 0));
98
      }
99
    }
100
  }
101
  else {
102
    $session = $collection->findOne(array('sid' => $sid));
103
  }
104
  $collection = mongodb_collection('fields_current', 'user');
105
  $user = (object) $collection->findOne(array('_id' => $session['uid']));
106
107
  if (!isset($user->uid)) {
108
    $user = db_query("SELECT * FROM {users} u WHERE uid = :uid", array(':uid' => $session['uid']))->fetchObject();
109
    // Add roles element to $user and insert an entry into fields_current.user
110
    // so next time we get it from Mongo.
111
    include_once dirname(__FILE__) . '/mongodb_session.module';
112
    $user->roles = array();
113
    $user->roles = mongodb_session_user_insert(array(), $user);
114
  }
115
  // We found the client's session record and they are an authenticated,
116
  // active user.
117
  if ($session && !empty($session['uid']) && $user->status == 1) {
118
    $user->session = $session['session'];
119
  }
120
  // We didn't find the client's record (session has expired), or they are
121
  // blocked, or they are an anonymous user.
122
  else {
123
    $user = drupal_anonymous_user();
124
    $user->session = !empty($session['session']) ? $session['session'] : '';
125
  }
126
127
  return $user->session;
128
}
129
130
/**
131
 * Session handler assigned by session_set_save_handler().
132
 *
133
 * This function will be called by PHP to store the current user's
134
 * session, which Drupal saves to the database.
135
 *
136
 * This function should not be called directly. Session data should
137
 * instead be accessed via the $_SESSION superglobal.
138
 *
139
 * @param string $sid
140
 *   Session ID.
141
 * @param array $value
142
 *   Serialized array of the session data.
143
 *
144
 * @return boolean
145
 *   This function will always return TRUE.
146
 */
147
function _drupal_session_write($sid, $value) {
148
  global $user, $is_https;
149
150
  if (!drupal_save_session()) {
151
    // We don't have anything to do if we are not allowed to save the session.
152
    return;
153
  }
154
155
  $fields = array(
156
    'uid' => (int) $user->uid,
157
    'cache' => isset($user->cache) ? (int) $user->cache : 0,
158
    'hostname' => ip_address(),
159
    'session' => $value,
160
    'timestamp' => REQUEST_TIME,
161
  );
162
  $key = array('sid' => $sid);
163
  if ($is_https) {
164
    $key['ssid'] = $sid;
165
    $insecure_session_name = substr(session_name(), 1);
166
    // The "secure pages" setting allows a site to simultaneously use both
167
    // secure and insecure session cookies. If enabled, use the insecure session
168
    // identifier as the sid.
169
    if (variable_get('https', FALSE) && isset($_COOKIE[$insecure_session_name])) {
170
      $key['sid'] = $_COOKIE[$insecure_session_name];
171
    }
172
    else {
173
      unset($key['sid']);
174
    }
175
  }
176
  elseif (variable_get('https', FALSE)) {
177
    unset($key['ssid']);
178
  }
179
180
  $collection = mongodb_collection(variable_get('mongodb_session', 'session'));
181
  $collection
182
    ->update($key, $key + $fields, array('upsert' => TRUE) + mongodb_default_write_options(FALSE));
183
184
  // Last access time is updated no more frequently than once every 180 seconds.
185
  // This reduces contention in the users table.
186
  if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
187
    $fields = array(
188
      'access' => REQUEST_TIME,
189
    );
190
    // Update SQL because user_load() falls back to that.
191
    db_update('users')
192
      ->fields($fields)
193
      ->condition('uid', $user->uid)
194
      ->execute();
195
    // Update MongoDB because we prefer that.
196
    mongodb_collection('fields_current', 'user')->update(array('_id' => (int) $user->uid), array('$set' => $fields), mongodb_default_write_options(FALSE));
197
    // Throw a bone to entitycache, too.
198
    if (variable_get('entitycache_enabled', FALSE)) {
199
      cache_clear_all($user->uid, 'cache_entity_user');
200
    }
201
  }
202
203
  return TRUE;
204
}
205
206
/**
207
 * Initialize the session handler, starting a session if needed.
208
 */
209
function drupal_session_initialize() {
210
  global $user, $is_https;
211
212
  session_set_save_handler('_drupal_session_open', '_drupal_session_close', '_drupal_session_read', '_drupal_session_write', '_drupal_session_destroy', '_drupal_session_garbage_collection');
213
214
  if (isset($_COOKIE[session_name()])) {
215
    // If a session cookie exists, initialize the session. Otherwise the
216
    // session is only started on demand in drupal_session_commit(), making
217
    // anonymous users not use a session cookie unless something is stored in
218
    // $_SESSION. This allows HTTP proxies to cache anonymous pageviews.
219
    drupal_session_start();
220
    if (!empty($user->uid) || !empty($_SESSION)) {
221
      drupal_page_is_cacheable(FALSE);
222
    }
223
  }
224
  else {
225
    // Set a session identifier for this request. This is necessary because
226
    // we lazyly start sessions at the end of this request, and some
227
    // processes (like drupal_get_token()) needs to know the future
228
    // session ID in advance.
229
    $GLOBALS['lazy_session'] = TRUE;
230
    $user = drupal_anonymous_user();
231
    // Less random sessions (which are much faster to generate) are used for
232
    // anonymous users than are generated in drupal_session_regenerate() when
233
    // a user becomes authenticated.
234
    session_id(md5(uniqid('', TRUE)));
235
    if ($is_https && variable_get('https', FALSE)) {
236
      $insecure_session_name = substr(session_name(), 1);
237
      $session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE));
238
      $_COOKIE[$insecure_session_name] = $session_id;
239
    }
240
  }
241
  date_default_timezone_set(drupal_get_user_timezone());
242
}
243
244
/**
245
 * Forcefully start a session, preserving already set session data.
246
 *
247
 * @ingroup php_wrappers
248
 */
249
function drupal_session_start() {
250
  if (!drupal_session_started()) {
251
    // Save current session data before starting it, as PHP will destroy it.
252
    $session_data = isset($_SESSION) ? $_SESSION : NULL;
253
254
    session_start();
255
    drupal_session_started(TRUE);
256
257
    // Restore session data.
258
    if (!empty($session_data)) {
259
      $_SESSION += $session_data;
260
    }
261
  }
262
}
263
264
/**
265
 * Commit the current session, if necessary.
266
 *
267
 * If an anonymous user already have an empty session, destroy it.
268
 */
269
function drupal_session_commit() {
270
  global $user, $is_https;
271
272
  if (!drupal_save_session()) {
273
    // We don't have anything to do if we are not allowed to save the session.
274
    return;
275
  }
276
277
  if (empty($user->uid) && empty($_SESSION)) {
278
    // There is no session data to store, destroy the session if it was
279
    // previously started.
280
    if (drupal_session_started()) {
281
      session_destroy();
282
    }
283
  }
284
  else {
285
    // There is session data to store. Start the session if it is not already
286
    // started.
287
    if (!drupal_session_started()) {
288
      drupal_session_start();
289
      if ($is_https && variable_get('https', FALSE)) {
290
        $insecure_session_name = substr(session_name(), 1);
291
        $params = session_get_cookie_params();
292
        $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
293
        setcookie($insecure_session_name, $_COOKIE[$insecure_session_name], $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
294
      }
295
    }
296
    // Write the session data.
297
    session_write_close();
298
  }
299
}
300
301
/**
302
 * Return whether a session has been started.
303
 */
304
function drupal_session_started($set = NULL) {
305
  static $session_started = FALSE;
306
  if (isset($set)) {
307
    $session_started = $set;
308
  }
309
  return $session_started && session_id();
310
}
311
312
/**
313
 * Called when an anonymous user becomes authenticated or vice-versa.
314
 *
315
 * @ingroup php_wrappers
316
 */
317
function drupal_session_regenerate() {
318
  global $user, $is_https;
319
  if ($is_https && variable_get('https', FALSE)) {
320
    $insecure_session_name = substr(session_name(), 1);
321
    if (!isset($GLOBALS['lazy_session']) && isset($_COOKIE[$insecure_session_name])) {
322
      $old_insecure_session_id = $_COOKIE[$insecure_session_name];
323
    }
324
    $params = session_get_cookie_params();
325
    $session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE) . drupal_random_bytes(55));
326
    // If a session cookie lifetime is set, the session will expire
327
    // $params['lifetime'] seconds from the current request. If it is not set,
328
    // it will expire when the browser is closed.
329
    $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
330
    setcookie($insecure_session_name, $session_id, $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
331
    $_COOKIE[$insecure_session_name] = $session_id;
332
  }
333
334
  if (drupal_session_started()) {
335
    $old_session_id = session_id();
336
    session_regenerate_id();
337
  }
338
  else {
339
    // Start the session when it doesn't exist yet.
340
    // Preserve the logged in user, as it will be reset to anonymous
341
    // by _drupal_session_read.
342
    $account = $user;
343
    drupal_session_start();
344
    $user = $account;
345
  }
346
  if (isset($user->timezone)) {
347
    date_default_timezone_set(drupal_get_user_timezone());
348
  }
349
  if (isset($old_session_id)) {
350
    $field = $is_https ? 'ssid' : 'sid';
351
    mongodb_collection(variable_get('mongodb_session', 'session'))
352
      ->update(array('sid' => $old_session_id), array('$set' => array($field => session_id())), mongodb_default_write_options(FALSE));
353
  }
354
}
355
356
/**
357
 * Session handler assigned by session_set_save_handler().
358
 *
359
 * Cleanup a specific session.
360
 *
361
 * @param string $sid
362
 *   Session ID.
363
 */
364
function _drupal_session_destroy($sid) {
365
  global $user, $is_https;
366
367
  $field = $is_https ? 'ssid' : 'sid';
368
  mongodb_collection(variable_get('mongodb_session', 'session'))
369
    ->remove(array($field => $sid), mongodb_default_write_options(FALSE));
370
371
  // Reset $_SESSION and $user to prevent a new session from being started
372
  // in drupal_session_commit().
373
  $_SESSION = array();
374
  $user = drupal_anonymous_user();
375
376
  // Unset the session cookies.
377
  _drupal_session_delete_cookie(session_name());
378
  if ($is_https) {
379
    _drupal_session_delete_cookie(substr(session_name(), 1), FALSE);
380
  }
381
  elseif (variable_get('https', FALSE)) {
382
    _drupal_session_delete_cookie('S' . session_name(), TRUE);
383
  }
384
}
385
386
/**
387
 * Deletes the session cookie.
388
 *
389
 * @param sting $name
390
 *   Name of session cookie to delete.
391
 * @param boolean $secure
392
 *   Force the secure value of the cookie.
393
 */
394
function _drupal_session_delete_cookie($name, $secure = NULL) {
395
  global $is_https;
396
  if (isset($_COOKIE[$name]) || (!$is_https && $secure === TRUE)) {
397
    $params = session_get_cookie_params();
398
    if ($secure !== NULL) {
399
      $params['secure'] = $secure;
400
    }
401
    setcookie($name, '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
402
    unset($_COOKIE[$name]);
403
  }
404
}
405
406
/**
407
 * End a specific user's session(s).
408
 *
409
 * @param string $uid
410
 *   User ID.
411
 */
412
function drupal_session_destroy_uid($uid) {
413
  mongodb_collection(variable_get('mongodb_session', 'session'))
414
    ->remove(array('uid' => $uid), mongodb_default_write_options(FALSE));
415
}
416
417
/**
418
 * Session handler assigned by session_set_save_handler().
419
 *
420
 * Cleanup stalled sessions.
421
 *
422
 * @param int $lifetime
423
 *   The value of session.gc_maxlifetime, passed by PHP.
424
 *   Sessions not updated for more than $lifetime seconds will be removed.
425
 */
426
function _drupal_session_garbage_collection($lifetime) {
427
  // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
428
  // value. For example, if you want user sessions to stay in your database
429
  // for three weeks before deleting them, you need to set gc_maxlifetime
430
  // to '1814400'. At that value, only after a user doesn't log in after
431
  // three weeks (1814400 seconds) will his/her session be removed.
432
  mongodb_collection(variable_get('mongodb_session', 'session'))
433
    ->remove(array('timestamp' => array('$lt' => REQUEST_TIME - $lifetime)), mongodb_default_write_options(FALSE));
434
  return TRUE;
435
}
436
437
/**
438
 * Determine whether to save session data of the current request.
439
 *
440
 * This function allows the caller to temporarily disable writing of
441
 * session data, should the request end while performing potentially
442
 * dangerous operations, such as manipulating the global $user object.
443
 * See http://drupal.org/node/218104 for usage.
444
 *
445
 * @param boolean $status
446
 *   Disables writing of session data when FALSE, (re-)enables
447
 *   writing when TRUE.
448
 *
449
 * @return boolean
450
 *   FALSE if writing session data has been disabled. Otherwise, TRUE.
451
 */
452
function drupal_save_session($status = NULL) {
453
  $save_session = &drupal_static(__FUNCTION__, TRUE);
454
  if (isset($status)) {
455
    $save_session = $status;
456
  }
457
  return $save_session;
458
}
459
460
}
461