Session.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The Minz_Session class handles user’s session
  5. */
  6. class Minz_Session {
  7. private static bool $volatile = false;
  8. /**
  9. * For mutual exclusion.
  10. */
  11. private static bool $locked = false;
  12. public static function lock(): bool {
  13. if (!self::$volatile && !self::$locked) {
  14. self::$locked = session_start();
  15. }
  16. return self::$locked;
  17. }
  18. public static function unlock(): bool {
  19. if (!self::$volatile) {
  20. session_write_close();
  21. self::$locked = false;
  22. }
  23. return self::$locked;
  24. }
  25. /**
  26. * Initialize and start the session, with a name
  27. * The session name is used as the name for cookies and URLs (i.e. PHPSESSID).
  28. * It should contain only alphanumeric characters; it should be short and descriptive
  29. * If the volatile parameter is true, then no cookie and not session storage are used.
  30. * Volatile is especially useful for API calls without cookie / Web session.
  31. */
  32. public static function init(string $name, bool $volatile = false): void {
  33. self::$volatile = $volatile;
  34. if (self::$volatile) {
  35. $_SESSION = [];
  36. return;
  37. }
  38. $params = session_get_cookie_params();
  39. // Sanitize lifetime of session cookies from PHP ini `session.cookie_lifetime` (default 0)
  40. $params['lifetime'] = ($params['lifetime'] <= 0 || $params['lifetime'] > 86400) ? 0 : $params['lifetime'];
  41. $params['path'] = ''; // Current directory
  42. $params['domain'] = ''; // Current domain
  43. $params['secure'] = Minz_Request::isHttps();
  44. $params['httponly'] = true;
  45. $params['samesite'] = 'Lax';
  46. session_set_cookie_params($params);
  47. session_name($name);
  48. // A browser session from before FreshRSS 1.29.0
  49. $hasDuplicatedCookie = self::hasDuplicatedSessionCookie($name);
  50. // Reject an uninitialized (e.g. attacker-supplied) session ID
  51. ini_set('session.use_strict_mode', '1');
  52. // When using cookies (default value), session_start() sends HTTP headers
  53. session_start();
  54. session_write_close();
  55. // Use cookie only the first time the session is started to avoid resending HTTP headers
  56. ini_set('session.use_cookies', '0');
  57. if ($hasDuplicatedCookie) {
  58. // Must be done after session_start(), which replaces the pending Set-Cookie header
  59. self::deleteLegacyCookie($name);
  60. }
  61. }
  62. /**
  63. * Allows you to retrieve a session variable
  64. * @param string $p the parameter to retrieve
  65. * @param mixed|false $default the default value if the parameter doesn’t exist
  66. * @return mixed|false the value of the session variable, false if doesn’t exist
  67. */
  68. #[Deprecated('Use typed versions instead')]
  69. public static function param(string $p, $default = false): mixed {
  70. return $_SESSION[$p] ?? $default;
  71. }
  72. /** @return array<string|int,string|array<string,mixed>> */
  73. public static function paramArray(string $key): array {
  74. if (empty($_SESSION[$key]) || !is_array($_SESSION[$key])) {
  75. return [];
  76. }
  77. $result = [];
  78. foreach ($_SESSION[$key] as $k => $v) {
  79. if (is_string($v) || (is_array($v) && is_array_keys_string($v))) {
  80. $result[$k] = $v;
  81. }
  82. }
  83. return $result;
  84. }
  85. public static function paramTernary(string $key): ?bool {
  86. if (isset($_SESSION[$key])) {
  87. $p = $_SESSION[$key];
  88. $tp = is_string($p) ? trim($p) : true;
  89. if ($tp === '' || $tp === 'null') {
  90. return null;
  91. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  92. return false;
  93. }
  94. return true;
  95. }
  96. return null;
  97. }
  98. public static function paramBoolean(string $key): bool {
  99. if (null === $value = self::paramTernary($key)) {
  100. return false;
  101. }
  102. return $value;
  103. }
  104. public static function paramInt(string $key): int {
  105. return empty($_SESSION[$key]) || !is_numeric($_SESSION[$key]) ? 0 : (int)$_SESSION[$key];
  106. }
  107. public static function paramString(string $key): string {
  108. if (isset($_SESSION[$key])) {
  109. $s = $_SESSION[$key];
  110. if (is_string($s)) {
  111. return $s;
  112. }
  113. if (is_int($s) || is_bool($s)) {
  114. return (string)$s;
  115. }
  116. }
  117. return '';
  118. }
  119. /**
  120. * Allows you to create or update a session variable
  121. * @param string $parameter the parameter to create or modify
  122. * @param mixed|false $value the value to assign, false to delete
  123. */
  124. public static function _param(string $parameter, $value = false): void {
  125. if (!self::$volatile && !self::$locked) {
  126. session_start();
  127. }
  128. if ($value === false) {
  129. unset($_SESSION[$parameter]);
  130. } else {
  131. $_SESSION[$parameter] = $value;
  132. }
  133. if (!self::$volatile && !self::$locked) {
  134. session_write_close();
  135. }
  136. }
  137. /**
  138. * @param array<string,string|bool|int|array<string>> $keyValues
  139. */
  140. public static function _params(array $keyValues): void {
  141. if (!self::$volatile && !self::$locked) {
  142. session_start();
  143. }
  144. foreach ($keyValues as $key => $value) {
  145. if ($value === false) {
  146. unset($_SESSION[$key]);
  147. } else {
  148. $_SESSION[$key] = $value;
  149. }
  150. }
  151. if (!self::$volatile && !self::$locked) {
  152. session_write_close();
  153. }
  154. }
  155. /**
  156. * Allows to delete a session
  157. * @param bool $force if false, does not clear the language parameter
  158. */
  159. public static function unset_session(bool $force = false): void {
  160. $language = self::paramString('language');
  161. if (!self::$volatile) {
  162. session_destroy();
  163. }
  164. $_SESSION = [];
  165. if (!$force) {
  166. self::_param('language', $language);
  167. Minz_Translate::reset($language);
  168. }
  169. }
  170. /**
  171. * Kept only to delete legacy cookies from before 1.29.0
  172. */
  173. protected static function getLegacyCookieDir(): string {
  174. // Get the script_name (e.g. /p/i/index.php) and keep only the path.
  175. $cookie_dir = '';
  176. if (!empty($_SERVER['HTTP_X_FORWARDED_PREFIX']) && is_string($_SERVER['HTTP_X_FORWARDED_PREFIX'])) {
  177. $cookie_dir .= rtrim($_SERVER['HTTP_X_FORWARDED_PREFIX'], '/ ');
  178. }
  179. $cookie_dir .= empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI'];
  180. if (substr($cookie_dir, -1) !== '/') {
  181. $cookie_dir = dirname($cookie_dir) . '/';
  182. }
  183. return $cookie_dir;
  184. }
  185. /**
  186. * Delete legacy cookie (before 1.29.0) if it exists
  187. * @return bool true if the cookie has been expired
  188. */
  189. public static function deleteLegacyCookie(string $name): bool {
  190. if (isset($_COOKIE[$name])) {
  191. $legacyDir = self::getLegacyCookieDir();
  192. if ($legacyDir !== '' && $legacyDir !== '/') {
  193. setcookie($name, '', ['expires' => 1, 'path' => $legacyDir]);
  194. return true;
  195. }
  196. }
  197. return false;
  198. }
  199. /**
  200. * Whether the request carries the session cookie twice, which happens when a browser profile
  201. * has the legacy cookie next to the current one with two different paths.
  202. */
  203. protected static function hasDuplicatedSessionCookie(string $name): bool {
  204. $header = $_SERVER['HTTP_COOKIE'] ?? null;
  205. return is_string($header) && substr_count($header, $name . '=') > 1;
  206. }
  207. /**
  208. * Regenerate a session id.
  209. *
  210. * @param bool $delete_old_session `true` to delete the old session file; set to `false` if it is known
  211. * not to contain authenticated data, to avoid breaking concurrent in-flight requests
  212. * @throws RuntimeException if the session could not be regenerated (e.g. unwritable session storage)
  213. */
  214. public static function regenerateID(string $name, bool $delete_old_session = true): void {
  215. if (self::$volatile) {
  216. return;
  217. }
  218. if (self::$locked) {
  219. throw new RuntimeException('Session is locked!');
  220. }
  221. // Ensure that regenerating the session won't send multiple cookies so we can send one ourselves instead
  222. ini_set('session.use_cookies', '0');
  223. if (session_name($name) === false || !@session_start()) {
  224. throw new RuntimeException("Session {$name} could not be started!");
  225. }
  226. if (!session_regenerate_id(delete_old_session: $delete_old_session)) {
  227. throw new RuntimeException('Session could not be regenerated!');
  228. }
  229. session_write_close();
  230. $newId = session_id();
  231. if ($newId === false) {
  232. throw new RuntimeException('Session ID could not be retrieved!');
  233. }
  234. $params = session_get_cookie_params();
  235. $params['expires'] = $params['lifetime'] > 0 ? time() + $params['lifetime'] : 0;
  236. unset($params['lifetime']);
  237. // session_start() may already have queued a cookie when there was no session
  238. // cookie in the request (e.g. during remember-me auto-login).
  239. $setCookieHeaders = [];
  240. foreach (headers_list() as $header) {
  241. if (stripos($header, 'Set-Cookie:') === 0) {
  242. $setCookieHeaders[] = $header;
  243. }
  244. }
  245. if ($setCookieHeaders !== []) {
  246. header_remove('Set-Cookie');
  247. $prefixLength = strlen('Set-Cookie:');
  248. foreach ($setCookieHeaders as $header) {
  249. $cookie = ltrim(substr($header, $prefixLength));
  250. if (!str_starts_with($cookie, $name . '=')) {
  251. header($header, replace: false);
  252. }
  253. }
  254. }
  255. if (!setcookie($name, $newId, $params)) {
  256. throw new RuntimeException('Failed to set session cookie!');
  257. }
  258. return;
  259. }
  260. public static function deleteLongTermCookie(string $name): void {
  261. $params = session_get_cookie_params();
  262. $params['expires'] = 1;
  263. unset($params['lifetime']);
  264. setcookie($name, '', $params);
  265. }
  266. public static function setLongTermCookie(string $name, string $value, int $expire): void {
  267. $params = session_get_cookie_params();
  268. $params['expires'] = $expire;
  269. unset($params['lifetime']);
  270. setcookie($name, $value, $params);
  271. }
  272. public static function getLongTermCookie(string $name): string {
  273. return is_string($_COOKIE[$name] ?? null) ? $_COOKIE[$name] : '';
  274. }
  275. }