Passed
Push — development ( b3bbd1...d832f6 )
by Nils
05:00 queued 01:04
created

encryptFollowingDefuse()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 15
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 15
b 0
f 0
nc 12
nop 2
dl 0
loc 34
rs 6.7272
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
 * Permits to encrypt a message using Defuse
73
 * @param  string $message   Message to encrypt
74
 * @param  string $ascii_key Key to hash
75
 * @return array             String + Error
76
 */
77
function encryptFollowingDefuse($message, $ascii_key)
78
{
79
    // load PhpEncryption library
80
    $path = '../includes/libraries/Encryption/Encryption/';
81
    require_once $path.'Crypto.php';
82
    require_once $path.'Encoding.php';
83
    require_once $path.'DerivedKeys.php';
84
    require_once $path.'Key.php';
85
    require_once $path.'KeyOrPassword.php';
86
    require_once $path.'File.php';
87
    require_once $path.'RuntimeTests.php';
88
    require_once $path.'KeyProtectedByPassword.php';
89
    require_once $path.'Core.php';
90
91
    // convert KEY
92
    $key = \Defuse\Crypto\Key::loadFromAsciiSafeString($ascii_key);
93
94
    try {
95
        $text = \Defuse\Crypto\Crypto::encrypt($message, $key);
96
    } catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) {
97
        $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.";
98
    } catch (Defuse\Crypto\Exception\BadFormatException $ex) {
99
        $err = $ex;
100
    } catch (Defuse\Crypto\Exception\EnvironmentIsBrokenException $ex) {
101
        $err = $ex;
102
    } catch (Defuse\Crypto\Exception\CryptoException $ex) {
103
        $err = $ex;
104
    } catch (Defuse\Crypto\Exception\IOException $ex) {
105
        $err = $ex;
106
    }
107
108
    return array(
109
        'string' => isset($text) ? $text : "",
110
        '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...
111
    );
112
}
113
114
115
// Prepare POST variables
116
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
117
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
118
$post_activity = filter_input(INPUT_POST, 'activity', FILTER_SANITIZE_STRING);
119
$post_task = filter_input(INPUT_POST, 'task', FILTER_SANITIZE_STRING);
120
$post_index = filter_input(INPUT_POST, 'index', FILTER_SANITIZE_NUMBER_INT);
121
$post_multiple = filter_input(INPUT_POST, 'multiple', FILTER_SANITIZE_STRING);
122
$post_db = filter_input(INPUT_POST, 'db', FILTER_SANITIZE_STRING);
123
124
// Load libraries
125
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
126
$superGlobal = new protect\SuperGlobal\SuperGlobal();
127
128
// Prepare SESSION variables
129
$session_url_path = $superGlobal->get("url_path", "SESSION");
130
$session_abspath = $superGlobal->get("abspath", "SESSION");
131
$session_db_encoding = $superGlobal->get("db_encoding", "SESSION");
132
133
$superGlobal->put("CPM", 1, "SESSION");
134
135
if (null !== $post_type) {
136
    switch ($post_type) {
137
        case "step_2":
138
            //decrypt
139
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
140
            $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

140
            $json = Encryption\Crypt\aesctr::decrypt($post_data, /** @scrutinizer ignore-type */ "cpm", 128);
Loading history...
141
            $data = json_decode($json, true);
142
            $json = Encryption\Crypt\aesctr::decrypt($post_activity, "cpm", 128);
143
            $data = array_merge($data, array("activity" => $json));
144
            $json = Encryption\Crypt\aesctr::decrypt($post_task, "cpm", 128);
145
            $data = array_merge($data, array("task" => $json));
146
147
            $abspath = str_replace('\\', '/', $data['root_path']);
148
            if (substr($abspath, strlen($abspath) - 1) == "/") {
149
                $abspath = substr($abspath, 0, strlen($abspath) - 1);
150
            }
151
            $session_abspath = $abspath;
152
            $session_url_path = $data['url_path'];
153
154
            if (isset($data['activity']) && $data['activity'] === "folder") {
155
                if (is_writable($abspath."/".$data['task']."/") === true) {
156
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
157
                } else {
158
                    echo '[{"error" : " Path '.$data['task'].' is not writable!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
159
                }
160
                break;
161
            }
162
163
            if (isset($data['activity']) && $data['activity'] === "extension") {
164
                if (extension_loaded($data['task'])) {
165
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
166
                } else {
167
                    echo '[{"error" : " Extension '.$data['task'].' is not loaded!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
168
                }
169
                break;
170
            }
171
172
            if (isset($data['activity']) && $data['activity'] === "function") {
173
                if (function_exists($data['task'])) {
174
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
175
                } else {
176
                    echo '[{"error" : " Function '.$data['task'].' is not available!", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
177
                }
178
                break;
179
            }
180
181
            if (isset($data['activity']) && $data['activity'] === "version") {
182
                if (version_compare(phpversion(), '5.5.0', '>=')) {
183
                    echo '[{"error" : "", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
184
                } else {
185
                    echo '[{"error" : "PHP version '.phpversion().' is not OK (minimum is 5.5.0)", "index" : "'.$post_index.'", "multiple" : "'.$post_multiple.'"}]';
186
                }
187
                break;
188
            }
189
190
            if (isset($data['activity']) && $data['activity'] === "ini") {
191
                if (ini_get($data['task']) >= 60) {
192
                    echo '[{"error" : "", "index" : "'.$post_index.'"}]';
193
                } else {
194
                    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.'"}]';
195
                }
196
                break;
197
            }
198
            break;
199
200
        case "step_3":
201
            //decrypt
202
            require_once 'libs/aesctr.php'; // AES Counter Mode implementation
203
            $json = Encryption\Crypt\aesctr::decrypt($post_data, "cpm", 128);
204
            $data = json_decode($json, true);
205
            $json = Encryption\Crypt\aesctr::decrypt($post_db, "cpm", 128);
206
            $db = json_decode($json, true);
207
208
            // launch
209
            if ($dbTmp = mysqli_connect($db['db_host'], $db['db_login'], $db['db_pw'], $db['db_bdd'], $db['db_port'])) {
210
                // create temporary INSTALL mysqli table
211
                $mysqli_result = mysqli_query(
212
                    $dbTmp,
213
                    "CREATE TABLE IF NOT EXISTS `_install` (
214
                    `key` varchar(100) NOT NULL,
215
                    `value` varchar(500) NOT NULL,
216
                    PRIMARY KEY (`key`)
217
                    ) CHARSET=utf8;"
218
                );
219
                // store values
220
                foreach ($data as $key => $value) {
221
                    $superGlobal->put($key, $value, "SESSION");
222
                    $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

222
                    $tmp = mysqli_num_rows(/** @scrutinizer ignore-type */ mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = '".$key."'"));
Loading history...
223
                    if (intval($tmp) === 0) {
224
                        mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('".$key."', '".$value."');");
225
                    } else {
226
                        mysqli_query($dbTmp, "UPDATE `_install` SET `value` = '".$value."' WHERE `key` = '".$key."';");
227
                    }
228
                }
229
                $tmp = mysqli_num_rows(mysqli_query($dbTmp, "SELECT * FROM `_install` WHERE `key` = 'url_path'"));
230
                if (intval($tmp) === 0) {
231
                    mysqli_query($dbTmp, "INSERT INTO `_install` (`key`, `value`) VALUES ('url_path', '".empty($session_url_path) ? $db['url_path'] : $session_url_path."');");
232
                } else {
233
                    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

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

549
                            /** @scrutinizer ignore-type */ $file_handler,
Loading history...
550
                            utf8_encode(
551
                                $config_text."
552
);"
553
                            )
554
                        );
555
                        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

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

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