Session.php 9.78 KB
Newer Older
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 5/4/16
 * Time: 1:34 PM
 */

Marc Egger's avatar
Marc Egger committed
9
namespace IMATHUZH\Qfq\Core\Store;
10

Marc Egger's avatar
Marc Egger committed
11
12
 
use IMATHUZH\Qfq\Core\Typo3\Misc;
13

14

15
16
17
18
/**
 * Class Session
 * @package qfq
 */
19
20
class Session
{
21

22
23
24
    private static $instance = null;
    private static $phpUnit = null;
    private static $sessionLocal = array();
25
26
    private static $sessionId = null;
    private static $sessionOpen = false;
27
    private static $lastActivity = false;
28
    private static $flagChangedCookieFe = false;
29
30
31

    /**
     * @param bool|false $phpUnit
Carsten  Rose's avatar
Carsten Rose committed
32
     *
Marc Egger's avatar
Marc Egger committed
33
     * @throws \CodeException
34
35
     */
    private function __construct($phpUnit = false) {
36

37
        #TODO: rewrite $phpUnit to: "if (!defined('PHPUNIT_QFQ')) {...}"
38
        if (self::$phpUnit !== null) {
Marc Egger's avatar
Marc Egger committed
39
            throw new \CodeException("Try to set flag phpunit again - that should not happen.", ERROR_CODE_SHOULD_NOT_HAPPEN);
40
        }
41
42

        self::$phpUnit = $phpUnit;
43

44
        if (self::$phpUnit === true) {
45
46
            self::$sessionLocal = array();
        } else {
47
48
            ini_set('session.cookie_httponly', 1);

49
            $lifetime = SYSTEM_COOKIE_LIFETIME;
50

51
            $path = $this->getSitePath();
52

53
54
            session_set_cookie_params($lifetime, $path);
            $currentCookieParams = session_get_cookie_params();
55

56
            session_name(SESSION_NAME);
57

58
            session_start();
59

60
61
62
            // Currently, setcookie() is only called to really extend the lifetime. All other parameter needs to be given again.
            setcookie(SESSION_NAME, session_id(), time() + $lifetime, $path, $currentCookieParams['domain'], $currentCookieParams['secure'], true);

63
            self::$sessionId = session_id();
64
        }
65
66
67

        self::$sessionOpen = true;

68
        self::checkFeUserUid();
69
70
71

    }

72
73
74
    /**
     * Extract the SitePath of the current T3 installation.
     *
75
     * @return bool|string - <path>  with a trailing '/'
Marc Egger's avatar
Marc Egger committed
76
     * @throws \CodeException
77
78
79
80
     */
    private static function getSitePath() {

        if (empty($_SERVER['SCRIPT_NAME'])) {
Marc Egger's avatar
Marc Egger committed
81
            throw new \CodeException('Missing _SERVER[SCRIPT_NAME]', ERROR_SESSION_BROKEN_SCRIPT_PATH);
82
83
        }

Carsten  Rose's avatar
Carsten Rose committed
84
        $path = $_SERVER['SCRIPT_NAME'] ?? '';
85
        $pos = strrpos($path, '/');
86

87
        if ($pos === false) {
Marc Egger's avatar
Marc Egger committed
88
            throw new \CodeException("Broken _SERVER[SCRIPT_NAME]: $path", ERROR_SESSION_BROKEN_SCRIPT_PATH);
89
90
91
92
93
        }
        // Remove PHP script
        $path = substr($path, 0, $pos + 1);

        // QFQ might be called by API - justify to the SitePath
94
        $pos = strpos($path, 'typo3conf/');
95
        if ($pos !== false) {
96
            $path = substr($path, 0, $pos - strlen($path));
97
98
99
        }

        if (empty($path)) {
Marc Egger's avatar
Marc Egger committed
100
            throw new \CodeException("Broken _SERVER[SCRIPT_NAME]: $path", ERROR_SESSION_BROKEN_SCRIPT_PATH);
101
102
103
104
105
        }

        return $path;
    }

106
107
108
109
    /**
     * Free a lock on the current session
     */
    public static function close() {
110
111
112
113

        if (self::$sessionOpen) {
            session_write_close();
        }
114
115
116
117
        self::$sessionOpen = false;

    }

118
119
120
121
    /**
     * Destroy a session - this is only needed in case of attacks
     */
    public static function destroy() {
122

123
        if (!defined('PHPUNIT_QFQ')) {
Carsten  Rose's avatar
Carsten Rose committed
124
125
126
127
128
129

            if (isset($_COOKIE[SESSION_NAME])) {
                unset($_COOKIE[SESSION_NAME]);
                setcookie(SESSION_NAME, '', time() - 86400, '/'); // empty value and old timestamp
            }

130
131
            session_destroy();
        }
132

Carsten  Rose's avatar
Carsten Rose committed
133
        $_SESSION = array();
134
135
    }

136
    /**
137
     * By default the session is opened during the bootstrap. In case the session has been closed manually, reopen it here.
138
139
140
141
142
143
     * This code has never been tested - it should not happen that a session needs manually closed and reopen than.
     * Nevertheless: This code is therefore a fallback in case the reopen really happens somewhat. Maybe this happens in
     * upcoming logic.
     *
     */
    public static function open() {
144

145
146
147
        if (self::$sessionOpen != true && self::$sessionId != null) {
            session_id(self::$sessionId);
            session_start();
148
            self::$sessionOpen = true;
149
        }
150
151
152
    }

    /**
153
     * Check if the feUserUid is stored in the session (even with 'false' which indicates not logged in user).
154
155
156
157
     *   If not,
     *    - clear the session
     *    - save the feUser, feUserUid in the session.
     *
Carsten  Rose's avatar
Carsten Rose committed
158
159
160
     * Check if the recent logged in feUserUid is equal to the one stored in session: If different, invalidate (clear)
     * the session and save the new feUser, feUserUid in the session. If isset($GLOBALS["TSFE"]), than we're in a T3
     * environment, else we are called as API classes and need to fake feUser / feUserUid from previous stored session.
161
     * It's necessary to have feUser / feUserUid available in API classes, due to dynamic update which might reload
Carsten  Rose's avatar
Carsten Rose committed
162
     * data based on feUser / feUserUid.
163
     */
164
    private static function checkFeUserUid() {
165

166
167
        $feUserUidSession = Session::get(SESSION_FE_USER_UID);
        $feUserSession = Session::get(SESSION_FE_USER);
168
        $feUserGroup = false;
169

170
171
        // Session Timeout only exists for logged in FE users - the default is no user logged in, so set to false to switch of session expiration.
        self::$lastActivity = false;
172

Carsten  Rose's avatar
Carsten Rose committed
173
        if (isset($GLOBALS["TSFE"])) {
174
            // if no one is logged in: 0
175
176
177
178
179
180
181
182
183
184
185
            $feUidLoggedIn = $GLOBALS["TSFE"]->fe_user->user["uid"] ?? false;
            $feUserSession = $GLOBALS["TSFE"]->fe_user->user["username"] ?? false;
            $feUserGroup = $GLOBALS["TSFE"]->fe_user->user["usergroup"] ?? false;
            $beUser = $GLOBALS["BE_USER"]->user["username"] ?? false;

            // Cookie identifier
            $cookieFe = ($_COOKIE['fe_typo_user']) ?? false;
            if ($cookieFe !== self::get(SESSION_LAST_COOKIE_FE)) {
                self::$flagChangedCookieFe = true; // Set the flag that the FE_USER User has changed
                // Update SESSION_LAST_FE_COOKIE
                self::set(SESSION_LAST_COOKIE_FE, $cookieFe);
186
187
188
            }

            // Manage Custom Session Timeout for logged in users
189
190
            if (isset($GLOBALS["TSFE"]->fe_user->user["username"]) && isset($_COOKIE['fe_typo_user'])) {

191
192
                if (self::$flagChangedCookieFe) {
                    // New user: start timeout timer
193
                    self::$lastActivity = time();
194
195
196
                } else {
                    // ok, still the same user is logged in: get the last activity timestamp to compare later against timeout.
                    self::$lastActivity = self::get(SESSION_LAST_ACTIVITY);
197
198
199
                }
            }

Carsten  Rose's avatar
Carsten Rose committed
200
        } else {
201
202
            // If we are called through API there is no T3 environment. Assume nothing has changed, and fake the following check to always 'no change'.
            $feUidLoggedIn = $feUserUidSession;
Carsten  Rose's avatar
Carsten Rose committed
203
204
        }

205
        if ($feUidLoggedIn != $feUserUidSession) {
206

207
            // save new feUserUid, feUserName
208
            Session::set(SESSION_FE_USER_UID, $feUidLoggedIn);
209
            Session::set(SESSION_FE_USER, $feUserSession);
210
            Session::set(SESSION_FE_USER_GROUP, $feUserGroup);
211
            Session::set(SESSION_BE_USER, $beUser);
212
        }
213
214
215
    }

    /**
216
217
218
     * Return content to given $key (=SIP).
     * Return 'false' if not found.
     *
219
     * @param $key
Carsten  Rose's avatar
Carsten Rose committed
220
     *
221
222
223
224
     * @return bool
     */
    public static function get($key) {

225
226
227
228
        if (!self::$sessionOpen) {
            self::open();
        }

229
        if (self::$phpUnit) {
230
            $value = isset(self::$sessionLocal[$key]) ? self::$sessionLocal[$key] : false;
231
        } else {
232
            $value = isset($_SESSION[SESSION_NAME][$key]) ? $_SESSION[SESSION_NAME][$key] : false;
233
234
235
236
237
        }

        return $value;
    }

238
239
240
    /**
     *
     */
Carsten  Rose's avatar
#2067    
Carsten Rose committed
241
    public static function clearAll() {
242

243
244
245
246
        if (!self::$sessionOpen) {
            self::open();
        }

247
248
249
250
251
252
253
        if (self::$phpUnit) {
            self::$sessionLocal = array();
        } else {
            $_SESSION[SESSION_NAME] = array();
        }
    }

254
255
256
257
258
259
    /**
     * @param $key
     * @param $value
     */
    public static function set($key, $value) {

260
261
262
263
        if (!self::$sessionOpen) {
            self::open();
        }

264
265
266
        if (self::$phpUnit) {
            self::$sessionLocal[$key] = $value;
        } else {
267
            $_SESSION[SESSION_NAME][$key] = $value;
268
269
270
        }
    }

Carsten  Rose's avatar
#2067    
Carsten Rose committed
271
272
273
274
275
276
277
    /**
     * Unset the given $key
     *
     * @param $key
     */
    public static function unsetItem($key) {

278
279
280
281
        if (!self::$sessionOpen) {
            self::open();
        }

Carsten  Rose's avatar
#2067    
Carsten Rose committed
282
283
284
285
286
287
        if (isset($_SESSION[SESSION_NAME][$key])) {
            unset($_SESSION[SESSION_NAME][$key]);
        }

    }

288
    /**
289
     * @param bool|false $phpUnit
Carsten  Rose's avatar
Carsten Rose committed
290
     *
291
     * @return Session class
Marc Egger's avatar
Marc Egger committed
292
     * @throws \CodeException
293
     */
294
    public static function getInstance($phpUnit = false) {
295

296
297
298
        // Design Pattern: Singleton
        if (self::$instance === null) {
            self::$instance = new self($phpUnit);
299
        }
300

301
302
303
304
        if (!self::$sessionOpen) {
            self::open();
        }

305
        return self::$instance;
306
307
    }

308
309
310
311
    /**
     * Checks if the QFQ session is expired.
     *
     * @param $timeout
Marc Egger's avatar
Marc Egger committed
312
     * @throws \UserFormException
313
314
315
316
317
318
319
320
321
322
323
     */
    public static function checkSessionExpired($timeout) {

        // Just to be sure that the given $timeout is supported by the current php.ini setup
        config::checkSessionTimeout($timeout);

        if (self::$lastActivity === false || $timeout === false || $timeout == 0) {
            return;
        }

        if (time() - self::$lastActivity > $timeout) {
324

325
326
            Misc::feLogOff();
            self::destroy();
327
328
        }
    }
329
330
331
332
333
334
335
336

    /**
     * Returns $flagFeUserChanged. In case it's true, set it to false.
     *
     * @return bool
     */
    public static function getAndDestroyFlagFeUserHasChanged() {

337
        $flag = self::$flagChangedCookieFe;
338

339
        self::$flagChangedCookieFe = false;
340
341
342

        return $flag;
    }
343
}