Session.php 6.3 KB

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