1
|
<?php
|
2
|
|
3
|
/**
|
4
|
* @file
|
5
|
* Contains FeedsAccountSwitcher class.
|
6
|
*/
|
7
|
|
8
|
/**
|
9
|
* An implementation of FeedsAccountSwitcherInterface.
|
10
|
*
|
11
|
* This allows for safe switching of user accounts by ensuring that session
|
12
|
* data for one user is not leaked in to others. It also provides a stack that
|
13
|
* allows reverting to a previous user after switching.
|
14
|
*/
|
15
|
class FeedsAccountSwitcher implements FeedsAccountSwitcherInterface {
|
16
|
|
17
|
/**
|
18
|
* A stack of previous overridden accounts.
|
19
|
*
|
20
|
* @var object[]
|
21
|
*/
|
22
|
protected $accountStack = array();
|
23
|
|
24
|
/**
|
25
|
* The current user service.
|
26
|
*
|
27
|
* @var object
|
28
|
*/
|
29
|
protected $currentUser = array();
|
30
|
|
31
|
/**
|
32
|
* The original state of session prior to account switching.
|
33
|
*
|
34
|
* @var bool
|
35
|
*/
|
36
|
protected $originalSessionSave;
|
37
|
|
38
|
/**
|
39
|
* Constructs a new FeedsAccountSwitcher.
|
40
|
*
|
41
|
* @param object $current_user
|
42
|
* (optional) The current user.
|
43
|
*/
|
44
|
public function __construct($current_user = NULL) {
|
45
|
if (is_null($current_user)) {
|
46
|
global $user;
|
47
|
$this->currentUser = $user;
|
48
|
}
|
49
|
else {
|
50
|
$this->currentUser = $current_user;
|
51
|
}
|
52
|
}
|
53
|
|
54
|
/**
|
55
|
* {@inheritdoc}
|
56
|
*/
|
57
|
public function switchTo($account) {
|
58
|
// Prevent session information from being saved and push previous account.
|
59
|
if (!isset($this->originalSessionSave)) {
|
60
|
// Ensure that only the first session saving status is saved.
|
61
|
$this->originalSessionSave = drupal_save_session();
|
62
|
drupal_save_session(FALSE);
|
63
|
}
|
64
|
array_push($this->accountStack, $this->currentUser);
|
65
|
$this->currentUser = $account;
|
66
|
$this->activateCurrentUser();
|
67
|
|
68
|
return $this;
|
69
|
}
|
70
|
|
71
|
/**
|
72
|
* {@inheritdoc}
|
73
|
*/
|
74
|
public function switchBack() {
|
75
|
// Restore the previous account from the stack.
|
76
|
if (!empty($this->accountStack)) {
|
77
|
$this->currentUser = array_pop($this->accountStack);
|
78
|
$this->activateCurrentUser();
|
79
|
}
|
80
|
else {
|
81
|
throw new FeedsAccountSwitcherException('No more accounts to revert to.');
|
82
|
}
|
83
|
// Restore original session saving status if all account switches are
|
84
|
// reverted.
|
85
|
if (empty($this->accountStack)) {
|
86
|
if ($this->originalSessionSave) {
|
87
|
drupal_save_session($this->originalSessionSave);
|
88
|
}
|
89
|
}
|
90
|
return $this;
|
91
|
}
|
92
|
|
93
|
/**
|
94
|
* Assigns current user from this class to the global $user object.
|
95
|
*/
|
96
|
protected function activateCurrentUser() {
|
97
|
global $user;
|
98
|
$user = $this->currentUser;
|
99
|
}
|
100
|
|
101
|
}
|