4
0

Session.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. // When using cookies (default value), session_start() sends HTTP headers
  50. session_start();
  51. session_write_close();
  52. // Use cookie only the first time the session is started to avoid resending HTTP headers
  53. ini_set('session.use_cookies', '0');
  54. }
  55. /**
  56. * Allows you to retrieve a session variable
  57. * @param string $p the parameter to retrieve
  58. * @param mixed|false $default the default value if the parameter doesn’t exist
  59. * @return mixed|false the value of the session variable, false if doesn’t exist
  60. */
  61. #[Deprecated('Use typed versions instead')]
  62. public static function param(string $p, $default = false): mixed {
  63. return $_SESSION[$p] ?? $default;
  64. }
  65. /** @return array<string|int,string|array<string,mixed>> */
  66. public static function paramArray(string $key): array {
  67. if (empty($_SESSION[$key]) || !is_array($_SESSION[$key])) {
  68. return [];
  69. }
  70. $result = [];
  71. foreach ($_SESSION[$key] as $k => $v) {
  72. if (is_string($v) || (is_array($v) && is_array_keys_string($v))) {
  73. $result[$k] = $v;
  74. }
  75. }
  76. return $result;
  77. }
  78. public static function paramTernary(string $key): ?bool {
  79. if (isset($_SESSION[$key])) {
  80. $p = $_SESSION[$key];
  81. $tp = is_string($p) ? trim($p) : true;
  82. if ($tp === '' || $tp === 'null') {
  83. return null;
  84. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  85. return false;
  86. }
  87. return true;
  88. }
  89. return null;
  90. }
  91. public static function paramBoolean(string $key): bool {
  92. if (null === $value = self::paramTernary($key)) {
  93. return false;
  94. }
  95. return $value;
  96. }
  97. public static function paramInt(string $key): int {
  98. return empty($_SESSION[$key]) || !is_numeric($_SESSION[$key]) ? 0 : (int)$_SESSION[$key];
  99. }
  100. public static function paramString(string $key): string {
  101. if (isset($_SESSION[$key])) {
  102. $s = $_SESSION[$key];
  103. if (is_string($s)) {
  104. return $s;
  105. }
  106. if (is_int($s) || is_bool($s)) {
  107. return (string)$s;
  108. }
  109. }
  110. return '';
  111. }
  112. /**
  113. * Allows you to create or update a session variable
  114. * @param string $parameter the parameter to create or modify
  115. * @param mixed|false $value the value to assign, false to delete
  116. */
  117. public static function _param(string $parameter, $value = false): void {
  118. if (!self::$volatile && !self::$locked) {
  119. session_start();
  120. }
  121. if ($value === false) {
  122. unset($_SESSION[$parameter]);
  123. } else {
  124. $_SESSION[$parameter] = $value;
  125. }
  126. if (!self::$volatile && !self::$locked) {
  127. session_write_close();
  128. }
  129. }
  130. /**
  131. * @param array<string,string|bool|int|array<string>> $keyValues
  132. */
  133. public static function _params(array $keyValues): void {
  134. if (!self::$volatile && !self::$locked) {
  135. session_start();
  136. }
  137. foreach ($keyValues as $key => $value) {
  138. if ($value === false) {
  139. unset($_SESSION[$key]);
  140. } else {
  141. $_SESSION[$key] = $value;
  142. }
  143. }
  144. if (!self::$volatile && !self::$locked) {
  145. session_write_close();
  146. }
  147. }
  148. /**
  149. * Allows to delete a session
  150. * @param bool $force if false, does not clear the language parameter
  151. */
  152. public static function unset_session(bool $force = false): void {
  153. $language = self::paramString('language');
  154. if (!self::$volatile) {
  155. session_destroy();
  156. }
  157. $_SESSION = [];
  158. if (!$force) {
  159. self::_param('language', $language);
  160. Minz_Translate::reset($language);
  161. }
  162. }
  163. /**
  164. * Regenerate a session id.
  165. */
  166. public static function regenerateID(string $name): void {
  167. if (self::$volatile || self::$locked) {
  168. return;
  169. }
  170. // Ensure that regenerating the session won't send multiple cookies so we can send one ourselves instead
  171. ini_set('session.use_cookies', '0');
  172. session_name($name);
  173. session_start();
  174. session_regenerate_id(true);
  175. session_write_close();
  176. $newId = session_id();
  177. if ($newId === false) {
  178. Minz_Error::error(500);
  179. return;
  180. }
  181. $params = session_get_cookie_params();
  182. $params['expires'] = $params['lifetime'] > 0 ? time() + $params['lifetime'] : 0;
  183. unset($params['lifetime']);
  184. setcookie($name, $newId, $params);
  185. }
  186. public static function deleteLongTermCookie(string $name): void {
  187. $params = session_get_cookie_params();
  188. $params['expires'] = 1;
  189. unset($params['lifetime']);
  190. setcookie($name, '', $params);
  191. }
  192. public static function setLongTermCookie(string $name, string $value, int $expire): void {
  193. $params = session_get_cookie_params();
  194. $params['expires'] = $expire;
  195. unset($params['lifetime']);
  196. setcookie($name, $value, $params);
  197. }
  198. public static function getLongTermCookie(string $name): string {
  199. return is_string($_COOKIE[$name] ?? null) ? $_COOKIE[$name] : '';
  200. }
  201. }