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

  • NHttpContext
  • NHttpRequest
  • NHttpRequestFactory
  • NHttpResponse
  • NHttpUploadedFile
  • NSession
  • NSessionSection
  • NUrl
  • NUrlScript
  • NUserStorage

Interfaces

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