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

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

11
use IMATHUZH\Qfq\Core\Database\Database;
12
use IMATHUZH\Qfq\Core\Helper\HelperFile;
Marc Egger's avatar
Marc Egger committed
13
use IMATHUZH\Qfq\Core\Helper\KeyValueStringParser;
14
use IMATHUZH\Qfq\Core\Helper\Logger;
Marc Egger's avatar
Marc Egger committed
15
16
17
use IMATHUZH\Qfq\Core\Helper\OnArray;
use IMATHUZH\Qfq\Core\Helper\Sanitize;
use IMATHUZH\Qfq\Core\Helper\Support;
18
19
20
21
22
23
24
25
26
27

/*
 * Stores:
 * - SIP
 * - webVar
 * - record
 * - form
 * - formElement
 */

Carsten  Rose's avatar
Carsten Rose committed
28
29
/**
 * Class Store
30
 * @package qfq
Carsten  Rose's avatar
Carsten Rose committed
31
 */
32
33
class Store {

Carsten  Rose's avatar
Carsten Rose committed
34
35
36
    /**
     * @var Store Instance of class Store. There should only be one class 'Store' at a time.
     */
37
38
    private static $instance = null;

Carsten  Rose's avatar
Carsten Rose committed
39
40
41
    /**
     * @var Sip Instance of class SIP
     */
42
43
    private static $sip = null;

44
45
46
    /**
     * @var Session Instance of class Session
     */
47
//    private static $session = null;
48

Carsten  Rose's avatar
Carsten Rose committed
49
50
51
52
53
54
55
56
57
58
    /**
     * @var array Stores all indiviudal stores with the variable raw values
     *
     * $raw['D']['id'] = 0  - Defaultvalues from Tabledefinition
     * ...
     * $raw['S']['r'] = 1234 - record ID from current SIP identifier
     * ...
     * $raw['C']['HTTP_SERVER'] = 'qfq' - Servername
     * $raw['C']['s'] = 'badcaffee1234' - recent SIP
     */
59
    private static $raw = array();
Carsten  Rose's avatar
Carsten Rose committed
60
61

    /**
Carsten  Rose's avatar
Carsten Rose committed
62
     * @var array Default sanitize classes.
Carsten  Rose's avatar
Carsten Rose committed
63
     */
Carsten  Rose's avatar
Carsten Rose committed
64
    private static $sanitizeClass = array();
Carsten  Rose's avatar
Carsten Rose committed
65
66

    /**
Carsten  Rose's avatar
Carsten Rose committed
67
68
     * $sanitizeClass['S'] = false
     * $sanitizeClass['C'] = true
Carsten  Rose's avatar
Carsten Rose committed
69
70
     * ...
     *
Carsten  Rose's avatar
Carsten Rose committed
71
     * @var array each entry with true/false - depending if store needs to be sanitized.
Carsten  Rose's avatar
Carsten Rose committed
72
     */
Carsten  Rose's avatar
Carsten Rose committed
73
    private static $sanitizeStore = array();
74

Carsten  Rose's avatar
Carsten Rose committed
75
    private static $phpUnit = false;
76

77

78
    /**
79
     * @param string $bodytext
80
     * @param string $fileConfigPhp
Carsten  Rose's avatar
Carsten Rose committed
81
     *
Marc Egger's avatar
Marc Egger committed
82
83
84
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
85
     */
86
    private function __construct($bodytext = '', $fileConfigPhp = '') {
87

88
//        self::$session = Session::getInstance(self::$phpUnit);
89

90
        // This check is critical for some unwanted exception recursion during startup.
Carsten  Rose's avatar
Carsten Rose committed
91
        if (!function_exists('normalizer_normalize')) {
Marc Egger's avatar
Marc Egger committed
92
            throw new \CodeException("Function normalizer_normalize() not found - Please install 'php-intl'", ERROR_MISSING_INTL);
93
94
        }

Carsten  Rose's avatar
Carsten Rose committed
95
96
97
98
99
100
101
102
        self::$sanitizeClass = [
//            TYPO3_DEBUG_LOAD => SANITIZE_ALLOW_DIGIT,
//            TYPO3_DEBUG_SAVE => SANITIZE_ALLOW_DIGIT,
//            TYPO3_FORM => SANITIZE_ALLOW_ALNUMX,
//            TYPO3_FE_USER => SANITIZE_ALLOW_ALNUMX,
//            TYPO3_FE_USER_UID => SANITIZE_ALLOW_DIGIT,
//            TYPO3_FE_USER_GROUP => SANITIZE_ALLOW_ALNUMX,

Carsten  Rose's avatar
Carsten Rose committed
103
104
105
106
            CLIENT_SIP => SANITIZE_ALLOW_ALNUMX,
            CLIENT_TYPO3VARS => SANITIZE_ALLOW_ALNUMX,
            CLIENT_RECORD_ID => SANITIZE_ALLOW_DIGIT,
            CLIENT_KEY_SEM_ID => SANITIZE_ALLOW_DIGIT,
Carsten  Rose's avatar
Carsten Rose committed
107
            CLIENT_KEY_SEM_ID_USER => SANITIZE_ALLOW_DIGIT,
Carsten  Rose's avatar
Carsten Rose committed
108
109
110
111
            CLIENT_PAGE_ID => SANITIZE_ALLOW_DIGIT,
            CLIENT_PAGE_TYPE => SANITIZE_ALLOW_DIGIT,
            CLIENT_PAGE_LANGUAGE => SANITIZE_ALLOW_DIGIT,
            CLIENT_FORM => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
112
113

            // Part of $_SERVER. Missing vars must be requested individual with the needed sanitize class.
Carsten  Rose's avatar
Carsten Rose committed
114
115
116
            CLIENT_SCRIPT_URL => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SCRIPT_URI => SANITIZE_ALLOW_ALNUMX,
            CLIENT_HTTP_HOST => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
117
            CLIENT_HTTP_USER_AGENT => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
118
            CLIENT_SERVER_NAME => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
119
            CLIENT_SERVER_ADDRESS => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
120
            CLIENT_SERVER_PORT => SANITIZE_ALLOW_DIGIT,
Carsten  Rose's avatar
Carsten Rose committed
121
122
            CLIENT_REMOTE_ADDRESS => SANITIZE_ALLOW_ALNUMX,
            CLIENT_REQUEST_SCHEME => SANITIZE_ALLOW_ALNUMX,
123
            CLIENT_REQUEST_METHOD => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
124
            CLIENT_SCRIPT_FILENAME => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
125
126
127
128
            CLIENT_QUERY_STRING => SANITIZE_ALLOW_ALL,
            CLIENT_REQUEST_URI => SANITIZE_ALLOW_ALL,
            CLIENT_SCRIPT_NAME => SANITIZE_ALLOW_ALNUMX,
            CLIENT_PHP_SELF => SANITIZE_ALLOW_ALNUMX,
129
//            CLIENT_UPLOAD_FILENAME => SANITIZE_ALLOW_ALLBUT,
Carsten  Rose's avatar
Carsten Rose committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147

//            SYSTEM_DBUSER => SANITIZE_ALLOW_ALNUMX,
//            SYSTEM_DBSERVER => SANITIZE_ALLOW_ALNUMX,
//            SYSTEM_DBPW => SANITIZE_ALLOW_ALL,
//            SYSTEM_DB => SANITIZE_ALLOW_ALNUMX,
//            SYSTEM_TESTDB => SANITIZE_ALLOW_ALNUMX,
//            SYSTEM_SESSIONNAME => SANITIZE_ALLOW_ALNUMX,
//            SYSTEM_DBH => SANITIZE_ALLOW_ALL,

//            SYSTEM_SQL_RAW => SANITIZE_ALLOW_ALL,
//            SYSTEM_SQL_FINAL => SANITIZE_ALLOW_ALL,
//            SYSTEM_SQL_COUNT => SANITIZE_ALLOW_DIGIT,
//            SYSTEM_SQL_PARAM_ARRAY => SANITIZE_ALLOW_ALL,

//            SIP_SIP => SANITIZE_ALLOW_ALNUMX,
//            SIP_RECORD_ID => SANITIZE_ALLOW_DIGIT,
//            SIP_FORM => SANITIZE_ALLOW_ALNUMX,
//            SIP_URLPARAM => SANITIZE_ALLOW_ALL
148

149
150
        ];

Carsten  Rose's avatar
Carsten Rose committed
151
        self::$sanitizeStore = [
Carsten  Rose's avatar
Carsten Rose committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
            STORE_FORM => true,
            STORE_SIP => false,
            STORE_RECORD => false,
            STORE_BEFORE => false,
            STORE_PARENT_RECORD => false,
            STORE_TABLE_DEFAULT => false,
            STORE_TABLE_COLUMN_TYPES => false,
            STORE_CLIENT => true,
            STORE_TYPO3 => false,
            STORE_VAR => false,
            STORE_ZERO => false,
            STORE_EMPTY => false,
            STORE_SYSTEM => false,
            STORE_EXTRA => false,
166
            STORE_USER => false,
Carsten  Rose's avatar
Carsten Rose committed
167
            STORE_LDAP => false,
Carsten  Rose's avatar
Carsten Rose committed
168
            STORE_ADDITIONAL_FORM_ELEMENTS => false,
169
170
        ];

171
        self::fillStoreTypo3($bodytext);  // should be filled before fillStoreSystem() to offer T3 variables, especially 'feUser'
172
        self::fillStoreClient();  // should be filled before fillStoreSystem() to offer Client variables
173
174
        self::fillStorePhpSession(STORE_EXTRA); // should be filled before fillStoreSystem() to restore variables like SYSTEM_SHOW_DEBUG_INFO
        self::fillStorePhpSession(STORE_USER); // should be filled before fillStoreSystem() to restore variables like SYSTEM_SHOW_DEBUG_INFO
175
        self::fillStoreSystem($fileConfigPhp);
176
        self::fillStoreSip();
177
    }
178

179
    /**
180
     * Returns a pointer to this Class.
Carsten  Rose's avatar
Carsten Rose committed
181
     *
182
183
     * @param string $bodytext
     * @param bool|false $phpUnit
184
     * @param string $qfqConfigPhpUnit
185
186
     *
     * @return null|Store
Marc Egger's avatar
Marc Egger committed
187
188
189
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
190
     */
191
    public static function getInstance($bodytext = '', $phpUnit = false, $qfqConfigPhpUnit = '') {
192

193
194
195
196
197
        if (defined('PHPUNIT_QFQ')) {
            self::$phpUnit = true;
        }

        if (self::$phpUnit) {
198

199
200
201
            // If $qfqConfigPhpUnit is given: clean STORE
//            if (self::$instance !== null && $qfqConfigPhpUnit != '') {
            if ($qfqConfigPhpUnit != '') {
Carsten  Rose's avatar
Carsten Rose committed
202

203
204
                if ($qfqConfigPhpUnit == 'init') {
                    $qfqConfigPhpUnit = '';
Carsten  Rose's avatar
Carsten Rose committed
205
206
207
208
209
210
211
212
                }
                // fake to have a clean environment for the next test.
                self::unsetStore(STORE_TYPO3);
                self::fillStoreTypo3($bodytext);

                self::unsetStore(STORE_CLIENT);
                self::fillStoreClient();
            }
213

214
            // Testing different config files means initialize completely
215
            if ($qfqConfigPhpUnit != '') {
216
217
218
219
220
221
                self::$instance = null;
            }
        }

        // Design Pattern: Singleton
        if (self::$instance === null) {
222
//            self::$phpUnit = $phpUnit;
223

224
            self::$instance = new self($bodytext, $qfqConfigPhpUnit);
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        } else {
            // Class Store seems to be persistent over multiple QFQ instantiation. Set bodytext again, with every new request (if bodytext is given).
            if ($bodytext !== '') {
                self::fillStoreTypo3($bodytext);
                self::unsetStore(STORE_RECORD); // At least in Multi DB Setup: STORE_RECORD of former  tt-content QFQ Records interfere with loading a form.
            }
        }

        // Disable TYPO3_DEBUG_SHOW_BODY_TEXT=1 if SYSTEM_SHOW_DEBUG_INFO!='yes'
        if (self::getVar(TYPO3_DEBUG_SHOW_BODY_TEXT, STORE_TYPO3) === '1' &&
            !Support::findInSet(SYSTEM_SHOW_DEBUG_INFO_YES, self::getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM))
        ) {
            self::setVar(TYPO3_DEBUG_SHOW_BODY_TEXT, '0', STORE_TYPO3);
        }

        return self::$instance;
241
242
243
    }

    /**
244
     * QFQ might be called via Typo3 (index.php) or directly via AJAX (directory: api). The
Carsten  Rose's avatar
Carsten Rose committed
245
     *
246
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
247
     *
248
249
     * @return array
     */
Carsten  Rose's avatar
Carsten Rose committed
250
    private static function doSystemPath(array $config) {
251

252
        // SYSTEM_PATH_EXT: compute only if not already defined.
253
        if (!isset($config[SYSTEM_EXT_PATH]) || $config[SYSTEM_EXT_PATH] === '' || $config[SYSTEM_EXT_PATH][0] !== '/') {
254
255
            $relExtDir = '/typo3conf/ext/' . EXT_KEY;

256
257
258
            if (defined('PHPUNIT_QFQ')) {
                $cwd = getcwd();
                $pos = strpos($cwd, '/typo3conf/');
259

260
261
                // this means phpUnit.
                $config[SYSTEM_SITE_PATH] = substr($cwd, 0, $pos);
262
                $config[SYSTEM_EXT_PATH] = $config[SYSTEM_SITE_PATH] . $relExtDir;
263
264
265

            } else {
                // If we are called through AJAX API (e.g. api/save.php), there is no TYPO3 environment.
Carsten  Rose's avatar
Carsten Rose committed
266
                $pos = strpos($_SERVER['SCRIPT_FILENAME'] ?? '', $relExtDir);
267
268
                if ($pos === false && isset($GLOBALS['TYPO3_LOADED_EXT'][EXT_KEY]['ext_localconf.php'])) {

269
                    // Typo3 extension: probably index.php
270
                    $config[SYSTEM_EXT_PATH] = dirname($GLOBALS['TYPO3_LOADED_EXT'][EXT_KEY]['ext_localconf.php']);
Carsten  Rose's avatar
Carsten Rose committed
271
                    $config[SYSTEM_SITE_PATH] = dirname($_SERVER['SCRIPT_FILENAME'] ?? '');
272
                } else {
273
                    // API
Carsten  Rose's avatar
Carsten Rose committed
274
275
                    $config[SYSTEM_EXT_PATH] = substr($_SERVER['SCRIPT_FILENAME'] ?? '', 0, $pos + strlen($relExtDir));
                    $config[SYSTEM_SITE_PATH] = substr($_SERVER['SCRIPT_FILENAME'] ?? '', 0, $pos);
276
277
278
                }
            }
        }
279

280
281
        Logger::setSystemSitePath($config[SYSTEM_SITE_PATH]);

282
283
284
285
286
287
288
        return $config;
    }

    /**
     * Depending on some configuration value, update corresponding values.
     *
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
289
     *
290
291
292
     * @return array
     */
    private static function adjustConfig(array $config) {
293
294

        $config[SYSTEM_SHOW_DEBUG_INFO] = self::adjustConfigShowDebugInfo($config[SYSTEM_SHOW_DEBUG_INFO], self::beUserLoggdIn());
295

Marc Egger's avatar
Marc Egger committed
296
        $config[SYSTEM_SEND_E_MAIL] = $config[SYSTEM_EXT_PATH] . '/Classes/External/sendEmail';
297

298
        // Make path absolute
299
        foreach ([SYSTEM_MAIL_LOG, SYSTEM_QFQ_LOG, SYSTEM_SQL_LOG] as $key) {
300
            if (!empty($config[$key]) && $config[$key][0] != '/') {
301
                $config[$key] = HelperFile::joinPathFilename($config[SYSTEM_SITE_PATH], $config[$key]);
302
303
304
            }
        }

305
306
307
308
309
310
311
312
        // In case the database credentials are given in the old style: copy them to the new style
        if (!isset($config[SYSTEM_DB_1_USER]) && isset($config[SYSTEM_DB_USER])) {
            $config[SYSTEM_DB_1_USER] = $config[SYSTEM_DB_USER];
            $config[SYSTEM_DB_1_SERVER] = $config[SYSTEM_DB_SERVER];
            $config[SYSTEM_DB_1_PASSWORD] = $config[SYSTEM_DB_PASSWORD];
            $config[SYSTEM_DB_1_NAME] = $config[SYSTEM_DB_NAME];
        }

313
314
315
316
        if ($config[SYSTEM_THROW_GENERAL_ERROR] == 'auto') {
            $config[SYSTEM_THROW_GENERAL_ERROR] = $config[SYSTEM_FLAG_PRODUCTION] == 'yes' ? 'no' : 'yes';
        }

317
        return $config;
318
319
    }

320
    /**
321
     * @param string $value
Carsten  Rose's avatar
Carsten Rose committed
322
     *
323
     * @param $flag
324
     * @return string
325
     */
326
    private static function adjustConfigShowDebugInfo($value, $flag) {
327

328
        // Check if SHOW_DEBUG_INFO contains 'auto'. Replace with appropriate.
329
330
        if (Support::findInSet(SYSTEM_SHOW_DEBUG_INFO_AUTO, $value) && $flag) {
            $value = str_replace(SYSTEM_SHOW_DEBUG_INFO_AUTO, SYSTEM_SHOW_DEBUG_INFO_YES, $value);
331
332
        }

333
334
335
336
337
338
339
340
341
342
343
        return $value;
    }

    /**
     * Check if there is a Typo3 beUser is logged in. This is only possible if QFQ is called via T3, not via API
     *
     * @return bool  true: current Browser session is a logged in BE User.
     */
    private static function beUserLoggdIn() {

        return (!empty($GLOBALS["TSFE"]->beUserLogin) && $GLOBALS["TSFE"]->beUserLogin === true);
344
345
    }

346
347
348
349
    /**
     * Iterate over all Parameter which have to exist in the config. Throw an array if any is missing.
     *
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
350
     *
Marc Egger's avatar
Marc Egger committed
351
     * @throws \UserFormException
352
353
     */
    private static function checkMandatoryParameter(array $config) {
354

355
        // Check mandatory config vars.
356
        $names = array_merge([SYSTEM_SQL_LOG, SYSTEM_SQL_LOG_MODE],
357
358
359
            self::dbCredentialName($config[SYSTEM_DB_INDEX_DATA]),
            self::dbCredentialName($config[SYSTEM_DB_INDEX_QFQ]));

360
361
        foreach ($names as $name) {
            if (!isset($config[$name])) {
Marc Egger's avatar
Marc Egger committed
362
                throw new \UserFormException ("Missing configuration in `" . CONFIG_QFQ_PHP . "`: $name", ERROR_MISSING_CONFIG_INI_VALUE);
363
364
365
366
            }
        }
    }

367
    /**
368
369
     * @param $index
     * @return array
370
371
372
373
374
375
376
377
378
379
380
     */
    private static function dbCredentialName($index) {
        $names = array();
        $names[] = 'DB_' . $index . '_USER';
        $names[] = 'DB_' . $index . '_SERVER';
        $names[] = 'DB_' . $index . '_PASSWORD';
        $names[] = 'DB_' . $index . '_NAME';

        return $names;
    }

381
    /**
Carsten  Rose's avatar
Carsten Rose committed
382
383
     * Set or overwrite a complete store.
     *
Carsten  Rose's avatar
Carsten Rose committed
384
     * @param array $dataArray
Carsten  Rose's avatar
Carsten Rose committed
385
     * @param string $store
386
     * @param bool|false $flagOverwrite
Carsten  Rose's avatar
Carsten Rose committed
387
     *
Marc Egger's avatar
Marc Egger committed
388
389
     * @throws \UserFormException
     * @throws \CodeException
390
     */
391
    public static function setStore(array $dataArray, $store, $flagOverwrite = false) {
392

393
        // Check valid store name
394
        if (!isset(self::$sanitizeStore)) {
Marc Egger's avatar
Marc Egger committed
395
            throw new \UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);
396
        }
Carsten  Rose's avatar
Carsten Rose committed
397

398
        if ($store === STORE_ZERO || $store === STORE_EMPTY) {
Marc Egger's avatar
Marc Egger committed
399
            throw new \CodeException("setVarArray() for STORE_ZERO/STORE_EMPTY is impossible - there are no values.", ERROR_SET_STORE_ZERO);
400
        }
401

Carsten  Rose's avatar
Carsten Rose committed
402
        if (!$flagOverwrite && isset(self::$raw[$store]) && count(self::$raw[$store]) > 0) {
Marc Egger's avatar
Marc Egger committed
403
            throw new \CodeException("Raw values already been copied to store '$store'. Do this only one time.", ERROR_STORE_VALUE_ALREADY_CODPIED);
404
        }
405

406
407
408
409
        if ($store === STORE_EXTRA || $store === STORE_USER) {
            Session::set($store, $dataArray);
        }

410
411
        self::$raw[$store] = $dataArray;
    }
412

413
414
415
416
417
    /**
     * Deletes a store assigning a new empty array to it.
     *
     * @param $store
     *
Marc Egger's avatar
Marc Egger committed
418
419
     * @throws \UserFormException
     * @throws \CodeException
420
421
422
423
424
425
426
427
428
     */
    public static function unsetStore($store) {

        self::setStore(array(), $store, true);
    }

    /**
     * Returns a complete $store.
     *
429
     * @param string $store STORE_SYSTEM, ...
430
431
     *
     * @return array
Marc Egger's avatar
Marc Egger committed
432
433
     * @throws \UserFormException
     * @throws \CodeException
434
435
436
437
     */
    public static function getStore($store) {
        $vars = array();

438
        // Check valid store name
439
        if (!isset(self::$sanitizeStore[$store])) {
Marc Egger's avatar
Marc Egger committed
440
            throw new \UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);
441
442
        }

443
        if ($store === STORE_ZERO || $store === STORE_EMPTY) {
Marc Egger's avatar
Marc Egger committed
444
            throw new \CodeException("getStore() for $store is impossible - there are no values saved.", ERROR_GET_INVALID_STORE);
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        }

        if (isset(self::$raw[$store])) {
            $vars = self::$raw[$store];
            if ($store == STORE_SIP) {
                $vars = self::checkDecodeBase64Arr($vars);
            }
        }

        return $vars;
    }


    /**
     * Fill the system store by reading config.qfq.ini. Also setup config defaults.
     *
461
     * @param string $fileConfigPhp
Marc Egger's avatar
Marc Egger committed
462
463
464
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
465
     */
466
    private static function fillStoreSystem($fileConfigPhp = '') {
467

468
        $config = Config::readConfig($fileConfigPhp);
469
470
471

        $config = self::doSystemPath($config);
        $config = self::adjustConfig($config);
472
        $config = self::setAutoConfigValue($config);
473
474
475
476
477
478

        self::checkMandatoryParameter($config);

        self::setStore($config, STORE_SYSTEM, true);
    }

479
480
481
482
483
484
485
486
    /**
     * Set automatic filled values
     *
     * @param array $config
     * @return array
     */
    public static function setAutoConfigValue(array $config) {

487
488
        $config[SYSTEM_DB_NAME_DATA] = $config['DB_' . $config[SYSTEM_DB_INDEX_DATA] . '_NAME'] ?? '';
        $config[SYSTEM_DB_NAME_QFQ] = $config['DB_' . $config[SYSTEM_DB_INDEX_QFQ] . '_NAME'] ?? '';
489
490
491
492

        return $config;
    }

493
    /**
494
     * Copy the BodyText as well as some T3 specific vars to STORE_TYPO3.
Carsten  Rose's avatar
Carsten Rose committed
495
496
     * Attention: if called through API, there is no T3 environment. The only values which are available are fe_user
     * and fe_user_uid.
497
     *
498
     * @param $bodytext
Carsten  Rose's avatar
Carsten Rose committed
499
     *
Marc Egger's avatar
Marc Egger committed
500
501
     * @throws \CodeException
     * @throws \UserFormException
502
     */
503
    private static function fillStoreTypo3($bodytext) {
504

505
        // form=, showDebugBodyText=, 10.20..
506
        $arr = KeyValueStringParser::parse($bodytext, "=", "\n");
507

508
        if (isset($GLOBALS["TSFE"])) {
509
            $arr = array_merge($arr, T3Info::getVars());
510
        } else {
511

512
            // No T3 environment (called by API): restore from SESSION
513
            foreach ([SESSION_FE_USER, SESSION_FE_USER_UID, SESSION_FE_USER_GROUP, SESSION_BE_USER] as $key) {
514
515
516
                if (isset($_SESSION[SESSION_NAME][$key])) {
                    $arr[$key] = $_SESSION[SESSION_NAME][$key];
                }
517
518
            }
        }
519

520
        self::setStore($arr, STORE_TYPO3, true);
521
    }
522

523
    /**
Carsten  Rose's avatar
Carsten Rose committed
524
525
     * Fills the STORE_CLIENT
     *
Marc Egger's avatar
Marc Egger committed
526
527
     * @throws \CodeException
     * @throws \UserFormException
528
     */
529
    private static function fillStoreClient() {
530

Carsten  Rose's avatar
Carsten Rose committed
531
        $arr = Client::getParam();
532

533
        self::setStore($arr, STORE_CLIENT, true);
534

535
    }
536

Carsten  Rose's avatar
Carsten Rose committed
537
    /**
Carsten  Rose's avatar
Carsten Rose committed
538
539
     * Fills the STORE_SIP. Reads therefore specified SIP, decode the values and stores them in STORE_SIP.
     *
540
     * @param bool|string $s
Marc Egger's avatar
Marc Egger committed
541
542
543
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Carsten Rose committed
544
     */
545
    public static function fillStoreSip($s = false) {
Carsten  Rose's avatar
Carsten Rose committed
546

547
548
549
550
551
552
553
        if (self::$sip === null) {
            self::$sip = new Sip(self::$phpUnit);
        }

        if ($s === false) {
            $s = self::getVar(CLIENT_SIP, STORE_CLIENT);
        }
554

555
556
557
        if ($s !== false) {
            // if session is given, copy values to store
            $param = self::$sip->getVarsFromSip($s);
558
559
            $param[SIP_SIP] = $s;
            $param[SIP_URLPARAM] = self::$sip->getQueryStringFromSip($s);
560

561
//            self::setVarArray(KeyValueStringParser::parse($param, "=", "&"), STORE_SIP);
562
            self::setStore($param, STORE_SIP, true);
563
564
565
        }
    }

566
567
568
569
    /**
     * Fills the STORE_EXTRA.
     *
     * @param string $storeName STORE_EXTRA, STORE_USER
Marc Egger's avatar
Marc Egger committed
570
571
     * @throws \CodeException
     * @throws \UserFormException
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
     */
    private static function fillStorePhpSession($storeName) {

        $value = Session::get($storeName);

        if (!isset($_SESSION[SESSION_NAME][$storeName]) || $_SESSION[SESSION_NAME][$storeName] === null) {
            $value = false;
        }

        if ($value === false) {
            self::setStore(array(), $storeName, true);
        } else {
            self::setStore($_SESSION[SESSION_NAME][$storeName], $storeName, true);
        }
    }

    /**
     * Fills STORE_TABLE_DEFAULT and STORE_TABLE_COLUMN_TYPES
     *
     * @param array $tableDefinition
     *
Marc Egger's avatar
Marc Egger committed
593
594
     * @throws \CodeException
     * @throws \UserFormException
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
     */
    public static function fillStoreTableDefaultColumnType(array $tableDefinition) {

        self::setStore(array_column($tableDefinition, 'Default', 'Field'), STORE_TABLE_DEFAULT, true);
        self::setStore(array_column($tableDefinition, 'Type', 'Field'), STORE_TABLE_COLUMN_TYPES, true);
    }


    /**
     * Set's a single $key/$value pair $store.
     *
     * @param string $key
     * @param string|array $value
     * @param string $storeName
     * @param bool|true $overWrite
     *
Marc Egger's avatar
Marc Egger committed
611
612
     * @throws \UserFormException
     * @throws \CodeException
613
614
     */
    public static function setVar($key, $value, $storeName, $overWrite = true) {
615
        // Check valid Store name
616
        if (!isset(self::$sanitizeStore)) {
Marc Egger's avatar
Marc Egger committed
617
            throw new \UserFormException("Unknown Store: $storeName", ERROR_UNNOWN_STORE);
618
619
620
        }

        if ($storeName === STORE_ZERO) {
Marc Egger's avatar
Marc Egger committed
621
            throw new \CodeException("setVar() for STORE_ZERO is impossible - there are no values.", ERROR_SET_STORE_ZERO);
622
623
624
625
        }

        // Complain if already set and different.
        if ($overWrite === false && isset(self::$raw[$storeName][$key]) && self::$raw[$storeName][$key] != $value) {
Marc Egger's avatar
Marc Egger committed
626
            throw new \UserFormException("Value of '$key' already set in store '$storeName'.", ERROR_STORE_KEY_EXIST);
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
        }

        self::$raw[$storeName][$key] = $value;

        // The STORE_EXTRA / STORE_USER saves arrays and is persistent
        if ($storeName === STORE_EXTRA || $storeName === STORE_USER) {

            $data = Session::get($storeName);

            if ($data === false) {
                $data = array();
            }

            // Switch FeUser: log this to qfq.log
            if ($storeName === STORE_USER && $key == TYPO3_FE_USER) {
                $qfqLog = self::getVar(SYSTEM_QFQ_LOG, STORE_SYSTEM);
                $feUserOld = isset($data[$key]) ? $data[$key] : self::getVar($key, STORE_TYPO3 . STORE_EMPTY);
                Logger::logMessage(date('Y.m.d H:i:s ') . ": Switch feUser '$feUserOld' to '$value'", $qfqLog);
            }

            $data[$key] = $value;
            Session::set($storeName, $data);
        }
    }

652
653
654
655
656
657
    /**
     * Unset a variable in store.
     *
     * @param $key
     * @param $store
     */
658
    public static function unsetVar($key, $store) {
659

660
        if (isset(self::$raw[$store][$key])) {
661
662
663
664
            unset(self::$raw[$store][$key]);
        }
    }

665
    /**
666
     * Cycles through all stores in $useStore.
667
     * First match will return the found value.
668
     * During cycling: fill cache with requested value and sanitize raw value.
669
     *
670
     * @param string $key
671
     * @param string $useStores f.e.: 'FSRVD'
Carsten  Rose's avatar
Carsten Rose committed
672
     * @param string $sanitizeClass
Carsten  Rose's avatar
Carsten Rose committed
673
674
675
     * @param string $foundInStore Returns the name of the store where $key has been found. If $key is not found,
     *                             return ''.
     *
676
     * @param string $typeMessageViolate
677
     * @return string|array a) if found: value, b) false. STORE_EXTRA returns an array for the given key.
Marc Egger's avatar
Marc Egger committed
678
679
     * @throws \CodeException
     * @throws \UserFormException    SANITIZE_TYPE_MESSAGE_VIOLATE_ZERO | SANITIZE_TYPE_MESSAGE_VIOLATE_EMPTY | SANITIZE_TYPE_MESSAGE_VIOLATE_CLASS
680
681
     * @throws \UserReportException
     * @throws \DbException
682
     */
683
    public static function getVar($key, $useStores = STORE_USE_DEFAULT, $sanitizeClass = '', &$foundInStore = '',
684
                                  $typeMessageViolate = SANITIZE_TYPE_MESSAGE_VIOLATE_CLASS, $default = '') {
685

686
        // no store specified?
687
        if ($useStores === "" || $useStores === null) {
688
            $useStores = STORE_USE_DEFAULT;
689
690
        }

691
        // no sanitizeClass specified: take predefined (if exist) or default.
692
        if ($sanitizeClass === '' || $sanitizeClass === null) {
Carsten  Rose's avatar
Carsten Rose committed
693
            $sanitizeClass = isset(self::$sanitizeClass[$key]) ? self::$sanitizeClass[$key] : SANITIZE_DEFAULT;
694
695
        }

Carsten  Rose's avatar
Carsten Rose committed
696
697
        $len = strlen(SIP_PREFIX_BASE64);

698
        while ($useStores !== false && $useStores !== '') {
699
            $store = $useStores[0]; // current store
700
701
702
703
704
705

            $finalKey = $key;
            if ($store == STORE_LDAP) {
                $finalKey = strtolower($key); // in STORE_LDAP all keys are lowercase
            }

Carsten  Rose's avatar
Carsten Rose committed
706
            $foundInStore = $store;
707
708
            $useStores = substr($useStores, 1); // shift left remaining stores

709
            if (!isset(self::$raw[$store][$finalKey])) {
710
711
712
                switch ($store) {
                    case STORE_ZERO:
                        return 0;
713
714
                    case STORE_EMPTY:
                        return '';
715
                    case STORE_VAR:
716
                        if ($finalKey === VAR_RANDOM) {
717
                            return Support::randomAlphaNum(RANDOM_LENGTH);
718
719
                        } elseif ($finalKey === VAR_RANDOM_UNIQ) {
                            return StoreVar::randomUniq($default);
720
721
722
723
724
725
726
                        } else {
                            continue 2;  // no value provided, continue with while loop
                        }
                        break;
                    default:
                        continue 2; // no value provided, continue with while loop
                        break;
Carsten  Rose's avatar
Carsten Rose committed
727
                }
728
729
            }

730
            $rawVal = isset(self::$raw[$store][$finalKey]) ? self::$raw[$store][$finalKey] : null;
Carsten  Rose's avatar
Carsten Rose committed
731
            if (self::$sanitizeStore[$store] && $sanitizeClass != '') {
732
                if ($sanitizeClass == SANITIZE_ALLOW_PATTERN) {
733
                    // We do not have any pattern at this point. For those who be affected, they already checked earlier. So set 'no check'
734
735
                    $sanitizeClass = SANITIZE_ALLOW_ALL;
                }
Carsten  Rose's avatar
Carsten Rose committed
736

737
                return Sanitize::sanitize($rawVal, $sanitizeClass, '', '', SANITIZE_EMPTY_STRING, '', $typeMessageViolate);
738
            } else {
Carsten  Rose's avatar
Carsten Rose committed
739
740
741
                if ($store == STORE_SIP && (substr($key, 0, $len) == SIP_PREFIX_BASE64)) {
                    $rawVal = base64_decode($rawVal);
                }
Carsten  Rose's avatar
Carsten Rose committed
742

743
                return $rawVal;
744
            }
745
        }
Carsten  Rose's avatar
Carsten Rose committed
746
        $foundInStore = '';
Carsten  Rose's avatar
Carsten Rose committed
747

748
        return false;
749
    }
750

751
    /**
Carsten  Rose's avatar
Carsten Rose committed
752
753
     * Create a SIP after a form load. This is necessary on forms without a sip and on forms with r=0 (new record).
     *
754
     * @param $formName
Carsten  Rose's avatar
Carsten Rose committed
755
     *
Marc Egger's avatar
Marc Egger committed
756
757
     * @throws \CodeException
     * @throws \UserFormException
758
     */
759
    public static function createSipAfterFormLoad($formName) {
760

761
        $recordId = self::getVar(CLIENT_RECORD_ID, STORE_TYPO3 . STORE_CLIENT);
762
763
764
765
        if ($recordId === false) {
            $recordId = 0;
        }

766
767
768
769
770
771
        // If there are existing SIP param, keep them by copying to the new SIP Param Array
        $tmpParam = self::getNonSystemSipParam();

        $tmpParam[SIP_RECORD_ID] = $recordId;
        $tmpParam[SIP_FORM] = $formName;

Carsten  Rose's avatar
#2067    
Carsten Rose committed
772
773
774
775
        if ($recordId == 0) {
            // SIPs for 'new records' needs to be uniq per TAB! Therefore add a uniq parameter
            $tmpParam[SIP_MAKE_URLPARAM_UNIQ] = uniqid();
        }
776
777

        // Construct fake urlparam
778
        $tmpUrlparam = OnArray::toString($tmpParam);
779
780

        // Create a fake SIP which has never been passed by URL - further processing might expect this to exist.
781
        $sip = self::getSipInstance()->queryStringToSip($tmpUrlparam, RETURN_SIP);
782
        self::setVar(CLIENT_SIP, $sip, STORE_CLIENT);
783
784
785

        // Store in SIP Store (cause it's empty until now).
        $tmpParam[SIP_SIP] = $sip;
786
        self::setStore($tmpParam, STORE_SIP, true);
787

788
789
790
    }

    /**
791
     * Return an array with non system SIP parameter. Take the whole STORE_SIP and search for non system parameter.
792
     *
793
     * @return array
Marc Egger's avatar
Marc Egger committed
794
795
     * @throws \UserFormException
     * @throws \CodeException
796
     */
797
    public static function getNonSystemSipParam() {
798
799
800
801
802
        $tmpParam = array();

        $sipArray = self::getStore(STORE_SIP);

        foreach ($sipArray as $key => $value) {
803

804
805
806
            if ($key[0] === '_') {
                continue;
            }
807

808
809
810
811
812
            switch ($key) {
                case SIP_SIP:
                case SIP_RECORD_ID:
                case SIP_FORM;
                case SIP_URLPARAM:
813
                    continue 2;
Carsten  Rose's avatar
Carsten Rose committed
814
                    break;
815
816
                default:
                    $tmpParam[$key] = $value;
Carsten  Rose's avatar
Carsten Rose committed
817
                    break;
818
819
820
821
            }
        }

        return $tmpParam;
822
    }
823

Carsten  Rose's avatar
Carsten Rose committed
824
825
826
827
828
    /**
     * Iterate over an array and look for keynames starting with SIP_PREFIX_BASE64.
     * Found elements will be base64_decode().
     *
     * @param array $vars
Carsten  Rose's avatar
Carsten Rose committed
829
     *
Carsten  Rose's avatar
Carsten Rose committed
830
831
832
833
834
835
836
837
838
839
840
     * @return array - incl. decoded base64 vars.
     */
    private static function checkDecodeBase64Arr(array $vars) {

        $len = strlen(SIP_PREFIX_BASE64);

        foreach ($vars as $key => $value) {
            if (substr($key, 0, $len) == SIP_PREFIX_BASE64) {
                $vars[$key] = base64_decode($value);
            }
        }
Carsten  Rose's avatar
Carsten Rose committed
841

Carsten  Rose's avatar
Carsten Rose committed
842
        return $vars;
843
844
    }

845
846
847
848
849
850
851
852
853
854
    /**
     * Returns a pointer to this class.
     *
     * @return null|Sip
     */
    public static function getSipInstance() {
        return self::$sip;
    }

    /**
855
856
857
858
     * Saves a subset of STORE_TYPO3 vars as a SIP. The SIP will be transmitted as hidden form element.
     *
     * More docs: CODING.md > 'Faking the STORE_TYPO3 for API calls'
     *
Marc Egger's avatar
Marc Egger committed
859
860
     * @throws \CodeException
     * @throws \UserFormException
861
862
863
864
865
     */
    public static function copyT3VarsToSip() {

        $tempArray = self::getStore(STORE_TYPO3);

866
        foreach ([TYPO3_FE_USER, TYPO3_FE_USER_UID, TYPO3_FE_USER_GROUP, TYPO3_TT_CONTENT_UID, TYPO3_PAGE_ID, TYPO3_PAGE_ALIAS, TYPO3_PAGE_TYPE, TYPO3_PAGE_LANGUAGE, TYPO3_BE_USER_LOGGED_IN] as $key) {
867
868
869
870
871
872
873
874
875
876
877
878
879
880
            if (isset($tempArray[$key])) {
                $t3varsArray[$key] = $tempArray[$key];
            }
        }

        $t3varsArray[TYPO3_BE_USER_LOGGED_IN] = (isset($GLOBALS["TSFE"]->beUserLogin) && $GLOBALS["TSFE"]->beUserLogin === true) ? 'yes' : 'no';

        $t3varsString = KeyValueStringParser::unparse($t3varsArray, '=', '&');
        $t3sip = self::$sip->queryStringToSip($t3varsString, RETURN_SIP);

        return $t3sip;
    }

    /**
881
882
883
     * Get stored STORE_TYPO3 vars from SIP and restore the store.
     *
     * More docs: CODING.md > 'Faking the STORE_TYPO3 for API calls'
884
885
     *
     * @param string $sipTypo3Vars
Marc Egger's avatar
Marc Egger committed
886
887
888
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
889
     */
Carsten  Rose's avatar
Carsten Rose committed
890
    public static function fillTypo3StoreFromSip($sipTypo3Vars) {
891
892
893
894
895
896
897
898
899
900
        $t3vars = self::getStore(STORE_TYPO3);

        // Do nothing if STORE_TYPO3 is already filled
        if (isset($t3vars[TYPO3_TT_CONTENT_UID]) && $t3vars[TYPO3_TT_CONTENT_UID] != '0') {
            return;
        }

        $typo3VarsArray = self::$sip->getVarsFromSip($sipTypo3Vars);

        self::setStore($typo3VarsArray, STORE_TYPO3, true);
Carsten  Rose's avatar
Carsten Rose committed
901

902
        $value = self::getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM);
903
904
        $flag = isset($typo3VarsArray[TYPO3_BE_USER_LOGGED_IN]) && ($typo3VarsArray[TYPO3_BE_USER_LOGGED_IN] == 'yes');
        $value = self::adjustConfigShowDebugInfo($value, $flag);
905
        self::setVar(SYSTEM_SHOW_DEBUG_INFO, $value, STORE_SYSTEM);
906
    }
907

908
909
910
    /**
     * Load $recordId from $tableName using $db and saves it in $store.
     *
911
912
913
914
     * @param string $tableName
     * @param int $recordId
     * @param Database $db
     * @param string $primaryKey
915
     * @param string $store
Marc Egger's avatar
Marc Egger committed
916
917
918
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
919
     */
920
    public static function fillStoreWithRecord($tableName, $recordId, Database $db,
921
                                               $primaryKey = F_PRIMARY_KEY_DEFAULT, $store = STORE_RECORD) {
922
923
        if ($recordId !== false && $recordId > 0 &&
            is_string($tableName) && $tableName !== '') {
924
925
926
            if (!$primaryKey) {
                $primaryKey = F_PRIMARY_KEY_DEFAULT;
            }
927

928
            $record = $db->sql("SELECT * FROM `$tableName` WHERE `$primaryKey` = ?", ROW_EXPECT_1, [$recordId]);
929
930
931
932
            self::setStore($record, $store, true);
        }
    }

933
    /**
934
     * Read SYSTEM_FILL_STORE_SYSTEM_BY_SQL_1|2|3 from SYSTEM_STORE and if set:
935
     * a) fire the SQL
936
     * b) merge all columns to STORE_SYSTEM
937
     *
Marc Egger's avatar
Marc Egger committed
938
939
940
941
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
942
     */
943
    public static function FillStoreSystemBySql() {
944

945
        $db = null;
946
        $flagDirty = false;
947
948
        $storeSystem = self::getStore(STORE_SYSTEM);

949
        for ($ii = 1; $ii <= 3; $ii++) {
950
            if (empty($storeSystem[SYSTEM_FILL_STORE_SYSTEM_BY_SQL . "$ii"])) {
951
952
953
954
                continue;
            }

            if ($db == null) {
Marc Egger's avatar
Marc Egger committed
955
                $db = new Database();