Packages

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • HttpContext
  • HttpRequest
  • HttpRequestFactory
  • HttpResponse
  • HttpUploadedFile
  • Session
  • SessionSection
  • Url
  • UrlScript
  • UserStorage

Interfaces

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