xref: /webtrees/app/Session.php (revision 81b729d3a9a6e0a0e8b96285d1ad7955d2d0c659)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Illuminate\Support\Str;
23use Psr\Http\Message\ServerRequestInterface;
24
25use function array_map;
26use function explode;
27use function implode;
28use function parse_url;
29use function rawurlencode;
30use function session_name;
31use function session_regenerate_id;
32use function session_register_shutdown;
33use function session_set_cookie_params;
34use function session_set_save_handler;
35use function session_start;
36use function session_status;
37use function session_write_close;
38
39use const PHP_SESSION_ACTIVE;
40use const PHP_URL_HOST;
41use const PHP_URL_PATH;
42use const PHP_URL_SCHEME;
43
44/**
45 * Session handling
46 */
47class Session
48{
49    // Use the secure prefix with HTTPS.
50    private const SESSION_NAME        = 'WT2_SESSION';
51    private const SECURE_SESSION_NAME = '__Secure-WT-ID';
52
53    /**
54     * Start a session
55     *
56     * @param ServerRequestInterface $request
57     *
58     * @return void
59     */
60    public static function start(ServerRequestInterface $request): void
61    {
62        // Store sessions in the database
63        session_set_save_handler(new SessionDatabaseHandler($request));
64
65        $url    = $request->getAttribute('base_url');
66        $secure = parse_url($url, PHP_URL_SCHEME) === 'https';
67        $domain = (string) parse_url($url, PHP_URL_HOST);
68        $path   = (string) parse_url($url, PHP_URL_PATH);
69
70        // Paths containing UTF-8 characters need special handling.
71        $path = implode('/', array_map(fn (string $x): string => rawurlencode($x), explode('/', $path)));
72
73        session_name($secure ? self::SECURE_SESSION_NAME : self::SESSION_NAME);
74        session_register_shutdown();
75        session_set_cookie_params([
76            'lifetime' => 0,
77            'path'     => $path . '/',
78            'domain'   => $domain,
79            'secure'   => $secure,
80            'httponly' => true,
81            'samesite' => 'Lax',
82        ]);
83        session_start();
84
85        // A new session? Prevent session fixation attacks by choosing a new session ID.
86        if (self::get('initiated') !== true) {
87            self::regenerate(true);
88            self::put('initiated', true);
89        }
90    }
91
92    /**
93     * Save/close the session.  This releases the session lock.
94     * Closing early can help concurrent connections.
95     */
96    public static function save(): void
97    {
98        if (session_status() === PHP_SESSION_ACTIVE) {
99            session_write_close();
100        }
101    }
102
103    /**
104     * Read a value from the session
105     *
106     * @param string $name
107     * @param mixed  $default
108     *
109     * @return mixed
110     */
111    public static function get(string $name, $default = null)
112    {
113        return $_SESSION[$name] ?? $default;
114    }
115
116    /**
117     * Read a value from the session and remove it.
118     *
119     * @param string $name
120     * @param mixed  $default
121     *
122     * @return mixed
123     */
124    public static function pull(string $name, $default = null)
125    {
126        $value = self::get($name, $default);
127        self::forget($name);
128
129        return $value;
130    }
131
132    /**
133     * After any change in authentication level, we should use a new session ID.
134     *
135     * @param bool $destroy
136     *
137     * @return void
138     */
139    public static function regenerate(bool $destroy = false): void
140    {
141        if ($destroy) {
142            self::clear();
143        }
144
145        if (session_status() === PHP_SESSION_ACTIVE) {
146            session_regenerate_id($destroy);
147        }
148    }
149
150    /**
151     * Remove all stored data from the session.
152     *
153     * @return void
154     */
155    public static function clear(): void
156    {
157        $_SESSION = [];
158    }
159
160    /**
161     * Write a value to the session
162     *
163     * @param string $name
164     * @param mixed  $value
165     *
166     * @return void
167     */
168    public static function put(string $name, $value): void
169    {
170        $_SESSION[$name] = $value;
171    }
172
173    /**
174     * Remove a value from the session
175     *
176     * @param string $name
177     *
178     * @return void
179     */
180    public static function forget(string $name): void
181    {
182        unset($_SESSION[$name]);
183    }
184
185    /**
186     * Cross-Site Request Forgery tokens - ensure that the user is submitting
187     * a form that was generated by the current session.
188     *
189     * @return string
190     */
191    public static function getCsrfToken(): string
192    {
193        if (!self::has('CSRF_TOKEN')) {
194            self::put('CSRF_TOKEN', Str::random(32));
195        }
196
197        return self::get('CSRF_TOKEN');
198    }
199
200    /**
201     * Does a session variable exist?
202     *
203     * @param string $name
204     *
205     * @return bool
206     */
207    public static function has(string $name): bool
208    {
209        return isset($_SESSION[$name]);
210    }
211}
212