Completed
Push — namespace-model ( 32fe71...476d0e )
by Sam
16:05
created

Session::set_cookie_domain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 3
c 1
b 1
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace SilverStripe\Control;
4
use Deprecation;
5
use Config;
6
use Injector;
7
8
9
/**
10
 * Handles all manipulation of the session.
11
 *
12
 * The static methods are used to manipulate the currently active controller's session.
13
 * The instance methods are used to manipulate a particular session.  There can be more than one of these created.
14
 *
15
 * In order to support things like testing, the session is associated with a particular Controller.  In normal usage,
16
 * this is loaded from and saved to the regular PHP session, but for things like static-page-generation and
17
 * unit-testing, you can create multiple Controllers, each with their own session.
18
 *
19
 * The instance object is basically just a way of manipulating a set of nested maps, and isn't specific to session
20
 * data.
21
 *
22
 * <b>Saving Data</b>
23
 *
24
 * You can write a value to a users session from your PHP code using the static function {@link Session::set()}. You
25
 * can add this line in any function or file you wish to save the value.
26
 *
27
 * <code>
28
 * 	Session::set('MyValue', 6);
29
 * </code>
30
 *
31
 * Saves the value of "6" to the MyValue session data. You can also save arrays or serialized objects in session (but
32
 * note there may be size restrictions as to how much you can save)
33
 *
34
 * <code>
35
 * 	// save a variable
36
 * 	$var = 1;
37
 * 	Session::set('MyVar', $var);
38
 *
39
 * 	// saves an array
40
 * 	Session::set('MyArrayOfValues', array('1', '2', '3'));
41
 *
42
 * 	// saves an object (you'll have to unserialize it back)
43
 * 	$object = new Object();
44
 *
45
 * 	Session::set('MyObject', serialize($object));
46
 * </code>
47
 *
48
 * <b>Accessing Data</b>
49
 *
50
 * Once you have saved a value to the Session you can access it by using the {@link Session::get()} function.
51
 * Like the {@link Session::set()} function you can use this anywhere in your PHP files.
52
 *
53
 * The values in the comments are the values stored from the previous example.
54
 *
55
 * <code>
56
 * public function bar() {
57
 * 	$value = Session::get('MyValue'); // $value = 6
58
 * 	$var   = Session::get('MyVar'); // $var = 1
59
 * 	$array = Session::get('MyArrayOfValues'); // $array = array(1,2,3)
60
 * 	$object = Session::get('MyObject', unserialize($object)); // $object = Object()
61
 * }
62
 * </code>
63
 *
64
 * You can also get all the values in the session at once. This is useful for debugging.
65
 *
66
 * <code>
67
 * Session::get_all(); // returns an array of all the session values.
68
 * </code>
69
 *
70
 * <b>Clearing Data</b>
71
 *
72
 * Once you have accessed a value from the Session it doesn't automatically wipe the value from the Session, you have
73
 * to specifically remove it. To clear a value you can either delete 1 session value by the name that you saved it
74
 *
75
 * <code>
76
 * Session::clear('MyValue'); // MyValue is no longer 6.
77
 * </code>
78
 *
79
 * Or you can clear every single value in the session at once. Note SilverStripe stores some of its own session data
80
 * including form and page comment information. None of this is vital but clear_all will clear everything.
81
 *
82
 * <code>
83
 * 	Session::clear_all();
84
 * </code>
85
 *
86
 * @see Cookie
87
 * @todo This class is currently really basic and could do with a more well-thought-out implementation.
88
 *
89
 * @package framework
90
 * @subpackage control
91
 */
92
93
class Session {
94
95
	/**
96
	 * @var $timeout Set session timeout in seconds.
97
	 * @config
98
	 */
99
	private static $timeout = 0;
100
101
	/**
102
	 * @config
103
	 * @var array
104
	 */
105
	private static $session_ips = array();
106
107
	/**
108
	 * @config
109
	 * @var string
110
	 */
111
	private static $cookie_domain;
112
113
	/**
114
	 * @config
115
	 * @var string
116
	 */
117
	private static $cookie_path;
118
119
	/**
120
	 * @config
121
	 * @var string
122
	 */
123
	private static $session_store_path;
124
125
	/**
126
	 * @config
127
	 * @var boolean
128
	 */
129
	private static $cookie_secure = false;
130
131
	/**
132
	 * Session data
133
	 */
134
	protected $data = array();
135
136
	protected $changedData = array();
137
138
	protected function userAgent() {
139
		if (isset($_SERVER['HTTP_USER_AGENT'])) {
140
			return $_SERVER['HTTP_USER_AGENT'];
141
		} else {
142
			return '';
143
		}
144
	}
145
146
	/**
147
	 * Start PHP session, then create a new Session object with the given start data.
148
	 *
149
	 * @param $data array|Session Can be an array of data (such as $_SESSION) or another Session object to clone.
150
	 */
151
	public function __construct($data) {
152
		if($data instanceof Session) $data = $data->inst_getAll();
153
154
		$this->data = $data;
155
156
		if (isset($this->data['HTTP_USER_AGENT'])) {
157
			if ($this->data['HTTP_USER_AGENT'] != $this->userAgent()) {
158
				// Funny business detected!
159
				$this->inst_clearAll();
160
				$this->inst_destroy();
161
				$this->inst_start();
162
			}
163
		}
164
	}
165
166
	/**
167
	 * Cookie domain, for example 'www.php.net'.
168
	 *
169
	 * To make cookies visible on all subdomains then the domain
170
	 * must be prefixed with a dot like '.php.net'.
171
	 *
172
	 * @deprecated 4.0 Use the "Session.cookie_domain" config setting instead
173
	 *
174
	 * @param string $domain The domain to set
175
	 */
176
	public static function set_cookie_domain($domain) {
177
		Deprecation::notice('4.0', 'Use the "Session.cookie_domain" config setting instead');
178
		Config::inst()->update('SilverStripe\Control\Session', 'cookie_domain', $domain);
179
	}
180
181
	/**
182
	 * Get the cookie domain.
183
	 *
184
	 * @deprecated 4.0 Use the "Session.cookie_domain" config setting instead
185
	 *
186
	 * @return string
187
	 */
188
	public static function get_cookie_domain() {
189
		Deprecation::notice('4.0', 'Use the "Session.cookie_domain" config setting instead');
190
		return Config::inst()->get('SilverStripe\Control\Session', 'cookie_domain');
191
	}
192
193
	/**
194
	 * Path to set on the domain where the session cookie will work.
195
	 * Use a single slash ('/') for all paths on the domain.
196
	 *
197
	 * @deprecated 4.0 Use the "Session.cookie_path" config setting instead
198
	 *
199
	 * @param string $path The path to set
200
	 */
201
	public static function set_cookie_path($path) {
202
		Deprecation::notice('4.0', 'Use the "Session.cookie_path" config setting instead');
203
		Config::inst()->update('SilverStripe\Control\Session', 'cookie_path', $path);
204
	}
205
206
	/**
207
	 * Get the path on the domain where the session cookie will work.
208
	 *
209
	 * @deprecated 4.0 Use the "Session.cookie_path" config setting instead
210
	 *
211
	 * @return string
212
	 */
213
	public static function get_cookie_path() {
214
		Deprecation::notice('4.0', 'Use the "Session.cookie_path" config setting instead');
215
		if(Config::inst()->get('SilverStripe\Control\Session', 'cookie_path')) {
216
			return Config::inst()->get('SilverStripe\Control\Session', 'cookie_path');
217
		} else {
218
			return Director::baseURL();
219
		}
220
	}
221
222
	/**
223
	 * Secure cookie, tells the browser to only send it over SSL.
224
	 *
225
	 * @deprecated 4.0 Use the "Session.cookie_secure" config setting instead
226
	 *
227
	 * @param boolean $secure
228
	 */
229
	public static function set_cookie_secure($secure) {
230
		Deprecation::notice('4.0', 'Use the "Session.cookie_secure" config setting instead');
231
		Config::inst()->update('SilverStripe\Control\Session', 'cookie_secure', (bool)$secure);
232
	}
233
234
	/**
235
	 * Get if the cookie is secure
236
	 *
237
	 * @deprecated 4.0 Use the "Session.cookie_secure" config setting instead
238
	 *
239
	 * @return boolean
240
	 */
241
	public static function get_cookie_secure() {
242
		Deprecation::notice('4.0', 'Use the "Session.cookie_secure" config setting instead');
243
		return Config::inst()->get('SilverStripe\Control\Session', 'cookie_secure');
244
	}
245
246
	/**
247
	 * Set the session store path
248
	 *
249
	 * @deprecated 4.0 Use the "Session.session_store_path" config setting instead
250
	 *
251
	 * @param string $path Filesystem path to the session store
252
	 */
253
	public static function set_session_store_path($path) {
254
		Deprecation::notice('4.0', 'Use the "Session.session_store_path" config setting instead');
255
		Config::inst()->update('SilverStripe\Control\Session', 'session_store_path', $path);
256
	}
257
258
	/**
259
	 * Get the session store path
260
	 * @return string
261
	 * @deprecated since version 4.0
262
	 */
263
	public static function get_session_store_path() {
264
		Deprecation::notice('4.0', 'Use the "Session.session_store_path" config setting instead');
265
		return Config::inst()->get('SilverStripe\Control\Session', 'session_store_path');
266
	}
267
268
	/**
269
	 * Provide an <code>array</code> of rules specifing timeouts for IPv4 address ranges or
270
	 * individual IPv4 addresses. The key is an IP address or range and the value is the time
271
	 * until the session expires in seconds. For example:
272
	 *
273
	 * Session::set_timeout_ips(array(
274
	 * 		'127.0.0.1' => 36000
275
	 * ));
276
	 *
277
	 * Any user connecting from 127.0.0.1 (localhost) will have their session expired after 10 hours.
278
	 *
279
	 * Session::set_timeout is used to set the timeout value for any users whose address is not in the given IP range.
280
	 *
281
	 * @deprecated 4.0 Use the "Session.timeout_ips" config setting instead
282
	 *
283
	 * @param array $session_ips Array of IPv4 rules.
0 ignored issues
show
Bug introduced by
There is no parameter named $session_ips. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
284
	 */
285
	public static function set_timeout_ips($ips) {
286
		Deprecation::notice('4.0', 'Use the "Session.timeout_ips" config setting instead');
287
		Config::inst()->update('SilverStripe\Control\Session', 'timeout_ips', $ips);
288
	}
289
290
	/**
291
	 * Add a value to a specific key in the session array
292
	 */
293
	public static function add_to_array($name, $val) {
294
		return self::current_session()->inst_addToArray($name, $val);
295
	}
296
297
	/**
298
	 * Set a key/value pair in the session
299
	 *
300
	 * @param string $name Key
301
	 * @param string $val Value
302
	 */
303
	public static function set($name, $val) {
304
		return self::current_session()->inst_set($name, $val);
305
	}
306
307
	/**
308
	 * Return a specific value by session key
309
	 *
310
	 * @param string $name Key to lookup
311
	 */
312
	public static function get($name) {
313
		return self::current_session()->inst_get($name);
314
	}
315
316
	/**
317
	 * Return all the values in session
318
	 *
319
	 * @return Array
320
	 */
321
	public static function get_all() {
322
		return self::current_session()->inst_getAll();
323
	}
324
325
	/**
326
	 * Clear a given session key, value pair.
327
	 *
328
	 * @param string $name Key to lookup
329
	 */
330
	public static function clear($name) {
331
		return self::current_session()->inst_clear($name);
332
	}
333
334
	/**
335
	 * Clear all the values
336
	 *
337
	 * @return void
338
	 */
339
	public static function clear_all() {
340
		self::current_session()->inst_clearAll();
341
		self::$default_session = null;
342
	}
343
344
	/**
345
	 * Save all the values in our session to $_SESSION
346
	 */
347
	public static function save() {
348
		return self::current_session()->inst_save();
349
	}
350
351
	protected static $default_session = null;
352
353
	protected static function current_session() {
354
		if(Controller::has_curr()) {
355
			return Controller::curr()->getSession();
356
		} else {
357
			if(!self::$default_session) {
358
				self::$default_session = Injector::inst()->create('SilverStripe\Control\Session', isset($_SESSION) ? $_SESSION : array());
359
			}
360
361
			return self::$default_session;
362
		}
363
	}
364
365
	public function inst_start($sid = null) {
366
		$path = Config::inst()->get('SilverStripe\Control\Session', 'cookie_path');
367
		if(!$path) $path = Director::baseURL();
368
		$domain = Config::inst()->get('SilverStripe\Control\Session', 'cookie_domain');
369
		$secure = Director::is_https() && Config::inst()->get('SilverStripe\Control\Session', 'cookie_secure');
370
		$session_path = Config::inst()->get('SilverStripe\Control\Session', 'session_store_path');
371
		$timeout = Config::inst()->get('SilverStripe\Control\Session', 'timeout');
372
373
		if(!session_id() && !headers_sent()) {
374
			if($domain) {
375
				session_set_cookie_params($timeout, $path, $domain, $secure, true);
376
			} else {
377
				session_set_cookie_params($timeout, $path, null, $secure, true);
378
			}
379
380
			// Allow storing the session in a non standard location
381
			if($session_path) session_save_path($session_path);
382
383
			// If we want a secure cookie for HTTPS, use a seperate session name. This lets us have a
384
			// seperate (less secure) session for non-HTTPS requests
385
			if($secure) session_name('SECSESSID');
386
387
			if($sid) session_id($sid);
388
			session_start();
389
390
			$this->data = isset($_SESSION) ? $_SESSION : array();
391
		}
392
393
		// Modify the timeout behaviour so it's the *inactive* time before the session expires.
394
		// By default it's the total session lifetime
395
		if($timeout && !headers_sent()) {
396
			Cookie::set(session_name(), session_id(), $timeout/86400, $path, $domain ? $domain
397
				: null, $secure, true);
398
		}
399
	}
400
401
	public function inst_destroy($removeCookie = true) {
402
		if(session_id()) {
403
			if($removeCookie) {
404
				$path = Config::inst()->get('SilverStripe\Control\Session', 'cookie_path') ?: Director::baseURL();
405
				$domain = Config::inst()->get('SilverStripe\Control\Session', 'cookie_domain');
406
				$secure = Config::inst()->get('SilverStripe\Control\Session', 'cookie_secure');
407
408
				Cookie::force_expiry(session_name(), $path, $domain, $secure, true);
409
			}
410
411
			session_destroy();
412
413
			// Clean up the superglobal - session_destroy does not do it.
414
			// http://nz1.php.net/manual/en/function.session-destroy.php
415
			unset($_SESSION);
416
			$this->data = array();
417
		}
418
	}
419
420
	public function inst_set($name, $val) {
421
		// Quicker execution path for "."-free names
422
		if(strpos($name, '.') === false) {
423
			$this->data[$name] = $val;
424
			$this->changedData[$name] = $val;
425
426
		} else {
427
			$names = explode('.', $name);
428
429
			// We still want to do this even if we have strict path checking for legacy code
430
			$var = &$this->data;
431
			$diffVar = &$this->changedData;
432
433
			// Iterate twice over the names - once to see if the value needs to be changed,
434
			// and secondly to get the changed data value. This is done to solve a problem
435
			// where iterating over the diff var would create empty arrays, and the value
436
			// would then not be set, inadvertently clearing session values.
437
			foreach($names as $n) {
438
				$var = &$var[$n];
439
			}
440
441
			if($var !== $val) {
442
				foreach($names as $n) {
443
					$diffVar = &$diffVar[$n];
444
				}
445
446
				$var = $val;
447
				$diffVar = $val;
448
			}
449
		}
450
	}
451
452
	public function inst_addToArray($name, $val) {
453
		$names = explode('.', $name);
454
455
		// We still want to do this even if we have strict path checking for legacy code
456
		$var = &$this->data;
457
		$diffVar = &$this->changedData;
458
459
		foreach($names as $n) {
460
			$var = &$var[$n];
461
			$diffVar = &$diffVar[$n];
462
		}
463
464
		$var[] = $val;
465
		$diffVar[sizeof($var)-1] = $val;
466
	}
467
468
	public function inst_get($name) {
469
		// Quicker execution path for "."-free names
470
		if(strpos($name, '.') === false) {
471
			if(isset($this->data[$name])) return $this->data[$name];
472
473
		} else {
474
			$names = explode('.', $name);
475
476
			if(!isset($this->data)) {
477
				return null;
478
			}
479
480
			$var = $this->data;
481
482
			foreach($names as $n) {
483
				if(!isset($var[$n])) {
484
					return null;
485
				}
486
				$var = $var[$n];
487
			}
488
489
			return $var;
490
		}
491
	}
492
493
	public function inst_clear($name) {
494
		$names = explode('.', $name);
495
496
		// We still want to do this even if we have strict path checking for legacy code
497
		$var = &$this->data;
498
		$diffVar = &$this->changedData;
499
500
		foreach($names as $n) {
501
			// don't clear a record that doesn't exist
502
			if(!isset($var[$n])) return;
503
			$var = &$var[$n];
504
		}
505
506
		// only loop to find data within diffVar if var is proven to exist in the above loop
507
		foreach($names as $n) {
508
			$diffVar = &$diffVar[$n];
509
		}
510
511
		if($var !== null) {
512
			$var = null;
513
			$diffVar = null;
514
		}
515
	}
516
517
	public function inst_clearAll() {
518
		if($this->data && is_array($this->data)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
519
			foreach(array_keys($this->data) as $key) {
520
				$this->inst_clear($key);
521
			}
522
		}
523
	}
524
525
	public function inst_getAll() {
526
		return $this->data;
527
	}
528
529
	public function inst_finalize() {
530
		$this->inst_set('HTTP_USER_AGENT', $this->userAgent());
531
	}
532
533
	/**
534
	 * Save data to session
535
	 * Only save the changes, so that anyone manipulating $_SESSION directly doesn't get burned.
536
	 */
537
	public function inst_save() {
538
		if($this->changedData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->changedData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
539
			$this->inst_finalize();
540
541
			if(!isset($_SESSION)) {
542
				$this->inst_start();
543
			}
544
545
			$this->recursivelyApply($this->changedData, $_SESSION);
546
		}
547
	}
548
549
	/**
550
	 * Recursively apply the changes represented in $data to $dest.
551
	 * Used to update $_SESSION
552
	 */
553
	protected function recursivelyApply($data, &$dest) {
554
		foreach($data as $k => $v) {
555
			if(is_array($v)) {
556
				if(!isset($dest[$k]) || !is_array($dest[$k])) $dest[$k] = array();
557
				$this->recursivelyApply($v, $dest[$k]);
558
			} else {
559
				$dest[$k] = $v;
560
			}
561
		}
562
	}
563
564
	/**
565
	 * Return the changed data, for debugging purposes.
566
	 * @return array
567
	 */
568
	public function inst_changedData() {
569
		return $this->changedData;
570
	}
571
572
	/**
573
	* Sets the appropriate form message in session, with type. This will be shown once,
574
	* for the form specified.
575
	*
576
	* @param string $formname the form name you wish to use ( usually $form->FormName() )
577
	* @param string $message the message you wish to add to it
578
	* @param string $type the type of message
579
	*/
580
	public static function setFormMessage($formname, $message, $type) {
581
		Session::set("FormInfo.$formname.formError.message", $message);
582
		Session::set("FormInfo.$formname.formError.type", $type);
583
	}
584
585
	/**
586
	 * Is there a session ID in the request?
587
	 * @return bool
588
	 */
589
	public static function request_contains_session_id() {
590
		$secure = Director::is_https() && Config::inst()->get('SilverStripe\Control\Session', 'cookie_secure');
591
		$name = $secure ? 'SECSESSID' : session_name();
592
		return isset($_COOKIE[$name]) || isset($_REQUEST[$name]);
593
	}
594
595
	/**
596
	 * Initialize session.
597
	 *
598
	 * @param string $sid Start the session with a specific ID
599
	 */
600
	public static function start($sid = null) {
601
		self::current_session()->inst_start($sid);
602
	}
603
604
	/**
605
	 * Destroy the active session.
606
	 *
607
	 * @param bool $removeCookie If set to TRUE, removes the user's cookie, FALSE does not remove
608
	 */
609
	public static function destroy($removeCookie = true) {
610
		self::current_session()->inst_destroy($removeCookie);
611
	}
612
613
	/**
614
	 * Set the timeout of a Session value
615
	 *
616
	 * @deprecated 4.0 Use the "Session.timeout" config setting instead
617
	 *
618
	 * @param int $timeout Time until a session expires in seconds. Defaults to expire when browser is closed.
619
	 */
620
	public static function set_timeout($timeout) {
621
		Deprecation::notice('4.0', 'Use the "Session.timeout" config setting instead');
622
		Config::inst()->update('SilverStripe\Control\Session', 'timeout', (int) $timeout);
623
	}
624
625
	/**
626
	 * @deprecated 4.0 Use the "Session.timeout" config setting instead
627
	 */
628
	public static function get_timeout() {
629
		Deprecation::notice('4.0', 'Use the "Session.timeout" config setting instead');
630
		return Config::inst()->get('SilverStripe\Control\Session', 'timeout');
631
	}
632
}
633