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
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Session\SaveHandler;
use MongoDB\BSON\Binary;
use MongoDB\BSON\UTCDatetime;
use MongoDB\Client as MongoClient;
use MongoDB\Collection as MongoCollection;
use Zend\Session\Exception\InvalidArgumentException;
/**
* MongoDB session save handler
*/
class MongoDB implements SaveHandlerInterface
{
/**
* MongoClient instance
*
* @var MongoClient
*/
protected $mongoClient;
/**
* MongoCollection instance
*
* @var MongoCollection
*/
protected $mongoCollection;
/**
* Session name
*
* @var string
*/
protected $sessionName;
/**
* Session lifetime
*
* @var int
*/
protected $lifetime;
/**
* MongoDB session save handler options
* @var MongoDBOptions
*/
protected $options;
/**
* Constructor
*
* @param MongoClient $mongoClient
* @param MongoDBOptions $options
* @throws InvalidArgumentException
*/
public function __construct($mongoClient, MongoDBOptions $options)
{
if (null === ($database = $options->getDatabase())) {
throw new InvalidArgumentException('The database option cannot be empty');
}
if (null === ($collection = $options->getCollection())) {
throw new InvalidArgumentException('The collection option cannot be empty');
}
$this->mongoClient = $mongoClient;
$this->options = $options;
}
/**
* Open session
*
* @param string $savePath
* @param string $name
* @return bool
*/
public function open($savePath, $name)
{
// Note: session save path is not used
$this->sessionName = $name;
$this->lifetime = (int) ini_get('session.gc_maxlifetime');
$this->mongoCollection = $this->mongoClient->selectCollection(
$this->options->getDatabase(),
$this->options->getCollection()
);
$this->mongoCollection->createIndex(
[$this->options->getModifiedField() => 1],
$this->options->useExpireAfterSecondsIndex() ? ['expireAfterSeconds' => $this->lifetime] : []
);
return true;
}
/**
* Close session
*
* @return bool
*/
public function close()
{
return true;
}
/**
* Read session data
*
* @param string $id
* @return string
*/
public function read($id)
{
$session = $this->mongoCollection->findOne([
'_id' => $id,
$this->options->getNameField() => $this->sessionName,
]);
if (null !== $session) {
// check if session has expired if index is not used
if (! $this->options->useExpireAfterSecondsIndex()) {
$timestamp = $session[$this->options->getLifetimeField()];
$timestamp += floor(((string)$session[$this->options->getModifiedField()]) / 1000);
// session expired
if ($timestamp <= time()) {
$this->destroy($id);
return '';
}
}
return $session[$this->options->getDataField()]->getData();
}
return '';
}
/**
* Write session data
*
* @param string $id
* @param string $data
* @return bool
*/
public function write($id, $data)
{
$saveOptions = array_replace(
$this->options->getSaveOptions(),
['upsert' => true, 'multiple' => false]
);
$criteria = [
'_id' => $id,
$this->options->getNameField() => $this->sessionName,
];
$newObj = [
'$set' => [
$this->options->getDataField() => new Binary((string)$data, Binary::TYPE_GENERIC),
$this->options->getLifetimeField() => $this->lifetime,
$this->options->getModifiedField() => new UTCDatetime(floor(microtime(true) * 1000)),
],
];
/* Note: a MongoCursorException will be thrown if a record with this ID
* already exists with a different session name, since the upsert query
* cannot insert a new document with the same ID and new session name.
* This should only happen if ID's are not unique or if the session name
* is altered mid-process.
*/
$result = $this->mongoCollection->updateOne($criteria, $newObj, $saveOptions);
return $result->isAcknowledged();
}
/**
* Destroy session
*
* @param string $id
* @return bool
*/
public function destroy($id)
{
$result = $this->mongoCollection->deleteOne(
[
'_id' => $id,
$this->options->getNameField() => $this->sessionName,
],
$this->options->getSaveOptions()
);
return $result->isAcknowledged();
}
/**
* Garbage collection
*
* Note: MongoDB 2.2+ supports TTL collections, which may be used in place
* of this method by indexing the "modified" field with an
* "expireAfterSeconds" option. Regardless of whether TTL collections are
* used, consider indexing this field to make the remove query more
* efficient.
*
* @see http://docs.mongodb.org/manual/tutorial/expire-data/
* @param int $maxlifetime
* @return bool
*/
public function gc($maxlifetime)
{
/* Note: unlike DbTableGateway, we do not use the lifetime field in
* each document. Doing so would require a $where query to work with the
* computed value (modified + lifetime) and be very inefficient.
*/
$microseconds = floor(microtime(true) * 1000) - $maxlifetime * 1000;
$result = $this->mongoCollection->deleteMany(
[
$this->options->getModifiedField() => ['$lt' => new UTCDateTime($microseconds)],
],
$this->options->getSaveOptions()
);
return $result->isAcknowledged();
}
}