Passed
Push — development ( 9180c6...6d01aa )
by Nils
03:31
created

encryptFollowingDefuse()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 16
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 16
b 0
f 0
nc 12
nop 2
dl 0
loc 34
rs 8.5706
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 20 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * @package       install.queries.php
4
 * @author        Nils Laumaillé <[email protected]>
5
 * @version       2.1.27
6
 * @copyright     2009-2018 Nils Laumaillé
7
 * @license       GNU GPL-3.0
8
 * @link          https://www.teampass.net
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
require_once('../sources/SecureHandler.php');
15
session_start();
16
error_reporting(E_ERROR | E_PARSE);
17
header("Content-type: text/html; charset=utf-8");
18
$session_db_encoding = "utf8";
19
20
function chmodRecursive($dir, $dirPermissions, $filePermissions)
21
{
22
    $pointer_dir = opendir($dir);
23
    $res = true;
24
    while ($file = readdir($pointer_dir)) {
0 ignored issues
show
Bug introduced by
It seems like $pointer_dir can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

24
    while ($file = readdir(/** @scrutinizer ignore-type */ $pointer_dir)) {
Loading history...
25
        if (($file == ".") || ($file == "..")) {
26
            continue;
27
        }
28
29
        $fullPath = $dir."/".$file;
30
31
        if (is_dir($fullPath)) {
32
            if ($res = @chmod($fullPath, $dirPermissions)) {
33
                $res = @chmodRecursive($fullPath, $dirPermissions, $filePermissions);
34
            }
35
        } else {
36
            $res = chmod($fullPath, $filePermissions);
37
        }
38
        if (!$res) {
39
            closedir($pointer_dir);
0 ignored issues
show
Bug introduced by
It seems like $pointer_dir can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

39
            closedir(/** @scrutinizer ignore-type */ $pointer_dir);
Loading history...
40
            return false;
41
        }
42
    }
43
    closedir($pointer_dir);
44
    if (is_dir($dir) && $res) {
45
            $res = @chmod($dir, $dirPermissions);
46
    }
47
48
    return $res;
49
}
50
51
/**
52
 * genHash()
53
 *
54
 * Generate a hash for user login
55
 * @param string $password
56
 */
57
function bCrypt($password, $cost)
58
{
59
    $salt = sprintf('$2y$%02d$', $cost);
60
    if (function_exists('openssl_random_pseudo_bytes')) {
61
        $salt .= bin2hex(openssl_random_pseudo_bytes(11));
62
    } else {
63
        $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
64
        for ($i = 0; $i < 22; $i++) {
65
            $salt .= $chars[mt_rand(0, 63)];
66
        }
67
    }
68
    return crypt($password, $salt);
69
}
70
71
/**
72
 * Generates a random key
73
 *
74
 * @return void
75
 */
76
function generateRandomKey()
77
{
78
    // load passwordLib library
79
    $path = '../includes/libraries/PasswordGenerator/Generator/';
80
    include_once $path.'ComputerPasswordGenerator.php';
81
82
    $generator = new PasswordGenerator\Generator\ComputerPasswordGenerator();
83
84
    $generator->setLength(40);
85
    $generator->setSymbols(false);
86
    $generator->setLowercase(true);
87
    $generator->setUppercase(true);
88
    $generator->setNumbers(true);
89
90
	$key = $generator->generatePasswords();
91
92
    return $key[0];
93
}
94
95
/**
96
 * Permits to encrypt a message using Defuse
97
 * @param  string $message   Message to encrypt
98
 * @param  string $ascii_key Key to hash
99
 * @return array             String + Error
100
 */
101
function encryptFollowingDefuse($message, $ascii_key)
102
{
103
    // load PhpEncryption library
104
    $path = '../includes/libraries/Encryption/Encryption/';
105
    require_once $path.'Crypto.php';
106
    require_once $path.'Encoding.php';
107
    require_once $path.'DerivedKeys.php';
108
    require_once $path.'Key.php';
109
    require_once $path.'KeyOrPassword.php';
110
    require_once $path.'File.php';
111
    require_once $path.'RuntimeTests.php';
112
    require_once $path.'KeyProtectedByPassword.php';
113
    require_once $path.'Core.php';
114
115
    // convert KEY
116
    $key = \Defuse\Crypto\Key::loadFromAsciiSafeString($ascii_key);
117
118
    try {
119
        $text = \Defuse\Crypto\Crypto::encrypt($message, $key);
120
    } catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) {
121
        $err = "an attack! either the wrong key was loaded, or the ciphertext has changed since it was created either corrupted in the database or intentionally modified by someone trying to carry out an attack.";
122
    } catch (Defuse\Crypto\Exception\BadFormatException $ex) {
123
        $err = $ex;
124
    } catch (Defuse\Crypto\Exception\EnvironmentIsBrokenException $ex) {
125
        $err = $ex;
126
    } catch (Defuse\Crypto\Exception\CryptoException $ex) {
127
        $err = $ex;
128
    } catch (Defuse\Crypto\Exception\IOException $ex) {
129
        $err = $ex;
130
    }
131
132
    return array(
133
        'string' => isset($text) ? $text : "",
134
        'error' => $err
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $err does not seem to be defined for all execution paths leading up to this point.
Loading history...
135
    );
136
}
137
138
139
// Prepare POST variables
140
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
141
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
142
$post_activity = filter_input(INPUT_POST, 'activity', FILTER_SANITIZE_STRING);
143
$post_task = filter_input(INPUT_POST, 'task', FILTER_SANITIZE_STRING);
144
$post_index = filter_input(INPUT_POST, 'index', FILTER_SANITIZE_NUMBER_INT);
145
$post_multiple = filter_input(INPUT_POST, 'multiple', FILTER_SANITIZE_STRING);
146
$post_db = filter_input(INPUT_POST, 'db', FILTER_SANITIZE_STRING);
147
148
// Load libraries
149
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
150
$superGlobal = new protect\SuperGlobal\SuperGlobal();
151
152
// Prepare SESSION variables
153
$session_url_path = $superGlobal->get("url_path", "SESSION");
154
$session_abspath = $superGlobal->get("abspath", "SESSION");
155
$session_db_encoding = $superGlobal->get("db_encoding", "SESSION");
156
157
$superGlobal->put("CPM", 1, "SESSION");
158
159
if (null !== $post_type) {
160
    switch ($post_type) {
161
        case "step_2":
162
            //decrypt
163
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
164
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
0 ignored issues
show
Bug introduced by
'cpm' of type string is incompatible with the type Encryption\Crypt\the expected by parameter $password of Encryption\Crypt\aesctr::decrypt(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

164
            $json = Encryption\Crypt\aesctr::decrypt($post_data, /** @scrutinizer ignore-type */ "cpm", 128);
Loading history...
165
            $data = json_decode($json, true);
166
            $json = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
167
            $data = array_merge($data, array("activity" => $json));
168
            $json = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
169
            $data = array_merge($data, array("task" => $json));
170
171
            $abspath = str_replace('\\', '/', $data['root_path']);
172
            if (substr($abspath, strlen($abspath) - 1) == "/") {
173
                $abspath = substr($abspath, 0, strlen($abspath) - 1);
174
            }
175
            $session_abspath = $abspath;
176
            $session_url_path = $data['url_path'];
177
178
            if (isset($data['activity']) && $data['activity'] === "folder") {
179
                if (is_writable($abspath."/".$data['task']."/") === true) {
180
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
181
                } else {
182
                    echo '[{"error" : " Path '.$data['task'].' is not writable!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
183
                }
184
                break;
185
            }
186
187
            if (isset($data['activity']) && $data['activity'] === "extension") {
188
                if (extension_loaded($data['task'])) {
189
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
190
                } else {
191
                    echo '[{"error" : " Extension '.$data['task'].' is not loaded!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
192
                }
193
                break;
194
            }
195
196
            if (isset($data['activity']) && $data['activity'] === "function") {
197
                if (function_exists($data['task'])) {
198
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
199
                } else {
200
                    echo '[{"error" : " Function '.$data['task'].' is not available!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
201
                }
202
                break;
203
            }
204
205
            if (isset($data['activity']) && $data['activity'] === "version") {
206
                if (version_compare(phpversion(), '5.5.0', '>=')) {
207
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
208
                } else {
209
                    echo '[{"error" : "PHP version '.phpversion().' is not OK (minimum is 5.5.0)", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
210
                }
211
                break;
212
            }
213
214
            if (isset($data['activity']) && $data['activity'] === "ini") {
215
                if (ini_get($data['task']) >= 60) {
216
                    echo '[{"error" : "", "index" : "'.$post_index.'"}]';
217
                } else {
218
                    echo '[{"error" : "PHP \"Maximum execution time\" is set to '.ini_get('max_execution_time').' seconds. Please try to set to 60s at least during installation.", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
219
                }
220
                break;
221
            }
222
            break;
223
224
        case "step_3":
225
            //decrypt
226
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
227
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
228
            $data = json_decode($json, true);
229
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
230
            $db = json_decode($json, true);
231
232
            // launch
233
            if ($dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port'])) {
234
                // create temporary INSTALL mysqli table
235
                $mysqli_result = mysqli_query(
236
                    $dbTmp,
237
                    "CREATE TABLE IF NOT EXISTS `_install` (
238
                    `key` varchar(100) NOT NULL,
239
                    `value` varchar(500) NOT NULL,
240
                    PRIMARY KEY (`key`)
241
                    ) CHARSET=utf8;"
242
                );
243
                // store values
244
                foreach ($data as $key => $value) {
245
                    $superGlobal->put($key, $value, "SESSION");
246
                    $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
0 ignored issues
show
Bug introduced by
It seems like mysqli_query($dbTmp, 'SE...key` = '' . $key . ''') can also be of type boolean; however, parameter $result of mysqli_num_rows() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
                    $tmp = mysqli_num_rows(/** @scrutinizer ignore-type */ mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
Loading history...
247
                    if (intval($tmp) === 0) {
248
                        mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
249
                    } else {
250
                        mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
251
                    }
252
                }
253
                $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = 'url_path'"));
254
                if (intval($tmp) === 0) {
255
                    mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('url_path', '".empty($session_url_path) ? $db['url_path'] : $session_url_path."');");
256
                } else {
257
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '", empty($session_url_path) ? $db['url_path'] : $session_url_path, "' WHERE `key` = 'url_path';");
0 ignored issues
show
Unused Code introduced by
The call to mysqli_query() has too many arguments starting with '' WHERE `key` = 'url_path';'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

257
                    /** @scrutinizer ignore-call */ 
258
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '", empty($session_url_path) ? $db['url_path'] : $session_url_path, "' WHERE `key` = 'url_path';");

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
258
                }
259
                $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = 'abspath'"));
260
                if (intval($tmp) === 0) {
261
                    mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('abspath', '".empty($session_abspath) ? $db['abspath'] : $session_abspath."');");
262
                } else {
263
                    mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".empty($session_abspath) ? $db['abspath'] : $session_abspath."' WHERE `key` = 'abspath';");
264
                }
265
266
                echo '[{"error" : "", "result" : "Connection is successful", "multiple" : ""}]';
267
            } else {
268
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
269
            }
270
            mysqli_close($dbTmp);
271
            break;
272
273
        case "step_4":
274
            //decrypt
275
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
276
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
277
            $data = json_decode($json, true);
278
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
279
            $db = json_decode($json, true);
280
281
            $dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port']);
282
283
            // prepare data
284
            foreach ($data as $key => $value) {
285
                $data[$key] = str_replace(array('&quot;', '&#92;'), array('""', '\\\\'), $value);
286
            }
287
288
            // check skpath
289
            if (empty($data['sk_path'])) {
290
                $data['sk_path'] = $session_abspath."/includes";
291
            } else {
292
                $data['sk_path'] = str_replace("&#92;", "/", $data['sk_path']);
293
            }
294
            if (substr($data['sk_path'], strlen($data['sk_path']) - 1) == "/" || substr($data['sk_path'], strlen($data['sk_path']) - 1) == "\"") {
295
                $data['sk_path'] = substr($data['sk_path'], 0, strlen($data['sk_path']) - 1);
296
            }
297
            if (is_dir($data['sk_path'])) {
298
                if (is_writable($data['sk_path'])) {
299
                    // store all variables in SESSION
300
                    foreach ($data as $key => $value) {
301
                        $superGlobal->put($key, $value, "SESSION");
302
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
303
                        if (intval($tmp) === 0) {
304
                            mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
305
                        } else {
306
                            mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
307
                        }
308
                    }
309
                    echo '[{"error" : "", "result" : "Information stored", "multiple" : ""}]';
310
                } else {
311
                    echo '[{"error" : "The Directory must be writable!", "result" : "Information stored", "multiple" : ""}]';
312
                }
313
            } else {
314
                echo '[{"error" : "'.$data['sk_path'].' is not a Directory!", "result" : "Information stored", "multiple" : ""}]';
315
            }
316
            mysqli_close($dbTmp);
317
            break;
318
319
        case "step_5":
320
            //decrypt
321
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
322
            $activity = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
323
            $task = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
324
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
325
            $db = json_decode($json, true);
326
327
            // launch
328
            $dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port']);
329
            $dbBdd = $db['db_bdd'];
330
            if ($dbTmp) {
0 ignored issues
show
introduced by
$dbTmp is of type mysqli, thus it always evaluated to true.
Loading history...
331
                $mysqli_result = "";
332
333
                // read install variables
334
                $result = mysqli_query($dbTmp, "SELECT * FROM `_install`");
335
                while ($row = $result->fetch_array()) {
336
                    $var[$row[0]] = $row[1];
337
                }
338
339
                if ($activity === "table") {
340
                    if ($task === "utf8") {
341
                        //FORCE UTF8 DATABASE
342
                        mysqli_query($dbTmp, "ALTER DATABASE `".$dbBdd."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
343
                    } elseif ($task === "items") {
344
                        $mysqli_result = mysqli_query(
345
                            $dbTmp,
346
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items` (
347
                            `id` int(12) NOT null AUTO_INCREMENT,
348
                            `label` varchar(500) NOT NULL,
349
                            `description` text DEFAULT NULL,
350
                            `pw` text DEFAULT NULL,
351
                            `pw_iv` text DEFAULT NULL,
352
                            `pw_len` int(5) NOT NULL DEFAULT '0',
353
                            `url` varchar(500) DEFAULT NULL,
354
                            `id_tree` varchar(10) DEFAULT NULL,
355
                            `perso` tinyint(1) NOT null DEFAULT '0',
356
                            `login` varchar(200) DEFAULT NULL,
357
                            `inactif` tinyint(1) NOT null DEFAULT '0',
358
                            `restricted_to` varchar(200) DEFAULT NULL,
359
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
360
                            `email` varchar(100) DEFAULT NULL,
361
                            `notification` varchar(250) DEFAULT NULL,
362
                            `viewed_no` int(12) NOT null DEFAULT '0',
363
                            `complexity_level` varchar(3) NOT null DEFAULT '-1',
364
                            `auto_update_pwd_frequency` tinyint(2) NOT null DEFAULT '0',
365
                            `auto_update_pwd_next_date` varchar(100) NOT null DEFAULT '0',
366
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
367
                            PRIMARY KEY (`id`),
368
                            KEY    `restricted_inactif_idx` (`restricted_to`,`inactif`)
369
                            ) CHARSET=utf8;"
370
                        );
371
                    } elseif ($task === "log_items") {
372
                        $mysqli_result = mysqli_query(
373
                            $dbTmp,
374
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_items` (
375
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
376
                            `id_item` int(8) NOT NULL,
377
                            `date` varchar(50) NOT NULL,
378
                            `id_user` int(8) NOT NULL,
379
                            `action` varchar(250) NULL,
380
                            `raison` text NULL,
381
                            `raison_iv` text NULL,
382
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
383
                            PRIMARY KEY (`increment_id`)
384
                            ) CHARSET=utf8;"
385
                        );
386
                        // create index
387
                        mysqli_query(
388
                            $dbTmp,
389
                            "CREATE INDEX teampass_log_items_id_item_IDX ON ".$var['tbl_prefix']."log_items (id_item,date);"
390
                        );
391
                    } elseif ($task === "misc") {
392
                        $mysqli_result = mysqli_query(
393
                            $dbTmp,
394
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."misc` (
395
                            `increment_id` int(12) NOT null AUTO_INCREMENT,
396
                            `type` varchar(50) NOT NULL,
397
                            `intitule` varchar(100) NOT NULL,
398
                            `valeur` varchar(500) NOT NULL,
399
                            PRIMARY KEY (`increment_id`)
400
                            ) CHARSET=utf8;"
401
                        );
402
403
                        // include constants
404
                        require_once "../includes/config/include.php";
405
406
                        // prepare config file
407
                        $tp_config_file = "../includes/config/tp.config.php";
408
                        if (file_exists($tp_config_file)) {
409
                            if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d", mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y'))))) {
410
                                echo '[{"error" : "includes/config/tp.config.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
411
                                break;
412
                            } else {
413
                                unlink($tp_config_file);
414
                            }
415
                        }
416
                        $file_handler = fopen($tp_config_file, 'w');
417
                        $config_text = "<?php
418
global \$SETTINGS;
419
\$SETTINGS = array (";
420
421
                        // add by default settings
422
                        $aMiscVal = array(
423
                            array('admin', 'max_latest_items', '10'),
424
                            array('admin', 'enable_favourites', '1'),
425
                            array('admin', 'show_last_items', '1'),
426
                            array('admin', 'enable_pf_feature', '0'),
427
                            array('admin', 'log_connections', '0'),
428
                            array('admin', 'log_accessed', '1'),
429
                            array('admin', 'time_format', 'H:i:s'),
430
                            array('admin', 'date_format', 'd/m/Y'),
431
                            array('admin', 'duplicate_folder', '0'),
432
                            array('admin', 'item_duplicate_in_same_folder', '0'),
433
                            array('admin', 'duplicate_item', '0'),
434
                            array('admin', 'number_of_used_pw', '3'),
435
                            array('admin', 'manager_edit', '1'),
436
                            array('admin', 'cpassman_dir', $var['abspath']),
437
                            array('admin', 'cpassman_url', $var['url_path']),
438
                            array('admin', 'favicon', $var['url_path'].'/favicon.ico'),
439
                            array('admin', 'path_to_upload_folder', $var['abspath'].'/upload'),
440
                            array('admin', 'url_to_upload_folder', $var['url_path'].'/upload'),
441
                            array('admin', 'path_to_files_folder', $var['abspath'].'/files'),
442
                            array('admin', 'url_to_files_folder', $var['url_path'].'/files'),
443
                            array('admin', 'activate_expiration', '0'),
444
                            array('admin', 'pw_life_duration', '0'),
445
                            array('admin', 'maintenance_mode', '1'),
446
                            array('admin', 'enable_sts', '0'),
447
                            array('admin', 'encryptClientServer', '1'),
448
                            array('admin', 'cpassman_version', $SETTINGS_EXT['version']),
449
                            array('admin', 'ldap_mode', '0'),
450
                            array('admin', 'ldap_type', '0'),
451
                            array('admin', 'ldap_suffix', '0'),
452
                            array('admin', 'ldap_domain_dn', '0'),
453
                            array('admin', 'ldap_domain_controler', '0'),
454
                            array('admin', 'ldap_user_attribute', '0'),
455
                            array('admin', 'ldap_ssl', '0'),
456
                            array('admin', 'ldap_tls', '0'),
457
                            array('admin', 'ldap_elusers', '0'),
458
                            array('admin', 'ldap_search_base', '0'),
459
                            array('admin', 'ldap_port', '389'),
460
                            array('admin', 'richtext', '0'),
461
                            array('admin', 'allow_print', '0'),
462
                            array('admin', 'roles_allowed_to_print', '0'),
463
                            array('admin', 'show_description', '1'),
464
                            array('admin', 'anyone_can_modify', '0'),
465
                            array('admin', 'anyone_can_modify_bydefault', '0'),
466
                            array('admin', 'nb_bad_authentication', '0'),
467
                            array('admin', 'utf8_enabled', '1'),
468
                            array('admin', 'restricted_to', '0'),
469
                            array('admin', 'restricted_to_roles', '0'),
470
                            array('admin', 'enable_send_email_on_user_login', '0'),
471
                            array('admin', 'enable_user_can_create_folders', '0'),
472
                            array('admin', 'insert_manual_entry_item_history', '0'),
473
                            array('admin', 'enable_kb', '0'),
474
                            array('admin', 'enable_email_notification_on_item_shown', '0'),
475
                            array('admin', 'enable_email_notification_on_user_pw_change', '0'),
476
                            array('admin', 'custom_logo', ''),
477
                            array('admin', 'custom_login_text', ''),
478
                            array('admin', 'default_language', 'english'),
479
                            array('admin', 'send_stats', '0'),
480
                            array('admin', 'send_statistics_items', 'stat_country;stat_users;stat_items;stat_items_shared;stat_folders;stat_folders_shared;stat_admins;stat_managers;stat_ro;stat_mysqlversion;stat_phpversion;stat_teampassversion;stat_languages;stat_kb;stat_suggestion;stat_customfields;stat_api;stat_2fa;stat_agses;stat_duo;stat_ldap;stat_syslog;stat_stricthttps;stat_fav;stat_pf;'),
481
                            array('admin', 'send_stats_time', time() - 2592000),
482
                            array('admin', 'get_tp_info', '1'),
483
                            array('admin', 'send_mail_on_user_login', '0'),
484
                            array('cron', 'sending_emails', '0'),
485
                            array('admin', 'nb_items_by_query', 'auto'),
486
                            array('admin', 'enable_delete_after_consultation', '0'),
487
                            array('admin', 'enable_personal_saltkey_cookie', '0'),
488
                            array('admin', 'personal_saltkey_cookie_duration', '31'),
489
                            array('admin', 'email_smtp_server', ''),
490
                            array('admin', 'email_smtp_auth', ''),
491
                            array('admin', 'email_auth_username', ''),
492
                            array('admin', 'email_auth_pwd', ''),
493
                            array('admin', 'email_port', ''),
494
                            array('admin', 'email_security', ''),
495
                            array('admin', 'email_server_url', ''),
496
                            array('admin', 'email_from', ''),
497
                            array('admin', 'email_from_name', ''),
498
                            array('admin', 'pwd_maximum_length', '40'),
499
                            array('admin', 'google_authentication', '0'),
500
                            array('admin', 'delay_item_edition', '0'),
501
                            array('admin', 'allow_import', '0'),
502
                            array('admin', 'proxy_ip', ''),
503
                            array('admin', 'proxy_port', ''),
504
                            array('admin', 'upload_maxfilesize', '10mb'),
505
                            array('admin', 'upload_docext', 'doc,docx,dotx,xls,xlsx,xltx,rtf,csv,txt,pdf,ppt,pptx,pot,dotx,xltx'),
506
                            array('admin', 'upload_imagesext', 'jpg,jpeg,gif,png'),
507
                            array('admin', 'upload_pkgext', '7z,rar,tar,zip'),
508
                            array('admin', 'upload_otherext', 'sql,xml'),
509
                            array('admin', 'upload_imageresize_options', '1'),
510
                            array('admin', 'upload_imageresize_width', '800'),
511
                            array('admin', 'upload_imageresize_height', '600'),
512
                            array('admin', 'upload_imageresize_quality', '90'),
513
                            array('admin', 'use_md5_password_as_salt', '0'),
514
                            array('admin', 'ga_website_name', 'TeamPass for ChangeMe'),
515
                            array('admin', 'api', '0'),
516
                            array('admin', 'subfolder_rights_as_parent', '0'),
517
                            array('admin', 'show_only_accessible_folders', '0'),
518
                            array('admin', 'enable_suggestion', '0'),
519
                            array('admin', 'otv_expiration_period', '7'),
520
                            array('admin', 'default_session_expiration_time', '60'),
521
                            array('admin', 'duo', '0'),
522
                            array('admin', 'enable_server_password_change', '0'),
523
                            array('admin', 'ldap_object_class', '0'),
524
                            array('admin', 'bck_script_path', $var['abspath']."/backups"),
525
                            array('admin', 'bck_script_filename', 'bck_teampass'),
526
                            array('admin', 'syslog_enable', '0'),
527
                            array('admin', 'syslog_host', 'localhost'),
528
                            array('admin', 'syslog_port', '514'),
529
                            array('admin', 'manager_move_item', '0'),
530
                            array('admin', 'create_item_without_password', '0'),
531
                            array('admin', 'otv_is_enabled', '0'),
532
                            array('admin', 'agses_authentication_enabled', '0'),
533
                            array('admin', 'item_extra_fields', '0'),
534
                            array('admin', 'saltkey_ante_2127', 'none'),
535
                            array('admin', 'migration_to_2127', 'done'),
536
                            array('admin', 'files_with_defuse', 'done'),
537
                            array('admin', 'timezone', 'UTC'),
538
                            array('admin', 'enable_attachment_encryption', '1'),
539
                            array('admin', 'personal_saltkey_security_level', '50'),
540
                            array('admin', 'ldap_new_user_is_administrated_by', '0'),
541
                            array('admin', 'disable_show_forgot_pwd_link', '0'),
542
                            array('admin', 'offline_key_level', '0'),
543
                            array('admin', 'enable_http_request_login', '0'),
544
                            array('admin', 'ldap_and_local_authentication', '0'),
545
                            array('admin', 'secure_display_image', '1'),
546
                            array('admin', 'upload_zero_byte_file', '0'),
547
                            array('admin', 'upload_all_extensions_file', '0'),
548
                            array('admin', 'bck_script_passkey', generateRandomKey())
0 ignored issues
show
Bug introduced by
Are you sure the usage of generateRandomKey() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
549
                        );
550
                        foreach ($aMiscVal as $elem) {
551
                            //Check if exists before inserting
552
                            $tmp = mysqli_num_rows(
553
                                mysqli_query(
554
                                    $dbTmp,
555
                                    "SELECT * FROM `".$var['tbl_prefix']."misc`
556
                                    WHERE type='".$elem[0]."' AND intitule='".$elem[1]."'"
557
                                )
558
                            );
559
                            if (intval($tmp) === 0) {
560
                                $queryRes = mysqli_query(
561
                                    $dbTmp,
562
                                    "INSERT INTO `".$var['tbl_prefix']."misc`
563
                                    (`type`, `intitule`, `valeur`) VALUES
564
                                    ('".$elem[0]."', '".$elem[1]."', '".
565
                                    str_replace("'", "", $elem[2])."');"
566
                                ); // or die(mysqli_error($dbTmp))
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
567
                            }
568
569
                            // append new setting in config file
570
                            $config_text .= "
571
    '".$elem[1]."' => '".str_replace("'", "", $elem[2])."',";
572
                        }
573
574
                        // write to config file
575
                        $result = fwrite(
576
                            $file_handler,
0 ignored issues
show
Bug introduced by
It seems like $file_handler can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

576
                            /** @scrutinizer ignore-type */ $file_handler,
Loading history...
577
                            utf8_encode(
578
                                $config_text."
579
);"
580
                            )
581
                        );
582
                        fclose($file_handler);
0 ignored issues
show
Bug introduced by
It seems like $file_handler can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

582
                        fclose(/** @scrutinizer ignore-type */ $file_handler);
Loading history...
583
                    } elseif ($task === "nested_tree") {
584
                        $mysqli_result = mysqli_query(
585
                            $dbTmp,
586
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."nested_tree` (
587
                            `id` bigint(20) unsigned NOT null AUTO_INCREMENT,
588
                            `parent_id` int(11) NOT NULL,
589
                            `title` varchar(255) NOT NULL,
590
                            `nleft` int(11) NOT NULL DEFAULT '0',
591
                            `nright` int(11) NOT NULL DEFAULT '0',
592
                            `nlevel` int(11) NOT NULL DEFAULT '0',
593
                            `bloquer_creation` tinyint(1) NOT null DEFAULT '0',
594
                            `bloquer_modification` tinyint(1) NOT null DEFAULT '0',
595
                            `personal_folder` tinyint(1) NOT null DEFAULT '0',
596
                            `renewal_period` int(5) NOT null DEFAULT '0',
597
                            PRIMARY KEY (`id`),
598
                            KEY `nested_tree_parent_id` (`parent_id`),
599
                            KEY `nested_tree_nleft` (`nleft`),
600
                            KEY `nested_tree_nright` (`nright`),
601
                            KEY `nested_tree_nlevel` (`nlevel`),
602
                            KEY `personal_folder_idx` (`personal_folder`)
603
                            ) CHARSET=utf8;"
604
                        );
605
                    } elseif ($task === "rights") {
606
                        $mysqli_result = mysqli_query(
607
                            $dbTmp,
608
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."rights` (
609
                            `id` int(12) NOT null AUTO_INCREMENT,
610
                            `tree_id` int(12) NOT NULL,
611
                            `fonction_id` int(12) NOT NULL,
612
                            `authorized` tinyint(1) NOT null DEFAULT '0',
613
                            PRIMARY KEY (`id`)
614
                            ) CHARSET=utf8;"
615
                        );
616
                    } elseif ($task === "users") {
617
                        $mysqli_result = mysqli_query(
618
                            $dbTmp,
619
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."users` (
620
                            `id` int(12) NOT null AUTO_INCREMENT,
621
                            `login` varchar(50) NOT NULL,
622
                            `pw` varchar(400) NOT NULL,
623
                            `groupes_visibles` varchar(250) NOT NULL,
624
                            `derniers` text NULL,
625
                            `key_tempo` varchar(100) NULL,
626
                            `last_pw_change` varchar(30) NULL,
627
                            `last_pw` text NULL,
628
                            `admin` tinyint(1) NOT null DEFAULT '0',
629
                            `fonction_id` varchar(255) NULL,
630
                            `groupes_interdits` varchar(255) NULL,
631
                            `last_connexion` varchar(30) NULL,
632
                            `gestionnaire` int(11) NOT null DEFAULT '0',
633
                            `email` varchar(300) NOT NULL DEFAULT 'none',
634
                            `favourites` varchar(300) NULL,
635
                            `latest_items` varchar(300) NULL,
636
                            `personal_folder` int(1) NOT null DEFAULT '0',
637
                            `disabled` tinyint(1) NOT null DEFAULT '0',
638
                            `no_bad_attempts` tinyint(1) NOT null DEFAULT '0',
639
                            `can_create_root_folder` tinyint(1) NOT null DEFAULT '0',
640
                            `read_only` tinyint(1) NOT null DEFAULT '0',
641
                            `timestamp` varchar(30) NOT null DEFAULT '0',
642
                            `user_language` varchar(50) NOT null DEFAULT '0',
643
                            `name` varchar(100) NULL,
644
                            `lastname` varchar(100) NULL,
645
                            `session_end` varchar(30) NULL,
646
                            `isAdministratedByRole` tinyint(5) NOT null DEFAULT '0',
647
                            `psk` varchar(400) NULL,
648
                            `ga` varchar(50) NULL,
649
                            `ga_temporary_code` VARCHAR(20) NOT NULL DEFAULT 'none',
650
                            `avatar` varchar(255) NULL,
651
                            `avatar_thumb` varchar(255) NULL,
652
                            `upgrade_needed` BOOLEAN NOT NULL DEFAULT FALSE,
653
                            `treeloadstrategy` varchar(30) NOT null DEFAULT 'full',
654
                            `can_manage_all_users` tinyint(1) NOT NULL DEFAULT '0',
655
                            `usertimezone` VARCHAR(50) NOT NULL DEFAULT 'not_defined',
656
                            `agses-usercardid` VARCHAR(50) NOT NULL DEFAULT '0',
657
                            `encrypted_psk` text NULL,
658
                            `user_ip` varchar(400) NOT null DEFAULT 'none',
659
                            `user_api_key` varchar(500) NOT null DEFAULT 'none',
660
                            `yubico_user_key` varchar(100) NOT null DEFAULT 'none',
661
                            `yubico_user_id` varchar(100) NOT null DEFAULT 'none',
662
                            PRIMARY KEY (`id`),
663
                            UNIQUE KEY `login` (`login`)
664
                            ) CHARSET=utf8;"
665
                        );
666
667
                        require_once "../includes/config/include.php";
668
                        // check that admin accounts doesn't exist
669
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE login = 'admin'"));
670
                        if ($tmp === 0) {
671
                            $mysqli_result = mysqli_query(
672
                                $dbTmp,
673
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `admin`, `gestionnaire`, `personal_folder`, `groupes_visibles`, `email`, `encrypted_psk`, `last_pw_change`) VALUES ('1', 'admin', '".bCrypt($var['admin_pwd'], '13')."', '1', '0', '0', '', '', '', '".time()."')"
674
                            );
675
                        } else {
676
                            $mysqli_result = mysqli_query($dbTmp, "UPDATE `".$var['tbl_prefix']."users` SET `pw` = '".bCrypt($var['admin_pwd'], '13')."' WHERE login = 'admin' AND id = '1'");
677
                        }
678
679
                        // check that API doesn't exist
680
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".API_USER_ID."'"));
681
                        if ($tmp === 0) {
682
                            $mysqli_result = mysqli_query(
683
                                $dbTmp,
684
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES ('".API_USER_ID."', 'API', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
685
                            );
686
                        }
687
688
                        // check that OTV doesn't exist
689
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."users` WHERE id = '".OTV_USER_ID."'"));
690
                        if ($tmp === 0) {
691
                            $mysqli_result = mysqli_query(
692
                                $dbTmp,
693
                                "INSERT INTO `".$var['tbl_prefix']."users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES ('".OTV_USER_ID."', 'OTV', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
694
                            );
695
                        }
696
                    } elseif ($task === "tags") {
697
                        $mysqli_result = mysqli_query(
698
                            $dbTmp,
699
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tags` (
700
                            `id` int(12) NOT null AUTO_INCREMENT,
701
                            `tag` varchar(30) NOT NULL,
702
                            `item_id` int(12) NOT NULL,
703
                            PRIMARY KEY (`id`)
704
                            ) CHARSET=utf8;"
705
                        );
706
                    } elseif ($task === "log_system") {
707
                        $mysqli_result = mysqli_query(
708
                            $dbTmp,
709
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."log_system` (
710
                            `id` int(12) NOT null AUTO_INCREMENT,
711
                            `type` varchar(20) NOT NULL,
712
                            `date` varchar(30) NOT NULL,
713
                            `label` text NOT NULL,
714
                            `qui` varchar(255) NOT NULL,
715
                            `field_1` varchar(250) DEFAULT NULL,
716
                            PRIMARY KEY (`id`)
717
                            ) CHARSET=utf8;"
718
                        );
719
                    } elseif ($task === "files") {
720
                        $mysqli_result = mysqli_query(
721
                            $dbTmp,
722
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."files` (
723
                            `id` int(11) NOT null AUTO_INCREMENT,
724
                            `id_item` int(11) NOT NULL,
725
                            `name` varchar(100) NOT NULL,
726
                            `size` int(10) NOT NULL,
727
                            `extension` varchar(10) NOT NULL,
728
                            `type` varchar(255) NOT NULL,
729
                            `file` varchar(50) NOT NULL,
730
                            `status` varchar(50) NOT NULL DEFAULT '0',
731
                            `content` longblob DEFAULT NULL,
732
                            PRIMARY KEY (`id`)
733
                           ) CHARSET=utf8;"
734
                        );
735
                    } elseif ($task === "cache") {
736
                        $mysqli_result = mysqli_query(
737
                            $dbTmp,
738
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."cache` (
739
                            `increment_id`INT(12) NOT NULL AUTO_INCREMENT,
740
                            `id` int(12) NOT NULL,
741
                            `label` varchar(500) NOT NULL,
742
                            `description` text NOT NULL,
743
                            `tags` text DEFAULT NULL,
744
                            `id_tree` int(12) NOT NULL,
745
                            `perso` tinyint(1) NOT NULL,
746
                            `restricted_to` varchar(200) DEFAULT NULL,
747
                            `login` varchar(200) DEFAULT NULL,
748
                            `folder` varchar(300) NOT NULL,
749
                            `author` varchar(50) NOT NULL,
750
                            `renewal_period` tinyint(4) NOT NULL DEFAULT '0',
751
                            `timestamp` varchar(50) DEFAULT NULL,
752
                            `url` varchar(500) NOT NULL DEFAULT '0',
753
                            `encryption_type` VARCHAR(50) DEFAULT NULL DEFAULT '0',
754
                            PRIMARY KEY (`increment_id`)
755
                            ) CHARSET=utf8;"
756
                        );
757
                    } elseif ($task === "roles_title") {
758
                        $mysqli_result = mysqli_query(
759
                            $dbTmp,
760
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_title` (
761
                            `id` int(12) NOT null AUTO_INCREMENT,
762
                            `title` varchar(50) NOT NULL,
763
                            `allow_pw_change` TINYINT(1) NOT null DEFAULT '0',
764
                            `complexity` INT(5) NOT null DEFAULT '0',
765
                            `creator_id` int(11) NOT null DEFAULT '0',
766
                            PRIMARY KEY (`id`)
767
                            ) CHARSET=utf8;"
768
                        );
769
                    } elseif ($task === "roles_values") {
770
                        $mysqli_result = mysqli_query(
771
                            $dbTmp,
772
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."roles_values` (
773
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT PRIMARY KEY,
774
                            `role_id` int(12) NOT NULL,
775
                            `folder_id` int(12) NOT NULL,
776
                            `type` varchar(5) NOT NULL DEFAULT 'R',
777
                            KEY `role_id_idx` (`role_id`)
778
                            ) CHARSET=utf8;"
779
                        );
780
                    } elseif ($task === "kb") {
781
                        $mysqli_result = mysqli_query(
782
                            $dbTmp,
783
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb` (
784
                            `id` int(12) NOT null AUTO_INCREMENT,
785
                            `category_id` int(12) NOT NULL,
786
                            `label` varchar(200) NOT NULL,
787
                            `description` text NOT NULL,
788
                            `author_id` int(12) NOT NULL,
789
                            `anyone_can_modify` tinyint(1) NOT null DEFAULT '0',
790
                            PRIMARY KEY (`id`)
791
                            ) CHARSET=utf8;"
792
                        );
793
                    } elseif ($task === "kb_categories") {
794
                        $mysqli_result = mysqli_query(
795
                            $dbTmp,
796
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_categories` (
797
                            `id` int(12) NOT null AUTO_INCREMENT,
798
                            `category` varchar(50) NOT NULL,
799
                            PRIMARY KEY (`id`)
800
                            ) CHARSET=utf8;"
801
                        );
802
                    } elseif ($task === "kb_items") {
803
                        $mysqli_result = mysqli_query(
804
                            $dbTmp,
805
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."kb_items` (
806
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
807
                            `kb_id` int(12) NOT NULL,
808
                            `item_id` int(12) NOT NULL,
809
                            PRIMARY KEY (`increment_id`)
810
                           ) CHARSET=utf8;"
811
                        );
812
                    } elseif ($task == "restriction_to_roles") {
813
                        $mysqli_result = mysqli_query(
814
                            $dbTmp,
815
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."restriction_to_roles` (
816
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
817
                            `role_id` int(12) NOT NULL,
818
                            `item_id` int(12) NOT NULL,
819
                            PRIMARY KEY (`increment_id`)
820
                            ) CHARSET=utf8;"
821
                        );
822
                    } elseif ($task === "languages") {
823
                        $mysqli_result = mysqli_query(
824
                            $dbTmp,
825
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."languages` (
826
                            `id` INT(10) NOT null AUTO_INCREMENT,
827
                            `name` VARCHAR(50) NOT null ,
828
                            `label` VARCHAR(50) NOT null ,
829
                            `code` VARCHAR(10) NOT null ,
830
                            `flag` VARCHAR(30) NOT NULL,
831
                            PRIMARY KEY (`id`)
832
                            ) CHARSET=utf8;"
833
                        );
834
835
                        // add lanaguages
836
                        $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `".$var['tbl_prefix']."languages` WHERE name = 'french'"));
837
                        if ($tmp[0] == 0) {
838
                            $mysql_result = mysqli_query(
839
                                $dbTmp,
840
                                "INSERT INTO `".$var['tbl_prefix']."languages` (`name`, `label`, `code`, `flag`) VALUES
841
                                ('french', 'French' , 'fr', 'fr.png'),
842
                                ('english', 'English' , 'us', 'us.png'),
843
                                ('spanish', 'Spanish' , 'es', 'es.png'),
844
                                ('german', 'German' , 'de', 'de.png'),
845
                                ('czech', 'Czech' , 'cz', 'cz.png'),
846
                                ('italian', 'Italian' , 'it', 'it.png'),
847
                                ('russian', 'Russian' , 'ru', 'ru.png'),
848
                                ('turkish', 'Turkish' , 'tr', 'tr.png'),
849
                                ('norwegian', 'Norwegian' , 'no', 'no.png'),
850
                                ('japanese', 'Japanese' , 'ja', 'ja.png'),
851
                                ('portuguese', 'Portuguese' , 'pr', 'pr.png'),
852
                                ('portuguese_br', 'Portuguese (Brazil)' , 'pr-bt', 'pr-bt.png'),
853
                                ('chinese', 'Chinese' , 'cn', 'cn.png'),
854
                                ('swedish', 'Swedish' , 'se', 'se.png'),
855
                                ('dutch', 'Dutch' , 'nl', 'nl.png'),
856
                                ('catalan', 'Catalan' , 'ct', 'ct.png'),
857
                                ('bulgarian', 'Bulgarian' , 'bg', 'bg.png'),
858
                                ('greek', 'Greek' , 'gr', 'gr.png'),
859
                                ('hungarian', 'Hungarian' , 'hu', 'hu.png'),
860
                                ('polish', 'Polish' , 'pl', 'pl.png'),
861
                                ('romanian', 'Romanian' , 'ro', 'ro.png'),
862
                                ('ukrainian', 'Ukrainian' , 'ua', 'ua.png'),
863
                                ('vietnamese', 'Vietnamese' , 'vi', 'vi.png'),
864
                                ('estonian', 'Estonian' , 'ee', 'ee.png');"
865
                            );
866
                        }
867
                    } elseif ($task === "emails") {
868
                        $mysqli_result = mysqli_query(
869
                            $dbTmp,
870
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."emails` (
871
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
872
                            `timestamp` INT(30) NOT null ,
873
                            `subject` VARCHAR(255) NOT null ,
874
                            `body` TEXT NOT null ,
875
                            `receivers` VARCHAR(255) NOT null ,
876
                            `status` VARCHAR(30) NOT NULL,
877
                            PRIMARY KEY (`increment_id`)
878
                            ) CHARSET=utf8;"
879
                        );
880
                    } elseif ($task === "automatic_del") {
881
                        $mysqli_result = mysqli_query(
882
                            $dbTmp,
883
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."automatic_del` (
884
                            `item_id` int(11) NOT NULL,
885
                            `del_enabled` tinyint(1) NOT NULL,
886
                            `del_type` tinyint(1) NOT NULL,
887
                            `del_value` varchar(35) NOT NULL,
888
                            PRIMARY KEY (`item_id`)
889
                            ) CHARSET=utf8;"
890
                        );
891
                    } elseif ($task === "items_edition") {
892
                        $mysqli_result = mysqli_query(
893
                            $dbTmp,
894
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_edition` (
895
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
896
                            `item_id` int(11) NOT NULL,
897
                            `user_id` int(12) NOT NULL,
898
                            `timestamp` varchar(50) NOT NULL,
899
                            KEY `item_id_idx` (`item_id`),
900
                            PRIMARY KEY (`increment_id`)
901
                            ) CHARSET=utf8;"
902
                        );
903
                    } elseif ($task === "categories") {
904
                        $mysqli_result = mysqli_query(
905
                            $dbTmp,
906
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories` (
907
                            `id` int(12) NOT NULL AUTO_INCREMENT,
908
                            `parent_id` int(12) NOT NULL,
909
                            `title` varchar(255) NOT NULL,
910
                            `level` int(2) NOT NULL,
911
                            `description` text NULL,
912
                            `type` varchar(50) NULL default '',
913
                            `masked` tinyint(1) NOT NULL default '0',
914
                            `order` int(12) NOT NULL default '0',
915
                            `encrypted_data` tinyint(1) NOT NULL default '1',
916
                            `role_visibility` varchar(255) NOT NULL DEFAULT 'all',
917
                            `is_mandatory` tinyint(1) NOT NULL DEFAULT '0',
918
                            PRIMARY KEY (`id`)
919
                            ) CHARSET=utf8;"
920
                        );
921
                    } elseif ($task === "categories_items") {
922
                        $mysqli_result = mysqli_query(
923
                            $dbTmp,
924
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_items` (
925
                            `id` int(12) NOT NULL AUTO_INCREMENT,
926
                            `field_id` int(11) NOT NULL,
927
                            `item_id` int(11) NOT NULL,
928
                            `data` text NOT NULL,
929
                            `data_iv` text NOT NULL,
930
                            `encryption_type` VARCHAR(20) NOT NULL DEFAULT 'not_set',
931
                            `is_mandatory` BOOLEAN NOT NULL DEFAULT FALSE ,
932
                            PRIMARY KEY (`id`)
933
                            ) CHARSET=utf8;"
934
                        );
935
                    } elseif ($task === "categories_folders") {
936
                        $mysqli_result = mysqli_query(
937
                            $dbTmp,
938
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."categories_folders` (
939
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
940
                            `id_category` int(12) NOT NULL,
941
                            `id_folder` int(12) NOT NULL,
942
                            PRIMARY KEY (`increment_id`)
943
                            ) CHARSET=utf8;"
944
                        );
945
                    } elseif ($task === "api") {
946
                        $mysqli_result = mysqli_query(
947
                            $dbTmp,
948
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."api` (
949
                            `id` int(20) NOT NULL AUTO_INCREMENT,
950
                            `type` varchar(15) NOT NULL,
951
                            `label` varchar(255) NOT NULL,
952
                            `value` varchar(255) NOT NULL,
953
                            `timestamp` varchar(50) NOT NULL,
954
                            PRIMARY KEY (`id`)
955
                            ) CHARSET=utf8;"
956
                        );
957
                    } elseif ($task === "otv") {
958
                        $mysqli_result = mysqli_query(
959
                            $dbTmp,
960
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."otv` (
961
                            `id` int(10) NOT NULL AUTO_INCREMENT,
962
                            `timestamp` text NOT NULL,
963
                            `code` varchar(100) NOT NULL,
964
                            `item_id` int(12) NOT NULL,
965
                            `originator` int(12) NOT NULL,
966
                            PRIMARY KEY (`id`)
967
                            ) CHARSET=utf8;"
968
                        );
969
                    } elseif ($task === "suggestion") {
970
                        $mysqli_result = mysqli_query(
971
                            $dbTmp,
972
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."suggestion` (
973
                            `id` tinyint(12) NOT NULL AUTO_INCREMENT,
974
                            `label` varchar(255) NOT NULL,
975
                            `pw` text NOT NULL,
976
                            `pw_iv` text NOT NULL,
977
                            `pw_len` int(5) NOT NULL,
978
                            `description` text NOT NULL,
979
                            `author_id` int(12) NOT NULL,
980
                            `folder_id` int(12) NOT NULL,
981
                            `comment` text NOT NULL,
982
                            `suggestion_type` varchar(10) NOT NULL default 'new',
983
                            PRIMARY KEY (`id`)
984
                            ) CHARSET=utf8;"
985
                        );
986
987
                        $mysqli_result = mysqli_query(
988
                            $dbTmp,
989
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."export` (
990
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
991
                            `id` int(12) NOT NULL,
992
                            `label` varchar(500) NOT NULL,
993
                            `login` varchar(100) NOT NULL,
994
                            `description` text NOT NULL,
995
                            `pw` text NOT NULL,
996
                            `path` varchar(500) NOT NULL,
997
                            `email` varchar(500) NOT NULL default 'none',
998
                            `url` varchar(500) NOT NULL default 'none',
999
                            `kbs` varchar(500) NOT NULL default 'none',
1000
                            `tags` varchar(500) NOT NULL default 'none',
1001
                            PRIMARY KEY (`increment_id`)
1002
                            ) CHARSET=utf8;"
1003
                        );
1004
                    } elseif ($task === "tokens") {
1005
                        $mysqli_result = mysqli_query(
1006
                            $dbTmp,
1007
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."tokens` (
1008
                            `id` int(12) NOT NULL AUTO_INCREMENT,
1009
                            `user_id` int(12) NOT NULL,
1010
                            `token` varchar(255) NOT NULL,
1011
                            `reason` varchar(255) NOT NULL,
1012
                            `creation_timestamp` varchar(50) NOT NULL,
1013
                            `end_timestamp` varchar(50) NOT NULL,
1014
                            PRIMARY KEY (`id`)
1015
                            ) CHARSET=utf8;"
1016
                        );
1017
                    } elseif ($task === "items_change") {
1018
                        $mysqli_result = mysqli_query(
1019
                            $dbTmp,
1020
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."items_change` (
1021
                            `id` int(12) NOT NULL AUTO_INCREMENT,
1022
                            `item_id` int(12) NOT NULL,
1023
                            `label` varchar(255) NOT NULL DEFAULT 'none',
1024
                            `pw` text NOT NULL,
1025
                            `login` varchar(255) NOT NULL DEFAULT 'none',
1026
                            `email` varchar(255) NOT NULL DEFAULT 'none',
1027
                            `url` varchar(255) NOT NULL DEFAULT 'none',
1028
                            `description` text NOT NULL,
1029
                            `comment` text NOT NULL,
1030
                            `folder_id` tinyint(12) NOT NULL,
1031
                            `user_id` int(12) NOT NULL,
1032
                            `timestamp` varchar(50) NOT NULL DEFAULT 'none',
1033
                            PRIMARY KEY (`id`)
1034
                            ) CHARSET=utf8;"
1035
                        );
1036
                    } elseif ($task === "templates") {
1037
                        $mysqli_result = mysqli_query(
1038
                            $dbTmp,
1039
                            "CREATE TABLE IF NOT EXISTS `".$var['tbl_prefix']."templates` (
1040
                            `increment_id` int(12) NOT NULL AUTO_INCREMENT,
1041
                            `item_id` int(12) NOT NULL,
1042
                            `category_id` int(12) NOT NULL,
1043
                            PRIMARY KEY (`increment_id`)
1044
                            ) CHARSET=utf8;"
1045
                        );
1046
                    }
1047
                }
1048
                // answer back
1049
                if ($mysqli_result) {
1050
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "task" : "'.$task.'", "activity" : "'.$activity.'"}]';
1051
                } else {
1052
                    echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_error())).'", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "table" : "'.$task.'"}]';
0 ignored issues
show
Bug introduced by
The call to mysqli_error() has too few arguments starting with link. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1052
                    echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), /** @scrutinizer ignore-call */ mysqli_error())).'", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'", "table" : "'.$task.'"}]';

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
1053
                }
1054
            } else {
1055
                echo '[{"error" : "'.addslashes(str_replace(array("'", "\n", "\r"), array('"', '', ''), mysqli_connect_error())).'", "result" : "Failed", "multiple" : ""}]';
1056
            }
1057
1058
            mysqli_close($dbTmp);
1059
            // Destroy session without writing to disk
1060
            define('NODESTROY_SESSION', 'true');
1061
            session_destroy();
1062
            break;
1063
1064
        case "step_6":
1065
            //decrypt
1066
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
1067
            $activity = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
1068
            $data_sent = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
1069
            $data_sent = json_decode($data_sent, true);
1070
            $task = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
1071
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
1072
            $db = json_decode($json, true);
1073
1074
            $dbTmp = mysqli_connect(
1075
                $db['db_host'],
1076
                $db['db_login'],
1077
                $db['db_pw'],
1078
                $db['db_bdd'],
1079
                $db['db_port']
1080
            );
1081
1082
            // read install variables
1083
            $result = mysqli_query($dbTmp, "SELECT * FROM `_install`");
1084
            while ($row = $result->fetch_array()) {
1085
                $var[$row[0]] = $row[1];
1086
            }
1087
1088
            // launch
1089
            if (empty($var['sk_path'])) {
1090
                $skFile = $var['abspath'].'/includes/sk.php';
1091
                $securePath = $var['abspath'];
1092
            } else {
1093
                //ensure $var['sk_path'] has no trailing slash
1094
                $var['sk_path'] = rtrim($var['sk_path'], '/\\');
1095
                $skFile = $var['sk_path'].'/sk.php';
1096
                $securePath = $var['sk_path'];
1097
            }
1098
1099
            $events = "";
1100
1101
            if ($activity === "file") {
1102
                if ($task === "settings.php") {
1103
                    // first is to create teampass-seckey.txt
1104
                    // 0- check if exists
1105
                    $filename_seckey = $securePath."/teampass-seckey.txt";
1106
1107
                    if (file_exists($filename_seckey)) {
1108
                        if (!copy($filename_seckey, $filename_seckey.'.'.date("Y_m_d", mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y'))))) {
1109
                            echo '[{"error" : "File `$filename_seckey` already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1110
                            break;
1111
                        } else {
1112
                            unlink($filename);
1113
                        }
1114
                    }
1115
1116
                    // 1- generate saltkey
1117
                    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
1118
                    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
1119
                    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
1120
                    require_once '../includes/libraries/Encryption/Encryption/Key.php';
1121
                    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
1122
                    require_once '../includes/libraries/Encryption/Encryption/File.php';
1123
                    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
1124
                    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
1125
                    require_once '../includes/libraries/Encryption/Encryption/Core.php';
1126
1127
                    $key = \Defuse\Crypto\Key::createNewRandomKey();
1128
                    $new_salt = $key->saveToAsciiSafeString();
1129
1130
                    // 2- store key in file
1131
                    file_put_contents(
1132
                        $filename_seckey,
1133
                        $new_salt
1134
                    );
1135
1136
                    // Now create settings file
1137
                    $filename = "../includes/config/settings.php";
1138
1139
                    if (file_exists($filename)) {
1140
                        if (!copy($filename, $filename.'.'.date("Y_m_d", mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y'))))) {
1141
                            echo '[{"error" : "Setting.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1142
                            break;
1143
                        } else {
1144
                            unlink($filename);
1145
                        }
1146
                    }
1147
1148
                    // Encrypt the DB password
1149
                    $encrypted_text = encryptFollowingDefuse(
1150
                        $db['db_pw'],
1151
                        $new_salt
1152
                    )['string'];
1153
1154
                    // Open and write Settings file
1155
                    $file_handler = fopen($filename, 'w');
1156
                    $result = fwrite(
1157
                        $file_handler,
1158
                        utf8_encode(
1159
                            "<?php
1160
global \$lang, \$txt, \$pathTeampas, \$urlTeampass, \$pwComplexity, \$mngPages;
1161
global \$server, \$user, \$pass, \$database, \$pre, \$db, \$port, \$encoding;
1162
1163
### DATABASE connexion parameters ###
1164
\$server = \"".$db['db_host']."\";
1165
\$user = \"".$db['db_login']."\";
1166
\$pass = \"".str_replace("$", "\\$", $encrypted_text)."\";
1167
\$database = \"".$db['db_bdd']."\";
1168
\$pre = \"".$var['tbl_prefix']."\";
1169
\$port = ".$db['db_port'].";
1170
\$encoding = \"".$session_db_encoding."\";
1171
1172
@date_default_timezone_set(\$_SESSION['settings']['timezone']);
1173
@define('SECUREPATH', '".$securePath."');
1174
if (file_exists(\"".str_replace('\\', '/', $skFile)."\")) {
1175
    require_once \"".str_replace('\\', '/', $skFile)."\";
1176
}
1177
"
1178
                        )
1179
                    );
1180
                    fclose($file_handler);
1181
                    if ($result === false) {
1182
                        echo '[{"error" : "Setting.php file could not be created. Please check the path and the rights", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1183
                    } else {
1184
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1185
                    }
1186
                } elseif ($task === "sk.php") {
1187
//Create sk.php file
1188
                    if (file_exists($skFile)) {
1189
                        if (!copy($skFile, $skFile.'.'.date("Y_m_d", mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y'))))) {
1190
                            echo '[{"error" : "sk.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1191
                            break;
1192
                        } else {
1193
                            unlink($skFile);
1194
                        }
1195
                    }
1196
                    $file_handler = fopen($skFile, 'w');
1197
1198
                    $result = fwrite(
1199
                        $file_handler,
1200
                        utf8_encode(
1201
                            "<?php
1202
@define('COST', '13'); // Don't change this.
1203
@define('AKEY', '');
1204
@define('IKEY', '');
1205
@define('SKEY', '');
1206
@define('HOST', '');
1207
?>"
1208
                        )
1209
                    );
1210
                    fclose($file_handler);
1211
1212
                    // finalize
1213
                    if ($result === false) {
1214
                        echo '[{"error" : "sk.php file could not be created. Please check the path and the rights.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1215
                    } else {
1216
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1217
                    }
1218
                } elseif ($task === "security") {
1219
                    # Sort out the file permissions
1220
1221
                    // is server Windows or Linux?
1222
                    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') {
1223
                        // Change directory permissions
1224
                        $result = chmodRecursive($session_abspath, 0770, 0740);
1225
                        if ($result) {
1226
                            $result = chmodRecursive($session_abspath.'/files', 0770, 0770);
1227
                        }
1228
                        if ($result) {
1229
                            $result = chmodRecursive($session_abspath.'/upload', 0770, 0770);
1230
                        }
1231
                    }
1232
1233
                    if ($result === false) {
1234
                        echo '[{"error" : "Cannot change directory permissions - please fix manually", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1235
                    } else {
1236
                        echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1237
                    }
1238
                } elseif ($task === "csrfp-token") {
1239
                    // update CSRFP TOKEN
1240
                    $csrfp_file_sample = "../includes/libraries/csrfp/libs/csrfp.config.sample.php";
1241
                    $csrfp_file = "../includes/libraries/csrfp/libs/csrfp.config.php";
1242
                    if (file_exists($csrfp_file)) {
1243
                        if (!copy($csrfp_file, $csrfp_file.'.'.date("Y_m_d", mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y'))))) {
1244
                            echo '[{"error" : "csrfp.config.php file already exists and cannot be renamed. Please do it by yourself and click on button Launch.", "result":"", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1245
                            break;
1246
                        } else {
1247
                            $events .= "The file $csrfp_file already exist. A copy has been created.<br />";
1248
                        }
1249
                    }
1250
                    unlink($csrfp_file); // delete existing csrfp.config file
1251
                    copy($csrfp_file_sample, $csrfp_file); // make a copy of csrfp.config.sample file
1252
                    $data = file_get_contents($csrfp_file);
1253
                    $newdata = str_replace('"CSRFP_TOKEN" => ""', '"CSRFP_TOKEN" => "'.bin2hex(openssl_random_pseudo_bytes(25)).'"', $data);
1254
                    $jsUrl = $data_sent['url_path'].'/includes/libraries/csrfp/js/csrfprotector.js';
1255
                    $newdata = str_replace('"jsUrl" => ""', '"jsUrl" => "'.$jsUrl.'"', $newdata);
1256
                    file_put_contents("../includes/libraries/csrfp/libs/csrfp.config.php", $newdata);
1257
1258
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1259
                }
1260
            } elseif ($activity === "install") {
1261
                if ($task === "cleanup") {
1262
                    // Mark a tag to force Install stuff (folders, files and table) to be cleanup while first login
1263
                    mysqli_query($dbTmp, "INSERT INTO `".$var['tbl_prefix']."misc` (`type`, `intitule`, `valeur`) VALUES ('install', 'clear_install_folder', 'true')");
1264
1265
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
1266
                }
1267
            }
1268
1269
            mysqli_close($dbTmp);
1270
            // Destroy session without writing to disk
1271
            define('NODESTROY_SESSION', 'true');
1272
            session_destroy();
1273
            break;
1274
    }
1275
}
1276