Config.php 17 KB
Newer Older
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 3/6/17
 * Time: 8:47 PM
 */

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

Marc Egger's avatar
Marc Egger committed
11
12
13
14
use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Helper\OnString;
 
15
16
17
18
/**
 * Class Config
 * @package qfq
 */
19
20
class Config {

21
    /**
22
     * Migrate config.qfq.ini to config.qfq.php
23
     *
24
25
26
     * @param $configIni
     * @param $configPhp
     */
27
    private static function migrateConfigIniToPhp($configIni, $configPhp) {
28
29
30
31
32
33

        $config = parse_ini_file($configIni, false);

        $pre = isset($config[SYSTEM_DB_NAME]) ? 'DB' : 'DB_1';

        $content = '<?php' . PHP_EOL . 'return [' . PHP_EOL;
34

35
        foreach ([$pre . '_NAME', $pre . '_PASSWORD', $pre . '_SERVER', $pre . '_USER', SYSTEM_LDAP_1_RDN, SYSTEM_LDAP_1_PASSWORD] as $key) {
Carsten  Rose's avatar
Carsten Rose committed
36
            $content .= "  '$key' => '" . ($config[$key] ?? "") . "'," . PHP_EOL;
37
38
        }

39
40
41
42
43
44
45
46
47
        $content .= "];" . PHP_EOL;

        // Write new config file
        file_put_contents($configPhp, $content);

        // Make old file unreadable
        chmod($configIni, 000);
    }

48
49
50
51
52
    /**
     * Iterates over all 30 custom vars, explode them to split between key and value, append to $config.
     *
     * @param array $config
     * @return array
Marc Egger's avatar
Marc Egger committed
53
     * @throws \UserReportException
54
     */
55
    private static function getCustomVariable(array $config) {
56
57
58
59
60
61

        for ($i = 1; $i <= 30; $i++) {
            if (isset($config['custom' . $i])) {
                $arr = explode('=', $config['custom' . $i], 2);
                if (!empty($arr[0]) && !empty($arr[1])) {

62
                    $arr[0] = trim($arr[0]);
63
                    $arr[1] = OnString::trimQuote(trim($arr[1]));
64
65

                    if (isset($config[$arr[0]])) {
Marc Egger's avatar
Marc Egger committed
66
                        throw new \UserReportException("Variable '$arr[0]' already defined", ERROR_INVALID_OR_MISSING_PARAMETER);
67
68
69
70
71
72
73
74
75
76
                    }

                    $config[$arr[0]] = $arr[1];
                }
            }
        }

        return $config;
    }

77
    /**
Carsten  Rose's avatar
Carsten Rose committed
78
     * Read config.qfq.ini. In case
79
     *
80
     * @param string $fileConfigPhp
81
     * @return array
Marc Egger's avatar
Marc Egger committed
82
83
84
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
85
     */
86
    public static function readConfig($fileConfigPhp = '') {
Carsten  Rose's avatar
Carsten Rose committed
87

88
        $configT3qfq = array();
89
        $configIni = ''; // outdated config file format
90
91
92
93
94
95
96
97

        // Production Path to CONFIG_INI
        $pathTypo3Conf = __DIR__ . '/../../../../..';
        if (!file_exists($pathTypo3Conf . '/' . CONFIG_T3)) {
            // PHPUnit Path to CONFIG_INI
            $pathTypo3Conf = __DIR__ . '/../../..';
        }

98
        // In case of missing $configPhp
99
        if (empty($fileConfigPhp)) {
100

101
102
103
            # Read 'LocalConfiguration.php'
            if (isset($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][EXT_KEY])) {
                $configT3qfq = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][EXT_KEY]);
104
                $configT3qfq[SYSTEM_DB_NAME_T3] = self::getDbName($GLOBALS['TYPO3_CONF_VARS']['DB']);
105

106
            } else {
107
                $all = include($pathTypo3Conf . '/' . CONFIG_T3);
108
                if (empty($all) || $all === true) {
Marc Egger's avatar
Marc Egger committed
109
                    throw new \UserFormException ("Error read file: " . $pathTypo3Conf . '/' . CONFIG_T3, ERROR_IO_READ_FILE);
110
111
                }

112
                $configT3qfq = unserialize($all['EXT']['extConf'][EXT_KEY]);
113
                if (!is_array($configT3qfq)) {
Marc Egger's avatar
Marc Egger committed
114
                    throw new \UserFormException ("Error read file: " . $pathTypo3Conf . '/' . CONFIG_T3, ERROR_IO_READ_FILE);
115
                }
116

117
                $configT3qfq[SYSTEM_DB_NAME_T3] = self::getDbName($all['DB']);
118
                unset($all);
119
            }
120

121
            $configIni = $pathTypo3Conf . '/' . CONFIG_QFQ_INI;
122
            $fileConfigPhp = $pathTypo3Conf . '/' . CONFIG_QFQ_PHP;
123

124
125
126
        }

        // Migrate legacy config file.
127
128
        if (is_readable($configIni) && !is_readable($fileConfigPhp)) {
            self::migrateConfigIniToPhp($configIni, $fileConfigPhp);
129
130
        }

131
        $config = include($fileConfigPhp);
132

133
        if ($config === false) {
Marc Egger's avatar
Marc Egger committed
134
            throw new \UserFormException ("Error read file: " . $fileConfigPhp, ERROR_IO_READ_FILE);
135
        }
136

137
138
139
        // in case $configIni doesn't exist: just skip
        if (!is_array($config)) {
            $config = array();
140
        }
141

142
        $configT3qfq = self::getCustomVariable($configT3qfq);
143

144
        // Settings in  config.qfq.php overwrite T3 settings
145
        $config = array_merge($configT3qfq, $config);
146
147

        $config = self::renameConfigElements($config);
148
        $config = self::setDefaults($config);
149
        self::checkDeprecated($config);
150

151
152
        self::checkForAttack($config);

153
        // Copy values to detect custom settings later
154
        $config[F_FE_DATA_PATTERN_ERROR_SYSTEM] = $config[F_FE_DATA_PATTERN_ERROR];
155

156
157
158
        return $config;
    }

159
160
161
162
163
164
    /**
     * Returns T3 DB-Name, depending on T3 version
     *
     * @param array $db
     * @return mixed
     */
Carsten  Rose's avatar
Carsten Rose committed
165
    private static function getDbName(array $db) {
166
167
168
169
170

        // T3 7.x: $GLOBALS['TYPO3_CONF_VARS']['DB']['database'],  T3 8.x: $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['dbname']
        return isset($db['database']) ? $db['database'] : $db['Connections']['Default']['dbname'];
    }

171
172
    /**
     * Checks for deprecated options.
173
     *
174
     * @param array $config
Marc Egger's avatar
Marc Egger committed
175
     * @throws \UserFormException
176
177
178
179
180
181
182
183
184
     */
    private static function checkDeprecated(array $config) {

        foreach ([SYSTEM_VAR_ADD_BY_SQL] as $key) {

            if (isset($config[$key])) {
                $msg = '';
                switch ($key) {
                    case SYSTEM_VAR_ADD_BY_SQL:
185
                        $msg = 'Replaced by: ' . SYSTEM_FILL_STORE_SYSTEM_BY_SQL . '1|2|3';
186
                }
Marc Egger's avatar
Marc Egger committed
187
                throw new \UserFormException ("Deprecated option in " . CONFIG_QFQ_PHP . ": " . SYSTEM_VAR_ADD_BY_SQL . " - " . $msg);
188
189
190
191
            }
        }
    }

192
    /**
193
194
     * Check for attack
     *
195
     * @param array $config
Marc Egger's avatar
Marc Egger committed
196
197
198
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
199
     */
200
    public static function checkForAttack(array $config) {
201
        $attack = false;
202
        $key = '';
203
        $reason = 'Problem: ';
204
205
206
207

        // Iterate over all fake vars
        $arr = explode(',', $config[SYSTEM_SECURITY_VARS_HONEYPOT]);
        foreach ($arr as $key) {
208

209
210
211
212
            $key = trim($key);
            if ($key === '') {
                continue;
            }
213
214

            if (!empty($_POST[$key])) {
215
                $attack = true;
216
                $reason .= "Post/Get Honeypot variable '$key' detected: " . htmlentities($_POST[$key]) . PHP_EOL;
217
218
219
220
221
            }
        }

        // Limit length of all get vars: protect against SQL injection based on long ...%34%34%24%34...
        $maxLength = $config[SYSTEM_SECURITY_GET_MAX_LENGTH];
222
        if ($maxLength > 0 && $attack === false) {
223
            foreach ($_GET as $key => $value) {
Carsten  Rose's avatar
Carsten Rose committed
224
225
226
227
228

                if (!is_string($value)) {
                    continue;
                }

229
230
                // Check if the variable is something like 'my_name_100' - if the part after the last '_' is numerical, this means a valid, non standard length.
                $arr = explode(GET_EXTRA_LENGTH_TOKEN, $key);
231

232
233
                $cnt = count($arr);
                if ($cnt > 1 && is_numeric($arr[$cnt - 1])) {
234
235
236
237
238
                    $maxLength = $arr[$cnt - 1];
                } else {
                    $maxLength = $config[SYSTEM_SECURITY_GET_MAX_LENGTH]; // might change again.
                }

239
240
                $len = strlen($value);
                if ($len > $maxLength) {
241
                    $attack = true;
242
                    $reason .= "Value of GET variable '$key' too long. Allowed: $maxLength, Length: $len. Value: '" . htmlentities($_GET[$key]) . "'" . PHP_EOL;
243
                }
244
245
246
247
            }
        }

        // Nothing found?
248
        if ($attack === false) {
249
250
251
            return;
        }

252
        self::attackDetectedExitNow($config, $reason);
253
254
255
    }

    /**
256
     * @param array $config
257
     * @param string $reason
Marc Egger's avatar
Marc Egger committed
258
259
260
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
261
     */
262
    public static function attackDetectedExitNow(array $config = array(), $reason = '') {
263
264
265

        if (count($config) == 0) {
            $config = self::readConfig();
266
267
        }

268
        Logger::logMessage(Logger::linePre() . 'Security: attack detected' . PHP_EOL . $reason,
269
            $config[SYSTEM_QFQ_LOG] ?? SYSTEM_QFQ_LOG_FILE);
270

271
272
273
        // In case of an attack: log out the current user.
        Session::destroy();

274
275
276
277
        // Sleep
        $penalty = (empty($config[SYSTEM_SECURITY_ATTACK_DELAY]) || !is_numeric($config[SYSTEM_SECURITY_ATTACK_DELAY])) ?
            SYSTEM_SECURITY_ATTACK_DELAY_DEFAULT : $config[SYSTEM_SECURITY_ATTACK_DELAY];

Carsten  Rose's avatar
Carsten Rose committed
278
279
280
        if (!defined('PHPUNIT_QFQ')) {
            sleep($penalty);
        }
281

282
        if ($config[SYSTEM_SECURITY_SHOW_MESSAGE] == 'true' || $config[SYSTEM_SECURITY_SHOW_MESSAGE] == 1) {
283

284
            echo "Attack detected - stop process <p>" . $reason . '</p>';
285
286
287
288
289
290
291
//            $answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
//            $answer[API_MESSAGE] = 'Attack detected - stop process.';
//            if($getParamName!='') {
//                $answer[API_MESSAGE] .= " Attack parameter: $getParamName";
//            }
//            header("Content-Type: application/json");
//            echo json_encode($answer);
292
293
        }

294
        if (defined('PHPUNIT_QFQ')) {
Marc Egger's avatar
Marc Egger committed
295
            throw new \UserFormException('Attack detected', 1);
296
297
        }

298
299
300
301
302
        exit;
    }

    /**
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
303
     *
304
305
     * @return array
     */
306
    public static function setDefaults(array $config) {
307
308
309

        $default = [

310
            SYSTEM_DB_INIT => 'set names utf8',
311
312
            SYSTEM_DB_INDEX_DATA => DB_INDEX_DEFAULT,
            SYSTEM_DB_INDEX_QFQ => DB_INDEX_DEFAULT,
313

314
            SYSTEM_RENDER => SYSTEM_RENDER_SINGLE,
315
316
            SYSTEM_DATE_FORMAT => 'yyyy-mm-dd',
            SYSTEM_SHOW_DEBUG_INFO => SYSTEM_SHOW_DEBUG_INFO_AUTO,
317
            SYSTEM_MAIL_LOG => SYSTEM_MAIL_LOG_FILE,
318
            SYSTEM_QFQ_LOG => SYSTEM_QFQ_LOG_FILE,
319
320
            SYSTEM_SQL_LOG => SYSTEM_SQL_LOG_FILE,
            SYSTEM_SQL_LOG_MODE => 'modify',
321
            SYSTEM_SQL_LOG_MODE_AUTOCRON => 'error',
322
323
324
325
            F_BS_COLUMNS => 'col-md-12 col-lg-10',
            F_BS_LABEL_COLUMNS => 'col-md-3 col-lg-3',
            F_BS_INPUT_COLUMNS => 'col-md-6 col-lg-6',
            F_BS_NOTE_COLUMNS => 'col-md-3 col-lg-3',
326

327
328
            F_CLASS => 'qfq-notify',

329
330
331
332
            F_CLASS_PILL => 'qfq-color-grey-1',
            F_CLASS_BODY => 'qfq-color-grey-2',

            F_SAVE_BUTTON_TEXT => '',
333
            F_SAVE_BUTTON_TOOLTIP => '',
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
            F_SAVE_BUTTON_CLASS => 'btn btn-default navbar-btn',
            F_SAVE_BUTTON_GLYPH_ICON => GLYPH_ICON_CHECK,

            F_CLOSE_BUTTON_TEXT => '',
            F_CLOSE_BUTTON_TOOLTIP => 'Close',
            F_CLOSE_BUTTON_CLASS => 'btn btn-default navbar-btn',
            F_CLOSE_BUTTON_GLYPH_ICON => GLYPH_ICON_CLOSE,

            F_DELETE_BUTTON_TEXT => '',
            F_DELETE_BUTTON_TOOLTIP => 'Delete',
            F_DELETE_BUTTON_CLASS => 'btn btn-default navbar-btn',
            F_DELETE_BUTTON_GLYPH_ICON => GLYPH_ICON_DELETE,

            F_NEW_BUTTON_TEXT => '',
            F_NEW_BUTTON_TOOLTIP => 'New',
            F_NEW_BUTTON_CLASS => 'btn btn-default navbar-btn',
            F_NEW_BUTTON_GLYPH_ICON => GLYPH_ICON_NEW,

            F_BUTTON_ON_CHANGE_CLASS => 'btn-info alert-info',
            SYSTEM_EDIT_FORM_PAGE => 'form',
354
            SYSTEM_SECURITY_VARS_HONEYPOT => SYSTEM_SECURITY_VARS_HONEYPOT_NAMES,
355
356
357
            SYSTEM_SECURITY_ATTACK_DELAY => SYSTEM_SECURITY_ATTACK_DELAY_DEFAULT,
            SYSTEM_SECURITY_SHOW_MESSAGE => '0',
            SYSTEM_SECURITY_GET_MAX_LENGTH => SYSTEM_SECURITY_GET_MAX_LENGTH_DEFAULT,
358
359
360

            SYSTEM_LABEL_ALIGN => SYSTEM_LABEL_ALIGN_LEFT,

361
            SYSTEM_ESCAPE_TYPE_DEFAULT => TOKEN_ESCAPE_MYSQL,
362
363
            SYSTEM_EXTRA_BUTTON_INFO_INLINE => '<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>',
            SYSTEM_EXTRA_BUTTON_INFO_BELOW => '<span class="glyphicon glyphicon-info-sign text-info" aria-hidden="true"></span>',
364
365
366
367
368
            SYSTEM_EXTRA_BUTTON_INFO_CLASS => '',

            SYSTEM_DB_UPDATE => SYSTEM_DB_UPDATE_AUTO,
            SYSTEM_RECORD_LOCK_TIMEOUT_SECONDS => SYSTEM_RECORD_LOCK_TIMEOUT_SECONDS_DEFAULT,

369
            SYSTEM_SESSION_TIMEOUT_SECONDS => self::getPhpSessionTimeout(),
370

371
            SYSTEM_DOCUMENTATION_QFQ => SYSTEM_DOCUMENTATION_QFQ_URL,
372
373
            SYSTEM_ENTER_AS_SUBMIT => 1,

374
            SYSTEM_CMD_WKHTMLTOPDF => '/opt/wkhtmltox/bin/wkhtmltopdf',
375
376
            SYSTEM_CMD_INKSCAPE => 'inkscape',
            SYSTEM_CMD_CONVERT => 'convert',
377
378
            SYSTEM_CMD_PDF2SVG => 'pdf2svg',
            SYSTEM_CMD_PDFTOCAIRO => 'pdftocairo',
379
380
381
            SYSTEM_CMD_QPDF => 'qpdf',
            SYSTEM_CMD_GS => 'gs',
            SYSTEM_CMD_PDFUNITE => 'pdfunite',
382
            SYSTEM_CMD_IMG2PDF => 'img2pdf',
383

384
385
386
            SYSTEM_THUMBNAIL_DIR_SECURE => SYSTEM_THUMBNAIL_DIR_SECURE_DEFAULT,
            SYSTEM_THUMBNAIL_DIR_PUBLIC => SYSTEM_THUMBNAIL_DIR_PUBLIC_DEFAULT,

387
            F_FE_DATA_REQUIRED_ERROR => F_FE_DATA_REQUIRED_ERROR_DEFAULT,
388
            F_FE_DATA_MATCH_ERROR => F_FE_DATA_MATCH_ERROR_DEFAULT,
389
            F_FE_DATA_ERROR => F_FE_DATA_ERROR_DEFAULT,
390
            F_FE_DATA_PATTERN_ERROR => F_FE_DATA_PATTERN_ERROR_DEFAULT,
391
392
393

            SYSTEM_FLAG_PRODUCTION => 'yes',
            SYSTEM_THROW_GENERAL_ERROR => 'auto',
Carsten  Rose's avatar
Carsten Rose committed
394
395

            SYSTEM_SECURITY_FAILED_AUTH_DELAY => '3',
396
397
398

            SYSTEM_FILE_MAX_FILE_SIZE => min(Support::returnBytes(ini_get('post_max_size')), Support::returnBytes(ini_get('upload_max_filesize'))),

399
400
        ];

401
402
403
404
405
406
        foreach ($default as $key => $value) {
            if (!isset($config[$key]) || $config[$key] == '') {
                $config[$key] = $value;
            }
        }

Marc Egger's avatar
Newdoc    
Marc Egger committed
407
408
409
410
411
        // don't accept deprecated documentation url
        if ($config[SYSTEM_DOCUMENTATION_QFQ] === 'https://docs.typo3.org/typo3cms/drafts/github/T3DocumentationStarter/Public-Info-053/Manual.html') {
            $config[SYSTEM_DOCUMENTATION_QFQ] = SYSTEM_DOCUMENTATION_QFQ_URL;
        }

412
        return $config;
413
414
    }

415

416
417
    /**
     * Rename Elements defined in config.qfq.ini to more appropriate in user interaction.
Carsten  Rose's avatar
Carsten Rose committed
418
419
     * E.g.: in config.qfq.ini everything is in upper case and word space is '_'. In Form.parameter it's lowercase and
     * camel hook.
420
421
     *
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
422
     *
423
424
425
426
427
428
     * @return array
     */
    private static function renameConfigElements(array $config) {

        // oldname > newname
        $setting = [
429
            [SYSTEM_FORM_BS_COLUMNS, F_BS_COLUMNS],
430
431
432
            [SYSTEM_FORM_BS_LABEL_COLUMNS, F_BS_LABEL_COLUMNS],
            [SYSTEM_FORM_BS_INPUT_COLUMNS, F_BS_INPUT_COLUMNS],
            [SYSTEM_FORM_BS_NOTE_COLUMNS, F_BS_NOTE_COLUMNS],
433

434
435
436
437
            [SYSTEM_FORM_DATA_PATTERN_ERROR, F_FE_DATA_PATTERN_ERROR],
            [SYSTEM_FORM_DATA_REQUIRED_ERROR, F_FE_DATA_REQUIRED_ERROR],
            [SYSTEM_FORM_DATA_MATCH_ERROR, F_FE_DATA_MATCH_ERROR],
            [SYSTEM_FORM_DATA_ERROR, F_FE_DATA_ERROR],
438

439
440
441
            [SYSTEM_CSS_CLASS_QFQ_FORM, F_CLASS],
            [SYSTEM_CSS_CLASS_QFQ_FORM_PILL, F_CLASS_PILL],
            [SYSTEM_CSS_CLASS_QFQ_FORM_BODY, F_CLASS_BODY],
442
            [SYSTEM_SAVE_BUTTON_CLASS_ON_CHANGE, F_BUTTON_ON_CHANGE_CLASS],
443

444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
        ];

        foreach ($setting as $row) {
            $oldName = $row[0];
            $newName = $row[1];

            if (isset($config[$oldName])) {
                $config[$newName] = $config[$oldName];
                if ($oldName != $newName) {
                    unset($config[$oldName]);
                }
            }
        }

        return $config;
    }
460
461

    /**
462
463
     * Check Session Timeout
     *
464
     * @param $timeout
Marc Egger's avatar
Marc Egger committed
465
     * @throws \UserFormException
466
467
468
     */
    public static function checkSessionTimeout($timeout) {

469
        if (self::getPhpSessionTimeout() < $timeout) {
Marc Egger's avatar
Marc Egger committed
470
            throw new \UserFormException ("The specified timeout of $timeout seconds is higher than the PHP config 'session.gc_maxlifetime' ("
471
472
                . ini_get('session.gc_maxlifetime') . ") and/or 'session.cookie_lifetime' ("
                . ini_get('session.cookie_lifetime') . ")");
473
474
475
        }

        if ($timeout > SYSTEM_COOKIE_LIFETIME) {
Marc Egger's avatar
Marc Egger committed
476
            throw new \UserFormException ("The specified timeout of $timeout seconds is higher than the hardcoded cookie lifetime (" . SYSTEM_COOKIE_LIFETIME . ")");
477
478
        }
    }
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

    /**
     * Get the minimum of 'session.cookie_lifetime' and 'session.gc_maxlifetime'
     * A zero means unlimited and will be limited to one day.
     *
     * @return int|string
     */
    private static function getPhpSessionTimeout() {
        $timeout = ini_get('session.cookie_lifetime');
        $gc_maxlifetime = ini_get('session.gc_maxlifetime');

        if ($timeout == 0) {
            $timeout = 86400;
        }

        if ($gc_maxlifetime == 0) {
            // Just to set a limit
            $timeout = 86400;
        }

        return $timeout > $gc_maxlifetime ? $gc_maxlifetime : $timeout;
    }
501
}