Completed
Push — development ( a62382...1718fc )
by Nils
17:49 queued 04:38
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 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 (L158-168) is considered.

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

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

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

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

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

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

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

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

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

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

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

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

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

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

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

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

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

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

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

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

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

Loading history...
130
 */
131
function cleanFields($txt)
132
{
133
    $tmp = str_replace(",", ";", trim($txt));
134
    if (empty($tmp)) {
135
        return $tmp;
136
    }
137
    if ($tmp === ";") {
138
        return "";
139
    }
140
    if (strpos($tmp, ';') === 0) {
141
        $tmp = substr($tmp, 1);
142
    }
143
    if (substr($tmp, -1) !== ";") {
144
        $tmp = $tmp.";";
145
    }
146
    return $tmp;
147
}
148
149
/*
150
** Checks if the column exists in the table
151
*/
152
function columnExists($tablename, $column)
153
{
154
    global $db_link;
155
    $checkcolumn = mysqli_query($db_link, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{$tablename}' AND COLUMN_NAME = '{$column}';");
156
    if (mysqli_num_rows($checkcolumn) > 0) {
157
        return true;
158
    } else {
159
        return false;
160
    }
161
}
162
163
// 2.1.27 introduce new encryption protocol with DEFUSE library.
164
// Now evaluate if current instance has already this version
165
$tmp = mysqli_fetch_row(mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'teampass_version'"));
166
if (count($tmp[0]) === 0 || empty($tmp[0])) {
167
    mysqli_query(
168
        $db_link,
169
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'teampass_version', '".$SETTINGS_EXT['version']."')"
170
    );
171
} else {
172
    mysqli_query(
173
        $db_link,
174
        "UPDATE `".$pre."misc`
175
        SET `valeur` = '".$SETTINGS_EXT['version']."'
176
        WHERE intitule = 'teampass_version' AND type = 'admin'"
177
    );
178
}
179
180
// add new admin setting "migration_to_2127"
181
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'migration_to_2127'"));
182
if (intval($tmp) === 0) {
183
    mysqli_query(
184
        $db_link,
185
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'migration_to_2127', '0')"
186
    );
187
}
188
189
190
// check if library defuse already on-going here
191
// if yes, then don't execute re-encryption
192
if (isset($session_tp_defuse_installed) === false) {
193
    $superGlobal->put("tp_defuse_installed", false, "SESSION");
194
    if (columnExists($pre."items", "encryption_type") === true) {
195
        $superGlobal->put("tp_defuse_installed", true, "SESSION");
196
    }
197
}
198
199
// alter table Items
200
mysqli_query($db_link, "ALTER TABLE `".$pre."items` MODIFY pw_len INT(5) NOT NULL DEFAULT '0'");
201
202
// alter table MISC - rename ID is exists
203
$res = addColumnIfNotExist(
204
    $pre."misc",
205
    "increment_id",
206
    "INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
207
);
208 View Code Duplication
if ($res === true) {
209
  // Change name of field
210
  mysqli_query($db_link, "ALTER TABLE `".$pre."misc` CHANGE `id` `increment_id` INT(12) NOT NULL AUTO_INCREMENT");
211
} elseif ($res === false) {
212
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding increment_id user_ip to table misc! '.mysqli_error($db_link).'!"}]';
213
    mysqli_close($db_link);
214
    exit();
215
}
216
217
218
// alter table misc to add an index
219
mysqli_query(
220
    $db_link,
221
    "ALTER TABLE `".$pre."log_items` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
222
);
223
// create index
224
mysqli_query(
225
    $db_link,
226
    "CREATE INDEX teampass_log_items_id_item_IDX ON ".$pre."log_items (id_item, date);"
227
);
228
229
// add field agses-usercardid to Users table
230
$res = addColumnIfNotExist(
231
    $pre."users",
232
    "agses-usercardid",
233
    "VARCHAR(12) NOT NULL DEFAULT '0'"
234
);
235
if ($res === false) {
236
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field agses-usercardid to table Users! '.mysqli_error($db_link).'!"}]';
237
    mysqli_close($db_link);
238
    exit();
239
}
240
241
242
// add field encrypted_data to Categories table
243
$res = addColumnIfNotExist(
244
    $pre."categories",
245
    "encrypted_data",
246
    "TINYINT(1) NOT NULL DEFAULT '1'"
247
);
248
if ($res === false) {
249
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table categories! '.mysqli_error($db_link).'!"}]';
250
    mysqli_close($db_link);
251
    exit();
252
}
253
254
255
// alter table USERS - user_language
256
mysqli_query($db_link, "ALTER TABLE `".$pre."users` MODIFY user_language VARCHAR(50) NOT NULL DEFAULT '0'");
257
258
// alter table USERS - just ensure correct naming of IsAdministratedByRole
259
mysqli_query($db_link, "ALTER TABLE `".$pre."users` CHANGE IsAdministratedByRole isAdministratedByRole tinyint(5) NOT NULL DEFAULT '0'");
260
261
// alter table OTV
262
mysqli_query($db_link, "ALTER TABLE `".$pre."otv` CHANGE originator originator int(12) NOT NULL DEFAULT '0'");
263
264
// do clean of users table
265
$fieldsToUpdate = ['groupes_visibles', 'fonction_id', 'groupes_interdits'];
266
$result = mysqli_query($db_link, "SELECT id, groupes_visibles, fonction_id, groupes_interdits FROM `".$pre."users`");
267
while ($row = mysqli_fetch_assoc($result)) {
268
    // check if field contains , instead of ;
269
    foreach ($fieldsToUpdate as $field) {
270
        $tmp = cleanFields($row[$field]);
271
        if ($tmp !== $row[$field]) {
272
            mysqli_query(
273
                $db_link,
274
                "UPDATE `".$pre."users`
275
                SET `".$field."` = '".$tmp."'
276
                WHERE id = '".$row['id']."'"
277
            );
278
        }
279
    }
280
}
281
mysqli_free_result($result);
282
283
284
// alter table KB_ITEMS
285
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `kb_id` `kb_id` INT(12) NOT NULL");
286
mysqli_query($db_link, "ALTER TABLE `".$pre."kb_items` CHANGE `item_id` `item_id` INT(12) NOT NULL");
287
288
289
// Alter table EXPORT - adapt field Label
290
mysqli_query($db_link, "ALTER TABLE `".$pre."export` CHANGE `label` `label` VARCHAR(500) NOT NULL");
291
292
// add field encrypted_data to CATEGORIES table
293
$res = addColumnIfNotExist(
294
    $pre."categories",
295
    "encrypted_data",
296
    "TINYINT(1) NOT NULL DEFAULT '1'"
297
);
298
if ($res === false) {
299
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_data to table CATEGORIES! '.mysqli_error($db_link).'!"}]';
300
    mysqli_close($db_link);
301
    exit();
302
}
303
304
mysqli_query(
305
    $db_link,
306
    "UPDATE `".$pre."misc`
307
    SET `valeur` = 'maintenance_mode'
308
    WHERE type = 'admin' AND intitule = '".$post_no_maintenance_mode."'"
309
);
310
311
312
// add field encryption_type to ITEMS table
313
$res = addColumnIfNotExist(
314
    $pre."items",
315
    "encryption_type",
316
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
317
);
318
if ($res === false) {
319
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table ITEMS! '.mysqli_error($db_link).'!"}]';
320
    mysqli_close($db_link);
321
    exit();
322
}
323
324
325
// add field encryption_type to categories_items table
326
$res = addColumnIfNotExist(
327
    $pre."categories_items",
328
    "encryption_type",
329
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
330
);
331
if ($res === false) {
332
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table categories_items! '.mysqli_error($db_link).'!"}]';
333
    mysqli_close($db_link);
334
    exit();
335
}
336
337
338
// add field encryption_type to LOG_ITEMS table
339
$res = addColumnIfNotExist(
340
    $pre."log_items",
341
    "encryption_type",
342
    "VARCHAR(20) NOT NULL DEFAULT 'not_set'"
343
);
344
if ($res === false) {
345
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encryption_type to table LOG_ITEMS! '.mysqli_error($db_link).'!"}]';
346
    mysqli_close($db_link);
347
    exit();
348
}
349
350
351
// add field URL to CACHE table
352
$res = addColumnIfNotExist(
353
    $pre."cache",
354
    "encryption_type",
355
    "VARCHAR(500) NOT NULL DEFAULT '0'"
356
);
357
if ($res === false) {
358
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field URL to table CACHE! '.mysqli_error($db_link).'!"}]';
359
    mysqli_close($db_link);
360
    exit();
361
}
362
363
364
// add field timestamp to CACHE table
365
$res = addColumnIfNotExist(
366
    $pre."cache",
367
    "timestamp",
368
    "VARCHAR(50) DEFAULT NULL DEFAULT '0'"
369
);
370
if ($res === false) {
371
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field url to table CACHE! '.mysqli_error($db_link).'!"}]';
372
    mysqli_close($db_link);
373
    exit();
374
}
375
376
377
// add field url to CACHE table
378
$res = addColumnIfNotExist(
379
    $pre."cache",
380
    "url",
381
    "VARCHAR(500) DEFAULT NULL"
382
);
383
if ($res === false) {
384
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field timestamp to table CACHE! '.mysqli_error($db_link).'!"}]';
385
    mysqli_close($db_link);
386
    exit();
387
}
388
389
390
// alter table CACHE to add an index
391
mysqli_query(
392
    $db_link,
393
    "ALTER TABLE `".$pre."cache` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`increment_id`)"
394
);
395
396
397
// alter table EXPORT to add an index
398
mysqli_query(
399
    $db_link,
400
    "ALTER TABLE `".$pre."export` ADD INDEX `id_idx` (`id`)"
401
);
402
403
// alter table ITEMS_EDITION to add an index
404
mysqli_query(
405
    $db_link,
406
    "ALTER TABLE `".$pre."items_edition` ADD INDEX `item_id_idx` (`item_id`)"
407
);
408
409
410
// alter table NESTEED_TREE to add an index
411
mysqli_query(
412
    $db_link,
413
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `nested_tree_parent_id` (`parent_id`)"
414
);
415
mysqli_query(
416
    $db_link,
417
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `nested_tree_nleft` (`nleft`)"
418
);
419
mysqli_query(
420
    $db_link,
421
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `nested_tree_nright` (`nright`)"
422
);
423
mysqli_query(
424
    $db_link,
425
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `nested_tree_nlevel` (`nlevel`)"
426
);
427
mysqli_query(
428
    $db_link,
429
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `personal_folder_idx` (`personal_folder`)"
430
);
431
mysqli_query(
432
    $db_link,
433
    "ALTER TABLE `".$pre."nested_tree` ADD KEY `id` (`id`)"
434
);
435
436
437
438
// alter table ROLES_VALUES to add an index
439
mysqli_query(
440
    $db_link,
441
    "ALTER TABLE `".$pre."roles_values` ADD KEY `role_id_idx` (`role_id`)"
442
);
443
// alter table ROLES_VALUES to add a primary key
444
mysqli_query(
445
    $db_link,
446
    "ALTER TABLE `".$pre."roles_values` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT PRIMARY KEY"
447
);
448
449
450
// alter table KB_ITEMS to add an index
451
mysqli_query(
452
    $db_link,
453
    "ALTER TABLE `".$pre."kb_items` ADD PRIMARY KEY (`kb_id`)"
454
);
455
456
457
// alter table EMAILS to add an index
458
mysqli_query(
459
    $db_link,
460
    "ALTER TABLE `".$pre."emails` ADD `increment_id` INT(12) NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (`increment_id`)"
461
);
462
463
464
// alter table AUTOMATIC_DEL to add an index
465
mysqli_query(
466
    $db_link,
467
    "ALTER TABLE `".$pre."automatic_del` ADD PRIMARY KEY (`item_id`)"
468
);
469
470
471
// alter table CATEGORY_FOLDERS to add an index
472
mysqli_query(
473
    $db_link,
474
    "ALTER TABLE `".$pre."categories_folders` ADD PRIMARY KEY (`id_category`)"
475
);
476
477
478
//-- generate new DEFUSE key
479
if (isset($session_tp_defuse_installed) === false || $session_tp_defuse_installed === false) {
480
    $filename = "../includes/config/settings.php";
481
    $settingsFile = file($filename);
482 View Code Duplication
    while (list($key, $val) = each($settingsFile)) {
483
        if (substr_count($val, 'require_once "') > 0 && substr_count($val, 'sk.php') > 0) {
484
            $superGlobal->put("sk_file", substr($val, 14, strpos($val, '";') - 14), "SESSION");
485
            $session_sk_file = $superGlobal->get("sk_file", "SESSION");
486
        }
487
    }
488
489
    copy(
490
        SECUREPATH."/teampass-seckey.txt",
491
        SECUREPATH."/teampass-seckey.txt".'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
492
    );
493
    $superGlobal->put("tp_defuse_new_key", true, "SESSION");
494
    $new_salt = defuse_generate_key();
495
    file_put_contents(
496
        SECUREPATH."/teampass-seckey.txt",
497
        $new_salt
498
    );
499
    $superGlobal->put("new_salt", $new_salt, "SESSION");
500
501
    // update sk.php file
502
    copy(
503
        $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 485

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...
504
        $session_sk_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))).".".time()
505
    );
506
    $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 485

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...
507
    function replace_a_line($data)
508
    {
509
        if (stristr($data, "@define('SALT'")) {
510
            return "";
511
        }
512
        return $data;
513
    }
514
    $data = array_map('replace_a_line', $data);
515
    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 485

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

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...
516
517
    //
518
    //
519
    //-- users need to perform re-encryption of their personal pwds
520
    $result = mysqli_query(
521
        $db_link,
522
        "SELECT valeur FROM `".$pre."misc` WHERE type='admin' AND intitule='encryption_type'"
523
    );
524
    $row = mysqli_fetch_assoc($result);
525
    if ($row['valeur'] !== "defuse") {
526
        $result = mysqli_query(
527
            $db_link,
528
            "SELECT id FROM `".$pre."users`"
529
        );
530
        while ($row_user = mysqli_fetch_assoc($result)) {
531
            $result_items = mysqli_query(
532
                $db_link,
533
                "SELECT i.id AS item_id
534
                FROM `".$pre."nested_tree` AS n
535
                INNER JOIN `".$pre."items` AS i ON (i.id_tree = n.id)
536
                WHERE n.title = ".$row_user['id']
537
            );
538
            if (mysqli_num_rows($result_items) > 0) {
539
                mysqli_query(
540
                    $db_link,
541
                    "UPDATE `".$pre."users`
542
                    SET `upgrade_needed` = '1'
543
                    WHERE id = ".$row_user['id']
544
                );
545
            } else {
546
                mysqli_query(
547
                    $db_link,
548
                    "UPDATE `".$pre."users`
549
                    SET `upgrade_needed` = '0'
550
                    WHERE id = ".$row_user['id']
551
                );
552
            }
553
        }
554
555
        mysqli_query(
556
            $db_link,
557
            "UPDATE `".$pre."misc`
558
            SET `valeur` = 'defuse'
559
            WHERE `type`='admin' AND `initule`='encryption_type'"
560
        );
561
    }
562
} else {
563
    $_SESSION['tp_defuse_new_key'] = false;
564
}
565
//--
566
567
568
// add field encrypted_psk to Users table
569
$res = addColumnIfNotExist(
570
    $pre."users",
571
    "encrypted_psk",
572
    "TEXT NOT NULL"
573
);
574
if ($res === false) {
575
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field encrypted_psk to table Users! '.mysqli_error($db_link).'!"}]';
576
    mysqli_close($db_link);
577
    exit();
578
}
579
580
581
// add new admin setting "manager_move_item"
582
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'manager_move_item'"));
583
if (intval($tmp) === 0) {
584
    mysqli_query(
585
        $db_link,
586
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'manager_move_item', '0')"
587
    );
588
}
589
590
// add new admin setting "create_item_without_password"
591
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'create_item_without_password'"));
592
if (intval($tmp) === 0) {
593
    mysqli_query(
594
        $db_link,
595
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'create_item_without_password', '0')"
596
    );
597
}
598
599
// add new admin setting "send_statistics_items"
600
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'send_statistics_items'"));
601
if (intval($tmp) === 0) {
602
    mysqli_query(
603
        $db_link,
604
        "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;')"
605
    );
606
}
607
608
// add new admin setting "send_stats_time"
609
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'send_stats_time'"));
610 View Code Duplication
if (intval($tmp) === 0) {
611
    mysqli_query(
612
        $db_link,
613
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'send_stats_time', '".(time() - 2592000)."')"
614
    );
615
}
616
617
// add new admin setting "agses_authentication_enabled"
618
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'agses_authentication_enabled'"));
619
if (intval($tmp) === 0) {
620
    mysqli_query(
621
        $db_link,
622
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'agses_authentication_enabled', '0')"
623
    );
624
}
625
626
// add new admin setting "timezone"
627
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'timezone'"));
628
if (intval($tmp) === 0) {
629
    mysqli_query(
630
        $db_link,
631
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'timezone', 'UTC')"
632
    );
633
}
634
635
// add new admin setting "personal_saltkey_security_level"
636
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'personal_saltkey_security_level'"));
637
if (intval($tmp) === 0) {
638
    mysqli_query(
639
        $db_link,
640
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'personal_saltkey_security_level', '0')"
641
    );
642
}
643
644
// add new admin setting "item_extra_fields"
645
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'item_extra_fields'"));
646
if (intval($tmp) === 0) {
647
    mysqli_query(
648
        $db_link,
649
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'item_extra_fields', '0')"
650
    );
651
}
652
653
// add new admin setting "ldap_new_user_is_administrated_by"
654
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'ldap_new_user_is_administrated_by'"));
655
if (intval($tmp) === 0) {
656
    mysqli_query(
657
        $db_link,
658
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'ldap_new_user_is_administrated_by', '0')"
659
    );
660
}
661
662
663
// add new admin setting "ldap_port"
664
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'ldap_port'"));
665
if (intval($tmp) === 0) {
666
    mysqli_query(
667
        $db_link,
668
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'ldap_port', '389')"
669
    );
670
}
671
672
// add new admin setting "offline_key_level"
673
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'offline_key_level'"));
674
if (intval($tmp) === 0) {
675
    mysqli_query(
676
        $db_link,
677
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'offline_key_level', '0')"
678
    );
679
}
680
681
// add new admin setting "enable_http_request_login"
682
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'enable_http_request_login'"));
683
if (intval($tmp) === 0) {
684
    mysqli_query(
685
        $db_link,
686
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'enable_http_request_login', '0')"
687
    );
688
}
689
690
691
// add new language "portuges_br"
692
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'portuguese_br'"));
693
if (intval($tmp) === 0) {
694
    mysqli_query(
695
        $db_link,
696
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('portuguese_br', 'Portuguese_br', 'pr-bt', 'pr-bt.png')"
697
    );
698
}
699
700
701
// add new language "Ukrainian"
702
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'ukrainian'"));
703
if (intval($tmp) === 0) {
704
    mysqli_query(
705
        $db_link,
706
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('ukrainian', 'Ukrainian', 'ua', 'ua.png')"
707
    );
708
}
709
710
711
// add new language "Romanian"
712
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'romanian'"));
713
if (intval($tmp) === 0) {
714
    mysqli_query(
715
        $db_link,
716
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('romanian', 'Romanian', 'ro', 'ro.png')"
717
    );
718
}
719
720
721
// add new language "Polish"
722
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'polish'"));
723
if (intval($tmp) === 0) {
724
    mysqli_query(
725
        $db_link,
726
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('polish', 'Polish', 'po', 'po.png')"
727
    );
728
}
729
730
731
// add new language "Hungarian"
732
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'hungarian'"));
733
if (intval($tmp) === 0) {
734
    mysqli_query(
735
        $db_link,
736
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('hungarian', 'Hungarian', 'hu', 'hu.png')"
737
    );
738
}
739
740
741
// add new language "Greek"
742
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'greek'"));
743
if (intval($tmp) === 0) {
744
    mysqli_query(
745
        $db_link,
746
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('greek', 'Greek', 'gr', 'gr.png')"
747
    );
748
}
749
750
751
// add new language "Bulgarian"
752
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."languages` WHERE name = 'bulgarian'"));
753
if (intval($tmp) === 0) {
754
    mysqli_query(
755
        $db_link,
756
        "INSERT INTO `".$pre."languages` (`name`, `label`, `code`, `flag`) VALUES ('bulgarian', 'Bulgarian', 'bg', 'bg.png')"
757
    );
758
}
759
760
761
// alter table USERS to add a new field "ga_temporary_code"
762
mysqli_query(
763
    $db_link,
764
    "ALTER TABLE `".$pre."users` ADD `ga_temporary_code` VARCHAR(20) NOT NULL DEFAULT 'none' AFTER `ga`;"
765
);
766
767
768
// alter table USERS to add a new field "user_ip"
769
$res = addColumnIfNotExist(
770
    $pre."users",
771
    "user_ip",
772
    "VARCHAR(400) NOT NULL DEFAULT 'none'"
773
);
774 View Code Duplication
if ($res === true) {
775
    // Change name of field
776
    mysqli_query($db_link, "ALTER TABLE `".$pre."users` CHANGE `user_ip` `user_ip` VARCHAR(400) NOT NULL DEFAULT 'none'");
777
} elseif ($res === false) {
778
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field user_ip to table Users! '.mysqli_error($db_link).'!"}]';
779
    mysqli_close($db_link);
780
    exit();
781
}
782
783
784
// alter table USERS to add a new field "user_api_key"
785
$res = addColumnIfNotExist(
786
    $pre."users",
787
    "user_api_key",
788
    "VARCHAR(500) NOT NULL DEFAULT 'none'"
789
);
790
if ($res === false) {
791
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field user_api_key to table Users! '.mysqli_error($db_link).'!"}]';
792
    mysqli_close($db_link);
793
    exit();
794
}
795
796
797
// alter table USERS to allow NULL on field "email"
798
mysqli_query(
799
    $db_link,
800
    "ALTER TABLE `".$pre."users` CHANGE `email` `email` VARCHAR(300) NOT NULL DEFAULT 'none';"
801
);
802
803
804
// alter table EXPORT to add a new fields
805
mysqli_query(
806
    $db_link,
807
    "ALTER TABLE `".$pre."export` ADD `email` VARCHAR(500) NOT NULL DEFAULT 'none';"
808
);
809
mysqli_query(
810
    $db_link,
811
    "ALTER TABLE `".$pre."export` ADD `url` VARCHAR(500) NOT NULL DEFAULT 'none';"
812
);
813
mysqli_query(
814
    $db_link,
815
    "ALTER TABLE `".$pre."export` ADD `kbs` VARCHAR(500) NOT NULL DEFAULT 'none';"
816
);
817
mysqli_query(
818
    $db_link,
819
    "ALTER TABLE `".$pre."export` ADD `tags` VARCHAR(500) NOT NULL DEFAULT 'none';"
820
);
821
822
mysqli_query(
823
    $db_link,
824
    "ALTER TABLE `".$pre."misc` CHANGE valeur valeur VARCHAR(500) NOT NULL DEFAULT 'none'"
825
);
826
827
// alter table ITEMS_CHANGE
828
mysqli_query(
829
    $db_link,
830
    "ALTER TABLE `".$pre."items_change` CHANGE user_id user_id INT(12) NOT NULL;"
831
);
832
833
// alter table ITEMS
834
mysqli_query(
835
    $db_link,
836
    "ALTER TABLE `".$pre."items` CHANGE auto_update_pwd_next_date auto_update_pwd_next_date VARCHAR(100) NOT NULL DEFAULT '0';"
837
);
838
839
840
// add new admin setting "otv_is_enabled"
841
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'otv_is_enabled'"));
842
if (intval($tmp) === 0) {
843
    mysqli_query(
844
        $db_link,
845
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'otv_is_enabled', '0')"
846
    );
847
}
848
849
850
// add new admin setting "ldap_and_local_authentication"
851
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'ldap_and_local_authentication'"));
852
if (intval($tmp) === 0) {
853
    mysqli_query(
854
        $db_link,
855
        "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('admin', 'ldap_and_local_authentication', '0')"
856
    );
857
}
858
859
860
861
// alter table NESTEED_TREE to INT(5) on field "renewal_period"
862
mysqli_query(
863
    $db_link,
864
    "ALTER TABLE `".$pre."nested_tree` CHANGE `renewal_period` `renewal_period` INT(5) NOT null DEFAULT '0';"
865
);
866
867
868
869
// add new field for items_change
870
mysqli_query(
871
    $db_link,
872
    "CREATE TABLE IF NOT EXISTS `".$pre."items_change` (
873
    `id` int(12) NOT NULL AUTO_INCREMENT,
874
    `item_id` int(12) NOT NULL,
875
    `label` varchar(255) NOT NULL DEFAULT 'none',
876
    `pw` text NOT NULL,
877
    `login` varchar(255) NOT NULL DEFAULT 'none',
878
    `email` varchar(255) NOT NULL DEFAULT 'none',
879
    `url` varchar(255) NOT NULL DEFAULT 'none',
880
    `description` text NOT NULL,
881
    `comment` text NOT NULL,
882
    `folder_id` tinyint(12) NOT NULL,
883
    `user_id` tinyint(12) NOT NULL,
884
    `timestamp` varchar(50) NOT NULL DEFAULT 'none',
885
    PRIMARY KEY (`id`)
886
    ) CHARSET=utf8;"
887
);
888
889
890
891
// File encryption
892
// add field status to FILE table
893
$res = addColumnIfNotExist(
894
    $pre."files",
895
    "status",
896
    "VARCHAR(50) NOT NULL DEFAULT '0'"
897
);
898
if ($res === false) {
899
    echo '[{"finish":"1", "msg":"", "error":"An error appears when adding field agses-usercardid to table Users! '.mysqli_error($db_link).'!"}]';
900
    mysqli_close($db_link);
901
    exit();
902
}
903
904
// fill in this new field with the current "encryption-file" status
905
$tmp = mysqli_fetch_row(mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE type = 'admin' AND intitule = 'enable_attachment_encryption'"));
906
if (!empty($tmp[0])) {
907
    if ($tmp[0] === "1") {
908
        $status = "encrypted";
909
    } else {
910
        $status = "clear";
911
    }
912
    mysqli_query($db_link, "update `".$pre."files` set status = '".$status."' where 1 = 1");
913
}
914
915
916
// add 2 generic users
917
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."users` WHERE id = '9999991' AND login = 'OTV'"));
918
if (intval($tmp) === 0) {
919
    mysqli_query(
920
        $db_link,
921
        "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')"
922
    );
923
}
924
$tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."users` WHERE id = '9999991' AND login = 'OTV'"));
925
if (intval($tmp) === 0) {
926
    mysqli_query(
927
        $db_link,
928
        "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')"
929
    );
930
}
931
932
933
// Update favico to favicon
934
$result = mysqli_query($db_link, "SELECT valeur FROM `".$pre."misc` WHERE intitule = 'cpassman_url' AND type = 'admin'");
935
$rows = mysqli_fetch_assoc($result);
936
mysqli_free_result($result);
937
mysqli_query(
938
    $db_link,
939
    "UPDATE `".$pre."misc`
940
    SET `valeur` = '".$rows['valeur']."/favicon.ico'
941
    WHERE intitule = 'favicon' AND type = 'admin'"
942
);
943
944
945
// Remove some indexes
946
mysqli_query($db_link, "ALTER TABLE ".$pre."nested_tree` DROP INDEX `id`;");
947
mysqli_query($db_link, "ALTER TABLE ".$pre."tags` DROP INDEX `id`;");
948
949
950
/*
951
* Introduce new CONFIG file
952
*/
953
$tp_config_file = "../includes/config/tp.config.php";
954 View Code Duplication
if (file_exists($tp_config_file)) {
955
    if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
956
        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.'"}]';
957
        return false;
958
    } else {
959
        unlink($tp_config_file);
960
    }
961
}
962
$file_handler = fopen($tp_config_file, 'w');
963
$config_text = "";
964
$any_settings = false;
965
966
$result = mysqli_query($db_link, "SELECT * FROM `".$pre."misc` WHERE type = 'admin'");
967 View Code Duplication
while ($row = mysqli_fetch_assoc($result)) {
968
    // append new setting in config file
969
    $config_text .= "
970
    '".$row['intitule']."' => '".$row['valeur']."',";
971
    if ($any_settings === false) {
972
        $any_settings = true;
973
    }
974
}
975
mysqli_free_result($result);
976
977
// write to config file
978 View Code Duplication
if ($any_settings === true) {
979
    $result = fwrite(
980
        $file_handler,
981
        utf8_encode(
982
            "<?php
983
global \$SETTINGS;
984
\$SETTINGS = array (" . $config_text . "
985
);"
986
        )
987
    );
988
}
989
fclose($file_handler);
990
991
992
// Generate API key by user
993
$result = mysqli_query($db_link, "SELECT id FROM `".$pre."users` WHERE login NOT IN ('admin', 'API', 'OTV')");
994
while ($row = mysqli_fetch_assoc($result)) {
995
    // Check if key already exists
996
    $tmp = mysqli_num_rows(mysqli_query($db_link, "SELECT * FROM `".$pre."api` WHERE label = '".$row['id']."'"));
997
    if (intval($tmp) === 0) {
998
        mysqli_query(
999
            $db_link,
1000
            "INSERT INTO `".$pre."api` (`type`, `label`, `value`, `timestamp`) VALUES ('user', '".$row['id']."', '".uniqidReal(39)."', '".time()."')"
1001
        );
1002
    }
1003
}
1004
1005
// Finished
1006
echo '[{"finish":"1" , "next":"", "error":""}]';
1007