Store.php 26.4 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
 */

9
namespace qfq;
10

11
use qfq\CodeException;
12
13
use qfq\keyValueStringParser;
use qfq\OnArray;
14
use qfq;
15

16
require_once(__DIR__ . '/../../qfq/helper/KeyValueStringParser.php');
Carsten  Rose's avatar
Carsten Rose committed
17
require_once(__DIR__ . '/../../qfq/helper/Sanitize.php');
18
require_once(__DIR__ . '/../../qfq/Constants.php');
19
require_once(__DIR__ . '/../../qfq/store/Sip.php');
20
//require_once(__DIR__ . '/../../qfq/store/Session.php');
21
require_once(__DIR__ . '/../../qfq/Database.php');
22
require_once(__DIR__ . '/../../qfq/store/Config.php');
23
24
25
26
27
28
29
30
31
32

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

Carsten  Rose's avatar
Carsten Rose committed
33
34
/**
 * Class Store
35
 * @package qfq
Carsten  Rose's avatar
Carsten Rose committed
36
 */
37
38
class Store {

Carsten  Rose's avatar
Carsten Rose committed
39
40
41
    /**
     * @var Store Instance of class Store. There should only be one class 'Store' at a time.
     */
42
43
    private static $instance = null;

Carsten  Rose's avatar
Carsten Rose committed
44
45
46
    /**
     * @var Sip Instance of class SIP
     */
47
48
    private static $sip = null;

49
50
51
    /**
     * @var Session Instance of class Session
     */
52
//    private static $session = null;
53

Carsten  Rose's avatar
Carsten Rose committed
54
55
56
57
58
59
60
61
62
63
    /**
     * @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
     */
64
    private static $raw = array();
Carsten  Rose's avatar
Carsten Rose committed
65
66

    /**
Carsten  Rose's avatar
Carsten Rose committed
67
     * @var array Default sanitize classes.
Carsten  Rose's avatar
Carsten Rose committed
68
     */
Carsten  Rose's avatar
Carsten Rose committed
69
    private static $sanitizeClass = array();
Carsten  Rose's avatar
Carsten Rose committed
70
71

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

Carsten  Rose's avatar
Carsten Rose committed
80
    private static $phpUnit = false;
81

82

83
    /**
84
     * @param string $bodytext
85
86
87
     * @param string $fileConfigIni
     * @throws UserFormException
     * @throws \qfq\CodeException
88
     */
89
    private function __construct($bodytext = '', $fileConfigIni = '') {
90

91
//        self::$session = Session::getInstance(self::$phpUnit);
92

93
94
95
96
97
        // This check is critical for some unwanted exception recursion during startup.
        if(!function_exists('normalizer_normalize')) {
            throw new CodeException("Function normalizer_normalize() not found - Please install 'php5-intl' / 'php7.0-intl'", ERROR_MISSING_INTL );
        }

Carsten  Rose's avatar
Carsten Rose committed
98
99
100
101
102
103
104
105
106
        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,

            CLIENT_SIP => SANITIZE_ALLOW_ALNUMX,
107
            CLIENT_TYPO3VARS => SANITIZE_ALLOW_ALNUMX,
Carsten  Rose's avatar
Carsten Rose committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
            CLIENT_RECORD_ID => SANITIZE_ALLOW_DIGIT,
            CLIENT_KEY_SEM_ID => SANITIZE_ALLOW_DIGIT,
            CLIENT_KEY_SEM_ID_USER => SANITIZE_ALLOW_DIGIT,
            CLIENT_PAGE_ID => SANITIZE_ALLOW_DIGIT,
            CLIENT_PAGE_TYPE => SANITIZE_ALLOW_DIGIT,
            CLIENT_PAGE_LANGUAGE => SANITIZE_ALLOW_DIGIT,
            CLIENT_FORM => SANITIZE_ALLOW_ALNUMX,

            // Part of $_SERVER. Missing vars must be requested individual with the needed sanitize class.
            CLIENT_SCRIPT_URL => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SCRIPT_URI => SANITIZE_ALLOW_ALNUMX,
            CLIENT_HTTP_HOST => SANITIZE_ALLOW_ALNUMX,
            CLIENT_HTTP_USER_AGENT => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SERVER_NAME => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SERVER_ADDRESS => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SERVER_PORT => SANITIZE_ALLOW_DIGIT,
            CLIENT_REMOTE_ADDRESS => SANITIZE_ALLOW_ALNUMX,
            CLIENT_REQUEST_SCHEME => SANITIZE_ALLOW_ALNUMX,
            CLIENT_SCRIPT_FILENAME => SANITIZE_ALLOW_ALNUMX,
            CLIENT_QUERY_STRING => SANITIZE_ALLOW_ALL,
            CLIENT_REQUEST_URI => SANITIZE_ALLOW_ALL,
            CLIENT_SCRIPT_NAME => SANITIZE_ALLOW_ALNUMX,
            CLIENT_PHP_SELF => SANITIZE_ALLOW_ALNUMX,
131
//            CLIENT_UPLOAD_FILENAME => SANITIZE_ALLOW_ALLBUT,
Carsten  Rose's avatar
Carsten Rose committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

//            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
150

151
152
        ];

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

172
        self::fillSystemStore($fileConfigIni);
173
        self::fillStoreTypo3($bodytext);
174
        self::fillStoreClient();
175
        self::fillStoreSip();
Carsten  Rose's avatar
Carsten Rose committed
176
        self::fillStoreExtra();
177
    }
178

179
    /**
180
     * Fill the system store by reading config.qfq.ini. Also setup config defaults.
Carsten  Rose's avatar
Carsten Rose committed
181
     *
182
     * @throws CodeException
183
     * @throws qfq\UserFormException
184
     */
185
    private static function fillSystemStore($fileConfigIni = '') {
186

187
188
        $cfg = new Config();
        $config = $cfg->readConfig($fileConfigIni);
189
190
191
192
193
194
195

        // Defaults
        Support::setIfNotSet($config, SYSTEM_DATE_FORMAT, 'yyyy-mm-dd');
        Support::setIfNotSet($config, SYSTEM_SHOW_DEBUG_INFO, 'auto');
        Support::setIfNotSet($config, F_BS_LABEL_COLUMNS, '3');
        Support::setIfNotSet($config, F_BS_INPUT_COLUMNS, '6');
        Support::setIfNotSet($config, F_BS_NOTE_COLUMNS, '3');
196
197
        Support::setIfNotSet($config, F_CLASS_PILL, 'qfq-color-grey-1');
        Support::setIfNotSet($config, F_CLASS_BODY, 'qfq-color-grey-2');
198
        Support::setIfNotSet($config, F_BUTTON_ON_CHANGE_CLASS, 'btn-info alert-info');
199
200
201


        $config = self::doSystemPath($config);
202
        $config = self::adjustConfig($config);
203

204
        self::checkMandatoryParameter($config);
205

206
        self::setStore($config, STORE_SYSTEM, true);
207
208
209
    }

    /**
210
     * QFQ might be called via Typo3 (index.php) or directly via AJAX (directory: api). The
211
212
213
214
215
     * @param array $config
     * @return array
     */
    private function doSystemPath(array $config) {

216
217
218
219
220
221
222
        // SYSTEM_PATH_EXT: compute only if not already defined.
        if (!isset($config[SYSTEM_PATH_EXT]) || $config[SYSTEM_PATH_EXT] === '' || $config[SYSTEM_PATH_EXT][0] !== '/') {
            $relExtDir = '/typo3conf/ext/' . EXT_KEY;

            // If we are called through AJAX API (e.g. api/save.php), there is no TYPO3 environment.
            if (isset($_SERVER['SCRIPT_FILENAME'])) {
                $pos = strpos($_SERVER['SCRIPT_FILENAME'], $relExtDir);
223
224
                if ($pos === false && isset($GLOBALS['TYPO3_LOADED_EXT'][EXT_KEY]['ext_localconf.php'])) {

225
                    // Typo3 extension: probably index.php
226
                    $config[SYSTEM_PATH_EXT] = dirname($GLOBALS['TYPO3_LOADED_EXT'][EXT_KEY]['ext_localconf.php']);
227
                    $config[SYSTEM_SITE_PATH] = dirname($_SERVER['SCRIPT_FILENAME']);
228
                } else {
229
                    // API
230
                    $config[SYSTEM_PATH_EXT] = substr($_SERVER['SCRIPT_FILENAME'], 0, $pos + strlen($relExtDir));
231
                    $config[SYSTEM_SITE_PATH] = substr($_SERVER['SCRIPT_FILENAME'], 0, $pos);
232
                }
233
234
235
236
            } else {
                // No $_SERVER >>this means phpUnit.
                $config[SYSTEM_SITE_PATH] = getcwd();
                $config[SYSTEM_PATH_EXT] = getcwd();
237
238
            }
        }
239
240
241
242
243
244
245
246
247
248
249
250
251

        return $config;
    }

    /**
     * Depending on some configuration value, update corresponding values.
     *
     * @param array $config
     * @return array
     */
    private static function adjustConfig(array $config) {
        // Adjust config
        if ($config[SYSTEM_SHOW_DEBUG_INFO] === 'auto') {
252
253
254
255
            $rc = self::beUserLoggdIn();
            if ($rc !== false) {
                $config[SYSTEM_SHOW_DEBUG_INFO] = $rc;
            }
256
257
258
259
260
261
262
        }

        // make SQL PATH absolute. This is necessary to work in different directories correctly.
        if (isset($config[SYSTEM_SQL_LOG]) && $config[SYSTEM_SQL_LOG][0] !== '/') {
            $config[SYSTEM_SQL_LOG] = $config[SYSTEM_PATH_EXT] . '/' . $config[SYSTEM_SQL_LOG];
        }

263
        return $config;
264
265
    }

266
267
268
269
270
271
272
273
274
275
276
277
278
279
    /**
     * @return bool|string
     */
    private static function beUserLoggdIn() {

        if (isset($GLOBALS["TSFE"])) {
            $rc = (isset($GLOBALS["TSFE"]->beUserLogin) && $GLOBALS["TSFE"]->beUserLogin === true) ? 'yes' : 'no';
        } else {
            $rc = false;
        }

        return $rc;
    }

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    /**
     * Iterate over all Parameter which have to exist in the config. Throw an array if any is missing.
     *
     * @param array $config
     * @throws UserFormException
     */
    private static function checkMandatoryParameter(array $config) {
        // Check mandatory config vars.
        $names = array('DB_USER', 'DB_SERVER', 'DB_PASSWORD', 'DB_NAME', 'SQL_LOG', 'SQL_LOG_MODE');
        foreach ($names as $name) {
            if (!isset($config[$name])) {
                throw new qfq\UserFormException ("Missing configuration in `config.ini`: $name", ERROR_MISSING_CONFIG_INI_VALUE);
            }
        }
    }

296
    /**
Carsten  Rose's avatar
Carsten Rose committed
297
298
     * Set or overwrite a complete store.
     *
299
300
     * @param array $dataArray
     * @param $store
301
     * @param bool|false $flagOverwrite
302
     * @throws UserFormException
303
     * @throws \qfq\CodeException
304
     */
305
    public static function setStore(array $dataArray, $store, $flagOverwrite = false) {
306

Carsten  Rose's avatar
Carsten Rose committed
307
        // Check valid Storename
Carsten  Rose's avatar
Carsten Rose committed
308
        if (!isset(self::$sanitizeStore))
309
            throw new UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);
Carsten  Rose's avatar
Carsten Rose committed
310

311
        if ($store === STORE_ZERO)
Carsten  Rose's avatar
Carsten Rose committed
312
            throw new CodeException("setVarArray() for STORE_ZERO is impossible - there are no values.", ERROR_SET_STORE_ZERO);
313

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

318
319
        self::$raw[$store] = $dataArray;
    }
320

321
    /**
322
323
324
     * Copy the BodyText as well as some T3 specific vars to STORE_TYPO3.
     * Attention: if called through API, there is no T3 environment. The only values which are available are fe_user and fe_user_uid.
     *
325
326
327
     * @param $bodytext
     * @throws CodeException
     */
328
    private static function fillStoreTypo3($bodytext) {
329

330
        // form=, showDebugBodyText=, 10.20..
331
        $arr = KeyValueStringParser::parse($bodytext, "=", "\n");
332

333
        if (isset($GLOBALS["TSFE"])) {
334

335
336
337
            if (isset($GLOBALS["TSFE"]->fe_user->user["username"])) {
                $arr[TYPO3_FE_USER] = $GLOBALS["TSFE"]->fe_user->user["username"];
            }
338

339
340
341
342
            if (isset($GLOBALS["TSFE"]->fe_user->user["uid"])) {
                $feUid = $GLOBALS["TSFE"]->fe_user->user["uid"];
                $arr[TYPO3_FE_USER_UID] = $GLOBALS["TSFE"]->fe_user->user["uid"];
            }
343

344
345
346
            if (isset($GLOBALS["TSFE"]->fe_user->user["usergroup"])) {
                $arr[TYPO3_FE_USER_GROUP] = $GLOBALS["TSFE"]->fe_user->user["usergroup"];
            }
Carsten  Rose's avatar
Carsten Rose committed
347

348
349
350
            if (isset($GLOBALS["TSFE"]->page["uid"])) {
                $arr[TYPO3_TT_CONTENT_UID] = $GLOBALS["TSFE"]->page["uid"];
            }
351

352
353
354
355
356
357
358
            if (isset($GLOBALS["TSFE"]->id)) {
                $arr[TYPO3_PAGE_ID] = $GLOBALS["TSFE"]->id;
            }

            if (isset($GLOBALS["TSFE"]->type)) {
                $arr[TYPO3_PAGE_TYPE] = $GLOBALS["TSFE"]->type;
            }
Carsten  Rose's avatar
Carsten Rose committed
359

360
361
362
            if (isset($GLOBALS["TSFE"]->sys_language_uid)) {
                $arr[TYPO3_PAGE_LANGUAGE] = $GLOBALS["TSFE"]->sys_language_uid;
            }
363

364
        } else {
365

366
367
            // No T3 environment (called by API): restore from SESSION
            foreach ([SESSION_FE_USER, SESSION_FE_USER_UID, SESSION_FE_USER_GROUP] as $key) {
368
369
370
                if (isset($_SESSION[SESSION_NAME][$key])) {
                    $arr[$key] = $_SESSION[SESSION_NAME][$key];
                }
371
372
            }
        }
373

374
        self::setStore($arr, STORE_TYPO3, true);
375
    }
376

377
    /**
Carsten  Rose's avatar
Carsten Rose committed
378
379
     * Fills the STORE_CLIENT
     *
380
381
     * @throws CodeException
     */
382
    private static function fillStoreClient() {
383
        // copy GET and POST and SERVER Parameter. Priority: SERVER, POST, GET
384
385
386
387
388
389
390
        $arr = array();
        if (isset($_GET))
            $arr = array_merge($arr, $_GET);

        if (isset($_POST))
            $arr = array_merge($arr, $_POST);

391
        // It's important to merge the SERVER array last: those entries shall overwrite client values.
392
393
        if (isset($_SERVER))
            $arr = array_merge($arr, $_SERVER);
394

395
        $arr = \qfq\Sanitize::normalize($arr);
396

397
        self::setStore($arr, STORE_CLIENT, true);
398

399
    }
400

Carsten  Rose's avatar
Carsten Rose committed
401
    /**
Carsten  Rose's avatar
Carsten Rose committed
402
403
     * Fills the STORE_SIP. Reads therefore specified SIP, decode the values and stores them in STORE_SIP.
     *
Carsten  Rose's avatar
Carsten Rose committed
404
     * @throws CodeException
405
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
406
     */
407
    private static function fillStoreSip() {
Carsten  Rose's avatar
Carsten Rose committed
408

409
        self::$sip = new Sip(self::$phpUnit);
410

411
412
413
414
        $s = self::getVar(CLIENT_SIP, STORE_CLIENT);
        if ($s !== false) {
            // if session is given, copy values to store
            $param = self::$sip->getVarsFromSip($s);
415
416
            $param[SIP_SIP] = $s;
            $param[SIP_URLPARAM] = self::$sip->getQueryStringFromSip($s);
417

418
//            self::setVarArray(KeyValueStringParser::parse($param, "=", "&"), STORE_SIP);
419
            self::setStore($param, STORE_SIP, true);
420
421
422
        }
    }

423
    /**
424
     * Cycles through all stores in $useStore.
425
     * First match will return the found value.
Carsten  Rose's avatar
Carsten Rose committed
426
     * During cycling: fill cache with requestet value and sanitize raw value.
427
     *
428
     * @param string $key
429
     * @param string $useStores f.e.: 'FSRD'
Carsten  Rose's avatar
Carsten Rose committed
430
     * @param string $sanitizeClass
Carsten  Rose's avatar
Carsten Rose committed
431
     * @param string $foundInStore Returns the name of the store where $key has been found. If $key is not found, return ''.
432
     * @return string a) if found: value, b) false
Carsten  Rose's avatar
Carsten Rose committed
433
     * @throws \qfq\CodeException
434
     */
Carsten  Rose's avatar
Carsten Rose committed
435
    public static function getVar($key, $useStores = STORE_USE_DEFAULT, $sanitizeClass = '', &$foundInStore = '') {
436
437

        // no store specifed?
438
        if ($useStores === "" || $useStores === null) {
439
            $useStores = STORE_USE_DEFAULT;
440
441
        }

442
        // no sanitizeClass specified: take predefined (if exist) or default.
443
        if ($sanitizeClass === '' || $sanitizeClass === null) {
Carsten  Rose's avatar
Carsten Rose committed
444
            $sanitizeClass = isset(self::$sanitizeClass[$key]) ? self::$sanitizeClass[$key] : SANITIZE_DEFAULT;
445
446
        }

447
448
449
        while ($useStores !== false) {

            $store = substr($useStores, 0, 1); // next store
Carsten  Rose's avatar
Carsten Rose committed
450
            $foundInStore = $store;
451
452
            $useStores = substr($useStores, 1); // shift left remaining stores

453
            if (!isset(self::$raw[$store][$key])) {
454
455
456
                switch ($store) {
                    case STORE_ZERO:
                        return 0;
457
458
                    case STORE_EMPTY:
                        return '';
459
460
                    case STORE_VAR:
                        if ($key === VAR_RANDOM) {
461
                            return Support::randomAlphaNum(RANDOM_LENGTH);
462
463
464
465
466
467
468
                        } 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
469
                }
470
471
            }

472
            $rawVal = isset(self::$raw[$store][$key]) ? self::$raw[$store][$key] : null;
Carsten  Rose's avatar
Carsten Rose committed
473
            if (self::$sanitizeStore[$store] && $sanitizeClass != '') {
474
475
476
477
478
                if ($sanitizeClass == SANITIZE_ALLOW_PATTERN || $sanitizeClass == SANITIZE_ALLOW_MIN_MAX || $sanitizeClass == SANITIZE_ALLOW_MIN_MAX_DATE) {
                    // We do not have any pattern or min|max values at this point. For those who be affected, they already checked earlier. So set 'no check'
                    $sanitizeClass = SANITIZE_ALLOW_ALL;
                }
                return \qfq\Sanitize::sanitize($rawVal, $sanitizeClass, '', SANATIZE_EMPTY_STRING);
479
480
            } else {
                return $rawVal;
481
            }
482
        }
Carsten  Rose's avatar
Carsten Rose committed
483
        $foundInStore = '';
484
        return false;
485
    }
486

Carsten  Rose's avatar
Carsten Rose committed
487
    /**
Carsten  Rose's avatar
Carsten Rose committed
488
489
     * Fills the STORE_EXTRA.
     *
Carsten  Rose's avatar
Carsten Rose committed
490
491
492
493
     * @throws UserFormException
     * @throws \qfq\CodeException
     */
    private static function fillStoreExtra() {
494

495
        $value = Session::get(STORE_EXTRA);
496

497
        if (!isset($_SESSION[SESSION_NAME][STORE_EXTRA]) || $_SESSION[SESSION_NAME][STORE_EXTRA] === null) {
498
499
500
501
            $value = false;
        }

        if ($value === false) {
502
            self::setStore(array(), STORE_EXTRA, true);
503
        } else {
504
            self::setStore($_SESSION[SESSION_NAME][STORE_EXTRA], STORE_EXTRA, true);
505
        }
Carsten  Rose's avatar
Carsten Rose committed
506
507
    }

508
    /**
Carsten  Rose's avatar
Carsten Rose committed
509
510
     * Returns a pointer to this Class.
     *
511
     * @param string $bodytext
512
     * @param bool|false $phpUnit
513
514
515
516
     * @param string $fileConfigIni
     * @return null|Store
     * @throws UserFormException
     * @throws \qfq\CodeException
517
     */
518
    public static function getInstance($bodytext = '', $phpUnit = false, $fileConfigIni = '') {
519

520
        if ($phpUnit) {
521

522
            if (self::$instance !== null) {
523
                // fake to have a clean environment for the next test.
524
525
526
527
528
                self::unsetStore(STORE_TYPO3);
                self::fillStoreTypo3($bodytext);

                self::unsetStore(STORE_CLIENT);
                self::fillStoreClient();
529
            }
530
531
532
533
534

            // Testing different config files means initialize completely
            if ($fileConfigIni != '') {
                self::$instance = null;
            }
535
536
537
538
        }

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

541
            self::$instance = new self($bodytext, $fileConfigIni);
Carsten  Rose's avatar
Carsten Rose committed
542
543
544
545
        } else {
            // Class Store seems to be presistent over multiple QFQ instantiation. Set bodytext again, with every new request (if bodytext is given).
            if ($bodytext !== '')
                self::fillStoreTypo3($bodytext);
546
547
        }

548
549
550
551
552
553
554
        // Disable TYPO3_DEBUG_SHOW_BODY_TEXT=1 if SYSTEM_SHOW_DEBUG_INFO!='yes'
        if (self::getVar(TYPO3_DEBUG_SHOW_BODY_TEXT, STORE_TYPO3) === '1' &&
            self::getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM) !== 'yes'
        ) {
            self::setVar(TYPO3_DEBUG_SHOW_BODY_TEXT, '0', STORE_TYPO3);
        }

555
        return self::$instance;
556
    }
557

558
    /**
Carsten  Rose's avatar
Carsten Rose committed
559
560
     * Deletes a store assigning a new empty array to it.
     *
561
     * @param $store
562
563
     * @throws UserFormException
     * @throws \qfq\CodeException
564
565
     */
    public static function unsetStore($store) {
Carsten  Rose's avatar
Carsten Rose committed
566
        // Check valid Storename
Carsten  Rose's avatar
Carsten Rose committed
567
        if (!isset(self::$sanitizeStore))
568
            throw new UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);
Carsten  Rose's avatar
Carsten Rose committed
569

570
        if ($store === STORE_ZERO)
Carsten  Rose's avatar
Carsten Rose committed
571
572
            throw new CodeException("unsetStore() for STORE_ZERO is impossible - there are no values.", ERROR_SET_STORE_ZERO);

573
574
575
        if (isset(self::$raw[$store])) {
            self::$raw[$store] = array();
        }
Carsten  Rose's avatar
Carsten Rose committed
576

577
578
    }

579
    /**
Carsten  Rose's avatar
Carsten Rose committed
580
581
     * Set's a single $key/$value pair $store.
     *
Carsten  Rose's avatar
Carsten Rose committed
582
583
584
     * @param string $key
     * @param string|array $value
     * @param string $store
585
586
587
588
589
590
591
592
593
594
595
596
597
     * @param bool|true $overWrite
     * @throws UserFormException
     * @throws \qfq\CodeException
     */
    public static function setVar($key, $value, $store, $overWrite = true) {
        // Check valid Storename
        if (!isset(self::$sanitizeStore))
            throw new UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);

        if ($store === STORE_ZERO)
            throw new CodeException("setVar() for STORE_ZERO is impossible - there are no values.", ERROR_SET_STORE_ZERO);

        if ($overWrite === false && isset(self::$raw[$store][$key])) {
598
            throw new UserFormException("Value of '$key' already set in store '$store'.", ERROR_STORE_KEY_EXIST);
599
600
601
        }

        self::$raw[$store][$key] = $value;
Carsten  Rose's avatar
Carsten Rose committed
602
603
604

        // The STORE_EXTRA saves arrays and is persistent
        if ($store === STORE_EXTRA) {
605

606
            $store = Session::get(STORE_EXTRA);
607
608

            if ($store === false) {
609
                $store = array();
610
611
            }

612
613
            $store[$key] = $value;
            Session::set(STORE_EXTRA, $store);
614

Carsten  Rose's avatar
Carsten Rose committed
615
        }
616
617
    }

618
    /**
Carsten  Rose's avatar
Carsten Rose committed
619
620
     * Create a SIP after a form load. This is necessary on forms without a sip and on forms with r=0 (new record).
     *
621
622
623
     * @param $formName
     * @throws CodeException
     */
624
    public static function createSipAfterFormLoad($formName) {
625

626
        $recordId = self::getVar(CLIENT_RECORD_ID, STORE_TYPO3 . STORE_CLIENT);
627
628
629
630
        if ($recordId === false) {
            $recordId = 0;
        }

631
632
633
634
635
636
        // 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
637
638
639
640
        if ($recordId == 0) {
            // SIPs for 'new records' needs to be uniq per TAB! Therefore add a uniq parameter
            $tmpParam[SIP_MAKE_URLPARAM_UNIQ] = uniqid();
        }
641
642

        // Construct fake urlparam
643
        $tmpUrlparam = OnArray::toString($tmpParam);
644
645

        // Create a fake SIP which has never been passed by URL - further processing might expect this to exist.
646
        $sip = self::getSipInstance()->queryStringToSip($tmpUrlparam, RETURN_SIP);
647
        self::setVar(CLIENT_SIP, $sip, STORE_CLIENT);
648
649
650

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

653
654
655
    }

    /**
656
     * Return an array with non system SIP parameter. Take the whole STORE_SIP and search for non system parameter.
657
     *
658
659
660
     * @return array
     * @throws UserFormException
     * @throws \qfq\CodeException
661
     */
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    private static function getNonSystemSipParam() {
        $tmpParam = array();

        $sipArray = self::getStore(STORE_SIP);

        foreach ($sipArray as $key => $value) {
            if ($key[0] === '_') {
                continue;
            }
            switch ($key) {
                case SIP_SIP:
                case SIP_RECORD_ID:
                case SIP_FORM;
                case SIP_URLPARAM:
                    continue;
                default:
                    $tmpParam[$key] = $value;
            }
        }

        return $tmpParam;
683
    }
684

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    /**
     * Returns a complete $store.
     *
     * @param $store
     * @return array
     * @throws UserFormException
     * @throws \qfq\CodeException
     */
    public static function getStore($store) {
        // Check valid Storename
        if (!isset(self::$sanitizeStore[$store]))
            throw new UserFormException("Unknown Store: $store", ERROR_UNNOWN_STORE);

        if ($store === STORE_ZERO)
            throw new CodeException("getStore() for STORE_ZERO is impossible - there are no values saved.", ERROR_GET_STORE_ZERO);

        if (isset(self::$raw[$store])) {
            return self::$raw[$store];
        }

        return array();
    }

708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    /**
     * Returns a pointer to this class.
     *
     * @return null|Sip
     */
    public static function getSipInstance() {
        return self::$sip;
    }

    /**
     * Fills STORE_TABLE_DEFAULT and STORE_TABLE_COLUMN_TYPES
     *
     * @param $tableName
     * @throws CodeException
     */
    public static function fillStoreTableDefaultColumnType($tableName) {
        $db = new qfq\Database();

        $tableDefinition = $db->getTableDefinition($tableName);

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

    /**
733
734
735
736
     * 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'
     *
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
     * @throws CodeException
     * @throws UserFormException
     */
    public static function copyT3VarsToSip() {

        $tempArray = self::getStore(STORE_TYPO3);

        foreach ([TYPO3_FE_USER, TYPO3_FE_USER_UID, TYPO3_FE_USER_GROUP, TYPO3_TT_CONTENT_UID, TYPO3_PAGE_ID, TYPO3_PAGE_TYPE, TYPO3_PAGE_LANGUAGE, TYPO3_BE_USER_LOGGED_IN] as $key) {
            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;
    }

    /**
759
760
761
     * Get stored STORE_TYPO3 vars from SIP and restore the store.
     *
     * More docs: CODING.md > 'Faking the STORE_TYPO3 for API calls'
762
763
764
765
766
767
768
769
770
771
772
773
774
775
     *
     * @param string $sipTypo3Vars
     */
    public function fillTypo3StoreFromSip($sipTypo3Vars) {
        $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
776

777
778
779
780
        // If necessary, update SYSTEM_SHOW_DEBUG_INFO
        if (self::getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM) == 'auto') {
            $val = ($typo3VarsArray[TYPO3_BE_USER_LOGGED_IN] == 'yes') ? 'yes' : 'no';
            self::setVar(SYSTEM_SHOW_DEBUG_INFO, $val, STORE_SYSTEM);
781
782
        }
    }
783

784
785
786
787
788
}