Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Utils
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • Context
  • FileUpload
  • Helpers
  • Request
  • RequestFactory
  • Response
  • Session
  • SessionSection
  • Url
  • UrlScript
  • UserStorage

Interfaces

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