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

namespace qfq;

use qfq;

13
14
require_once(__DIR__ . '/../Constants.php');
require_once(__DIR__ . '/../helper/Support.php');
15

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

22
    /**
23
     * Migrate config.qfq.ini to config.qfq.php
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
53
54
    /**
     * Iterates over all 30 custom vars, explode them to split between key and value, append to $config.
     *
     * @param array $config
     * @return array
     * @throws UserReportException
     */
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
66
67
68
69
70
71
72
73
74
75
76

                    if (isset($config[$arr[0]])) {
                        throw new UserReportException("Variable '$arr[0]' already defined", ERROR_INVALID_OR_MISSING_PARAMETER);
                    }

                    $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 $configIni
81
82
     * @return array
     * @throws UserFormException
83
     * @throws UserReportException
84
     */
85
    public static function readConfig($fileConfigPhp = '') {
Carsten  Rose's avatar
Carsten Rose committed
86

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

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

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

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

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

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

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

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

123
124
125
        }

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

130
        $config = include($fileConfigPhp);
131

132
        if ($config === false) {
133
            throw new qfq\UserFormException ("Error read file: " . $fileConfigPhp, ERROR_IO_READ_FILE);
134
        }
135

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

141
        $configT3qfq = self::getCustomVariable($configT3qfq);
142
        // Settings in  config.qfq.php overwrite T3 settings
143
        $config = array_merge($configT3qfq, $config);
144
145

        $config = self::renameConfigElements($config);
146
        $config = self::setDefaults($config);
147
        self::checkDeprecated($config);
148

149
150
151
152
153
        self::checkForAttack($config);

        return $config;
    }

154
155
156
157
158
159
    /**
     * Returns T3 DB-Name, depending on T3 version
     *
     * @param array $db
     * @return mixed
     */
Carsten  Rose's avatar
Carsten Rose committed
160
    private static function getDbName(array $db) {
161
162
163
164
165

        // 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'];
    }

166
167
    /**
     * Checks for deprecated options.
168
169
     * @param array $config
     * @throws UserFormException
170
171
172
173
174
175
176
177
178
     */
    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:
179
                        $msg = 'Replaced by: ' . SYSTEM_FILL_STORE_SYSTEM_BY_SQL . '1|2|3';
180
                }
181
                throw new qfq\UserFormException ("Deprecated option in " . CONFIG_QFQ_PHP . ": " . SYSTEM_VAR_ADD_BY_SQL . " - " . $msg);
182
183
184
185
186
            }
        }
    }


187
188
    /**
     * @param array $config
189
     * @throws UserFormException
190
     * @throws UserReportException
191
192
     */
    private static function checkForAttack(array $config) {
193
        $attack = false;
194
        $key = '';
195
        $reason = 'please help';
196
197
198
199

        // Iterate over all fake vars
        $arr = explode(',', $config[SYSTEM_SECURITY_VARS_HONEYPOT]);
        foreach ($arr as $key) {
200
201
202
203
            $key = trim($key);
            if ($key === '') {
                continue;
            }
204
            if (!empty($_POST[$key]) || !empty($_GET[$key])) {
205
                $attack = true;
206
                $reason .= "Post/Get Honeypot variable '$key' detected: " . htmlentities($_POST[$key] . $_GET[$key]) . PHP_EOL;
207
208
209
210
211
212
            }
        }

        // Limit length of all get vars: protect against SQL injection based on long ...%34%34%24%34...
        $maxLength = $config[SYSTEM_SECURITY_GET_MAX_LENGTH];
        if ($maxLength > 0) {
213
214
215
            foreach ($_GET as $key => $value) {
                // 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);
216

217
218
                $cnt = count($arr);
                if ($cnt > 1 && is_numeric($arr[$cnt - 1])) {
219
220
221
222
223
224
                    $maxLength = $arr[$cnt - 1];
                } else {
                    $maxLength = $config[SYSTEM_SECURITY_GET_MAX_LENGTH]; // might change again.
                }

                if (strlen($value) > $maxLength) {
225
                    $attack = true;
226
                    $reason .= "Get variable '$key' longer than $maxLength: " . htmlentities($_POST[$key]);
227
                    break;
228
                }
229
230
231
232
            }
        }

        // Nothing found?
233
        if ($attack === false) {
234
235
236
            return;
        }

237
        self::attackDetectedExitNow($config, $reason);
238
239
240
    }

    /**
241
     * @param array $config
242
     * @param string $reason
243
     * @throws UserFormException
244
     * @throws UserReportException
245
     */
246
    public static function attackDetectedExitNow(array $config = array(), $reason = '') {
247
248
249

        if (count($config) == 0) {
            $config = self::readConfig();
250
251
        }

252
253
254
        Logger::logMessage(Logger::linePre() . 'Security: attack detected' . PHP_EOL . $reason,
            empty($config[SYSTEM_QFQ_LOG]) ? SYSTEM_QFQ_LOG_FILE : $config[SYSTEM_QFQ_LOG]);

255
256
257
        // In case of an attack: log out the current user.
        Session::destroy();

258
259
260
261
262
263
        // 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];

        sleep($penalty);

264
        if ($config[SYSTEM_SECURITY_SHOW_MESSAGE] == 'true' || $config[SYSTEM_SECURITY_SHOW_MESSAGE] == 1) {
265

266
            echo "Attack detected - stop process <p>" . $reason . '</p>';
267
268
269
270
271
272
273
//            $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);
274
275
276
277
278
279
280
        }

        exit;
    }

    /**
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
281
     *
282
283
284
     * @return array
     */
    private static function setDefaults(array $config) {
285
286
287
288
        // Defaults: do not worry: parse_ini_file() will replace 'none' and 'off' by ''.

        $default = [

289
            SYSTEM_DB_INIT => 'set names utf8',
290
291
            SYSTEM_DB_INDEX_DATA => DB_INDEX_DEFAULT,
            SYSTEM_DB_INDEX_QFQ => DB_INDEX_DEFAULT,
292
293
294

            SYSTEM_DATE_FORMAT => 'yyyy-mm-dd',
            SYSTEM_SHOW_DEBUG_INFO => SYSTEM_SHOW_DEBUG_INFO_AUTO,
295
            SYSTEM_MAIL_LOG => SYSTEM_MAIL_LOG_FILE,
296
            SYSTEM_QFQ_LOG => SYSTEM_QFQ_LOG_FILE,
297
298
            SYSTEM_SQL_LOG => SYSTEM_SQL_LOG_FILE,
            SYSTEM_SQL_LOG_MODE => 'modify',
299
300
301
302
            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',
303

304
            SYSTEM_CMD_WKHTMLTOPDF => '/opt/wkhtmltox/bin/wkhtmltopdf',
305
306
307
308
309

            F_CLASS_PILL => 'qfq-color-grey-1',
            F_CLASS_BODY => 'qfq-color-grey-2',

            F_SAVE_BUTTON_TEXT => '',
310
            F_SAVE_BUTTON_TOOLTIP => '',
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            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',
Carsten  Rose's avatar
Carsten Rose committed
331
            SYSTEM_SECURITY_VARS_HONEYPOT => 'email,username,password',
332
333
334
            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,
335
336
337

            SYSTEM_LABEL_ALIGN => SYSTEM_LABEL_ALIGN_LEFT,

338
            SYSTEM_ESCAPE_TYPE_DEFAULT => TOKEN_ESCAPE_MYSQL,
339
340
            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>',
341
342
343
344
345
            SYSTEM_EXTRA_BUTTON_INFO_CLASS => '',

            SYSTEM_DB_UPDATE => SYSTEM_DB_UPDATE_AUTO,
            SYSTEM_RECORD_LOCK_TIMEOUT_SECONDS => SYSTEM_RECORD_LOCK_TIMEOUT_SECONDS_DEFAULT,

346
347
            SYSTEM_SESSION_TIMEOUT_SECONDS => SYSTEM_SESSION_TIMEOUT_SECONDS_DEFAULT,

348
            SYSTEM_DOCUMENTATION_QFQ => SYSTEM_DOCUMENTATION_QFQ_URL,
349
350
351
352
353
354
355
            SYSTEM_ENTER_AS_SUBMIT => 1,

            SYSTEM_CMD_INKSCAPE => 'inkscape',
            SYSTEM_CMD_CONVERT => 'convert',
            SYSTEM_THUMBNAIL_DIR_SECURE => SYSTEM_THUMBNAIL_DIR_SECURE_DEFAULT,
            SYSTEM_THUMBNAIL_DIR_PUBLIC => SYSTEM_THUMBNAIL_DIR_PUBLIC_DEFAULT,

356
            F_FE_DATA_REQUIRED_ERROR => F_FE_DATA_REQUIRED_ERROR_DEFAULT,
357
358
            F_FE_DATA_MATCH_ERROR => F_FE_DATA_MATCH_ERROR_DEFAULT,
            F_FE_DATA_ERROR => 'error',
359
360
361

            SYSTEM_FLAG_PRODUCTION => 'yes',
            SYSTEM_THROW_GENERAL_ERROR => 'auto',
362
363
        ];

364
        // To let run legacy code
365
366
//        $config[SYSTEM_DB_INDEX_DATA_DEPRECATED] = $config[SYSTEM_DB_INDEX_DATA];
//        $config[SYSTEM_DB_INDEX_QFQ_DEPRECATED] = $config[SYSTEM_DB_INDEX_QFQ];
367

368
369
370
371
372
373
374
375
        foreach ($default as $key => $value) {
            if (!isset($config[$key]) || $config[$key] == '') {
                $config[$key] = $value;
            }
        }

//        return array_merge($default, $config);
        return $config;
376
377
    }

378

379
380
    /**
     * Rename Elements defined in config.qfq.ini to more appropriate in user interaction.
Carsten  Rose's avatar
Carsten Rose committed
381
382
     * E.g.: in config.qfq.ini everything is in upper case and word space is '_'. In Form.parameter it's lowercase and
     * camel hook.
383
384
     *
     * @param array $config
Carsten  Rose's avatar
Carsten Rose committed
385
     *
386
387
388
389
390
391
     * @return array
     */
    private static function renameConfigElements(array $config) {

        // oldname > newname
        $setting = [
392
            [SYSTEM_FORM_BS_COLUMNS, F_BS_COLUMNS],
393
394
395
            [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],
396

397
398
399
400
            [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],
401

402
403
404
            [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],
405
            [SYSTEM_SAVE_BUTTON_CLASS_ON_CHANGE, F_BUTTON_ON_CHANGE_CLASS],
406

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        ];

        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;
    }
423
424
425
426
427
428
429
430
431
432

    /**
     * @param $timeout
     * @throws UserFormException
     */
    public static function checkSessionTimeout($timeout) {

        if (ini_get('session.gc_maxlifetime') < $timeout ||
            ini_get('session.cookie_lifetime') < $timeout
        ) {
433
434
435
            throw new qfq\UserFormException ("The specified timeout of $timeout seconds is higher than the PHP config 'session.gc_maxlifetime' ("
                . ini_get('session.gc_maxlifetime') . ") and/or 'session.cookie_lifetime' ("
                . ini_get('session.cookie_lifetime') . ")");
436
437
438
        }

        if ($timeout > SYSTEM_COOKIE_LIFETIME) {
439
            throw new qfq\UserFormException ("The specified timeout of $timeout seconds is higher than the hardcoded cookie lifetime (" . SYSTEM_COOKIE_LIFETIME . ")");
440
441
442

        }
    }
443
}