Overview

Namespaces

  • Budovy
  • Kdyby
    • BootstrapFormRenderer
      • DI
      • Latte
  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Diagnostics
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
      • Diagnostics
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • PhpGenerator
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
  • NetteModule
  • Nextras
    • Datagrid
  • None
  • PHP
  • Tester
    • CodeCoverage
    • Runner
      • Output
  • Vodacek
    • Forms
      • Controls
  • WebLoader
    • Filter
    • Nette

Classes

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

Interfaces

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