Session.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // Reject an uninitialized (e.g. attacker-supplied) session ID
  49. ini_set('session.use_strict_mode', '1');
  50. // When using cookies (default value), session_start() sends HTTP headers
  51. session_start();
  52. session_write_close();
  53. // Use cookie only the first time the session is started to avoid resending HTTP headers
  54. ini_set('session.use_cookies', '0');
  55. }
  56. /**
  57. * Allows you to retrieve a session variable
  58. * @param string $p the parameter to retrieve
  59. * @param mixed|false $default the default value if the parameter doesn’t exist
  60. * @return mixed|false the value of the session variable, false if doesn’t exist
  61. */
  62. #[Deprecated('Use typed versions instead')]
  63. public static function param(string $p, $default = false): mixed {
  64. return $_SESSION[$p] ?? $default;
  65. }
  66. /** @return array<string|int,string|array<string,mixed>> */
  67. public static function paramArray(string $key): array {
  68. if (empty($_SESSION[$key]) || !is_array($_SESSION[$key])) {
  69. return [];
  70. }
  71. $result = [];
  72. foreach ($_SESSION[$key] as $k => $v) {
  73. if (is_string($v) || (is_array($v) && is_array_keys_string($v))) {
  74. $result[$k] = $v;
  75. }
  76. }
  77. return $result;
  78. }
  79. public static function paramTernary(string $key): ?bool {
  80. if (isset($_SESSION[$key])) {
  81. $p = $_SESSION[$key];
  82. $tp = is_string($p) ? trim($p) : true;
  83. if ($tp === '' || $tp === 'null') {
  84. return null;
  85. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  86. return false;
  87. }
  88. return true;
  89. }
  90. return null;
  91. }
  92. public static function paramBoolean(string $key): bool {
  93. if (null === $value = self::paramTernary($key)) {
  94. return false;
  95. }
  96. return $value;
  97. }
  98. public static function paramInt(string $key): int {
  99. return empty($_SESSION[$key]) || !is_numeric($_SESSION[$key]) ? 0 : (int)$_SESSION[$key];
  100. }
  101. public static function paramString(string $key): string {
  102. if (isset($_SESSION[$key])) {
  103. $s = $_SESSION[$key];
  104. if (is_string($s)) {
  105. return $s;
  106. }
  107. if (is_int($s) || is_bool($s)) {
  108. return (string)$s;
  109. }
  110. }
  111. return '';
  112. }
  113. /**
  114. * Allows you to create or update a session variable
  115. * @param string $parameter the parameter to create or modify
  116. * @param mixed|false $value the value to assign, false to delete
  117. */
  118. public static function _param(string $parameter, $value = false): void {
  119. if (!self::$volatile && !self::$locked) {
  120. session_start();
  121. }
  122. if ($value === false) {
  123. unset($_SESSION[$parameter]);
  124. } else {
  125. $_SESSION[$parameter] = $value;
  126. }
  127. if (!self::$volatile && !self::$locked) {
  128. session_write_close();
  129. }
  130. }
  131. /**
  132. * @param array<string,string|bool|int|array<string>> $keyValues
  133. */
  134. public static function _params(array $keyValues): void {
  135. if (!self::$volatile && !self::$locked) {
  136. session_start();
  137. }
  138. foreach ($keyValues as $key => $value) {
  139. if ($value === false) {
  140. unset($_SESSION[$key]);
  141. } else {
  142. $_SESSION[$key] = $value;
  143. }
  144. }
  145. if (!self::$volatile && !self::$locked) {
  146. session_write_close();
  147. }
  148. }
  149. /**
  150. * Allows to delete a session
  151. * @param bool $force if false, does not clear the language parameter
  152. */
  153. public static function unset_session(bool $force = false): void {
  154. $language = self::paramString('language');
  155. if (!self::$volatile) {
  156. session_destroy();
  157. }
  158. $_SESSION = [];
  159. if (!$force) {
  160. self::_param('language', $language);
  161. Minz_Translate::reset($language);
  162. }
  163. }
  164. /**
  165. * Kept only to delete legacy cookies from before 1.29.0
  166. */
  167. protected static function getLegacyCookieDir(): string {
  168. // Get the script_name (e.g. /p/i/index.php) and keep only the path.
  169. $cookie_dir = '';
  170. if (!empty($_SERVER['HTTP_X_FORWARDED_PREFIX']) && is_string($_SERVER['HTTP_X_FORWARDED_PREFIX'])) {
  171. $cookie_dir .= rtrim($_SERVER['HTTP_X_FORWARDED_PREFIX'], '/ ');
  172. }
  173. $cookie_dir .= empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI'];
  174. if (substr($cookie_dir, -1) !== '/') {
  175. $cookie_dir = dirname($cookie_dir) . '/';
  176. }
  177. return $cookie_dir;
  178. }
  179. /** Delete legacy cookie (before 1.29.0) if it exists */
  180. public static function deleteLegacyCookie(string $name): void {
  181. if (isset($_COOKIE[$name])) {
  182. $legacyDir = self::getLegacyCookieDir();
  183. if ($legacyDir !== '' && $legacyDir !== '/') {
  184. setcookie($name, '', ['expires' => 1, 'path' => $legacyDir]);
  185. }
  186. }
  187. }
  188. /**
  189. * Regenerate a session id.
  190. *
  191. * @throws RuntimeException if the session could not be regenerated (e.g. unwritable session storage)
  192. */
  193. public static function regenerateID(string $name): void {
  194. if (self::$volatile) {
  195. return;
  196. }
  197. if (self::$locked) {
  198. throw new RuntimeException('Session is locked!');
  199. }
  200. // Ensure that regenerating the session won't send multiple cookies so we can send one ourselves instead
  201. ini_set('session.use_cookies', '0');
  202. if (session_name($name) === false || !session_start()) {
  203. throw new RuntimeException("Session {$name} could not be started!");
  204. }
  205. if (!session_regenerate_id(delete_old_session: true)) {
  206. throw new RuntimeException('Session could not be regenerated!');
  207. }
  208. session_write_close();
  209. $newId = session_id();
  210. if ($newId === false) {
  211. throw new RuntimeException('Session ID could not be retrieved!');
  212. }
  213. $params = session_get_cookie_params();
  214. $params['expires'] = $params['lifetime'] > 0 ? time() + $params['lifetime'] : 0;
  215. unset($params['lifetime']);
  216. // session_start() may already have queued a cookie when there was no session
  217. // cookie in the request (e.g. during remember-me auto-login).
  218. $setCookieHeaders = [];
  219. foreach (headers_list() as $header) {
  220. if (stripos($header, 'Set-Cookie:') === 0) {
  221. $setCookieHeaders[] = $header;
  222. }
  223. }
  224. if ($setCookieHeaders !== []) {
  225. header_remove('Set-Cookie');
  226. $prefixLength = strlen('Set-Cookie:');
  227. foreach ($setCookieHeaders as $header) {
  228. $cookie = ltrim(substr($header, $prefixLength));
  229. if (!str_starts_with($cookie, $name . '=')) {
  230. header($header, replace: false);
  231. }
  232. }
  233. }
  234. if (!setcookie($name, $newId, $params)) {
  235. throw new RuntimeException('Failed to set session cookie!');
  236. }
  237. return;
  238. }
  239. public static function deleteLongTermCookie(string $name): void {
  240. $params = session_get_cookie_params();
  241. $params['expires'] = 1;
  242. unset($params['lifetime']);
  243. setcookie($name, '', $params);
  244. }
  245. public static function setLongTermCookie(string $name, string $value, int $expire): void {
  246. $params = session_get_cookie_params();
  247. $params['expires'] = $expire;
  248. unset($params['lifetime']);
  249. setcookie($name, $value, $params);
  250. }
  251. public static function getLongTermCookie(string $name): string {
  252. return is_string($_COOKIE[$name] ?? null) ? $_COOKIE[$name] : '';
  253. }
  254. }