Session.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. * @deprecated Use typed versions instead
  55. */
  56. public static function param(string $p, $default = false) {
  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. return $_SESSION[$key];
  65. }
  66. public static function paramTernary(string $key): ?bool {
  67. if (isset($_SESSION[$key])) {
  68. $p = $_SESSION[$key];
  69. $tp = is_string($p) ? trim($p) : true;
  70. if ($tp === '' || $tp === 'null') {
  71. return null;
  72. } elseif ($p == false || $tp == '0' || $tp === 'false' || $tp === 'no') {
  73. return false;
  74. }
  75. return true;
  76. }
  77. return null;
  78. }
  79. public static function paramBoolean(string $key): bool {
  80. if (null === $value = self::paramTernary($key)) {
  81. return false;
  82. }
  83. return $value;
  84. }
  85. public static function paramInt(string $key): int {
  86. if (!empty($_SESSION[$key])) {
  87. return intval($_SESSION[$key]);
  88. }
  89. return 0;
  90. }
  91. public static function paramString(string $key): string {
  92. if (isset($_SESSION[$key])) {
  93. $s = $_SESSION[$key];
  94. if (is_string($s)) {
  95. return $s;
  96. }
  97. if (is_int($s) || is_bool($s)) {
  98. return (string)$s;
  99. }
  100. }
  101. return '';
  102. }
  103. /**
  104. * Allows you to create or update a session variable
  105. * @param string $parameter the parameter to create or modify
  106. * @param mixed|false $value the value to assign, false to delete
  107. */
  108. public static function _param(string $parameter, $value = false): void {
  109. if (!self::$volatile && !self::$locked) {
  110. session_start();
  111. }
  112. if ($value === false) {
  113. unset($_SESSION[$parameter]);
  114. } else {
  115. $_SESSION[$parameter] = $value;
  116. }
  117. if (!self::$volatile && !self::$locked) {
  118. session_write_close();
  119. }
  120. }
  121. /**
  122. * @param array<string,string|bool|int|array<string>> $keyValues
  123. */
  124. public static function _params(array $keyValues): void {
  125. if (!self::$volatile && !self::$locked) {
  126. session_start();
  127. }
  128. foreach ($keyValues as $key => $value) {
  129. if ($value === false) {
  130. unset($_SESSION[$key]);
  131. } else {
  132. $_SESSION[$key] = $value;
  133. }
  134. }
  135. if (!self::$volatile && !self::$locked) {
  136. session_write_close();
  137. }
  138. }
  139. /**
  140. * Allows to delete a session
  141. * @param bool $force if false, does not clear the language parameter
  142. */
  143. public static function unset_session(bool $force = false): void {
  144. $language = self::paramString('language');
  145. if (!self::$volatile) {
  146. session_destroy();
  147. }
  148. $_SESSION = array();
  149. if (!$force) {
  150. self::_param('language', $language);
  151. Minz_Translate::reset($language);
  152. }
  153. }
  154. public static function getCookieDir(): string {
  155. // Get the script_name (e.g. /p/i/index.php) and keep only the path.
  156. $cookie_dir = '';
  157. if (!empty($_SERVER['HTTP_X_FORWARDED_PREFIX'])) {
  158. $cookie_dir .= rtrim($_SERVER['HTTP_X_FORWARDED_PREFIX'], '/ ');
  159. }
  160. $cookie_dir .= empty($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI'];
  161. if (substr($cookie_dir, -1) !== '/') {
  162. $cookie_dir = dirname($cookie_dir) . '/';
  163. }
  164. return $cookie_dir;
  165. }
  166. /**
  167. * Specifies the lifetime of the cookies
  168. * @param int $l the lifetime
  169. */
  170. public static function keepCookie(int $l): void {
  171. session_set_cookie_params($l, self::getCookieDir(), '', Minz_Request::isHttps(), true);
  172. }
  173. /**
  174. * Regenerate a session id.
  175. * Useful to call session_set_cookie_params after session_start()
  176. */
  177. public static function regenerateID(): void {
  178. session_regenerate_id(true);
  179. }
  180. public static function deleteLongTermCookie(string $name): void {
  181. setcookie($name, '', 1, '', '', Minz_Request::isHttps(), true);
  182. }
  183. public static function setLongTermCookie(string $name, string $value, int $expire): void {
  184. setcookie($name, $value, $expire, '', '', Minz_Request::isHttps(), true);
  185. }
  186. public static function getLongTermCookie(string $name): string {
  187. return $_COOKIE[$name] ?? '';
  188. }
  189. }