summaryrefslogtreecommitdiffstats
path: root/inc/session.inc.php
blob: 6718006b86c85b759cf82d2841e2e86d011e4130 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php


class Session
{
	private static $sid = false;
	private static $data = false;
	private static $needUpdate = true;
	
	private static function generateSessionId()
	{
		if (self::$sid !== false) Util::traceError('Error: Asked to generate session id when already set.');
		self::$sid = sha1(
			mt_rand(0, 65535)
			. $_SERVER['REMOTE_ADDR']
			. mt_rand(0, 65535)
			. $_SERVER['REMOTE_PORT']
			. mt_rand(0, 65535)
			. $_SERVER['HTTP_USER_AGENT']
			. mt_rand(0, 65535)
			. microtime(true)
			. mt_rand(0, 65535)
		);
	}

	public static function create()
	{
		self::generateSessionId();
		self::$data = array();
	}

	public static function load()
	{
		// Try to load session id from cookie
		if (!self::loadSessionId()) return false;
		// Succeded, now try to load session data. If successful, job is done
		if (self::readSessionData()) return true;
		// Loading session data failed
		self::delete();
		return false;
	}

	public static function getUid()
	{
		return self::get('uid');
	}

	public static function setUid($value)
	{
		if (!is_numeric($value) || $value < 1)
			Util::traceError('Invalid user id: ' . $value);
		self::set('uid', (int)$value);
	}

	public static function get($key)
	{
		if (isset(self::$data[$key]))
			return self::$data[$key];
		return false;
	}

	public static function set($key, $value)
	{
		if (!is_array(self::$data))
			Util::traceError('Tried to set session data with no active session');
		if (isset(self::$data[$key]) && self::$data[$key] === $value)
			return;
		self::$data[$key] = $value;
		self::$needUpdate = true;
	}

	private static function loadSessionId()
	{
		if (self::$sid !== false)
			die('Error: Asked to load session id when already set.');
		if (empty($_COOKIE['sid']))
			return false;
		$id = preg_replace('/[^a-zA-Z0-9]/', '', $_COOKIE['sid']);
		if (empty($id))
			return false;
		self::$sid = $id;
		return true;
	}

	public static function delete()
	{
		if (self::$sid === false) return;
		Database::exec('DELETE FROM websession WHERE sid = :sid', array('sid' => self::$sid));
		@setcookie('sid', '', time() - 8640000, null, null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
		self::$sid = false;
		self::$data = false;
	}

	public static function save()
	{
		if (self::$sid === false || self::$data === false || !self::$needUpdate)
			return;
		$data = json_encode(self::$data);
		$ret = Database::exec('INSERT INTO websession (sid, dateline, data) '
			. ' VALUES (:sid, UNIX_TIMESTAMP(), :data) '
			. ' ON DUPLICATE KEY UPDATE dateline = VALUES(dateline), data = VALUES(data)',
			array('sid' => self::$sid, 'data' => $data));
		if ($ret === false)
			Util::traceError('Storing session data in Dahdähbank failed.');
		$ret = @setcookie('sid', self::$sid, time() + CONFIG_SESSION_TIMEOUT, null, null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
		if ($ret === false)
			Util::traceError('Error: Could not set Cookie for Client (headers already sent)');
	}

	public static function readSessionData()
	{
		if (self::$sid === false || self::$data !== false)
			Util::traceError('Tried to readSessionData on an active session!');
		$data = Database::queryFirst('SELECT dateline, data FROM websession WHERE sid = :sid LIMIT 1', array('sid' => self::$sid));
		if ($data === false)
			return false;
		if ($data['dateline'] + CONFIG_SESSION_TIMEOUT < time()) {
			self::delete();
			return false;
		}
		self::$needUpdate = ($data['dateline'] + 3600 < time());
		self::$data = @json_decode($data['data'], true);
		if (!is_array(self::$data))
			self::$data = array();
		return true;
	}

}