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

upgrade_ajax.php ➔ addColumnIfNotExist()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 5
nop 3
dl 0
loc 15
rs 9.2
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
require_once('../sources/SecureHandler.php');
16
session_start();
17
error_reporting(E_ERROR | E_PARSE);
18
$_SESSION['CPM'] = 1;
19
20
require_once '../includes/language/english.php';
21
require_once '../includes/config/include.php';
22
23
// manage settings.php file
24
if (!file_exists("../includes/config/settings.php")) {
25
    if (file_exists("../includes/settings.php")) {
26
        // since 2.1.27, this file has changed location
27
        if (copy("../includes/settings.php", "../includes/config/settings.php")) {
28
            unlink("../includes/settings.php");
29
        } else {
30
            echo 'document.getElementById("res_step1_error").innerHTML = '.
31
                '"Could not copy /includes/settings.php to /includes/config/settings.php! '.
32
                'Please do it manually and press button Launch.";';
33
            echo 'document.getElementById("loader").style.display = "none";';
34
            exit;
35
        }
36
    } else {
37
        echo 'document.getElementById("res_step1_error").innerHTML = '.
38
            '"File settings.php does not exist in folder includes/! '.
39
            'If it is an upgrade, it should be there, otherwise select install!";';
40
        echo 'document.getElementById("loader").style.display = "none";';
41
        exit;
42
    }
43
}
44
require_once '../includes/config/settings.php';
45
require_once '../sources/main.functions.php';
46
47
48
//define pbkdf2 iteration count
49
define('ITCOUNT', '2072');
50
51
52
// Prepare POST variables
53
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
54
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
55
$post_index = filter_input(INPUT_POST, 'index', FILTER_SANITIZE_NUMBER_INT);
56
$post_multiple = filter_input(INPUT_POST, 'multiple', FILTER_SANITIZE_STRING);
57
$post_login = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_STRING);
58
$post_pwd = filter_input(INPUT_POST, 'pwd', FILTER_SANITIZE_STRING);
59
$post_fullurl = filter_input(INPUT_POST, 'fullurl', FILTER_SANITIZE_STRING);
60
$post_abspath = filter_input(INPUT_POST, 'abspath', FILTER_SANITIZE_STRING);
61
$post_no_previous_sk = filter_input(INPUT_POST, 'no_previous_sk', FILTER_SANITIZE_STRING);
62
$post_session_salt = filter_input(INPUT_POST, 'session_salt', FILTER_SANITIZE_STRING);
63
$post_previous_sk = filter_input(INPUT_POST, 'previous_sk', FILTER_SANITIZE_STRING);
64
$post_no_maintenance_mode = filter_input(INPUT_POST, 'no_maintenance_mode', FILTER_SANITIZE_STRING);
65
$post_prefix_before_convert = filter_input(INPUT_POST, 'prefix_before_convert', FILTER_SANITIZE_STRING);
66
$post_sk_path = filter_input(INPUT_POST, 'sk_path', FILTER_SANITIZE_STRING);
67
$post_url_path = filter_input(INPUT_POST, 'url_path', FILTER_SANITIZE_STRING);
68
69
70
// Test DB connexion
71
$pass = defuse_return_decrypted($pass);
72
if (mysqli_connect(
73
    $server,
74
    $user,
75
    $pass,
76
    $database,
77
    $port
78
)
79
) {
80
    $db_link = mysqli_connect(
81
        $server,
82
        $user,
83
        $pass,
84
        $database,
85
        $port
86
    );
87
    $res = "Connection is successful";
88
} else {
89
    $res = "Impossible to get connected to server. Error is: ".addslashes(mysqli_connect_error());
90
    echo 'document.getElementById("but_next").disabled = "disabled";';
91
    echo 'document.getElementById("res_".$post_type).innerHTML = "'.$res.'";';
92
    echo 'document.getElementById("loader").style.display = "none";';
93
    return false;
94
}
95
96
97
// Load libraries
98
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
99
$superGlobal = new protect\SuperGlobal\SuperGlobal();
100
101
// Set Session
102
$superGlobal->put("CPM", 1, "SESSION");
103
$superGlobal->put("db_encoding", "utf8", "SESSION");
104
$_SESSION['settings']['loaded'] = "";
105
if (empty($post_fullurl) === false) {
106
    $superGlobal->put("fullurl", $post_fullurl, "SESSION");
107
}
108
if (empty($abspath) === false) {
109
    $superGlobal->put("abspath", $abspath, "SESSION");
110
}
111
112
// Get Sessions
113
$session_url_path = $superGlobal->get("url_path", "SESSION");
114
115
################
116
## Function permits to get the value from a line
117
################
118
/**
119
 * @param string $val
120
 */
121
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...
122
{
123
    $val = trim(strstr($val, "="));
124
    return trim(str_replace('"', '', substr($val, 1, strpos($val, ";") - 1)));
125
}
126
127
################
128
## Function permits to check if a column exists, and if not to add it
129
################
130
function addColumnIfNotExist($dbname, $column, $columnAttr = "VARCHAR(255) NULL")
131
{
132
    global $db_link;
133
    $exists = false;
134
    $columns = mysqli_query($db_link, "show columns from $dbname");
135
    while ($col = mysqli_fetch_assoc($columns)) {
136
        if ($col['Field'] == $column) {
137
            $exists = true;
138
            break;
139
        }
140
    }
141
    if (!$exists) {
142
        return mysqli_query($db_link, "ALTER TABLE `$dbname` ADD `$column`  $columnAttr");
143
    }
144
}
145
146 View Code Duplication
function addIndexIfNotExist($table, $index, $sql)
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...
147
{
148
    global $db_link;
149
150
    $mysqli_result = mysqli_query($db_link, "SHOW INDEX FROM $table WHERE key_name LIKE \"$index\"");
151
    $res = mysqli_fetch_row($mysqli_result);
152
153
    // if index does not exist, then add it
154
    if (!$res) {
155
        $res = mysqli_query($db_link, "ALTER TABLE `$table` ".$sql);
156
    }
157
158
    return $res;
159
}
160
161 View Code Duplication
function tableExists($tablename)
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...
162
{
163
    global $db_link, $database;
164
165
    $res = mysqli_query(
166
        $db_link,
167
        "SELECT COUNT(*) as count
168
        FROM information_schema.tables
169
        WHERE table_schema = '".$database."'
170
        AND table_name = '$tablename'"
171
    );
172
173
    if ($res > 0) {
174
        return true;
175
    } else {
176
        return false;
177
    }
178
}
179
180
if (isset($post_type)) {
181
    switch ($post_type) {
182
        case "step0":
183
            // erase session table
184
            $_SESSION = array();
185
            setcookie('pma_end_session');
186
            session_destroy();
187
188
            echo 'document.getElementById("res_step0").innerHTML = "";';
189
            require_once 'libs/aesctr.php';
190
191
            // check if path in settings.php are consistent
192
            if (!is_dir(SECUREPATH)) {
193
                echo 'document.getElementById("but_next").disabled = "disabled";';
194
                echo 'document.getElementById("res_step0").innerHTML = "Error in settings.php file!<br>Check correctness of path indicated in file `includes/config/settings.php`.<br>Reload this page and retry.";';
195
                echo 'document.getElementById("loader").style.display = "none";';
196
                break;
197
            }
198
            if (!file_exists(SECUREPATH."/sk.php")) {
199
                echo 'document.getElementById("but_next").disabled = "disabled";';
200
                echo 'document.getElementById("res_step0").innerHTML = "Error in settings.php file!<br>Check that file `sk.php` exists as defined in `includes/config/settings.php`.<br>Reload this page and retry.";';
201
                echo 'document.getElementById("loader").style.display = "none";';
202
                break;
203
            }
204
205
            $_SESSION['settings']['cpassman_dir'] = "..";
206
            require_once '../includes/libraries/PasswordLib/Random/Generator.php';
207
            require_once '../includes/libraries/PasswordLib/Random/Source.php';
208
            require_once '../includes/libraries/PasswordLib/Random/Source/MTRand.php';
209
            require_once '../includes/libraries/PasswordLib/Random/Source/Rand.php';
210
            require_once '../includes/libraries/PasswordLib/Random/Source/UniqID.php';
211
            require_once '../includes/libraries/PasswordLib/Random/Source/URandom.php';
212
            require_once '../includes/libraries/PasswordLib/Random/Source/MicroTime.php';
213
            require_once '../includes/libraries/PasswordLib/Random/Source/CAPICOM.php';
214
            require_once '../includes/libraries/PasswordLib/Random/Mixer.php';
215
            require_once '../includes/libraries/PasswordLib/Random/AbstractMixer.php';
216
            require_once '../includes/libraries/PasswordLib/Random/Mixer/Hash.php';
217
            require_once '../includes/libraries/PasswordLib/Password/AbstractPassword.php';
218
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Hash.php';
219
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Crypt.php';
220
            require_once '../includes/libraries/PasswordLib/Password/Implementation/SHA256.php';
221
            require_once '../includes/libraries/PasswordLib/Password/Implementation/SHA512.php';
222
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PHPASS.php';
223
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PHPBB.php';
224
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PBKDF.php';
225
            require_once '../includes/libraries/PasswordLib/Password/Implementation/MediaWiki.php';
226
            require_once '../includes/libraries/PasswordLib/Password/Implementation/MD5.php';
227
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Joomla.php';
228
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Drupal.php';
229
            require_once '../includes/libraries/PasswordLib/Password/Implementation/APR1.php';
230
            require_once '../includes/libraries/PasswordLib/PasswordLib.php';
231
            $pwdlib = new PasswordLib\PasswordLib();
232
233
            // Connect to db and check user is granted
234
            $user_info = mysqli_fetch_array(
235
                mysqli_query(
236
                    $db_link,
237
                    "SELECT pw, admin FROM ".$pre."users
238
                    WHERE login='".mysqli_escape_string($db_link, stripslashes($post_login))."'"
239
                )
240
            );
241
242
            if (empty($user_info['pw']) || $user_info['pw'] === null) {
243
                echo 'document.getElementById("but_next").disabled = "disabled";';
244
                echo 'document.getElementById("res_step0").innerHTML = "This user is not allowed!";';
245
                echo 'document.getElementById("user_granted").value = "0";';
246
                $superGlobal->put("user_granted", false, "SESSION");
247
            } else {
248
                if ($pwdlib->verifyPasswordHash(Encryption\Crypt\aesctr::decrypt(base64_decode($post_pwd), "cpm", 128), $user_info['pw']) === true && $user_info['admin'] === "1") {
0 ignored issues
show
Documentation introduced by
base64_decode($post_pwd) is of type string, but the function expects a object<Encryption\Crypt\source>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
'cpm' is of type string, but the function expects a object<Encryption\Crypt\the>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
249
                    echo 'document.getElementById("but_next").disabled = "";';
250
                    echo 'document.getElementById("res_step0").innerHTML = "User is granted.";';
251
                    echo 'document.getElementById("step").value = "1";';
252
                    echo 'document.getElementById("user_granted").value = "1";';
253
                    $superGlobal->put("user_granted", true, "SESSION");
254
                } else {
255
                    echo 'document.getElementById("but_next").disabled = "disabled";';
256
                    echo 'document.getElementById("res_step0").innerHTML = "This user is not allowed!";';
257
                    echo 'document.getElementById("user_granted").value = "0";';
258
                    $superGlobal->put("user_granted", false, "SESSION");
259
                }
260
            }
261
262
            echo 'document.getElementById("loader").style.display = "none";';
263
            break;
264
265
        case "step1":
266
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
267
268
            if (intval($session_user_granted) !== 1) {
269
                echo 'document.getElementById("res_step1").innerHTML = "User not connected anymore!";';
270
                echo 'document.getElementById("loader").style.display = "none";';
271
                break;
272
            }
273
274
            $abspath = str_replace('\\', '/', $post_abspath);
275 View Code Duplication
            if (substr($abspath, strlen($abspath) - 1) == "/") {
276
                $abspath = substr($abspath, 0, strlen($abspath) - 1);
277
            }
278
            $okWritable = true;
279
            $okExtensions = true;
280
            $txt = "";
281
            $var_x = 1;
282
            $tab = array(
283
                $abspath."/includes/config/settings.php",
284
                $abspath."/includes/libraries/csrfp/libs/",
285
                $abspath."/install/",
286
                $abspath."/includes/",
287
                $abspath."/includes/config/",
288
                $abspath."/includes/avatars/",
289
                $abspath."/files/",
290
                $abspath."/upload/"
291
            );
292
            foreach ($tab as $elem) {
293
                // try to create it if not existing
294
                if (substr($elem, -1) === '/' && !is_dir($elem)) {
295
                    mkdir($elem);
296
                }
297
                // check if writable
298
                if (is_writable($elem)) {
299
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">'.
300
                        $elem.'&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
301
                } else {
302
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">'.
303
                        $elem.'&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
304
                    $okWritable = false;
305
                }
306
                $var_x++;
307
            }
308
309
            if (!extension_loaded('mcrypt')) {
310
                $okExtensions = false;
311
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mcrypt\"'.
312
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
313
            } else {
314
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mcrypt\"'.
315
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
316
            }
317
            if (!extension_loaded('openssl')) {
318
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
319
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"openssl\"'.
320
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
321
            } else {
322
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"openssl\"'.
323
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
324
            }
325
            if (!extension_loaded('gd')) {
326
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
327
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"gd\"'.
328
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
329
            } else {
330
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"gd\"'.
331
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
332
            }
333
            if (!extension_loaded('mbstring')) {
334
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
335
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mbstring\"'.
336
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
337
            } else {
338
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mbstring\"'.
339
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
340
            }
341
            if (!extension_loaded('bcmath')) {
342
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
343
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"bcmath\"'.
344
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
345
            } else {
346
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"bcmath\"'.
347
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
348
            }
349
            if (!extension_loaded('iconv')) {
350
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
351
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"iconv\"'.
352
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
353
            } else {
354
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"iconv\"'.
355
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
356
            }
357 View Code Duplication
            if (!extension_loaded('xml')) {
358
                //$okExtensions = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
359
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"xml\"'.
360
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
361
            } else {
362
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"xml\"'.
363
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
364
            }
365 View Code Duplication
            if (!extension_loaded('curl')) {
366
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"curl\"'.
367
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
368
            } else {
369
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"curl\"'.
370
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
371
            }
372
            if (ini_get('max_execution_time') < 60) {
373
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP \"Maximum '.
374
                    'execution time\" is set to '.ini_get('max_execution_time').' seconds.'.
375
                    ' Please try to set to 60s at least until Upgrade is finished.&nbsp;'.
376
                    '&nbsp;<img src=\"images/minus-circle.png\"></span> <br />';
377
            } else {
378
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP \"Maximum '.
379
                    'execution time\" is set to '.ini_get('max_execution_time').' seconds'.
380
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
381
            }
382
            if (version_compare(phpversion(), '5.5.0', '<')) {
383
                $okVersion = false;
384
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP version '.
385
                    phpversion().' is not OK (minimum is 5.5.0) &nbsp;&nbsp;'.
386
                    '<img src=\"images/minus-circle.png\"></span><br />';
387
            } else {
388
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP version '.
389
                    phpversion().' is OK&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
390
                    '</span><br />';
391
            }
392
393
            //get infos from SETTINGS.PHP file
394
            $filename = "../includes/config/settings.php";
395
            $events = "";
396
            if (file_exists($filename)) {
397
                //copy some constants from this existing file
398
                $settingsFile = file($filename);
399
                while (list($key, $val) = each($settingsFile)) {
400
                    if (substr_count($val, 'charset') > 0) {
401
                        $superGlobal->put("charset", getSettingValue($val), "SESSION");
402
                    } elseif (substr_count($val, '@define(') > 0 && substr_count($val, 'SALT') > 0) {
403
                        $superGlobal->put("encrypt_key", substr($val, 17, strpos($val, "')") - 17), "SESSION");
404
                    } elseif (substr_count($val, '$smtp_server') > 0) {
405
                        $superGlobal->put("smtp_server", getSettingValue($val), "SESSION");
406
                    } elseif (substr_count($val, '$smtp_auth') > 0) {
407
                        $superGlobal->put("smtp_auth", getSettingValue($val), "SESSION");
408
                    } elseif (substr_count($val, '$smtp_auth_username') > 0) {
409
                        $superGlobal->put("smtp_auth_username", getSettingValue($val), "SESSION");
410
                    } elseif (substr_count($val, '$smtp_auth_password') > 0) {
411
                        $superGlobal->put("smtp_auth_password", getSettingValue($val), "SESSION");
412
                    } elseif (substr_count($val, '$smtp_port') > 0) {
413
                        $superGlobal->put("smtp_port", getSettingValue($val), "SESSION");
414
                    } elseif (substr_count($val, '$smtp_security') > 0) {
415
                        $superGlobal->put("smtp_security", getSettingValue($val), "SESSION");
416
                    } elseif (substr_count($val, '$email_from') > 0) {
417
                        $superGlobal->put("email_from", getSettingValue($val), "SESSION");
418
                    } elseif (substr_count($val, '$email_from_name') > 0) {
419
                        $superGlobal->put("email_from_name", getSettingValue($val), "SESSION");
420
                    } elseif (substr_count($val, '$server') > 0) {
421
                        $superGlobal->put("server", getSettingValue($val), "SESSION");
422
                    } elseif (substr_count($val, '$user') > 0) {
423
                        $superGlobal->put("user", getSettingValue($val), "SESSION");
424
                    } elseif (substr_count($val, '$pass') > 0) {
425
                        $superGlobal->put("pass", getSettingValue($val), "SESSION");
426
                    } elseif (substr_count($val, '$port') > 0) {
427
                        $superGlobal->put("port", getSettingValue($val), "SESSION");
428
                    } elseif (substr_count($val, '$database') > 0) {
429
                        $database = getSettingValue($val);
430
                    } elseif (substr_count($val, '$pre') > 0) {
431
                        $pre = getSettingValue($val);
432
                    } elseif (substr_count($val, "define('SECUREPATH',") > 0) {
433
                        $superGlobal->put("sk_file", substr($val, 23, strpos($val, ');')-24)."/sk.php", "SESSION");
434
                    }
435
                }
436
            }
437
            $session_sk_file = $superGlobal->get("sk_file", "SESSION");
438
            if (isset($session_sk_file) && !empty($session_sk_file)
439
                && file_exists($session_sk_file)
440
            ) {
441
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">sk.php file'.
442
                    ' found in \"'.addslashes($session_sk_file).'\"&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
443
                    '</span><br />';
444
                //copy some constants from this existing file
445
                $skFile = file($session_sk_file);
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_ajax.php on line 437

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...
446 View Code Duplication
                while (list($key, $val) = each($skFile)) {
447
                    if (substr_count($val, "@define('SALT'") > 0) {
448
                        $superGlobal->put("encrypt_key", substr($val, 17, strpos($val, "')") - 17), "SESSION");
449
                        $session_encrypt_key = $superGlobal->get("encrypt_key", "SESSION");
450
                        echo '$("#session_salt").val("'.$session_encrypt_key.'");';
0 ignored issues
show
Security Cross-Site Scripting introduced by
'$("#session_salt").val(...ion_encrypt_key . '");' can contain request data and is used in output 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_encrypt_key is assigned
    in install/upgrade_ajax.php on line 449

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

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...
451
                    }
452
                }
453
            }
454
455
            // check if 2.1.27 already installed
456
            $okEncryptKey = false;
457
            $defuse_file = substr($session_sk_file, 0, strrpos($session_sk_file, "/"))."/teampass-seckey.txt";
458
            if (file_exists($defuse_file)) {
459
                $okEncryptKey = true;
460
                $superGlobal->put("tp_defuse_installed", true, "SESSION");
461
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">Defuse encryption key is defined&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
462
                    '</span><br />';
463
            }
464
465
            if ($okEncryptKey === false) {
466
                if (!isset($session_encrypt_key) || empty($session_encrypt_key)) {
467
                    $superGlobal->put("tp_defuse_installed", false, "SESSION");
468
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">Encryption Key (SALT) '.
469
                        ' could not be recovered &nbsp;&nbsp;'.
470
                        '<img src=\"images/minus-circle.png\"></span><br />';
471
                } else {
472
                    $okEncryptKey = true;
473
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">Encryption Key (SALT) is available&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
474
                        '</span><br />';
475
                }
476
            }
477
478
            if ($okWritable === true && $okExtensions === true && $okEncryptKey === true) {
479
                echo 'document.getElementById("but_next").disabled = "";';
480
                echo 'document.getElementById("res_step1").innerHTML = "Elements are OK.";';
481
            } else {
482
                echo 'document.getElementById("but_next").disabled = "disabled";';
483
                echo 'document.getElementById("res_step1").innerHTML = "Correct the shown '.
484
                    'errors and click on button Launch to refresh";';
485
            }
486
487
            echo 'document.getElementById("res_step1").innerHTML = "'.$txt.'";';
0 ignored issues
show
Security Cross-Site Scripting introduced by
'document.getElementById...HTML = "' . $txt . '";' can contain request data and is used in output 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_ajax.php on line 437
  3. $session_sk_file is escaped by addslashes() for sql, xpath context(s)
    in install/upgrade_ajax.php on line 442
  4. $txt is assigned
    in install/upgrade_ajax.php on line 441

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

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...
488
            echo 'document.getElementById("loader").style.display = "none";';
489
            break;
490
491
            #==========================
492
        case "step2":
493
            $res = "";
494
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
495
496
            if ($session_user_granted !== "1") {
497
                echo 'document.getElementById("res_step2").innerHTML = "User not connected anymore!";';
498
                echo 'document.getElementById("loader").style.display = "none";';
499
                break;
500
            }
501
            //decrypt the password
502
            // AES Counter Mode implementation
503
            require_once 'libs/aesctr.php';
504
505
            // check in db if previous saltk exists
506
            if ($post_no_previous_sk === "false" || $post_no_previous_sk === "previous_sk_sel") {
507
                $db_sk = mysqli_fetch_row(mysqli_query($db_link, "SELECT count(*) FROM ".$pre."misc
508
                WHERE type='admin' AND intitule = 'saltkey_ante_2127'"));
509
                if (!empty($post_previous_sk) || !empty($post_session_salt)) {
510
                    // get sk
511
                    if (!empty($post_session_salt)) {
512
                        $sk_val = filter_var($post_session_salt, FILTER_SANITIZE_STRING);
513
                    } else {
514
                        $sk_val = filter_var($post_previous_sk, FILTER_SANITIZE_STRING);
515
                    }
516
517
                    // Update
518
                    if (!empty($db_sk[0])) {
519
                        mysqli_query(
520
                            $db_link,
521
                            "UPDATE `".$pre."misc`
522
                            SET `valeur` = '".$sk_val."'
523
                            WHERE type = 'admin' AND intitule = 'saltkey_ante_2127'"
524
                        );
525
                    } else {
526
                        mysqli_query(
527
                            $db_link,
528
                            "INSERT INTO `".$pre."misc`
529
                            (`valeur`, `type`, `intitule`)
530
                            VALUES ('".$sk_val."', 'admin', 'saltkey_ante_2127')"
531
                        );
532
                    }
533
                } elseif (empty($db_sk[0])) {
534
                    $res = "Please provide Teampass instance history.";
535
                    echo 'document.getElementById("but_next").disabled = "disabled";';
536
                    echo 'document.getElementById("res_step2").innerHTML = "'.$res.'";';
537
                    echo 'document.getElementById("loader").style.display = "none";';
538
                    echo 'document.getElementById("no_encrypt_key").style.display = "";';
539
                }
540
            } else {
541
                // user said that database has not being used for an older version
542
                // no old sk is available
543
                    $tmp = mysqli_num_rows(mysqli_query(
544
                        $db_link,
545
                        "SELECT * FROM `".$pre."misc`
546
                        WHERE type = 'admin' AND intitule = 'saltkey_ante_2127'"
547
                    ));
548
                if ($tmp == 0) {
549
                    mysqli_query(
550
                        $db_link,
551
                        "INSERT INTO `".$pre."misc`
552
                        (`valeur`, `type`, `intitule`)
553
                        VALUES ('none', 'admin', 'saltkey_ante_2127')"
554
                    );
555
                } else {
556
                    mysqli_query(
557
                        $db_link,
558
                        "INSERT INTO `".$pre."misc`
559
                        (`valeur`, `type`, `intitule`)
560
                        VALUES ('none', 'admin', 'saltkey_ante_2127')"
561
                    );
562
                }
563
                $superGlobal->put("tp_defuse_installed", true, "SESSION");
564
            }
565
566
            //What CPM version
567
            if (mysqli_query(
568
                $db_link,
569
                "SELECT valeur FROM ".$pre."misc
570
                WHERE type='admin' AND intitule = 'cpassman_version'"
571
            )) {
572
                $tmpResult = mysqli_query(
573
                    $db_link,
574
                    "SELECT valeur FROM ".$pre."misc
575
                    WHERE type='admin' AND intitule = 'cpassman_version'"
576
                );
577
                $cpmVersion = mysqli_fetch_row($tmpResult);
578
                echo 'document.getElementById("actual_cpm_version").value = "'.
579
                    $cpmVersion[0].'";';
580
            } else {
581
                echo 'document.getElementById("actual_cpm_version").value = "0";';
582
            }
583
584
            //Get some infos from DB
585
            if (@mysqli_fetch_row(
586
                mysqli_query(
587
                    $db_link,
588
                    "SELECT valeur FROM ".$pre."misc
589
                    WHERE type='admin' AND intitule = 'utf8_enabled'"
590
                )
591
            )
592
            ) {
593
                $cpmIsUTF8 = mysqli_fetch_row(
594
                    mysqli_query(
595
                        $db_link,
596
                        "SELECT valeur FROM ".$pre."misc
597
                        WHERE type='admin' AND intitule = 'utf8_enabled'"
598
                    )
599
                );
600
                echo 'document.getElementById("cpm_isUTF8").value = "'.$cpmIsUTF8[0].'";';
601
                $superGlobal->put("utf8_enabled", $cpmIsUTF8[0], "SESSION");
602
            } else {
603
                echo 'document.getElementById("cpm_isUTF8").value = "0";';
604
                $superGlobal->put("utf8_enabled", 0, "SESSION");
605
            }
606
607
            // put TP in maintenance mode or not
608
            @mysqli_query(
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...
609
                $db_link,
610
                "UPDATE `".$pre."misc`
611
                SET `valeur` = 'maintenance_mode'
612
                WHERE type = 'admin' AND intitule = '".$post_no_maintenance_mode."'"
613
            );
614
615
            echo 'document.getElementById("dump").style.display = "";';
616
617
618
            echo 'document.getElementById("res_step2").innerHTML = "'.$res.'";';
619
            echo 'document.getElementById("loader").style.display = "none";';
620
            break;
621
622
            #==========================
623
        case "step3":
624
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
625
626
            if ($session_user_granted !== "1") {
627
                echo 'document.getElementById("res_step3").innerHTML = "User not connected anymore!";';
628
                echo 'document.getElementById("loader").style.display = "none";';
629
                break;
630
            }
631
632
            //rename tables
633
            if (isset($post_prefix_before_convert) && $post_prefix_before_convert == "true") {
634
                $tables = mysqli_query($db_link, 'SHOW TABLES');
635
                while ($table = mysqli_fetch_row($tables)) {
636
                    if (tableExists("old_".$table[0]) != 1 && substr($table[0], 0, 4) != "old_") {
637
                        mysqli_query($db_link, "CREATE TABLE old_".$table[0]." LIKE ".$table[0]);
638
                        mysqli_query($db_link, "INSERT INTO old_".$table[0]." SELECT * FROM ".$table[0]);
639
                    }
640
                }
641
            }
642
643
            //convert database
644
            mysqli_query(
645
                $db_link,
646
                "ALTER DATABASE `".$database."`
647
                DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"
648
            );
649
650
            //convert tables
651
            $res = mysqli_query($db_link, "SHOW TABLES FROM `".$database."`");
652
            while ($table = mysqli_fetch_row($res)) {
653
                if (substr($table[0], 0, 4) != "old_") {
654
                    mysqli_query(
655
                        $db_link,
656
                        "ALTER TABLE ".$database.".`{$table[0]}`
657
                        CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci"
658
                    );
659
                    mysqli_query(
660
                        $db_link,
661
                        "ALTER TABLE".$database.".`{$table[0]}`
662
                        DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"
663
                    );
664
                }
665
            }
666
667
            echo 'document.getElementById("res_step3").innerHTML = "Done!";';
668
            echo 'document.getElementById("loader").style.display = "none";';
669
            echo 'document.getElementById("but_next").disabled = "";';
670
            echo 'document.getElementById("but_launch").disabled = "disabled";';
671
672
            mysqli_close($db_link);
673
            break;
674
675
            #==========================
676
677
678
            //=============================
679
        case "step5":
680
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
681
682
            if ($session_user_granted !== "1") {
683
                echo 'document.getElementById("res_step5").innerHTML = "User not connected anymore!";';
684
                echo 'document.getElementById("loader").style.display = "none";';
685
                break;
686
            }
687
688
            $filename = "../includes/config/settings.php";
689
            $events = "";
690
            if (file_exists($filename)) {
691
                //Do a copy of the existing file
692
                if (!copy(
693
                    $filename,
694
                    $filename.'.'.date(
695
                        "Y_m_d",
696
                        mktime(0, 0, 0, date('m'), date('d'), date('y'))
697
                    )
698
                )) {
699
                    echo 'document.getElementById("res_step5").innerHTML = '.
700
                        '"Setting.php file already exists and cannot be renamed. '.
701
                        'Please do it by yourself and click on button Launch.";';
702
                    echo 'document.getElementById("loader").style.display = "none";';
703
                    break;
704
                } else {
705
                    $events .= "The file $filename already exist. A copy has been created.<br />";
706
                    unlink($filename);
707
                }
708
709
                //manage SK path
710
                if (isset($post_sk_path) && !empty($post_sk_path)) {
711
                    $skFile = str_replace('\\', '/', $post_sk_path.'/sk.php');
712
                    $securePath = str_replace('\\', '/', $post_sk_path);
713
                } else {
714
                    echo 'document.getElementById("res_step5").innerHTML = '.
715
                        '"<img src=\"images/exclamation-red.png\"> The SK path must be indicated.";
716
                        document.getElementById("loader").style.display = "none";';
717
                    break;
718
                }
719
720
                //Check if path is ok
721
                if (is_dir($securePath)) {
722
                    if (is_writable($securePath)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
723
                        //Do nothing
724
                    } else {
725
                        echo 'document.getElementById("res_step5").innerHTML = '.
726
                            '"<img src=\"images/exclamation-red.png\"> The SK path must be writable!";
727
                            document.getElementById("loader").style.display = "none";';
728
                        break;
729
                    }
730
                } else {
731
                    echo 'document.getElementById("res_step5").innerHTML = '.
732
                        '"<img src=\"images/exclamation-red.png\"> '.
733
                        'Path for SK is not a Directory!";
734
                    document.getElementById("loader").style.display = "none";';
735
                    break;
736
                }
737
738
                $file_handled = fopen($filename, 'w');
739
740
                //prepare smtp_auth variable
741
                if (empty($superGlobal->get("smtp_auth", "SESSION"))) {
742
                    $superGlobal->put("smtp_auth", "false", "SESSION");
743
                }
744
                if (empty($superGlobal->get("smtp_auth_username", "SESSION"))) {
745
                    $superGlobal->put("smtp_auth_username", "false", "SESSION");
746
                }
747
                if (empty($superGlobal->get("smtp_auth_password", "SESSION"))) {
748
                    $superGlobal->put("smtp_auth_password", "false", "SESSION");
749
                }
750
                if (empty($superGlobal->get("email_from_name", "SESSION"))) {
751
                    $superGlobal->put("email_from_name", "false", "SESSION");
752
                }
753
754
                $result1 = fwrite(
755
                    $file_handled,
756
                    utf8_encode(
757
                        "<?php
758
global \$lang, \$txt, \$pathTeampas, \$urlTeampass, \$pwComplexity, \$mngPages;
759
global \$server, \$user, \$pass, \$database, \$pre, \$db, \$port, \$encoding;
760
761
### DATABASE connexion parameters ###
762
\$server = \"".$server."\";
763
\$user = \"".$user."\";
764
\$pass = \"".cryption($pass, "", "encrypt")['string']."\";
765
\$database = \"".$database."\";
766
\$port = ".$port.";
767
\$pre = \"".$pre."\";
768
\$encoding = \"".$encoding."\";
769
770
@date_default_timezone_set(\$_SESSION['settings']['timezone']);
771
@define('SECUREPATH', '".substr($skFile, 0, strlen($skFile) - 7)."');
772
if (file_exists(\"".$skFile."\")) {
773
    require_once \"".$skFile."\";
774
}
775
@define('COST', '13'); // Don't change this.
776
"
777
                    )
778
                );
779
780
                fclose($file_handled);
781
                if ($result1 === false) {
782
                    echo 'document.getElementById("res_step5").innerHTML = '.
783
                        '"Setting.php file could not be created. '.
784
                        'Please check the path and the rights.";';
785
                } else {
786
                    echo 'document.getElementById("step5_settingFile").innerHTML = '.
787
                        '"<img src=\"images/tick.png\">";';
788
                }
789
790
                //Create sk.php file
791
                if (file_exists($skFile) === false) {
792
                    $file_handled = fopen($skFile, 'w');
793
794
                    $result2 = fwrite(
795
                        $file_handled,
796
                        utf8_encode(
797
                            "<?php
798
@define('COST', '13'); // Don't change this.
799
@define('AKEY', '');
800
@define('IKEY', '');
801
@define('SKEY', '');
802
@define('HOST', '');
803
?>"
804
                        )
805
                    );
806
                    fclose($file_handled);
807
                }
808
809
                // update CSRFP TOKEN
810
                $csrfp_file_sample = "../includes/libraries/csrfp/libs/csrfp.config.sample.php";
811
                $csrfp_file = "../includes/libraries/csrfp/libs/csrfp.config.php";
812 View Code Duplication
                if (file_exists($csrfp_file) === true) {
813
                    if (!copy($filename, $filename.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
814
                        echo '[{"error" : "csrfp.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.'"}]';
815
                        break;
816
                    } else {
817
                        $events .= "The file $csrfp_file already exist. A copy has been created.<br />";
818
                    }
819
                }
820
                unlink($csrfp_file); // delete existing csrfp.config file
821
                copy($csrfp_file_sample, $csrfp_file); // make a copy of csrfp.config.sample file
822
                $data = file_get_contents("../includes/libraries/csrfp/libs/csrfp.config.php");
823
                $newdata = str_replace('"CSRFP_TOKEN" => ""', '"CSRFP_TOKEN" => "'.bin2hex(openssl_random_pseudo_bytes(25)).'"', $data);
824
                $newdata = str_replace('"tokenLength" => "25"', '"tokenLength" => "50"', $newdata);
825
                $jsUrl = $post_url_path.'/includes/libraries/csrfp/js/csrfprotector.js';
826
                $newdata = str_replace('"jsUrl" => ""', '"jsUrl" => "'.$jsUrl.'"', $newdata);
827
                $newdata = str_replace('"verifyGetFor" => array()', '"verifyGetFor" => array("*page=items&type=duo_check*")', $newdata);
828
                file_put_contents("../includes/libraries/csrfp/libs/csrfp.config.php", $newdata);
829
830
831
                // finalize
832
                if (isset($result2) && $result2 === false) {
833
                    echo 'document.getElementById("res_step5").innerHTML = '.
834
                        '"$skFile could not be created. Please check the path and the rights.";';
835
                } else {
836
                    echo 'document.getElementById("step5_skFile").innerHTML = '.
837
                        '"<img src=\"images/tick.png\">";';
838
                }
839
840
                // Mark a tag to force Install stuff (folders, files and table) to be cleanup while first login
841
                mysqli_query(
842
                    $db_link,
843
                    "INSERT INTO `".$pre."misc` (`type`, `intitule`, `valeur`) VALUES ('install', 'clear_install_folder', 'true')"
844
                );
845
846
847
                //Finished
848
                if ($result1 !== false
849
                    && (!isset($result2) || (isset($result2) && $result2 !== false))
850
                ) {
851
                    echo 'document.getElementById("but_next").disabled = "";';
852
                    echo 'document.getElementById("res_step5").innerHTML = '.
853
                        '"Operations are successfully completed.";';
854
                    echo 'document.getElementById("loader").style.display = "none";';
855
                    echo 'document.getElementById("but_launch").disabled = "disabled";';
856
                }
857
            } else {
858
                //settings.php file doesn't exit => ERROR !!!!
859
                echo 'document.getElementById("res_step5").innerHTML = '.
860
                        '"<img src=\"images/error.png\">&nbsp;Setting.php '.
861
                        'file doesn\'t exist! Upgrade can\'t continue without this file.<br />'.
862
                        'Please copy your existing settings.php into the \"includes\" '.
863
                        'folder of your TeamPass installation ";';
864
                echo 'document.getElementById("loader").style.display = "none";';
865
            }
866
867
            break;
868
869
        case "perform_database_dump":
870
            $filename = "../includes/config/settings.php";
871
872
            require_once "../sources/main.functions.php";
873
            $pass = defuse_return_decrypted($pass);
874
875
            $mtables = array();
876
877
            $mysqli = new mysqli($server, $user, $pass, $database, $port);
878
            if ($mysqli->connect_error) {
879
                die('Error : ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
880
            }
881
882
            $results = $mysqli->query("SHOW TABLES");
883
884
            while ($row = $results->fetch_array()) {
885
                $mtables[] = $row[0];
886
            }
887
888
            foreach ($mtables as $table) {
889
                $contents .= "-- Table `".$table."` --\n";
890
891
                $results = $mysqli->query("SHOW CREATE TABLE ".$table);
892
                while ($row = $results->fetch_array()) {
893
                    $contents .= $row[1].";\n\n";
894
                }
895
896
                $results = $mysqli->query("SELECT * FROM ".$table);
897
                $row_count = $results->num_rows;
898
                $fields = $results->fetch_fields();
899
                $fields_count = count($fields);
900
901
                $insert_head = "INSERT INTO `".$table."` (";
902
                for ($i = 0; $i < $fields_count; $i++) {
903
                    $insert_head .= "`".$fields[$i]->name."`";
904
                    if ($i < $fields_count - 1) {
905
                        $insert_head .= ', ';
906
                    }
907
                }
908
                $insert_head .= ")";
909
                $insert_head .= " VALUES\n";
910
911
                if ($row_count > 0) {
912
                    $r = 0;
913
                    while ($row = $results->fetch_array()) {
914
                        if (($r % 400) == 0) {
915
                            $contents .= $insert_head;
916
                        }
917
                        $contents .= "(";
918
                        for ($i = 0; $i < $fields_count; $i++) {
919
                            $row_content = str_replace("\n", "\\n", $mysqli->real_escape_string($row[$i]));
920
921
                            switch ($fields[$i]->type) {
922
                                case 8:
923
                                case 3:
924
                                    $contents .= $row_content;
925
                                    break;
926
                                default:
927
                                    $contents .= "'".$row_content."'";
928
                            }
929
                            if ($i < $fields_count - 1) {
930
                                $contents .= ', ';
931
                            }
932
                        }
933
                        if (($r + 1) == $row_count || ($r % 400) == 399) {
934
                            $contents .= ");\n\n";
935
                        } else {
936
                            $contents .= "),\n";
937
                        }
938
                        $r++;
939
                    }
940
                }
941
            }
942
943
            $backup_file_name = "sql-backup-".date("d-m-Y--h-i-s").".sql";
944
945
            $fp = fopen("../files/".$backup_file_name, 'w+');
946
            if (($result = fwrite($fp, $contents))) {
947
                echo '[{ "error" : "" , "file" : "files/'.$backup_file_name.'"}]';
948
            } else {
949
                echo '[{ "error" : "Backup fails - please do it manually."}]';
950
            }
951
            fclose($fp);
952
            return false;
953
954
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
955
    }
956
}
957
echo 'document.getElementById("but_next").disabled = "";';
958