1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Http;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class Session
17: {
18: use Nette\SmartObject;
19:
20:
21: const DEFAULT_FILE_LIFETIME = 3 * Nette\Utils\DateTime::HOUR;
22:
23:
24: private $regenerated = false;
25:
26:
27: private static $started = false;
28:
29:
30: private $options = [
31:
32: 'referer_check' => '',
33: 'use_cookies' => 1,
34: 'use_only_cookies' => 1,
35: 'use_trans_sid' => 0,
36:
37:
38: 'cookie_lifetime' => 0,
39: 'cookie_path' => '/',
40: 'cookie_domain' => '',
41: 'cookie_secure' => false,
42: 'cookie_httponly' => true,
43:
44:
45: 'gc_maxlifetime' => self::DEFAULT_FILE_LIFETIME,
46: ];
47:
48:
49: private $request;
50:
51:
52: private $response;
53:
54:
55: private $handler;
56:
57:
58: public function __construct(IRequest $request, IResponse $response)
59: {
60: $this->request = $request;
61: $this->response = $response;
62: }
63:
64:
65: 66: 67: 68: 69:
70: public function start()
71: {
72: if (self::$started) {
73: return;
74: }
75:
76: $this->configure($this->options);
77:
78: $id = $this->request->getCookie(session_name());
79: if (is_string($id) && preg_match('#^[0-9a-zA-Z,-]{22,256}\z#i', $id)) {
80: session_id($id);
81: } else {
82: unset($_COOKIE[session_name()]);
83: }
84:
85: try {
86:
87: Nette\Utils\Callback::invokeSafe('session_start', [], function ($message) use (&$e) {
88: $e = new Nette\InvalidStateException($message);
89: });
90: } catch (\Exception $e) {
91: }
92:
93: if ($e) {
94: @session_write_close();
95: throw $e;
96: }
97:
98: self::$started = true;
99:
100: 101: 102: 103: 104:
105: $nf = &$_SESSION['__NF'];
106:
107: if (!is_array($nf)) {
108: $nf = [];
109: }
110:
111:
112: if (empty($nf['Time'])) {
113: $nf['Time'] = time();
114: $this->regenerated = true;
115: }
116:
117:
118: $this->sendCookie();
119:
120:
121: if (isset($nf['META'])) {
122: $now = time();
123:
124: foreach ($nf['META'] as $section => $metadata) {
125: if (is_array($metadata)) {
126: foreach ($metadata as $variable => $value) {
127: if (!empty($value['T']) && $now > $value['T']) {
128: if ($variable === '') {
129: unset($nf['META'][$section], $nf['DATA'][$section]);
130: continue 2;
131: }
132: unset($nf['META'][$section][$variable], $nf['DATA'][$section][$variable]);
133: }
134: }
135: }
136: }
137: }
138:
139: if ($this->regenerated) {
140: $this->regenerated = false;
141: $this->regenerateId();
142: }
143:
144: register_shutdown_function([$this, 'clean']);
145: }
146:
147:
148: 149: 150: 151:
152: public function isStarted()
153: {
154: return (bool) self::$started;
155: }
156:
157:
158: 159: 160: 161:
162: public function close()
163: {
164: if (self::$started) {
165: $this->clean();
166: session_write_close();
167: self::$started = false;
168: }
169: }
170:
171:
172: 173: 174: 175:
176: public function destroy()
177: {
178: if (!self::$started) {
179: throw new Nette\InvalidStateException('Session is not started.');
180: }
181:
182: session_destroy();
183: $_SESSION = null;
184: self::$started = false;
185: if (!$this->response->isSent()) {
186: $params = session_get_cookie_params();
187: $this->response->deleteCookie(session_name(), $params['path'], $params['domain'], $params['secure']);
188: }
189: }
190:
191:
192: 193: 194: 195:
196: public function exists()
197: {
198: return self::$started || $this->request->getCookie($this->getName()) !== null;
199: }
200:
201:
202: 203: 204: 205: 206:
207: public function regenerateId()
208: {
209: if (self::$started && !$this->regenerated) {
210: if (headers_sent($file, $line)) {
211: throw new Nette\InvalidStateException('Cannot regenerate session ID after HTTP headers have been sent' . ($file ? " (output started at $file:$line)." : '.'));
212: }
213: if (session_status() === PHP_SESSION_ACTIVE) {
214: session_regenerate_id(true);
215: session_write_close();
216: }
217: $backup = $_SESSION;
218: session_start();
219: $_SESSION = $backup;
220: }
221: $this->regenerated = true;
222: }
223:
224:
225: 226: 227: 228:
229: public function getId()
230: {
231: return session_id();
232: }
233:
234:
235: 236: 237: 238: 239:
240: public function setName($name)
241: {
242: if (!is_string($name) || !preg_match('#[^0-9.][^.]*\z#A', $name)) {
243: throw new Nette\InvalidArgumentException('Session name must be a string and cannot contain dot.');
244: }
245:
246: session_name($name);
247: return $this->setOptions([
248: 'name' => $name,
249: ]);
250: }
251:
252:
253: 254: 255: 256:
257: public function getName()
258: {
259: return isset($this->options['name']) ? $this->options['name'] : session_name();
260: }
261:
262:
263:
264:
265:
266: 267: 268: 269: 270: 271: 272:
273: public function getSection($section, $class = SessionSection::class)
274: {
275: return new $class($this, $section);
276: }
277:
278:
279: 280: 281: 282: 283:
284: public function hasSection($section)
285: {
286: if ($this->exists() && !self::$started) {
287: $this->start();
288: }
289:
290: return !empty($_SESSION['__NF']['DATA'][$section]);
291: }
292:
293:
294: 295: 296: 297:
298: public function getIterator()
299: {
300: if ($this->exists() && !self::$started) {
301: $this->start();
302: }
303:
304: if (isset($_SESSION['__NF']['DATA'])) {
305: return new \ArrayIterator(array_keys($_SESSION['__NF']['DATA']));
306:
307: } else {
308: return new \ArrayIterator;
309: }
310: }
311:
312:
313: 314: 315: 316: 317:
318: public function clean()
319: {
320: if (!self::$started || empty($_SESSION)) {
321: return;
322: }
323:
324: $nf = &$_SESSION['__NF'];
325: if (isset($nf['META']) && is_array($nf['META'])) {
326: foreach ($nf['META'] as $name => $foo) {
327: if (empty($nf['META'][$name])) {
328: unset($nf['META'][$name]);
329: }
330: }
331: }
332:
333: if (empty($nf['META'])) {
334: unset($nf['META']);
335: }
336:
337: if (empty($nf['DATA'])) {
338: unset($nf['DATA']);
339: }
340: }
341:
342:
343:
344:
345:
346: 347: 348: 349: 350: 351: 352:
353: public function setOptions(array $options)
354: {
355: $normalized = [];
356: foreach ($options as $key => $value) {
357: if (!strncmp($key, 'session.', 8)) {
358: $key = substr($key, 8);
359: }
360: $key = strtolower(preg_replace('#(.)(?=[A-Z])#', '$1_', $key));
361: $normalized[$key] = $value;
362: }
363: if (self::$started) {
364: $this->configure($normalized);
365: }
366: $this->options = $normalized + $this->options;
367: if (!empty($normalized['auto_start'])) {
368: $this->start();
369: }
370: return $this;
371: }
372:
373:
374: 375: 376: 377:
378: public function getOptions()
379: {
380: return $this->options;
381: }
382:
383:
384: 385: 386: 387: 388:
389: private function configure(array $config)
390: {
391: $special = ['cache_expire' => 1, 'cache_limiter' => 1, 'save_path' => 1, 'name' => 1];
392:
393: foreach ($config as $key => $value) {
394: if ($value === null || ini_get("session.$key") == $value) {
395: continue;
396:
397: } elseif (strncmp($key, 'cookie_', 7) === 0) {
398: if (!isset($cookie)) {
399: $cookie = session_get_cookie_params();
400: }
401: $cookie[substr($key, 7)] = $value;
402:
403: } else {
404: if (session_status() === PHP_SESSION_ACTIVE) {
405: throw new Nette\InvalidStateException("Unable to set 'session.$key' to value '$value' when session has been started" . (self::$started ? '.' : ' by session.auto_start or session_start().'));
406: }
407: if (isset($special[$key])) {
408: $key = "session_$key";
409: $key($value);
410:
411: } elseif (function_exists('ini_set')) {
412: ini_set("session.$key", (string) $value);
413:
414: } elseif (ini_get("session.$key") != $value) {
415: throw new Nette\NotSupportedException("Unable to set 'session.$key' to '$value' because function ini_set() is disabled.");
416: }
417: }
418: }
419:
420: if (isset($cookie)) {
421: session_set_cookie_params(
422: $cookie['lifetime'], $cookie['path'], $cookie['domain'],
423: $cookie['secure'], $cookie['httponly']
424: );
425: if (self::$started) {
426: $this->sendCookie();
427: }
428: }
429:
430: if ($this->handler) {
431: session_set_save_handler($this->handler);
432: }
433: }
434:
435:
436: 437: 438: 439: 440:
441: public function setExpiration($time)
442: {
443: if (empty($time)) {
444: return $this->setOptions([
445: 'gc_maxlifetime' => self::DEFAULT_FILE_LIFETIME,
446: 'cookie_lifetime' => 0,
447: ]);
448:
449: } else {
450: $time = Nette\Utils\DateTime::from($time)->format('U') - time();
451: return $this->setOptions([
452: 'gc_maxlifetime' => $time,
453: 'cookie_lifetime' => $time,
454: ]);
455: }
456: }
457:
458:
459: 460: 461: 462: 463: 464: 465:
466: public function setCookieParameters($path, $domain = null, $secure = null)
467: {
468: return $this->setOptions([
469: 'cookie_path' => $path,
470: 'cookie_domain' => $domain,
471: 'cookie_secure' => $secure,
472: ]);
473: }
474:
475:
476: 477: 478: 479:
480: public function getCookieParameters()
481: {
482: return session_get_cookie_params();
483: }
484:
485:
486: 487: 488: 489:
490: public function setSavePath($path)
491: {
492: return $this->setOptions([
493: 'save_path' => $path,
494: ]);
495: }
496:
497:
498: 499: 500: 501:
502: public function setStorage(ISessionStorage $storage)
503: {
504: if (self::$started) {
505: throw new Nette\InvalidStateException('Unable to set storage when session has been started.');
506: }
507: session_set_save_handler(
508: [$storage, 'open'], [$storage, 'close'], [$storage, 'read'],
509: [$storage, 'write'], [$storage, 'remove'], [$storage, 'clean']
510: );
511: return $this;
512: }
513:
514:
515: 516: 517: 518:
519: public function setHandler(\SessionHandlerInterface $handler)
520: {
521: if (self::$started) {
522: throw new Nette\InvalidStateException('Unable to set handler when session has been started.');
523: }
524: $this->handler = $handler;
525: return $this;
526: }
527:
528:
529: 530: 531: 532:
533: private function sendCookie()
534: {
535: $cookie = $this->getCookieParameters();
536: $this->response->setCookie(
537: session_name(), session_id(),
538: $cookie['lifetime'] ? $cookie['lifetime'] + time() : 0,
539: $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']
540: );
541: }
542: }
543: