Completed
Push — development ( 73b519...b85158 )
by Nils
09:02
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);
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_tbl_prefix = filter_input(INPUT_POST, 'tbl_prefix', FILTER_SANITIZE_STRING);
65
$post_no_maintenance_mode = filter_input(INPUT_POST, 'no_maintenance_mode', FILTER_SANITIZE_STRING);
66
$post_prefix_before_convert = filter_input(INPUT_POST, 'prefix_before_convert', FILTER_SANITIZE_STRING);
67
$post_sk_path = filter_input(INPUT_POST, 'sk_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
    echo 'document.getElementById("but_next").disabled = "";';
89
} else {
90
    $res = "Impossible to get connected to server. Error is: ".addslashes(mysqli_connect_error());
91
    echo 'document.getElementById("but_next").disabled = "disabled";';
92
    echo 'document.getElementById("res_".$post_type).innerHTML = "'.$res.'";';
93
    echo 'document.getElementById("loader").style.display = "none";';
94
    return false;
95
}
96
97
98
// Load libraries
99
require_once '../includes/libraries/protect/SuperGlobal/SuperGlobal.php';
100
$superGlobal = new protect\SuperGlobal\SuperGlobal();
101
102
// Set Session
103
$superGlobal->put("CPM", 1, "SESSION");
104
$superGlobal->put("db_encoding", "utf8", "SESSION");
105
$_SESSION['settings']['loaded'] = "";
106
$superGlobal->put("fullurl", $post_fullurl, "SESSION");
107
$superGlobal->put("abspath", $abspath, "SESSION");
108
109
// Get Sessions
110
$session_url_path = $superGlobal->get("url_path", "SESSION");
111
112
################
113
## Function permits to get the value from a line
114
################
115
/**
116
 * @param string $val
117
 */
118
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...
119
{
120
    $val = trim(strstr($val, "="));
121
    return trim(str_replace('"', '', substr($val, 1, strpos($val, ";") - 1)));
122
}
123
124
################
125
## Function permits to check if a column exists, and if not to add it
126
################
127
function addColumnIfNotExist($dbname, $column, $columnAttr = "VARCHAR(255) NULL")
128
{
129
    global $db_link;
130
    $exists = false;
131
    $columns = mysqli_query($db_link, "show columns from $dbname");
132
    while ($col = mysqli_fetch_assoc($columns)) {
133
        if ($col['Field'] == $column) {
134
            $exists = true;
135
            break;
136
        }
137
    }
138
    if (!$exists) {
139
        return mysqli_query($db_link, "ALTER TABLE `$dbname` ADD `$column`  $columnAttr");
140
    }
141
}
142
143 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...
144
{
145
    global $db_link;
146
147
    $mysqli_result = mysqli_query($db_link, "SHOW INDEX FROM $table WHERE key_name LIKE \"$index\"");
148
    $res = mysqli_fetch_row($mysqli_result);
149
150
    // if index does not exist, then add it
151
    if (!$res) {
152
        $res = mysqli_query($db_link, "ALTER TABLE `$table` ".$sql);
153
    }
154
155
    return $res;
156
}
157
158 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...
159
{
160
    global $db_link, $database;
161
162
    $res = mysqli_query(
163
        $db_link,
164
        "SELECT COUNT(*) as count
165
        FROM information_schema.tables
166
        WHERE table_schema = '".$database."'
167
        AND table_name = '$tablename'"
168
    );
169
170
    if ($res > 0) {
171
        return true;
172
    } else {
173
        return false;
174
    }
175
}
176
177
if (isset($post_type)) {
178
    switch ($post_type) {
179
        case "step0":
180
            // erase session table
181
            $_SESSION = array();
182
            setcookie('pma_end_session');
183
            session_destroy();
184
185
            echo 'document.getElementById("res_step0").innerHTML = "";';
186
            require_once 'libs/aesctr.php';
187
188
            // check if path in settings.php are consistent
189
            if (!is_dir(SECUREPATH)) {
190
                echo 'document.getElementById("but_next").disabled = "disabled";';
191
                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.";';
192
                echo 'document.getElementById("loader").style.display = "none";';
193
                break;
194
            }
195
            if (!file_exists(SECUREPATH."/sk.php")) {
196
                echo 'document.getElementById("but_next").disabled = "disabled";';
197
                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.";';
198
                echo 'document.getElementById("loader").style.display = "none";';
199
                break;
200
            }
201
202
            $_SESSION['settings']['cpassman_dir'] = "..";
203
            require_once '../includes/libraries/PasswordLib/Random/Generator.php';
204
            require_once '../includes/libraries/PasswordLib/Random/Source.php';
205
            require_once '../includes/libraries/PasswordLib/Random/Source/MTRand.php';
206
            require_once '../includes/libraries/PasswordLib/Random/Source/Rand.php';
207
            require_once '../includes/libraries/PasswordLib/Random/Source/UniqID.php';
208
            require_once '../includes/libraries/PasswordLib/Random/Source/URandom.php';
209
            require_once '../includes/libraries/PasswordLib/Random/Source/MicroTime.php';
210
            require_once '../includes/libraries/PasswordLib/Random/Source/CAPICOM.php';
211
            require_once '../includes/libraries/PasswordLib/Random/Mixer.php';
212
            require_once '../includes/libraries/PasswordLib/Random/AbstractMixer.php';
213
            require_once '../includes/libraries/PasswordLib/Random/Mixer/Hash.php';
214
            require_once '../includes/libraries/PasswordLib/Password/AbstractPassword.php';
215
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Hash.php';
216
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Crypt.php';
217
            require_once '../includes/libraries/PasswordLib/Password/Implementation/SHA256.php';
218
            require_once '../includes/libraries/PasswordLib/Password/Implementation/SHA512.php';
219
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PHPASS.php';
220
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PHPBB.php';
221
            require_once '../includes/libraries/PasswordLib/Password/Implementation/PBKDF.php';
222
            require_once '../includes/libraries/PasswordLib/Password/Implementation/MediaWiki.php';
223
            require_once '../includes/libraries/PasswordLib/Password/Implementation/MD5.php';
224
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Joomla.php';
225
            require_once '../includes/libraries/PasswordLib/Password/Implementation/Drupal.php';
226
            require_once '../includes/libraries/PasswordLib/Password/Implementation/APR1.php';
227
            require_once '../includes/libraries/PasswordLib/PasswordLib.php';
228
            $pwdlib = new PasswordLib\PasswordLib();
229
230
            // Connect to db and check user is granted
231
            $user_info = mysqli_fetch_array(
232
                mysqli_query(
233
                    $db_link,
234
                    "SELECT pw, admin FROM ".$pre."users
235
                    WHERE login='".mysqli_escape_string($db_link, stripslashes($post_login))."'"
236
                )
237
            );
238
239
            if (empty($user_info['pw']) || $user_info['pw'] === null) {
240
                echo 'document.getElementById("but_next").disabled = "disabled";';
241
                echo 'document.getElementById("res_step0").innerHTML = "This user is not allowed!";';
242
                echo 'document.getElementById("user_granted").value = "0";';
243
                $superGlobal->put("user_granted", false, "SESSION");
244
            } else {
245
                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...
246
                    echo 'document.getElementById("but_next").disabled = "";';
247
                    echo 'document.getElementById("res_step0").innerHTML = "User is granted.";';
248
                    echo 'document.getElementById("step").value = "1";';
249
                    echo 'document.getElementById("user_granted").value = "1";';
250
                    $superGlobal->put("user_granted", true, "SESSION");
251
                } else {
252
                    echo 'document.getElementById("but_next").disabled = "disabled";';
253
                    echo 'document.getElementById("res_step0").innerHTML = "This user is not allowed!";';
254
                    echo 'document.getElementById("user_granted").value = "0";';
255
                    $superGlobal->put("user_granted", false, "SESSION");
256
                }
257
            }
258
259
            echo 'document.getElementById("loader").style.display = "none";';
260
            break;
261
262
        case "step1":
263
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
264
265
            if (intval($session_user_granted) !== 1) {
266
                echo 'document.getElementById("res_step1").innerHTML = "User not connected anymore!";';
267
                echo 'document.getElementById("loader").style.display = "none";';
268
                break;
269
            }
270
271
            $abspath = str_replace('\\', '/', $post_abspath);
272 View Code Duplication
            if (substr($abspath, strlen($abspath) - 1) == "/") {
273
                $abspath = substr($abspath, 0, strlen($abspath) - 1);
274
            }
275
            $okWritable = true;
276
            $okExtensions = true;
277
            $txt = "";
278
            $var_x = 1;
279
            $tab = array(
280
                $abspath."/includes/config/settings.php",
281
                $abspath."/includes/libraries/csrfp/libs/",
282
                $abspath."/install/",
283
                $abspath."/includes/",
284
                $abspath."/includes/config/",
285
                $abspath."/includes/avatars/",
286
                $abspath."/files/",
287
                $abspath."/upload/"
288
            );
289
            foreach ($tab as $elem) {
290
                // try to create it if not existing
291
                if (substr($elem, -1) === '/' && !is_dir($elem)) {
292
                    mkdir($elem);
293
                }
294
                // check if writable
295
                if (is_writable($elem)) {
296
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">'.
297
                        $elem.'&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
298
                } else {
299
                    $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">'.
300
                        $elem.'&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
301
                    $okWritable = false;
302
                }
303
                $var_x++;
304
            }
305
306
            if (!extension_loaded('mcrypt')) {
307
                $okExtensions = false;
308
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mcrypt\"'.
309
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
310
            } else {
311
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mcrypt\"'.
312
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
313
            }
314
            if (!extension_loaded('openssl')) {
315
                //$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...
316
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"openssl\"'.
317
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
318
            } else {
319
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"openssl\"'.
320
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
321
            }
322
            if (!extension_loaded('gd')) {
323
                //$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...
324
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"gd\"'.
325
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
326
            } else {
327
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"gd\"'.
328
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
329
            }
330
            if (!extension_loaded('mbstring')) {
331
                //$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...
332
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mbstring\"'.
333
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
334
            } else {
335
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"mbstring\"'.
336
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
337
            }
338
            if (!extension_loaded('bcmath')) {
339
                //$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...
340
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"bcmath\"'.
341
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
342
            } else {
343
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"bcmath\"'.
344
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
345
            }
346
            if (!extension_loaded('iconv')) {
347
                //$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...
348
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"iconv\"'.
349
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
350
            } else {
351
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"iconv\"'.
352
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
353
            }
354 View Code Duplication
            if (!extension_loaded('xml')) {
355
                //$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...
356
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"xml\"'.
357
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
358
            } else {
359
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"xml\"'.
360
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
361
            }
362 View Code Duplication
            if (!extension_loaded('curl')) {
363
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"curl\"'.
364
                    '&nbsp;&nbsp;<img src=\"images/minus-circle.png\"></span><br />';
365
            } else {
366
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP extension \"curl\"'.
367
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
368
            }
369
            if (ini_get('max_execution_time') < 60) {
370
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP \"Maximum '.
371
                    'execution time\" is set to '.ini_get('max_execution_time').' seconds.'.
372
                    ' Please try to set to 60s at least until Upgrade is finished.&nbsp;'.
373
                    '&nbsp;<img src=\"images/minus-circle.png\"></span> <br />';
374
            } else {
375
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP \"Maximum '.
376
                    'execution time\" is set to '.ini_get('max_execution_time').' seconds'.
377
                    '&nbsp;&nbsp;<img src=\"images/tick-circle.png\"></span><br />';
378
            }
379
            if (version_compare(phpversion(), '5.5.0', '<')) {
380
                $okVersion = false;
381
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP version '.
382
                    phpversion().' is not OK (minimum is 5.5.0) &nbsp;&nbsp;'.
383
                    '<img src=\"images/minus-circle.png\"></span><br />';
384
            } else {
385
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">PHP version '.
386
                    phpversion().' is OK&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
387
                    '</span><br />';
388
            }
389
390
            //get infos from SETTINGS.PHP file
391
            $filename = "../includes/config/settings.php";
392
            $events = "";
393
            if (file_exists($filename)) {
394
                //copy some constants from this existing file
395
                $settingsFile = file($filename);
396
                while (list($key, $val) = each($settingsFile)) {
397
                    if (substr_count($val, 'charset') > 0) {
398
                        $superGlobal->put("charset", getSettingValue($val), "SESSION");
399
                    } elseif (substr_count($val, '@define(') > 0 && substr_count($val, 'SALT') > 0) {
400
                        $superGlobal->put("encrypt_key", substr($val, 17, strpos($val, "')") - 17), "SESSION");
401
                    } elseif (substr_count($val, '$smtp_server') > 0) {
402
                        $superGlobal->put("smtp_server", getSettingValue($val), "SESSION");
403
                    } elseif (substr_count($val, '$smtp_auth') > 0) {
404
                        $superGlobal->put("smtp_auth", getSettingValue($val), "SESSION");
405
                    } elseif (substr_count($val, '$smtp_auth_username') > 0) {
406
                        $superGlobal->put("smtp_auth_username", getSettingValue($val), "SESSION");
407
                    } elseif (substr_count($val, '$smtp_auth_password') > 0) {
408
                        $superGlobal->put("smtp_auth_password", getSettingValue($val), "SESSION");
409
                    } elseif (substr_count($val, '$smtp_port') > 0) {
410
                        $superGlobal->put("smtp_port", getSettingValue($val), "SESSION");
411
                    } elseif (substr_count($val, '$smtp_security') > 0) {
412
                        $superGlobal->put("smtp_security", getSettingValue($val), "SESSION");
413
                    } elseif (substr_count($val, '$email_from') > 0) {
414
                        $superGlobal->put("email_from", getSettingValue($val), "SESSION");
415
                    } elseif (substr_count($val, '$email_from_name') > 0) {
416
                        $superGlobal->put("email_from_name", getSettingValue($val), "SESSION");
417
                    } elseif (substr_count($val, '$server') > 0) {
418
                        $superGlobal->put("server", getSettingValue($val), "SESSION");
419
                    } elseif (substr_count($val, '$user') > 0) {
420
                        $superGlobal->put("user", getSettingValue($val), "SESSION");
421
                    } elseif (substr_count($val, '$pass') > 0) {
422
                        $superGlobal->put("pass", getSettingValue($val), "SESSION");
423
                    } elseif (substr_count($val, '$port') > 0) {
424
                        $superGlobal->put("port", getSettingValue($val), "SESSION");
425
                    } elseif (substr_count($val, '$database') > 0) {
426
                        $database = getSettingValue($val);
427
                    } elseif (substr_count($val, '$pre') > 0) {
428
                        $pre = getSettingValue($val);
429
                    } elseif (substr_count($val, "define('SECUREPATH',") > 0) {
430
                        $superGlobal->put("sk_file", substr($val, 23, strpos($val, ');')-24)."/sk.php", "SESSION");
431
                    }
432
                }
433
            }
434
            $session_sk_file = $superGlobal->get("sk_file", "SESSION");
435
            if (isset($session_sk_file) && !empty($session_sk_file)
436
                && file_exists($session_sk_file)
437
            ) {
438
                $txt .= '<span style=\"padding-left:30px;font-size:13pt;\">sk.php file'.
439
                    ' found in \"'.addslashes($session_sk_file).'\"&nbsp;&nbsp;<img src=\"images/tick-circle.png\">'.
440
                    '</span><br />';
441
                //copy some constants from this existing file
442
                $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 434

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...
443 View Code Duplication
                while (list($key, $val) = each($skFile)) {
444
                    if (substr_count($val, "@define('SALT'") > 0) {
445
                        $superGlobal->put("encrypt_key", substr($val, 17, strpos($val, "')") - 17), "SESSION");
446
                        $session_encrypt_key = $superGlobal->get("encrypt_key", "SESSION");
447
                        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 446

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

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...
483
            echo 'document.getElementById("loader").style.display = "none";';
484
            break;
485
486
            #==========================
487
        case "step2":
488
            $res = "";
489
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
490
491
            if ($session_user_granted !== "1") {
492
                echo 'document.getElementById("res_step2").innerHTML = "User not connected anymore!";';
493
                echo 'document.getElementById("loader").style.display = "none";';
494
                break;
495
            }
496
            //decrypt the password
497
            // AES Counter Mode implementation
498
            require_once 'libs/aesctr.php';
499
500
            // check in db if previous saltk exists
501
            if ($post_no_previous_sk === "false" || $post_no_previous_sk === "previous_sk_sel") {
502
                $db_sk = mysqli_fetch_row(mysqli_query($db_link, "SELECT count(*) FROM ".$pre."misc
503
                WHERE type='admin' AND intitule = 'saltkey_ante_2127'"));
504
                if (!empty($post_previous_sk) || !empty($post_session_salt)) {
505
                    // get sk
506
                    if (!empty($post_session_salt)) {
507
                        $sk_val = filter_var($post_session_salt, FILTER_SANITIZE_STRING);
508
                    } else {
509
                        $sk_val = filter_var($post_previous_sk, FILTER_SANITIZE_STRING);
510
                    }
511
512
                    // Update
513
                    if (!empty($db_sk[0])) {
514
                        mysqli_query(
515
                            $db_link,
516
                            "UPDATE `".$pre."misc`
517
                            SET `valeur` = '".$sk_val."'
518
                            WHERE type = 'admin' AND intitule = 'saltkey_ante_2127'"
519
                        );
520
                    } else {
521
                        mysqli_query(
522
                            $db_link,
523
                            "INSERT INTO `".$pre."misc`
524
                            (`valeur`, `type`, `intitule`)
525
                            VALUES ('".$sk_val."', 'admin', 'saltkey_ante_2127')"
526
                        );
527
                    }
528
                } elseif (empty($db_sk[0])) {
529
                    $res = "Please provide Teampass instance history.";
530
                    echo 'document.getElementById("but_next").disabled = "disabled";';
531
                    echo 'document.getElementById("res_step2").innerHTML = "'.$res.'";';
532
                    echo 'document.getElementById("loader").style.display = "none";';
533
                    echo 'document.getElementById("no_encrypt_key").style.display = "";';
534
                }
535
            } else {
536
                // user said that database has not being used for an older version
537
                // no old sk is available
538
                    $tmp = mysqli_num_rows(mysqli_query(
539
                        $db_link,
540
                        "SELECT * FROM `".$var['tbl_prefix']."misc`
541
                        WHERE type = 'admin' AND intitule = 'saltkey_ante_2127'"
542
                    ));
543
                if ($tmp == 0) {
544
                    mysqli_query(
545
                        $db_link,
546
                        "INSERT INTO `".$pre."misc`
547
                        (`valeur`, `type`, `intitule`)
548
                        VALUES ('none', 'admin', 'saltkey_ante_2127')"
549
                    );
550
                } else {
551
                    mysqli_query(
552
                        $db_link,
553
                        "INSERT INTO `".$pre."misc`
554
                        (`valeur`, `type`, `intitule`)
555
                        VALUES ('none', 'admin', 'saltkey_ante_2127')"
556
                    );
557
                }
558
                $superGlobal->put("tp_defuse_installed", true, "SESSION");
559
            }
560
561
            //What CPM version
562
            if (mysqli_query(
563
                $db_link,
564
                "SELECT valeur FROM ".$post_tbl_prefix."misc
565
                WHERE type='admin' AND intitule = 'cpassman_version'"
566
            )) {
567
                $tmpResult = mysqli_query(
568
                    $db_link,
569
                    "SELECT valeur FROM ".$post_tbl_prefix."misc
570
                    WHERE type='admin' AND intitule = 'cpassman_version'"
571
                );
572
                $cpmVersion = mysqli_fetch_row($tmpResult);
573
                echo 'document.getElementById("actual_cpm_version").value = "'.
574
                    $cpmVersion[0].'";';
575
            } else {
576
                echo 'document.getElementById("actual_cpm_version").value = "0";';
577
            }
578
579
            //Get some infos from DB
580
            if (@mysqli_fetch_row(
581
                mysqli_query(
582
                    $db_link,
583
                    "SELECT valeur FROM ".$post_tbl_prefix."misc
584
                    WHERE type='admin' AND intitule = 'utf8_enabled'"
585
                )
586
            )
587
            ) {
588
                $cpmIsUTF8 = mysqli_fetch_row(
589
                    mysqli_query(
590
                        $db_link,
591
                        "SELECT valeur FROM ".$post_tbl_prefix."misc
592
                        WHERE type='admin' AND intitule = 'utf8_enabled'"
593
                    )
594
                );
595
                echo 'document.getElementById("cpm_isUTF8").value = "'.$cpmIsUTF8[0].'";';
596
                $superGlobal->put("utf8_enabled", $cpmIsUTF8[0], "SESSION");
597
            } else {
598
                echo 'document.getElementById("cpm_isUTF8").value = "0";';
599
                $superGlobal->put("utf8_enabled", 0, "SESSION");
600
            }
601
602
            // put TP in maintenance mode or not
603
            @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...
604
                $db_link,
605
                "UPDATE `".$pre."misc`
606
                SET `valeur` = 'maintenance_mode'
607
                WHERE type = 'admin' AND intitule = '".$post_no_maintenance_mode."'"
608
            );
609
610
            echo 'document.getElementById("dump").style.display = "";';
611
612
613
            echo 'document.getElementById("res_step2").innerHTML = "'.$res.'";';
614
            echo 'document.getElementById("loader").style.display = "none";';
615
            break;
616
617
            #==========================
618
        case "step3":
619
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
620
621
            if ($session_user_granted !== "1") {
622
                echo 'document.getElementById("res_step3").innerHTML = "User not connected anymore!";';
623
                echo 'document.getElementById("loader").style.display = "none";';
624
                break;
625
            }
626
627
            //rename tables
628
            if (isset($post_prefix_before_convert) && $post_prefix_before_convert == "true") {
629
                $tables = mysqli_query($db_link, 'SHOW TABLES');
630
                while ($table = mysqli_fetch_row($tables)) {
631
                    if (tableExists("old_".$table[0]) != 1 && substr($table[0], 0, 4) != "old_") {
632
                        mysqli_query($db_link, "CREATE TABLE old_".$table[0]." LIKE ".$table[0]);
633
                        mysqli_query($db_link, "INSERT INTO old_".$table[0]." SELECT * FROM ".$table[0]);
634
                    }
635
                }
636
            }
637
638
            //convert database
639
            mysqli_query(
640
                $db_link,
641
                "ALTER DATABASE `".$database."`
642
                DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"
643
            );
644
645
            //convert tables
646
            $res = mysqli_query($db_link, "SHOW TABLES FROM `".$database."`");
647
            while ($table = mysqli_fetch_row($res)) {
648
                if (substr($table[0], 0, 4) != "old_") {
649
                    mysqli_query(
650
                        $db_link,
651
                        "ALTER TABLE ".$database.".`{$table[0]}`
652
                        CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci"
653
                    );
654
                    mysqli_query(
655
                        $db_link,
656
                        "ALTER TABLE".$database.".`{$table[0]}`
657
                        DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"
658
                    );
659
                }
660
            }
661
662
            echo 'document.getElementById("res_step3").innerHTML = "Done!";';
663
            echo 'document.getElementById("loader").style.display = "none";';
664
            echo 'document.getElementById("but_next").disabled = "";';
665
            echo 'document.getElementById("but_launch").disabled = "disabled";';
666
667
            mysqli_close($db_link);
668
            break;
669
670
            #==========================
671
672
673
            //=============================
674
        case "step5":
675
            $session_user_granted = $superGlobal->get("user_granted", "SESSION");
676
677
            if ($session_user_granted !== "1") {
678
                echo 'document.getElementById("res_step5").innerHTML = "User not connected anymore!";';
679
                echo 'document.getElementById("loader").style.display = "none";';
680
                break;
681
            }
682
683
            $filename = "../includes/config/settings.php";
684
            $events = "";
685
            if (file_exists($filename)) {
686
                //Do a copy of the existing file
687
                if (!copy(
688
                    $filename,
689
                    $filename.'.'.date(
690
                        "Y_m_d",
691
                        mktime(0, 0, 0, date('m'), date('d'), date('y'))
692
                    )
693
                )) {
694
                    echo 'document.getElementById("res_step5").innerHTML = '.
695
                        '"Setting.php file already exists and cannot be renamed. '.
696
                        'Please do it by yourself and click on button Launch.";';
697
                    echo 'document.getElementById("loader").style.display = "none";';
698
                    break;
699
                } else {
700
                    $events .= "The file $filename already exist. A copy has been created.<br />";
701
                    unlink($filename);
702
                }
703
704
                //manage SK path
705
                if (isset($post_sk_path) && !empty($post_sk_path)) {
706
                    $skFile = str_replace('\\', '/', $post_sk_path.'/sk.php');
707
                    $securePath = str_replace('\\', '/', $post_sk_path);
708
                } else {
709
                    echo 'document.getElementById("res_step5").innerHTML = '.
710
                        '"<img src=\"images/exclamation-red.png\"> The SK path must be indicated.";
711
                        document.getElementById("loader").style.display = "none";';
712
                    break;
713
                }
714
715
                //Check if path is ok
716
                if (is_dir($securePath)) {
717
                    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...
718
                        //Do nothing
719
                    } else {
720
                        echo 'document.getElementById("res_step5").innerHTML = '.
721
                            '"<img src=\"images/exclamation-red.png\"> The SK path must be writable!";
722
                            document.getElementById("loader").style.display = "none";';
723
                        break;
724
                    }
725
                } else {
726
                    echo 'document.getElementById("res_step5").innerHTML = '.
727
                        '"<img src=\"images/exclamation-red.png\"> '.
728
                        'Path for SK is not a Directory!";
729
                    document.getElementById("loader").style.display = "none";';
730
                    break;
731
                }
732
733
                $file_handled = fopen($filename, 'w');
734
735
                //prepare smtp_auth variable
736
                if (empty($superGlobal->get("smtp_auth", "SESSION"))) {
737
                    $superGlobal->put("smtp_auth", "false", "SESSION");
738
                }
739
                if (empty($superGlobal->get("smtp_auth_username", "SESSION"))) {
740
                    $superGlobal->put("smtp_auth_username", "false", "SESSION");
741
                }
742
                if (empty($superGlobal->get("smtp_auth_password", "SESSION"))) {
743
                    $superGlobal->put("smtp_auth_password", "false", "SESSION");
744
                }
745
                if (empty($superGlobal->get("email_from_name", "SESSION"))) {
746
                    $superGlobal->put("email_from_name", "false", "SESSION");
747
                }
748
749
                $result1 = fwrite(
750
                    $file_handled,
751
                    utf8_encode(
752
                        "<?php
753
global \$lang, \$txt, \$pathTeampas, \$urlTeampass, \$pwComplexity, \$mngPages;
754
global \$server, \$user, \$pass, \$database, \$pre, \$db, \$port, \$encoding;
755
756
### DATABASE connexion parameters ###
757
\$server = \"".$server."\";
758
\$user = \"".$user."\";
759
\$pass = \"". str_replace("$", "\\$", $pass)."\";
760
\$database = \"".$database."\";
761
\$port = ".$port.";
762
\$pre = \"".$pre."\";
763
\$encoding = \"".$encoding."\";
764
765
@date_default_timezone_set(\$_SESSION['settings']['timezone']);
766
@define('SECUREPATH', '".substr($skFile, 0, strlen($skFile) - 7)."');
767
if (file_exists(\"".$skFile."\")) {
768
    require_once \"".$skFile."\";
769
}
770
@define('COST', '13'); // Don't change this.
771
"
772
                    )
773
                );
774
775
                fclose($file_handled);
776
                if ($result1 === false) {
777
                    echo 'document.getElementById("res_step5").innerHTML = '.
778
                        '"Setting.php file could not be created. '.
779
                        'Please check the path and the rights.";';
780
                } else {
781
                    echo 'document.getElementById("step5_settingFile").innerHTML = '.
782
                        '"<img src=\"images/tick.png\">";';
783
                }
784
785
                //Create sk.php file
786
                if (!file_exists($skFile)) {
787
                    $file_handled = fopen($skFile, 'w');
788
789
                    $result2 = fwrite(
790
                        $file_handled,
791
                        utf8_encode(
792
                            "<?php
793
@define('COST', '13'); // Don't change this.
794
@define('AKEY', '');
795
@define('IKEY', '');
796
@define('SKEY', '');
797
@define('HOST', '');
798
?>"
799
                        )
800
                    );
801
                    fclose($file_handled);
802
                }
803
804
                // update CSRFP TOKEN
805
                $csrfp_file_sample = "../includes/libraries/csrfp/libs/csrfp.config.sample.php";
806
                $csrfp_file = "../includes/libraries/csrfp/libs/csrfp.config.php";
807
                if (file_exists($csrfp_file)) {
808
                    if (!copy($filename, $filename.'.'.date("Y_m_d", mktime(0, 0, 0, date('m'), date('d'), date('y'))))) {
809
                        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.'"}]';
810
                        break;
811
                    } else {
812
                        $events .= "The file $csrfp_file already exist. A copy has been created.<br />";
813
                    }
814
                }
815
                unlink($csrfp_file); // delete existing csrfp.config file
816
                copy($csrfp_file_sample, $csrfp_file); // make a copy of csrfp.config.sample file
817
                $data = file_get_contents("../includes/libraries/csrfp/libs/csrfp.config.php");
818
                $newdata = str_replace('"CSRFP_TOKEN" => ""', '"CSRFP_TOKEN" => "'.bin2hex(openssl_random_pseudo_bytes(25)).'"', $data);
819
                $newdata = str_replace('"tokenLength" => "25"', '"tokenLength" => "50"', $newdata);
820
                $jsUrl = $_SESSION['fullurl'].'/includes/libraries/csrfp/js/csrfprotector.js';
821
                $newdata = str_replace('"jsUrl" => ""', '"jsUrl" => "'.$jsUrl.'"', $newdata);
822
                $newdata = str_replace('"verifyGetFor" => array()', '"verifyGetFor" => array("*page=items&type=duo_check*")', $newdata);
823
                file_put_contents("../includes/libraries/csrfp/libs/csrfp.config.php", $newdata);
824
825
826
                // finalize
827
                if (isset($result2) && $result2 === false) {
828
                    echo 'document.getElementById("res_step5").innerHTML = '.
829
                        '"$skFile could not be created. Please check the path and the rights.";';
830
                } else {
831
                    echo 'document.getElementById("step5_skFile").innerHTML = '.
832
                        '"<img src=\"images/tick.png\">";';
833
                }
834
835
                //Finished
836
                if ($result1 !== false
837
                    && (!isset($result2) || (isset($result2) && $result2 !== false))
838
                ) {
839
                    echo 'document.getElementById("but_next").disabled = "";';
840
                    echo 'document.getElementById("res_step5").innerHTML = '.
841
                        '"Operations are successfully completed.";';
842
                    echo 'document.getElementById("loader").style.display = "none";';
843
                    echo 'document.getElementById("but_launch").disabled = "disabled";';
844
                }
845
            } else {
846
                //settings.php file doesn't exit => ERROR !!!!
847
                echo 'document.getElementById("res_step5").innerHTML = '.
848
                        '"<img src=\"images/error.png\">&nbsp;Setting.php '.
849
                        'file doesn\'t exist! Upgrade can\'t continue without this file.<br />'.
850
                        'Please copy your existing settings.php into the \"includes\" '.
851
                        'folder of your TeamPass installation ";';
852
                echo 'document.getElementById("loader").style.display = "none";';
853
            }
854
855
            break;
856
857
        case "perform_database_dump":
858
            $filename = "../includes/config/settings.php";
859
860
            require_once "../sources/main.functions.php";
861
            $pass = defuse_return_decrypted($pass);
862
863
            $mtables = array();
864
865
            $mysqli = new mysqli($server, $user, $pass, $database, $port);
866
            if ($mysqli->connect_error) {
867
                die('Error : ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
868
            }
869
870
            $results = $mysqli->query("SHOW TABLES");
871
872
            while ($row = $results->fetch_array()) {
873
                $mtables[] = $row[0];
874
            }
875
876
            foreach ($mtables as $table) {
877
                $contents .= "-- Table `".$table."` --\n";
878
879
                $results = $mysqli->query("SHOW CREATE TABLE ".$table);
880
                while ($row = $results->fetch_array()) {
881
                    $contents .= $row[1].";\n\n";
882
                }
883
884
                $results = $mysqli->query("SELECT * FROM ".$table);
885
                $row_count = $results->num_rows;
886
                $fields = $results->fetch_fields();
887
                $fields_count = count($fields);
888
889
                $insert_head = "INSERT INTO `".$table."` (";
890
                for ($i = 0; $i < $fields_count; $i++) {
891
                    $insert_head .= "`".$fields[$i]->name."`";
892
                    if ($i < $fields_count - 1) {
893
                        $insert_head .= ', ';
894
                    }
895
                }
896
                $insert_head .= ")";
897
                $insert_head .= " VALUES\n";
898
899
                if ($row_count > 0) {
900
                    $r = 0;
901
                    while ($row = $results->fetch_array()) {
902
                        if (($r % 400) == 0) {
903
                            $contents .= $insert_head;
904
                        }
905
                        $contents .= "(";
906
                        for ($i = 0; $i < $fields_count; $i++) {
907
                            $row_content = str_replace("\n", "\\n", $mysqli->real_escape_string($row[$i]));
908
909
                            switch ($fields[$i]->type) {
910
                                case 8: case 3:
911
                                    $contents .= $row_content;
912
                                    break;
913
                                default:
914
                                    $contents .= "'".$row_content."'";
915
                            }
916
                            if ($i < $fields_count - 1) {
917
                                $contents .= ', ';
918
                            }
919
                        }
920
                        if (($r + 1) == $row_count || ($r % 400) == 399) {
921
                            $contents .= ");\n\n";
922
                        } else {
923
                            $contents .= "),\n";
924
                        }
925
                        $r++;
926
                    }
927
                }
928
            }
929
930
            $backup_file_name = "sql-backup-".date("d-m-Y--h-i-s").".sql";
931
932
            $fp = fopen("../files/".$backup_file_name, 'w+');
933
            if (($result = fwrite($fp, $contents))) {
934
                echo '[{ "error" : "" , "file" : "files/'.$backup_file_name.'"}]';
935
            } else {
936
                echo '[{ "error" : "Backup fails - please do it manually."}]';
937
            }
938
            fclose($fp);
939
940
            break;
941
    }
942
}
943