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