Completed
Push — development ( b35951...20b5a5 )
by Nils
07:29
created

upgrade_run_2.1.27.php ➔ columnExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 9
rs 9.6666
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
function columnExists($tablename, $column)
150
{
151
    $checkcolumn = mysqli_query($db_link, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{$tablename}' AND COLUMN_NAME = '{$column}';");
0 ignored issues
show
Bug introduced by
The variable $db_link does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

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

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...
403
        $session_sk_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
404
    );
405
    $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 384

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...
406
    function replace_a_line($data)
407
    {
408
        if (stristr($data, "@define('SALT'")) {
409
            return "";
410
        }
411
        return $data;
412
    }
413
    $data = array_map('replace_a_line', $data);
414
    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 384

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

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