4
0

Session.php 7.4 KB

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