-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSession.php
More file actions
265 lines (230 loc) · 6.29 KB
/
Session.php
File metadata and controls
265 lines (230 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
namespace Gt\Session;
use ArrayAccess;
use ArrayObject;
use Exception;
use Gt\TypeSafeGetter\NullableTypeSafeGetter;
use Gt\TypeSafeGetter\TypeSafeGetter;
use SessionHandlerInterface;
use Throwable;
use Traversable;
class Session implements SessionContainer, TypeSafeGetter {
use NullableTypeSafeGetter;
const DEFAULT_SESSION_NAME = "PHPSESSID";
const DEFAULT_SESSION_LIFETIME = 0;
const DEFAULT_SESSION_PATH = "/tmp";
const DEFAULT_SESSION_DOMAIN = "";
const DEFAULT_SESSION_SECURE = true;
const DEFAULT_SESSION_HTTPONLY = true;
const DEFAULT_COOKIE_PATH = "/";
const DEFAULT_COOKIE_SAMESITE = "Lax";
const DEFAULT_STRICT_MODE = true;
const DEFAULT_SESSION_ID_LENGTH = 64;
const DEFAULT_SESSION_ID_BITS_PER_CHARACTER = 5;
protected string $id;
protected SessionHandlerInterface $sessionHandler;
protected ?SessionStore $store;
/** @var array<string, mixed> */
protected array $config;
/** @param iterable<string,mixed> $config */
public function __construct(
SessionHandlerInterface $sessionHandler,
iterable $config = [],
?string $id = null,
) {
$this->sessionHandler = $sessionHandler;
if(!is_array($config)) {
$config = iterator_to_array($config);
}
/** @var array<string,mixed> $config */
$this->config = $config;
if(is_null($id)) {
$id = $this->getId();
}
$this->id = $id;
$sessionPath = $this->normaliseSavePath(
$config["save_path"] ?? self::DEFAULT_SESSION_PATH
);
$sessionName = $config["name"] ?? self::DEFAULT_SESSION_NAME;
$this->attemptStart($sessionPath, $sessionName, $config);
$this->sessionHandler->open($sessionPath, $sessionName);
$this->store = $this->readSessionData();
if(is_null($this->store)) {
$this->store = new SessionStore(__NAMESPACE__, $this);
}
}
public function kill():void {
$this->sessionHandler->destroy($this->getId());
$params = session_get_cookie_params();
setcookie(
session_name() ?: "",
"",
-1,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
public function getStore(
string $namespace,
bool $createIfNotExists = false
):?SessionStoreInterface {
return $this->store->getStore(
$namespace,
$createIfNotExists
);
}
public function get(string $key):mixed {
return $this->store->get($key);
}
public function set(string $key, mixed $value):void {
$this->store->set($key, $value);
}
public function contains(string $key):bool {
return $this->store->contains($key);
}
public function remove(string $key):void {
$this->store->remove($key);
}
public function getId():string {
$id = session_id();
if(empty($id)) {
session_id($this->createNewId());
}
return session_id() ?: "";
}
protected function normaliseSavePath(string $path):string {
if($this->isDsn($path)) {
return $path;
}
$path = str_replace(
["/", "\\"],
DIRECTORY_SEPARATOR,
$path
);
if($path[0] !== DIRECTORY_SEPARATOR) {
$path = implode(DIRECTORY_SEPARATOR, [
sys_get_temp_dir(),
$path,
]);
}
return $path;
}
protected function isDsn(string $path):bool {
return (bool)preg_match('/^[a-z][a-z0-9+.-]*:\/\//i', $path);
}
/** @SuppressWarnings("PHPMD.Superglobals") */
protected function createNewId():string {
if(($this->config["use_trans_sid"] ?? null)
&& !$this->config["use_cookies"]) {
return $_GET[$this->config["name"]] ?? session_create_id();
}
return session_create_id() ?: "";
}
/** @SuppressWarnings("PHPMD.EmptyCatchBlock") */
protected function readSessionData():?SessionStore {
try {
$data = $this->sessionHandler->read($this->id) ?: "";
$store = unserialize($data);
if ($store instanceof SessionStore) {
return $store;
}
}
// PHPCS:ignore
catch (Throwable) {}
return null;
}
public function write():bool {
return $this->sessionHandler->write(
$this->id,
serialize($this->store)
);
}
/**
* @param string $sessionPath
* @param string $sessionName
* @param array<string,mixed> $config
* @SuppressWarnings("PHPMD.UnusedFormalParameter")
* @return void
*/
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
private function attemptStart(
string $sessionPath,
string $sessionName,
array $config,
?string $unusedContext = null,
):void {
$sessionOptions = $this->getSessionOptions(
$sessionPath,
$sessionName,
$config,
);
$this->tryStartSession($sessionOptions);
}
/**
* @param array<string,mixed> $config
* @return array<string,mixed>
*/
private function getSessionOptions(
string $sessionPath,
string $sessionName,
array $config
):array {
$defaultConfig = [
"use_only_cookies" => true,
"use_cookies" => true,
"use_trans_sid" => false,
"cookie_lifetime" => self::DEFAULT_SESSION_LIFETIME,
"cookie_path" => self::DEFAULT_COOKIE_PATH,
"cookie_domain" => self::DEFAULT_SESSION_DOMAIN,
"cookie_secure" => self::DEFAULT_SESSION_SECURE,
"cookie_httponly" => self::DEFAULT_SESSION_HTTPONLY,
"cookie_samesite" => self::DEFAULT_COOKIE_SAMESITE,
"use_strict_mode" => self::DEFAULT_STRICT_MODE,
];
$config = array_merge($defaultConfig, $config);
return [
"save_path" => $sessionPath,
"name" => $sessionName,
"serialize_handler" => "php_serialize",
"use_only_cookies" => $config["use_only_cookies"],
"use_cookies" => $config["use_cookies"],
"use_trans_sid" => $config["use_trans_sid"] ?? false,
"cookie_lifetime" => $config["cookie_lifetime"],
"cookie_path" => $config["cookie_path"],
"cookie_domain" => $config["cookie_domain"],
"cookie_secure" => $config["cookie_secure"],
"cookie_httponly" => $config["cookie_httponly"],
"cookie_samesite" => $config["cookie_samesite"],
"use_strict_mode" => $config["use_strict_mode"],
];
}
/**
* @param array<string,mixed> $sessionOptions
* @SuppressWarnings("PHPMD.EmptyCatchBlock")
*/
private function tryStartSession(array $sessionOptions):void {
$startAttempts = 0;
do {
$success = false;
try {
if(session_status() !== PHP_SESSION_ACTIVE) {
$success = session_start($sessionOptions);
}
}
// PHPCS:ignore
catch(Throwable) {}
if(!$success) {
if(session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
if(session_id()) {
session_regenerate_id(true);
}
}
$startAttempts++;
}
while(!$success && $startAttempts <= 1);
}
}