Completed
Push — development ( c4d33f...5f74fd )
by Nils
09:26
created

upgrade_run_2.1.27.php ➔ cleanFields()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 6
nop 1
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * @file          upgrade.ajax.php
4
 * @author        Nils Laumaillé
5
 * @version       2.1.27
6
 * @copyright     (c) 2009-2017 Nils Laumaillé
7
 * @licensing     GNU AFFERO GPL 3.0
8
 * @link          http://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
15
/*
16
** Upgrade script for release 2.1.27
17
*/
18
require_once('../sources/SecureHandler.php');
19
session_start();
20
error_reporting(E_ERROR | E_PARSE);
21
$_SESSION['db_encoding'] = "utf8";
22
$_SESSION['CPM'] = 1;
23
24
25
//include librairies
26
require_once '../includes/language/english.php';
27
require_once '../includes/config/include.php';
28
require_once '../includes/config/settings.php';
29
require_once '../sources/main.functions.php';
30
require_once '../includes/libraries/Tree/NestedTree/NestedTree.php';
31
32
$_SESSION['settings']['loaded'] = "";
33
//define pbkdf2 iteration count
34
@define('ITCOUNT', '2072');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
35
$return_error = "";
36
$res = "";
37
38
39
//Build tree
40
$tree = new Tree\NestedTree\NestedTree(
41
    $pre.'nested_tree',
42
    'id',
43
    'parent_id',
44
    'title'
45
);
46
47
48
// Prepare POST variables
49
$post_no_maintenance_mode = filter_input(INPUT_POST, 'no_maintenance_mode', FILTER_SANITIZE_NUMBER_INT);
50
$post_index = filter_input(INPUT_POST, 'index', FILTER_SANITIZE_NUMBER_INT);
51
$post_multiple = filter_input(INPUT_POST, 'multiple', FILTER_SANITIZE_STRING);
52
53
// DataBase
54
// Test DB connexion
55
$pass = defuse_return_decrypted($pass);
56 View Code Duplication
if (mysqli_connect(
57
    $server,
58
    $user,
59
    $pass,
60
    $database,
61
    $port
62
)
63
) {
64
    $db_link = mysqli_connect(
65
        $server,
66
        $user,
67
        $pass,
68
        $database,
69
        $port
70
    );
71
} else {
72
    $res = "Impossible to get connected to server. Error is: ".addslashes(mysqli_connect_error());
73
    echo '[{"finish":"1", "msg":"", "error":"Impossible to get connected to server. Error is: '.addslashes(mysqli_connect_error()).'!"}]';
74
    mysqli_close($db_link);
75
    exit();
76
}
77
78
// Load libraries
79
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
80
$superGlobal = new protect\SuperGlobal\SuperGlobal();
81
82
// Set Session
83
$superGlobal->put("db_encoding", "utf8", "SESSION");
84
$_SESSION['settings']['loaded'] = "";
85
$superGlobal->put("fullurl", $post_fullurl, "SESSION");
86
$superGlobal->put("abspath", $abspath, "SESSION");
87
88
// Get Sessions
89
$session_tp_defuse_installed = $superGlobal->get("tp_defuse_installed", "SESSION");
90
91
/**
92
 * Function permits to get the value from a line
93
 * @param  string $val [description]
94
 * @return string      [description]
95
 */
96
function getSettingValue($val)
0 ignored issues
show
Best Practice introduced by
The function getSettingValue() has been defined more than once; this definition is ignored, only the first definition in api/functions.php (L150-160) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
97
{
98
    $val = trim(strstr($val, "="));
99
    return trim(str_replace('"', '', substr($val, 1, strpos($val, ";") - 1)));
100
}
101
102
/**
103
 * Function permits to check if a column exists, and if not to add it
104
 * @param string $dbname     [description]
105
 * @param string $column     [description]
106
 * @param string $columnAttr [description]
107
 */
108 View Code Duplication
function addColumnIfNotExist($dbname, $column, $columnAttr = "VARCHAR(255) NULL")
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Best Practice introduced by
The function addColumnIfNotExist() has been defined more than once; this definition is ignored, only the first definition in install/upgrade_ajax.php (L130-144) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
109
{
110
    global $db_link;
111
    $exists = false;
112
    $columns = mysqli_query($db_link, "show columns from $dbname");
113
    while ($col = mysqli_fetch_assoc($columns)) {
114
        if ($col['Field'] == $column) {
115
            $exists = true;
0 ignored issues
show
Unused Code introduced by
$exists is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
116
            return true;
117
        }
118
    }
119
    if (!$exists) {
120
        return mysqli_query($db_link, "ALTER TABLE `$dbname` ADD `$column`  $columnAttr");
121
    }
122
123
    return false;
124
}
125
126
/**
127
 * [cleanFields description]
128
 * @param  [type] $txt [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
129
 * @return [type]      [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
130
 */
131
function cleanFields($txt)
132
{
133
    $tmp = str_replace(",", ";", trim($txt));
134
    if (empty($tmp)) {
135
        return $tmp;
136
    }
137
    if ($tmp === ";") {
138
        return "";
139
    }
140
    if (strpos($tmp, ';') === 0) {
141
        $tmp = substr($tmp, 1);
142
    }
143
    if (substr($tmp, -1) !== ";") {
144
        $tmp = $tmp.";";
145
    }
146
    return $tmp;
147
}
148
149
/*
150
** Checks if the column exists in the table
151
*/
152
function columnExists($tablename, $column)
153
{
154
    global $db_link;
155
    $checkcolumn = mysqli_query($db_link, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{$tablename}' AND COLUMN_NAME = '{$column}';");
156
    if (mysqli_num_rows($checkcolumn) > 0) {
157
        return true;
158
    } else {
159
        return false;
160
    }
161
}
162
163
// 2.1.27 introduce new encryption protocol with DEFUSE library.
164
// Now evaluate if current instance has already this version
165
$tmp = mysqli_fetch_row(mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'teampass_version'"));
166
if (count($tmp[0]) === 0 || empty($tmp[0])) {
167
    mysqli_query(
168
        $db_link,
169
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'teampass_version', '".$SETTINGS_EXT['version']."')"
170
    );
171
} else {
172
    mysqli_query(
173
        $db_link,
174
        "UPDATE `".$pre."misc`
175
        SET `valeur` = '".$SETTINGS_EXT['version']."'
176
        WHERE intitule = 'teampass_version' AND type = 'admin'"
177
    );
178
}
179
180
// add new admin setting "migration_to_2127"
181
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'migration_to_2127'"));
182
if (intval($tmp) === 0) {
183
    mysqli_query(
184
        $db_link,
185
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'migration_to_2127', '0')"
186
    );
187
}
188
189
190
// check if library defuse already on-going here
191
// if yes, then don't execute re-encryption
192
if (isset($session_tp_defuse_installed) === false) {
193
    $superGlobal->put("tp_defuse_installed", false, "SESSION");
194
    if (columnExists($pre."items", "encryption_type") === true) {
195
        $superGlobal->put("tp_defuse_installed", true, "SESSION");
196
    }
197
}
198
199
// alter table Items
200
mysqli_query($db_link, "ALTER TABLE `".$pre."items` MODIFY pw_len INT(5) NOT NULL DEFAULT '0'");
201
202
// alter table MISC - rename ID is exists
203 View Code Duplication
if (columnExists($pre."misc", "id") === true) {
204
    // Change name of field
205
    mysqli_query($db_link, "ALTER TABLE `".$pre."misc` CHANGE `id` `increment_id` INT(12) NOT NULL AUTO_INCREMENT");
206
} else {
207
    // alter table misc to add an index
208
    $res = addColumnIfNotExist(
209
        $pre."misc",
210
        "increment_id",
211
        "INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
212
    );
213
}
214
215
// alter table misc to add an index
216
mysqli_query(
217
    $db_link,
218
    "ALTER TABLE `".$pre."log_items` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
219
);
220
221
// add field agses-usercardid to Users table
222
$res = addColumnIfNotExist(
223
    $pre."users",
224
    "agses-usercardid",
225
    "VARCHAR(12) NOT NULL DEFAULT '0'"
226
);
227
if ($res === false) {
228
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field agses-usercardid to table Users! '.mysqli_error($db_link).'!"}]';
229
    mysqli_close($db_link);
230
    exit();
231
}
232
233
234
// add field encrypted_data to Categories table
235
$res = addColumnIfNotExist(
236
    $pre."categories",
237
    "encrypted_data",
238
    "TINYINT(1) NOT NULL DEFAULT '1'"
239
);
240
if ($res === false) {
241
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table categories! '.mysqli_error($db_link).'!"}]';
242
    mysqli_close($db_link);
243
    exit();
244
}
245
246
247
// alter table USERS - user_language
248
mysqli_query($db_link, "ALTER TABLE `".$pre."users` MODIFY user_language VARCHAR(50) NOT NULL DEFAULT '0'");
249
250
// alter table USERS - just ensure correct naming of IsAdministratedByRole
251
mysqli_query($db_link, "ALTER TABLE `".$pre."users` CHANGE IsAdministratedByRole isAdministratedByRole tinyint(5) NOT NULL DEFAULT '0'");
252
253
// alter table OTV
254
mysqli_query($db_link, "ALTER TABLE `".$pre."otv` CHANGE originator originator int(12) NOT NULL DEFAULT '0'");
255
256
// do clean of users table
257
$fieldsToUpdate = ['groupes_visibles', 'fonction_id', 'groupes_interdits'];
258
$result = mysqli_query($db_link, "SELECT id, groupes_visibles, fonction_id, groupes_interdits FROM `".$pre."users`");
259
while ($row = mysqli_fetch_assoc($result)) {
260
    // check if field contains , instead of ;
261
    foreach ($fieldsToUpdate as $field) {
262
        $tmp = cleanFields($row[$field]);
263
        if ($tmp !== $row[$field]) {
264
            mysqli_query(
265
                $db_link,
266
                "UPDATE `".$pre."users`
267
                SET `".$field."` = '".$tmp."'
268
                WHERE id = '".$row['id']."'"
269
            );
270
        }
271
    }
272
}
273
mysqli_free_result($result);
274
275
276
// alter table KB_ITEMS
277
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `kb_id` `kb_id` INT(12) NOT NULL");
278
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `item_id` `item_id` INT(12) NOT NULL");
279
280
281
// Alter table EXPORT - adapt field Label
282
mysqli_query($db_link, "ALTER TABLE `".$pre."export` CHANGE `label` `label` VARCHAR(500) NOT NULL");
283
284
// add field encrypted_data to CATEGORIES table
285
$res = addColumnIfNotExist(
286
    $pre."categories",
287
    "encrypted_data",
288
    "TINYINT(1) NOT NULL DEFAULT '1'"
289
);
290
if ($res === false) {
291
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table CATEGORIES! '.mysqli_error($db_link).'!"}]';
292
    mysqli_close($db_link);
293
    exit();
294
}
295
296
mysqli_query(
297
    $db_link,
298
    "UPDATE `".$pre."misc`
299
    SET `valeur` = 'maintenance_mode'
300
    WHERE type = 'admin' AND intitule = '".$post_no_maintenance_mode."'"
301
);
302
303
304
// add field encryption_type to ITEMS table
305
$res = addColumnIfNotExist(
306
    $pre."items",
307
    "encryption_type",
308
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
309
);
310
if ($res === false) {
311
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table ITEMS! '.mysqli_error($db_link).'!"}]';
312
    mysqli_close($db_link);
313
    exit();
314
}
315
316
317
// add field encryption_type to categories_items table
318
$res = addColumnIfNotExist(
319
    $pre."categories_items",
320
    "encryption_type",
321
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
322
);
323
if ($res === false) {
324
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table categories_items! '.mysqli_error($db_link).'!"}]';
325
    mysqli_close($db_link);
326
    exit();
327
}
328
329
330
// add field encryption_type to LOG_ITEMS table
331
$res = addColumnIfNotExist(
332
    $pre."log_items",
333
    "encryption_type",
334
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
335
);
336
if ($res === false) {
337
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table LOG_ITEMS! '.mysqli_error($db_link).'!"}]';
338
    mysqli_close($db_link);
339
    exit();
340
}
341
342
343
// add field URL to CACHE table
344
$res = addColumnIfNotExist(
345
    $pre."cache",
346
    "encryption_type",
347
    "VARCHAR(500) NOT NULL DEFAULT '0'"
348
);
349
if ($res === false) {
350
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field URL to table CACHE! '.mysqli_error($db_link).'!"}]';
351
    mysqli_close($db_link);
352
    exit();
353
}
354
355
356
// add field timestamp to CACHE table
357
$res = addColumnIfNotExist(
358
    $pre."cache",
359
    "timestamp",
360
    "VARCHAR(50) DEFAULT NULL DEFAULT '0'"
361
);
362
if ($res === false) {
363
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field url to table CACHE! '.mysqli_error($db_link).'!"}]';
364
    mysqli_close($db_link);
365
    exit();
366
}
367
368
369
// add field url to CACHE table
370
$res = addColumnIfNotExist(
371
    $pre."cache",
372
    "url",
373
    "VARCHAR(500) DEFAULT NULL"
374
);
375
if ($res === false) {
376
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field timestamp to table CACHE! '.mysqli_error($db_link).'!"}]';
377
    mysqli_close($db_link);
378
    exit();
379
}
380
381
//-- generate new DEFUSE key
382
if (isset($session_tp_defuse_installed) === false || $session_tp_defuse_installed === false) {
383
    $filename = "../includes/config/settings.php";
384
    $settingsFile = file($filename);
385 View Code Duplication
    while (list($key, $val) = each($settingsFile)) {
386
        if (substr_count($val, 'require_once "') > 0 && substr_count($val, 'sk.php') > 0) {
387
            $superGlobal->put("sk_file", substr($val, 14, strpos($val, '";') - 14), "SESSION");
388
            $session_sk_file = $superGlobal->get("sk_file", "SESSION");
389
        }
390
    }
391
392
    copy(
393
        SECUREPATH."/teampass-seckey.txt",
394
        SECUREPATH."/teampass-seckey.txt".'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
395
    );
396
    $superGlobal->put("tp_defuse_new_key", true, "SESSION");
397
    $new_salt = defuse_generate_key();
398
    file_put_contents(
399
        SECUREPATH."/teampass-seckey.txt",
400
        $new_salt
401
    );
402
    $superGlobal->put("new_salt", $new_salt, "SESSION");
403
404
    // update sk.php file
405
    copy(
406
        $session_sk_file,
0 ignored issues
show
Security File Manipulation introduced by
$session_sk_file can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_sk_file is assigned
    in install/upgrade_run_2.1.27.php on line 388

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
407
        $session_sk_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
408
    );
409
    $data = file($session_sk_file); // reads an array of lines
0 ignored issues
show
Security File Exposure introduced by
$session_sk_file can contain request data and is used in file inclusion context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_sk_file is assigned
    in install/upgrade_run_2.1.27.php on line 388

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
410
    function replace_a_line($data)
411
    {
412
        if (stristr($data, "@define('SALT'")) {
413
            return "";
414
        }
415
        return $data;
416
    }
417
    $data = array_map('replace_a_line', $data);
418
    file_put_contents($session_sk_file, implode('', $data));
0 ignored issues
show
Security File Manipulation introduced by
$session_sk_file can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_sk_file is assigned
    in install/upgrade_run_2.1.27.php on line 388

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
Security File Manipulation introduced by
implode('', $data) can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_GET
    in includes/libraries/protect/SuperGlobal/SuperGlobal.php on line 45
  2. SuperGlobal::get() returns tainted data, and $session_sk_file is assigned
    in install/upgrade_run_2.1.27.php on line 388
  3. $session_sk_file is passed through file(), and $data is assigned
    in install/upgrade_run_2.1.27.php on line 409
  4. $data is passed through array_map(), and $data is assigned
    in install/upgrade_run_2.1.27.php on line 417
  5. $data is passed through implode()
    in install/upgrade_run_2.1.27.php on line 418

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
419
420
    //
421
    //
422
    //-- users need to perform re-encryption of their personal pwds
423
    $result = mysqli_query(
424
        $db_link,
425
        "SELECT valeur FROM `".$pre."misc` WHERE type='admin' AND intitule='encryption_type'"
426
    );
427
    $row = mysqli_fetch_assoc($result);
428
    if ($row['valeur'] !== "defuse") {
429
        $result = mysqli_query(
430
            $db_link,
431
            "SELECT id FROM `".$pre."users`"
432
        );
433
        while ($row_user = mysqli_fetch_assoc($result)) {
434
            $result_items = mysqli_query(
435
                $db_link,
436
                "SELECT i.id AS item_id
437
                FROM `".$pre."nested_tree` AS n
438
                INNER JOIN `".$pre."items` AS i ON (i.id_tree = n.id)
439
                WHERE n.title = ".$row_user['id']
440
            );
441
            if (mysqli_num_rows($result_items) > 0) {
442
                mysqli_query(
443
                    $db_link,
444
                    "UPDATE `".$pre."users`
445
                    SET `upgrade_needed` = '1'
446
                    WHERE id = ".$row_user['id']
447
                );
448
            } else {
449
                mysqli_query(
450
                    $db_link,
451
                    "UPDATE `".$pre."users`
452
                    SET `upgrade_needed` = '0'
453
                    WHERE id = ".$row_user['id']
454
                );
455
            }
456
        }
457
458
        mysqli_query(
459
            $db_link,
460
            "UPDATE `".$pre."misc`
461
            SET `valeur` = 'defuse'
462
            WHERE `type`='admin' AND `initule`='encryption_type'"
463
        );
464
    }
465
} else {
466
    $_SESSION['tp_defuse_new_key'] = false;
467
}
468
//--
469
470
471
// add field encrypted_psk to Users table
472
$res = addColumnIfNotExist(
473
    $pre."users",
474
    "encrypted_psk",
475
    "TEXT NOT NULL"
476
);
477
if ($res === false) {
478
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_psk to table Users! '.mysqli_error($db_link).'!"}]';
479
    mysqli_close($db_link);
480
    exit();
481
}
482
483
484
// add new admin setting "manager_move_item"
485
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'manager_move_item'"));
486
if (intval($tmp) === 0) {
487
    mysqli_query(
488
        $db_link,
489
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'manager_move_item', '0')"
490
    );
491
}
492
493
// add new admin setting "create_item_without_password"
494
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'create_item_without_password'"));
495
if (intval($tmp) === 0) {
496
    mysqli_query(
497
        $db_link,
498
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'create_item_without_password', '0')"
499
    );
500
}
501
502
// add new admin setting "send_statistics_items"
503
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'send_statistics_items'"));
504
if (intval($tmp) === 0) {
505
    mysqli_query(
506
        $db_link,
507
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('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;')"
508
    );
509
}
510
511
// add new admin setting "send_stats_time"
512
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'send_stats_time'"));
513 View Code Duplication
if (intval($tmp) === 0) {
514
    mysqli_query(
515
        $db_link,
516
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'send_stats_time', '".(time() - 2592000)."')"
517
    );
518
}
519
520
// add new admin setting "agses_authentication_enabled"
521
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'agses_authentication_enabled'"));
522
if (intval($tmp) === 0) {
523
    mysqli_query(
524
        $db_link,
525
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'agses_authentication_enabled', '0')"
526
    );
527
}
528
529
// add new admin setting "timezone"
530
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'timezone'"));
531
if (intval($tmp) === 0) {
532
    mysqli_query(
533
        $db_link,
534
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'timezone', 'UTC')"
535
    );
536
}
537
538
// add new admin setting "personal_saltkey_security_level"
539
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'personal_saltkey_security_level'"));
540
if (intval($tmp) === 0) {
541
    mysqli_query(
542
        $db_link,
543
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'personal_saltkey_security_level', '0')"
544
    );
545
}
546
547
// add new admin setting "item_extra_fields"
548
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'item_extra_fields'"));
549
if (intval($tmp) === 0) {
550
    mysqli_query(
551
        $db_link,
552
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'item_extra_fields', '0')"
553
    );
554
}
555
556
// add new admin setting "ldap_new_user_is_administrated_by"
557
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'ldap_new_user_is_administrated_by'"));
558
if (intval($tmp) === 0) {
559
    mysqli_query(
560
        $db_link,
561
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'ldap_new_user_is_administrated_by', '0')"
562
    );
563
}
564
565
566
// add new language "portuges_br"
567
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'portuguese_br'"));
568
if (intval($tmp) === 0) {
569
    mysqli_query(
570
        $db_link,
571
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('portuguese_br', 'Portuguese_br', 'pr-bt', 'pr-bt.png')"
572
    );
573
}
574
575
576
// alter table USERS to add a new field "ga_temporary_code"
577
mysqli_query(
578
    $db_link,
579
    "ALTER TABLE `".$pre."users` ADD `ga_temporary_code` VARCHAR(20) NOT NULL DEFAULT 'none' AFTER `ga`;"
580
);
581
// alter table USERS to add a new field "user_ip"
582 View Code Duplication
if (columnExists($pre."users", "user_ip") === true) {
583
    // Change name of field
584
    mysqli_query($db_link, "ALTER TABLE `".$pre."users` CHANGE `user_ip` `user_ip` VARCHAR(400) NOT NULL DEFAULT 'none'");
585
} else {
586
    // alter table misc to add an index
587
    $res = addColumnIfNotExist(
588
        $pre."users",
589
        "user_ip",
590
        "VARCHAR(400) NOT NULL DEFAULT 'none'"
591
    );
592
}
593
594
// alter table USERS to allow NULL on field "email"
595
mysqli_query(
596
    $db_link,
597
    "ALTER TABLE `".$pre."users` CHANGE `email` `email` VARCHAR(300) NOT NULL DEFAULT 'none';"
598
);
599
600
601
// alter table EXPORT to add a new fields
602
mysqli_query(
603
    $db_link,
604
    "ALTER TABLE `".$pre."export` ADD `email` VARCHAR(500) NOT NULL DEFAULT 'none';"
605
);
606
mysqli_query(
607
    $db_link,
608
    "ALTER TABLE `".$pre."export` ADD `url` VARCHAR(500) NOT NULL DEFAULT 'none';"
609
);
610
mysqli_query(
611
    $db_link,
612
    "ALTER TABLE `".$pre."export` ADD `kbs` VARCHAR(500) NOT NULL DEFAULT 'none';"
613
);
614
mysqli_query(
615
    $db_link,
616
    "ALTER TABLE `".$pre."export` ADD `tags` VARCHAR(500) NOT NULL DEFAULT 'none';"
617
);
618
619
mysqli_query(
620
    $db_link,
621
    "ALTER TABLE `".$pre."misc` CHANGE valeur valeur VARCHAR(500) NOT NULL DEFAULT 'none'"
622
);
623
624
// alter table ITEMS_CHANGE
625
mysqli_query(
626
    $db_link,
627
    "ALTER TABLE `".$pre."items_change` CHANGE user_id user_id INT(12) NOT NULL;"
628
);
629
630
// alter table ITEMS
631
mysqli_query(
632
    $db_link,
633
    "ALTER TABLE `".$pre."items` CHANGE auto_update_pwd_next_date auto_update_pwd_next_date VARCHAR(100) NOT NULL DEFAULT '0';"
634
);
635
636
637
// add new admin setting "otv_is_enabled"
638
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'otv_is_enabled'"));
639
if (intval($tmp) === 0) {
640
    mysqli_query(
641
        $db_link,
642
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'otv_is_enabled', '0')"
643
    );
644
}
645
646
647
// add new field for items_change
648
mysqli_query(
649
    $db_link,
650
    "CREATE TABLE IF NOT EXISTS `".$pre."items_change` (
651
    `id` int(12) NOT NULL AUTO_INCREMENT,
652
    `item_id` int(12) NOT NULL,
653
    `label` varchar(255) NOT NULL DEFAULT 'none',
654
    `pw` text NOT NULL,
655
    `login` varchar(255) NOT NULL DEFAULT 'none',
656
    `email` varchar(255) NOT NULL DEFAULT 'none',
657
    `url` varchar(255) NOT NULL DEFAULT 'none',
658
    `description` text NOT NULL,
659
    `comment` text NOT NULL,
660
    `folder_id` tinyint(12) NOT NULL,
661
    `user_id` tinyint(12) NOT NULL,
662
    `timestamp` varchar(50) NOT NULL DEFAULT 'none',
663
    PRIMARY KEY (`id`)
664
    ) CHARSET=utf8;"
665
);
666
667
668
669
// File encryption
670
// add field status to FILE table
671
$res = addColumnIfNotExist(
672
    $pre."files",
673
    "status",
674
    "VARCHAR(50) NOT NULL DEFAULT '0'"
675
);
676
if ($res === false) {
677
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field agses-usercardid to table Users! '.mysqli_error($db_link).'!"}]';
678
    mysqli_close($db_link);
679
    exit();
680
}
681
682
// fill in this new field with the current "encryption-file" status
683
$tmp = mysqli_fetch_row(mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'enable_attachment_encryption'"));
684
if (!empty($tmp[0])) {
685
    if ($tmp[0] === "1") {
686
        $status = "encrypted";
687
    } else {
688
        $status = "clear";
689
    }
690
    mysqli_query($db_link, "update `".$pre."files` set status = '".$status."' where 1 = 1");
691
}
692
693
694
// add 2 generic users
695
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."users` WHERE id = '9999991' AND login = 'OTV'"));
696
if (intval($tmp) === 0) {
697
    mysqli_query(
698
        $db_link,
699
        "INSERT INTO `".$pre."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 ('9999991', 'OTV', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
700
    );
701
}
702
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."users` WHERE id = '9999991' AND login = 'OTV'"));
703
if (intval($tmp) === 0) {
704
    mysqli_query(
705
        $db_link,
706
        "INSERT INTO `".$pre."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 ('9999999', 'API', '', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')"
707
    );
708
}
709
710
711
// Update favico to favicon
712
$result = mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE intitule = 'cpassman_url' AND type = 'admin'");
713
$rows = mysqli_fetch_assoc($result);
714
mysqli_free_result($result);
715
mysqli_query(
716
    $db_link,
717
    "UPDATE `".$pre."misc`
718
    SET `valeur` = '".$rows['valeur']."/favicon.ico'
719
    WHERE intitule = 'favicon' AND type = 'admin'"
720
);
721
722
723
// Remove some indexes
724
mysqli_query($db_link, "ALTER TABLE ".$pre."nested_tree` DROP INDEX `id`;");
725
mysqli_query($db_link, "ALTER TABLE ".$pre."tags` DROP INDEX `id`;");
726
727
728
/*
729
* Introduce new CONFIG file
730
*/
731
$tp_config_file = "../includes/config/tp.config.php";
732 View Code Duplication
if (file_exists($tp_config_file)) {
733
    if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
734
        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.'"}]';
735
        return false;
736
    } else {
737
        unlink($tp_config_file);
738
    }
739
}
740
$file_handler = fopen($tp_config_file, 'w');
741
$config_text = "";
742
$any_settings = false;
743
744
$result = mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin'");
745 View Code Duplication
while ($row = mysqli_fetch_assoc($result)) {
746
    // append new setting in config file
747
    $config_text .= "
748
    '".$row['intitule']."' => '".$row['valeur']."',";
749
    if ($any_settings === false) {
750
        $any_settings = true;
751
    }
752
}
753
mysqli_free_result($result);
754
755
// write to config file
756 View Code Duplication
if ($any_settings === true) {
757
    $result = fwrite(
758
        $file_handler,
759
        utf8_encode(
760
            "<?php
761
global \$SETTINGS;
762
\$SETTINGS = array (" . $config_text . "
763
    );"
764
        )
765
    );
766
}
767
fclose($file_handler);
768
769
770
771
// Finished
772
echo '[{"finish":"1" , "next":"", "error":""}]';
773