Session.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. session_start();
  15. self::$locked = true;
  16. }
  17. return self::$locked;
  18. }
  19. public static function unlock(): bool {
  20. if (!self::$volatile) {
  21. session_write_close();
  22. self::$locked = false;
  23. }
  24. return self::$locked;
  25. }
  26. /**
  27. * Initialize and start the session, with a name
  28. * The session name is used as the name for cookies and URLs (i.e. PHPSESSID).
  29. * It should contain only alphanumeric characters; it should be short and descriptive
  30. * If the volatile parameter is true, then no cookie and not session storage are used.
  31. * Volatile is especially useful for API calls without cookie / Web session.
  32. */
  33. public static function init(string $name, bool $volatile = false): void {
  34. self::$volatile = $volatile;
  35. if (self::$volatile) {
  36. $_SESSION = [];
  37. return;
  38. }
  39. $params = session_get_cookie_params();
  40. // Sanitize lifetime of session cookies from PHP ini `session.cookie_lifetime` (default 0)
  41. $params['lifetime'] = ($params['lifetime'] <= 0 || $params['lifetime'] > 86400) ? 0 : $params['lifetime'];
  42. $params['path'] = ''; // Current directory
  43. $params['domain'] = ''; // Current domain
  44. $params['secure'] = Minz_Request::isHttps();
  45. $params['httponly'] = true;
  46. $params['samesite'] = 'Lax';
  47. session_set_cookie_params($params);
  48. session_name($name);
  49. // Delete legacy cookie (before 1.29.0) if it exists
  50. if (isset($_COOKIE[$name])) {
  51. $legacyDir = self::getLegacyCookieDir();
  52. if ($legacyDir !== '' && $legacyDir !== '/') {
  53. setcookie($name, '', ['expires' => 1, 'path' => $legacyDir]);
  54. }
  55. }
  56. // When using cookies (default value), session_start() sends HTTP headers
  57. session_start();
  58. session_write_close();
  59. // Use cookie only the first time the session is started to avoid resending HTTP headers
  60. ini_set('session.use_cookies', '0');
  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. * Regenerate a session id.
  187. */
  188. public static function regenerateID(string $name): void {
  189. if (self::$volatile || self::$locked) {
  190. return;
  191. }
  192. // Ensure that regenerating the session won't send multiple cookies so we can send one ourselves instead
  193. ini_set('session.use_cookies', '0');
  194. session_name($name);
  195. session_start();
  196. session_regenerate_id(true);
  197. session_write_close();
  198. $newId = session_id();
  199. if ($newId === false) {
  200. Minz_Error::error(500);
  201. return;
  202. }
  203. $params = session_get_cookie_params();
  204. $params['expires'] = $params['lifetime'] > 0 ? time() + $params['lifetime'] : 0;
  205. unset($params['lifetime']);
  206. setcookie($name, $newId, $params);
  207. }
  208. public static function deleteLongTermCookie(string $name): void {
  209. $params = session_get_cookie_params();
  210. $params['expires'] = 1;
  211. unset($params['lifetime']);
  212. setcookie($name, '', $params);
  213. }
  214. public static function setLongTermCookie(string $name, string $value, int $expire): void {
  215. $params = session_get_cookie_params();
  216. $params['expires'] = $expire;
  217. unset($params['lifetime']);
  218. setcookie($name, $value, $params);
  219. }
  220. public static function getLongTermCookie(string $name): string {
  221. return is_string($_COOKIE[$name] ?? null) ? $_COOKIE[$name] : '';
  222. }
  223. }