Completed
Push — development ( 676bb1...171946 )
by Nils
08:33
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) !== true) {
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 to add an index
192
mysqli_query(
193
    $db_link,
194
    "ALTER TABLE `".$pre."misc` ADD `id` INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`id`)"
195
);
196
197
// alter table misc to add an index
198
mysqli_query(
199
    $db_link,
200
    "ALTER TABLE `".$pre."log_items` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
201
);
202
203
// add field agses-usercardid to Users table
204
$res = addColumnIfNotExist(
205
    $pre."users",
206
    "agses-usercardid",
207
    "VARCHAR(12) NOT NULL DEFAULT '0'"
208
);
209 View Code Duplication
if ($res === false) {
210
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field agses-usercardid to table Users! '.mysqli_error($db_link).'!"}]';
211
    mysqli_close($db_link);
212
    exit();
213
}
214
215
216
// add field encrypted_data to Categories table
217
$res = addColumnIfNotExist(
218
    $pre."categories",
219
    "encrypted_data",
220
    "TINYINT(1) NOT NULL DEFAULT '1'"
221
);
222 View Code Duplication
if ($res === false) {
223
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table categories! '.mysqli_error($db_link).'!"}]';
224
    mysqli_close($db_link);
225
    exit();
226
}
227
228
229
// alter table USERS - user_language
230
mysqli_query($db_link, "ALTER TABLE `".$pre."users` MODIFY user_language VARCHAR(50) NOT NULL DEFAULT '0'");
231
232
// alter table USERS - just ensure correct naming of IsAdministratedByRole
233
mysqli_query($db_link, "ALTER TABLE `".$pre."users` CHANGE IsAdministratedByRole isAdministratedByRole tinyint(5) NOT NULL DEFAULT '0'");
234
235
// alter table OTV
236
mysqli_query($db_link, "ALTER TABLE `".$pre."otv` CHANGE originator originator int(12) NOT NULL DEFAULT '0'");
237
238
// do clean of users table
239
$fieldsToUpdate = ['groupes_visibles', 'fonction_id', 'groupes_interdits'];
240
$result = mysqli_query($db_link, "SELECT id, groupes_visibles, fonction_id, groupes_interdits FROM `".$pre."users`");
241
while ($row = mysqli_fetch_assoc($result)) {
242
    // check if field contains , instead of ;
243
    foreach ($fieldsToUpdate as $field) {
244
        $tmp = cleanFields($row[$field]);
245
        if ($tmp !== $row[$field]) {
246
            mysqli_query(
247
                $db_link,
248
                "UPDATE `".$pre."users`
249
                SET `".$field."` = '".$tmp."'
250
                WHERE id = '".$row['id']."'"
251
            );
252
        }
253
    }
254
}
255
mysqli_free_result($result);
256
257
258
// alter table KB_ITEMS
259
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `kb_id` `kb_id` INT(12) NOT NULL");
260
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `item_id` `item_id` INT(12) NOT NULL");
261
262
263
// add field encrypted_data to CATEGORIES table
264
$res = addColumnIfNotExist(
265
    $pre."categories",
266
    "encrypted_data",
267
    "TINYINT(1) NOT NULL DEFAULT '1'"
268
);
269 View Code Duplication
if ($res === false) {
270
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table CATEGORIES! '.mysqli_error($db_link).'!"}]';
271
    mysqli_close($db_link);
272
    exit();
273
}
274
275
mysqli_query(
276
    $db_link,
277
    "UPDATE `".$pre."misc`
278
    SET `valeur` = 'maintenance_mode'
279
    WHERE type = 'admin' AND intitule = '".$post_no_maintenance_mode."'"
280
);
281
282
283
// add field encryption_type to ITEMS table
284
$res = addColumnIfNotExist(
285
    $pre."items",
286
    "encryption_type",
287
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
288
);
289 View Code Duplication
if ($res === false) {
290
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table ITEMS! '.mysqli_error($db_link).'!"}]';
291
    mysqli_close($db_link);
292
    exit();
293
}
294
295
296
// add field encryption_type to categories_items table
297
$res = addColumnIfNotExist(
298
    $pre."categories_items",
299
    "encryption_type",
300
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
301
);
302 View Code Duplication
if ($res === false) {
303
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table categories_items! '.mysqli_error($db_link).'!"}]';
304
    mysqli_close($db_link);
305
    exit();
306
}
307
308
309
// add field encryption_type to LOG_ITEMS table
310
$res = addColumnIfNotExist(
311
    $pre."log_items",
312
    "encryption_type",
313
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
314
);
315 View Code Duplication
if ($res === false) {
316
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table LOG_ITEMS! '.mysqli_error($db_link).'!"}]';
317
    mysqli_close($db_link);
318
    exit();
319
}
320
321
322
// add field URL to CACHE table
323
$res = addColumnIfNotExist(
324
    $pre."cache",
325
    "encryption_type",
326
    "VARCHAR(500) NOT NULL DEFAULT '0'"
327
);
328 View Code Duplication
if ($res === false) {
329
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field URL to table CACHE! '.mysqli_error($db_link).'!"}]';
330
    mysqli_close($db_link);
331
    exit();
332
}
333
334
335
// add field timestamp to CACHE table
336
$res = addColumnIfNotExist(
337
    $pre."cache",
338
    "timestamp",
339
    "VARCHAR(50) DEFAULT NULL DEFAULT '0'"
340
);
341 View Code Duplication
if ($res === false) {
342
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field url to table CACHE! '.mysqli_error($db_link).'!"}]';
343
    mysqli_close($db_link);
344
    exit();
345
}
346
347
348
// add field url to CACHE table
349
$res = addColumnIfNotExist(
350
    $pre."cache",
351
    "url",
352
    "VARCHAR(500) DEFAULT NULL"
353
);
354 View Code Duplication
if ($res === false) {
355
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field timestamp to table CACHE! '.mysqli_error($db_link).'!"}]';
356
    mysqli_close($db_link);
357
    exit();
358
}
359
360
//-- generate new DEFUSE key
361
if (!isset($session_tp_defuse_installed) || $session_tp_defuse_installed === false) {
362
    $filename = "../includes/config/settings.php";
363
    $settingsFile = file($filename);
364 View Code Duplication
    while (list($key, $val) = each($settingsFile)) {
365
        if (substr_count($val, 'require_once "') > 0 && substr_count($val, 'sk.php') > 0) {
366
            $superGlobal->put("sk_file", substr($val, 14, strpos($val, '";') - 14), "SESSION");
367
            $session_sk_file = $superGlobal->get("sk_file", "SESSION");
368
        }
369
    }
370
371
    copy(
372
        SECUREPATH."/teampass-seckey.txt",
373
        SECUREPATH."/teampass-seckey.txt".'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
374
    );
375
    $superGlobal->put("tp_defuse_new_key", true, "SESSION");
376
    $new_salt = defuse_generate_key();
377
    file_put_contents(
378
        SECUREPATH."/teampass-seckey.txt",
379
        $new_salt
380
    );
381
    $superGlobal->put("new_salt", $new_salt, "SESSION");
382
383
    // update sk.php file
384
    copy(
385
        $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 367

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...
386
        $session_sk_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
387
    );
388
    $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 367

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...
389
    function replace_a_line($data)
390
    {
391
        if (stristr($data, "@define('SALT'")) {
392
            return "";
393
        }
394
        return $data;
395
    }
396
    $data = array_map('replace_a_line', $data);
397
    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 367

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

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