aboutsummaryrefslogtreecommitdiff
path: root/lib/Minz/Session.php
blob: aafbbbde8a718749d53f8829cf33b2fc445ce6e4 (plain)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<?php
declare(strict_types=1);

/**
 * The Minz_Session class handles user’s session
 */
class Minz_Session {

	private static bool $volatile = false;

	/**
	 * For mutual exclusion.
	 */
	private static bool $locked = false;

	public static function lock(): bool {
		if (!self::$volatile && !self::$locked) {
			session_start();
			self::$locked = true;
		}
		return self::$locked;
	}

	public static function unlock(): bool {
		if (!self::$volatile) {
			session_write_close();
			self::$locked = false;
		}
		return self::$locked;
	}

	/**
	 * Initialize the session, with a name
	 * The session name is used as the name for cookies and URLs (i.e. PHPSESSID).
	 * It should contain only alphanumeric characters; it should be short and descriptive
	 * If the volatile parameter is true, then no cookie and not session storage are used.
	 * Volatile is especially useful for API calls without cookie / Web session.
	 */
	public static function init(string $name, bool $volatile = false): void {
		self::$volatile = $volatile;
		if (self::$volatile) {
			$_SESSION = [];
			return;
		}

		$cookie = session_get_cookie_params();
		self::keepCookie($cookie['lifetime']);

		// start session
		session_name($name);
		//When using cookies (default value), session_stars() sends HTTP headers
		session_start();
		session_write_close();
		//Use cookie only the first time the session is started to avoid resending HTTP headers
		ini_set('session.use_cookies', '0');
	}


	/**
	 * Allows you to retrieve a session variable
	 * @param string $p the parameter to retrieve
	 * @param mixed|false $default the default value if the parameter doesn’t exist
	 * @return mixed|false the value of the session variable, false if doesn’t exist
	 */
	#[Deprecated('Use typed versions instead')]
	public static function param(string $p, $default = false): mixed {
		return $_SESSION[$p] ?? $default;
	}

	/** @return array<string|int,string|array<string,mixed>> */
	public static function paramArray(string $key): array {
		if (empty($_SESSION[$key]) || !is_array($_SESSION[$key])) {
			return [];
		}
		$result = [];
		foreach ($_SESSION[$key] as $k => $v) {
			if (is_string($v) || (is_array($v) && is_array_keys_string($v))) {
				$result[$k] = $v;
			}
		}
		return $result;
	}

	public static function paramTernary(string $key): ?bool {
		if (isset($_SESSION[$key])) {
			$p = $_SESSION[$key];
			$tp = is_string($p) ? trim($p) : true;
			if ($tp === '' || $tp === 'null') {
				return null;
			} elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
				return false;
			}
			return true;
		}
		return null;
	}

	public static function paramBoolean(string $key): bool {
		if (null === $value = self::paramTernary($key)) {
			return false;
		}
		return $value;
	}

	public static function paramInt(string $key): int {
		return empty($_SESSION[$key]) || !is_numeric($_SESSION[$key]) ? 0 : (int)$_SESSION[$key];
	}

	public static function paramString(string $key): string {
		if (isset($_SESSION[$key])) {
			$s = $_SESSION[$key];
			if (is_string($s)) {
				return $s;
			}
			if (is_int($s) || is_bool($s)) {
				return (string)$s;
			}
		}
		return '';
	}

	/**
	 * Allows you to create or update a session variable
	 * @param string $parameter the parameter to create or modify
	 * @param mixed|false $value the value to assign, false to delete
	 */
	public static function _param(string $parameter, $value = false): void {
		if (!self::$volatile && !self::$locked) {
			session_start();
		}
		if ($value === false) {
			unset($_SESSION[$parameter]);
		} else {
			$_SESSION[$parameter] = $value;
		}
		if (!self::$volatile && !self::$locked) {
			session_write_close();
		}
	}

	/**
	 * @param array<string,string|bool|int|array<string>> $keyValues
	 */
	public static function _params(array $keyValues): void {
		if (!self::$volatile && !self::$locked) {
			session_start();
		}
		foreach ($keyValues as $key => $value) {
			if ($value === false) {
				unset($_SESSION[$key]);
			} else {
				$_SESSION[$key] = $value;
			}
		}
		if (!self::$volatile && !self::$locked) {
			session_write_close();
		}
	}

	/**
	 * Allows to delete a session
	 * @param bool $force if false, does not clear the language parameter
	 */
	public static function unset_session(bool $force = false): void {
		$language = self::paramString('language');

		if (!self::$volatile) {
			session_destroy();
		}
		$_SESSION = [];

		if (!$force) {
			self::_param('language', $language);
			Minz_Translate::reset($language);
		}
	}

	public static function getCookieDir(): string {
		// Get the script_name (e.g. /p/i/index.php) and keep only the path.
		$cookie_dir = '';
		if (!empty($_SERVER['HTTP_X_FORWARDED_PREFIX']) && is_string($_SERVER['HTTP_X_FORWARDED_PREFIX'])) {
			$cookie_dir .= rtrim($_SERVER['HTTP_X_FORWARDED_PREFIX'], '/ ');
		}
		$cookie_dir .= empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI'];
		if (substr($cookie_dir, -1) !== '/') {
			$cookie_dir = dirname($cookie_dir) . '/';
		}
		return $cookie_dir;
	}

	/**
	 * Specifies the lifetime of the cookies
	 * @param int $l the lifetime
	 */
	public static function keepCookie(int $l): void {
		session_set_cookie_params($l, self::getCookieDir(), '', Minz_Request::isHttps(), true);
	}

	/**
	 * Regenerate a session id.
	 */
	public static function regenerateID(string $name): void {
		if (self::$volatile || self::$locked) {
			return;
		}
		// Ensure that regenerating the session won't send multiple cookies so we can send one ourselves instead
		ini_set('session.use_cookies', '0');
		session_name($name);
		session_start();
		session_regenerate_id(true);
		session_write_close();
		$newId = session_id();
		if ($newId === false) {
			Minz_Error::error(500);
			return;
		}
		$lifetime = session_get_cookie_params()['lifetime'];
		$expire = $lifetime > 0 ? time() + $lifetime : 0;
		setcookie($name, $newId, $expire, self::getCookieDir(), '', Minz_Request::isHttps(), true);
	}

	public static function deleteLongTermCookie(string $name): void {
		setcookie($name, '', 1, '', '', Minz_Request::isHttps(), true);
	}

	public static function setLongTermCookie(string $name, string $value, int $expire): void {
		setcookie($name, $value, $expire, '', '', Minz_Request::isHttps(), true);
	}

	public static function getLongTermCookie(string $name): string {
		return is_string($_COOKIE[$name] ?? null) ? $_COOKIE[$name] : '';
	}

}