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

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...
397
        $session_sk_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
398
    );
399
    $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 378

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...
400
    function replace_a_line($data)
401
    {
402
        if (stristr($data, "@define('SALT'")) {
403
            return "";
404
        }
405
        return $data;
406
    }
407
    $data = array_map('replace_a_line', $data);
408
    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 378

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 378
  3. $session_sk_file is passed through file(), and $data is assigned
    in install/upgrade_run_2.1.27.php on line 399
  4. $data is passed through array_map(), and $data is assigned
    in install/upgrade_run_2.1.27.php on line 407
  5. $data is passed through implode()
    in install/upgrade_run_2.1.27.php on line 408

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