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

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

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

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