Completed
Push — development ( 8b4e00...3f8e8f )
by Nils
08:22
created

main.queries.php ➔ mainQuery()   F

Complexity

Conditions 151
Paths 211

Size

Total Lines 1184
Code Lines 722

Duplication

Lines 49
Ratio 4.14 %

Importance

Changes 0
Metric Value
cc 151
eloc 722
nc 211
nop 0
dl 49
loc 1184
rs 3.8533
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 *
4
 * @file          main.queries.php
5
 * @author        Nils Laumaillé
6
 * @version       2.1.27
7
 * @copyright     (c) 2009-2017 Nils Laumaillé
8
 * @licensing     GNU AFFERO GPL 3.0
9
 * @link          http://www.teampass.net
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
 */
15
16
$debugLdap = 0; //Can be used in order to debug LDAP authentication
17
18
require_once 'SecureHandler.php';
19
session_start();
20
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
21
    $_SESSION['error']['code'] = "1004"; //Hacking attempt
22
    include '../error.php';
23
    exit();
24
}
25
26
// Load config
27 View Code Duplication
if (file_exists('../includes/config/tp.config.php')) {
28
    require_once '../includes/config/tp.config.php';
29
} elseif (file_exists('./includes/config/tp.config.php')) {
30
    require_once './includes/config/tp.config.php';
31
} else {
32
    throw new Exception("Error file '/includes/config/tp.config.php' not exists", 1);
33
}
34
35
/* do checks */
36
require_once $SETTINGS['cpassman_dir'].'/includes/config/include.php';
37
require_once $SETTINGS['cpassman_dir'].'/sources/checks.php';
38
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
39
if (isset($post_type) && ($post_type === "ga_generate_qr"
40
    || $post_type === "send_pw_by_email" || $post_type === "generate_new_password")
41
) {
42
    // continue
43
    mainQuery();
44
} elseif (isset($_SESSION['user_id']) && !checkUser($_SESSION['user_id'], $_SESSION['key'], "home")) {
45
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
46
    include $SETTINGS['cpassman_dir'].'/error.php';
47
    exit();
48
} elseif ((isset($_SESSION['user_id']) && isset($_SESSION['key'])) ||
49
    (isset($post_type) && $post_type === "change_user_language"
50
        && null !== filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES))
51
) {
52
    // continue
53
    mainQuery();
54
} else {
55
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
56
    include $SETTINGS['cpassman_dir'].'/error.php';
57
    exit();
58
}
59
60
/*
61
** Executes expected queries
62
*/
63
function mainQuery()
64
{
65
    global $server, $user, $pass, $database, $port, $encoding, $pre, $LANG;
66
    global $SETTINGS;
67
68
    include $SETTINGS['cpassman_dir'].'/includes/config/settings.php';
69
    header("Content-type: text/html; charset=utf-8");
70
    header("Cache-Control: no-cache, must-revalidate");
71
    header("Pragma: no-cache");
72
    error_reporting(E_ERROR);
73
    require_once $SETTINGS['cpassman_dir'].'/sources/main.functions.php';
74
    require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
75
76
    // connect to the server
77
    require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
78
    $pass = defuse_return_decrypted($pass);
79
    DB::$host = $server;
80
    DB::$user = $user;
81
    DB::$password = $pass;
82
    DB::$dbName = $database;
83
    DB::$port = $port;
84
    DB::$encoding = $encoding;
85
    DB::$error_handler = true;
86
    $link = mysqli_connect($server, $user, $pass, $database, $port);
87
    $link->set_charset($encoding);
88
89
    // User's language loading
90
    require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
91
    // Manage type of action asked
92
    switch (filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING)) {
93
        case "change_pw":
94
            // decrypt and retreive data in JSON format
95
            $dataReceived = prepareExchangedData(
96
                filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES),
97
                "decode"
98
            );
99
100
            // load passwordLib library
101
            $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
102
            $pwdlib->register();
103
            $pwdlib = new PasswordLib\PasswordLib();
104
105
            // Prepare variables
106
            $newPw = $pwdlib->createPasswordHash(htmlspecialchars_decode($dataReceived['new_pw']));
107
108
            // User has decided to change is PW
109
            if (null !== filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING)
110
                && filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) === "user_change"
111
                && $_SESSION['user_admin'] !== "1"
112
            ) {
113
                // check if expected security level is reached
114
                $data_roles = DB::queryfirstrow("SELECT fonction_id FROM ".prefix_table("users")." WHERE id = %i", $_SESSION['user_id']);
115
116
                // check if badly written
117
                $data_roles['fonction_id'] = array_filter(explode(',', str_replace(';', ',', $data_roles['fonction_id'])));
118
                if ($data_roles['fonction_id'][0] === "") {
119
                    $data_roles['fonction_id'] = implode(';', $data_roles['fonction_id']);
120
                    DB::update(
121
                        prefix_table("users"),
122
                        array(
123
                            'fonction_id' => $data_roles['fonction_id']
124
                            ),
125
                        "id = %i",
126
                        $_SESSION['user_id']
127
                    );
128
                }
129
130
                $data = DB::query(
131
                    "SELECT complexity
132
                    FROM ".prefix_table("roles_title")."
133
                    WHERE id IN (".implode(',', $data_roles['fonction_id']).")
134
                    ORDER BY complexity DESC"
135
                );
136
                if (intval(filter_input(INPUT_POST, 'complexity', FILTER_SANITIZE_NUMBER_INT)) < intval($data[0]['complexity'])) {
137
                    echo '[ { "error" : "complexity_level_not_reached" } ]';
138
                    break;
139
                }
140
141
                // Get a string with the old pw array
142
                $lastPw = explode(';', $_SESSION['last_pw']);
143
                // if size is bigger then clean the array
144
                if (sizeof($lastPw) > $SETTINGS['number_of_used_pw']
145
                        && $SETTINGS['number_of_used_pw'] > 0
146
                ) {
147
                    for ($x_counter = 0; $x_counter < $SETTINGS['number_of_used_pw']; $x_counter++) {
148
                        unset($lastPw[$x_counter]);
149
                    }
150
                    // reinit SESSION
151
                    $_SESSION['last_pw'] = implode(';', $lastPw);
152
                    // specific case where admin setting "number_of_used_pw"
153
                } elseif ($SETTINGS['number_of_used_pw'] == 0) {
154
                    $_SESSION['last_pw'] = "";
155
                    $lastPw = array();
156
                }
157
158
                // check if new pw is different that old ones
159
                if (in_array($newPw, $lastPw)) {
160
                    echo '[ { "error" : "already_used" } ]';
161
                    break;
162
                }
163
164
                // update old pw with new pw
165
                if (sizeof($lastPw) == ($SETTINGS['number_of_used_pw'] + 1)) {
166
                    unset($lastPw[0]);
167
                } else {
168
                    array_push($lastPw, $newPw);
169
                }
170
                // create a list of last pw based on the table
171
                $oldPw = "";
172
                foreach ($lastPw as $elem) {
173
                    if (!empty($elem)) {
174
                        if (empty($oldPw)) {
175
                            $oldPw = $elem;
176
                        } else {
177
                            $oldPw .= ";".$elem;
178
                        }
179
                    }
180
                }
181
182
                // update sessions
183
                $_SESSION['last_pw'] = $oldPw;
184
                $_SESSION['last_pw_change'] = mktime(0, 0, 0, date('m'), date('d'), date('y'));
185
                $_SESSION['validite_pw'] = true;
186
187
                // BEfore updating, check that the pwd is correct
188
                if ($pwdlib->verifyPasswordHash(htmlspecialchars_decode($dataReceived['new_pw']), $newPw) === true) {
189
                    // update DB
190
                    DB::update(
191
                        prefix_table("users"),
192
                        array(
193
                            'pw' => $newPw,
194
                            'last_pw_change' => mktime(0, 0, 0, date('m'), date('d'), date('y')),
195
                            'last_pw' => $oldPw
196
                            ),
197
                        "id = %i",
198
                        $_SESSION['user_id']
199
                    );
200
                    // update LOG
201
                    logEvents('user_mngt', 'at_user_pwd_changed', $_SESSION['user_id'], $_SESSION['login'], $_SESSION['user_id']);
202
                    echo '[ { "error" : "none" } ]';
203
                } else {
204
                     echo '[ { "error" : "pwd_hash_not_correct" } ]';
205
                }
206
                break;
207
208
            // ADMIN has decided to change the USER's PW
209
            } elseif (null !== filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING)
210
                && ((filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) === "admin_change"
211
                    || filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) === "user_change"
212
                    ) && ($_SESSION['user_admin'] === "1"|| $_SESSION['user_manager'] === "1"
213
                    || $_SESSION['user_can_manage_all_users'] === "1")
214
                )
215
            ) {
216
                // check if user is admin / Manager
217
                $userInfo = DB::queryFirstRow(
218
                    "SELECT admin, gestionnaire
219
                    FROM ".prefix_table("users")."
220
                    WHERE id = %i",
221
                    $_SESSION['user_id']
222
                );
223
                if ($userInfo['admin'] != 1 && $userInfo['gestionnaire'] != 1) {
224
                    echo '[ { "error" : "not_admin_or_manager" } ]';
225
                    break;
226
                }
227
228
                // BEfore updating, check that the pwd is correct
229
                if ($pwdlib->verifyPasswordHash(htmlspecialchars_decode($dataReceived['new_pw']), $newPw) === true) {
230
                    // adapt
231
                    if (filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) === "user_change") {
232
                        $dataReceived['user_id'] = $_SESSION['user_id'];
233
                    }
234
235
                    // update DB
236
                    DB::update(
237
                        prefix_table("users"),
238
                        array(
239
                            'pw' => $newPw,
240
                            'last_pw_change' => mktime(0, 0, 0, date('m'), date('d'), date('y'))
241
                            ),
242
                        "id = %i",
243
                        $dataReceived['user_id']
244
                    );
245
246
                    // update LOG
247
                    logEvents('user_mngt', 'at_user_pwd_changed', $_SESSION['user_id'], $_SESSION['login'], $dataReceived['user_id']);
248
249
                    //Send email to user
250
                    if (filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) !== "admin_change") {
251
                        $row = DB::queryFirstRow(
252
                            "SELECT email FROM ".prefix_table("users")."
253
                            WHERE id = %i",
254
                            $dataReceived['user_id']
255
                        );
256
                        if (!empty($row['email']) && isset($SETTINGS['enable_email_notification_on_user_pw_change']) && $SETTINGS['enable_email_notification_on_user_pw_change'] == 1) {
257
                            sendEmail(
258
                                $LANG['forgot_pw_email_subject'],
259
                                $LANG['forgot_pw_email_body']." ".htmlspecialchars_decode($dataReceived['new_pw']),
260
                                $row[0],
261
                                $LANG['forgot_pw_email_altbody_1']." ".htmlspecialchars_decode($dataReceived['new_pw'])
262
                            );
263
                        }
264
                    }
265
266
                    echo '[ { "error" : "none" } ]';
267
                } else {
268
                    echo '[ { "error" : "pwd_hash_not_correct" } ]';
269
                }
270
                break;
271
272
                // ADMIN first login
273
            } elseif (null !== filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING)
274
                && filter_input(INPUT_POST, 'change_pw_origine', FILTER_SANITIZE_STRING) == "first_change"
275
            ) {
276
                // update DB
277
                DB::update(
278
                    prefix_table("users"),
279
                    array(
280
                        'pw' => $newPw,
281
                        'last_pw_change' => mktime(0, 0, 0, date('m'), date('d'), date('y'))
282
                        ),
283
                    "id = %i",
284
                    $_SESSION['user_id']
285
                );
286
287
                // update sessions
288
                $_SESSION['last_pw'] = "";
289
                $_SESSION['last_pw_change'] = mktime(0, 0, 0, date('m'), date('d'), date('y'));
290
                $_SESSION['validite_pw'] = true;
291
292
                // update LOG
293
                logEvents('user_mngt', 'at_user_initial_pwd_changed', $_SESSION['user_id'], $_SESSION['login'], $_SESSION['user_id']);
294
295
                echo '[ { "error" : "none" } ]';
296
                break;
297
            } else {
298
                // DEFAULT case
299
                echo '[ { "error" : "nothing_to_do" } ]';
300
            }
301
            break;
302
        /**
303
         * This will generate the QR Google Authenticator
304
         */
305
        case "ga_generate_qr":
306
            // is this allowed by setting
307
            if ((isset($SETTINGS['ga_reset_by_user']) === false || $SETTINGS['ga_reset_by_user'] !== "1")
308
                && (null === filter_input(INPUT_POST, 'demand_origin', FILTER_SANITIZE_STRING)
309
                    || filter_input(INPUT_POST, 'demand_origin', FILTER_SANITIZE_STRING) !== "users_management_list")
310
            ) {
311
                // User cannot ask for a new code
312
                echo '[{"error" : "not_allowed"}]';
313
                break;
314
            }
315
316
            // Check if user exists
317
            if (null === filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)
318
                || empty(filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)) === true
319
            ) {
320
                // decrypt and retreive data in JSON format
321
                $dataReceived = prepareExchangedData(
322
                    filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES),
323
                    "decode"
324
                );
325
                // Prepare variables
326
                $login = htmlspecialchars_decode($dataReceived['login']);
327
328
                $data = DB::queryfirstrow(
329
                    "SELECT id, email
330
                    FROM ".prefix_table("users")."
331
                    WHERE login = %s",
332
                    $login
333
                );
334
            } else {
335
                $data = DB::queryfirstrow(
336
                    "SELECT id, login, email
337
                    FROM ".prefix_table("users")."
338
                    WHERE id = %i",
339
                    filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)
340
                );
341
            }
342
            $counter = DB::count();
343
            if ($counter == 0) {
344
                // not a registered user !
345
                echo '[{"error" : "no_user"}]';
346
            } else {
347
                if (empty($data['email'])) {
348
                    echo '[{"error" : "no_email"}]';
349
                } else {
350
                    // generate new GA user code
351
                    include_once($SETTINGS['cpassman_dir']."/includes/libraries/Authentication/TwoFactorAuth/TwoFactorAuth.php");
352
                    $tfa = new Authentication\TwoFactorAuth\TwoFactorAuth($SETTINGS['ga_website_name']);
353
                    $gaSecretKey = $tfa->createSecret();
354
                    $gaTemporaryCode = GenerateCryptKey(12);
355
356
                    // save the code
357
                    DB::update(
358
                        prefix_table("users"),
359
                        array(
360
                            'ga' => $gaSecretKey,
361
                            'ga_temporary_code' => $gaTemporaryCode
362
                            ),
363
                        "id = %i",
364
                        $data['id']
365
                    );
366
367
                    // send mail?
368
                    if (null !== filter_input(INPUT_POST, 'send_email', FILTER_SANITIZE_STRING)
369
                        && filter_input(INPUT_POST, 'send_email', FILTER_SANITIZE_STRING) === "1"
370
                    ) {
371
                        sendEmail(
372
                            $LANG['email_ga_subject'],
373
                            str_replace(
374
                                "#2FACode#",
375
                                $gaTemporaryCode,
376
                                $LANG['email_ga_text']
377
                            ),
378
                            $data['email']
379
                        );
380
                    }
381
382
                    // send back
383
                    echo '[{ "error" : "0" , "email" : "'.$data['email'].'" , "msg" : "'.str_replace("#email#", "<b>".$data['email']."</b>", addslashes($LANG['admin_email_result_ok'])).'"}]';
384
                }
385
            }
386
            break;
387
        /**
388
         * Increase the session time of User
389
         */
390
        case "increase_session_time":
391
            // check if session is not already expired.
392
            if ($_SESSION['fin_session'] > time()) {
393
                // Calculate end of session
394
                $_SESSION['fin_session'] = (integer) ($_SESSION['fin_session'] + filter_input(INPUT_POST, 'duration', FILTER_SANITIZE_NUMBER_INT));
395
                // Update table
396
                DB::update(
397
                    prefix_table("users"),
398
                    array(
399
                        'session_end' => $_SESSION['fin_session']
400
                    ),
401
                    "id = %i",
402
                    $_SESSION['user_id']
403
                );
404
                // Return data
405
                echo '[{"new_value":"'.$_SESSION['fin_session'].'"}]';
406
            } else {
407
                echo '[{"new_value":"expired"}]';
408
            }
409
            break;
410
        /**
411
         * Hide maintenance message
412
         */
413
        case "hide_maintenance":
414
            $_SESSION['hide_maintenance'] = 1;
415
            break;
416
        /**
417
         * Used in order to send the password to the user by email
418
         */
419
        case "send_pw_by_email":
420
            // generate key
421
            $key = GenerateCryptKey(50);
422
423
            // Prepare post variables
424
            $post_email = mysqli_escape_string($link, stripslashes(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING)));
425
            $post_login = mysqli_escape_string($link, filter_input(INPUT_POST, 'login', FILTER_SANITIZE_STRING));
426
427
            // Get account and pw associated to email
428
            DB::query(
429
                "SELECT * FROM ".prefix_table("users")." WHERE email = %s",
430
                $post_email
431
            );
432
            $counter = DB::count();
433
            if ($counter != 0) {
434
                $data = DB::query(
435
                    "SELECT login,pw FROM ".prefix_table("users")." WHERE email = %s",
436
                    $post_email
437
                );
438
                $textMail = $LANG['forgot_pw_email_body_1']." <a href=\"".
439
                    $SETTINGS['cpassman_url']."/index.php?action=password_recovery&key=".$key.
440
                    "&login=".$post_login."\">".$SETTINGS['cpassman_url'].
441
                    "/index.php?action=password_recovery&key=".$key."&login=".$post_login."</a>.<br><br>".$LANG['thku'];
442
                $textMailAlt = $LANG['forgot_pw_email_altbody_1']." ".$LANG['at_login']." : ".$post_login." - ".
443
                    $LANG['index_password']." : ".md5($data['pw']);
444
445
                // Check if email has already a key in DB
446
                DB::query(
447
                    "SELECT * FROM ".prefix_table("misc")." WHERE intitule = %s AND type = %s",
448
                    $post_login,
449
                    "password_recovery"
450
                );
451
                $counter = DB::count();
452
                if ($counter != 0) {
453
                    DB::update(
454
                        prefix_table("misc"),
455
                        array(
456
                            'valeur' => $key
457
                        ),
458
                        "type = %s and intitule = %s",
459
                        "password_recovery",
460
                        $post_login
461
                    );
462
                } else {
463
                    // store in DB the password recovery informations
464
                    DB::insert(
465
                        prefix_table("misc"),
466
                        array(
467
                            'type' => 'password_recovery',
468
                            'intitule' => $post_login,
469
                            'valeur' => $key
470
                        )
471
                    );
472
                }
473
474
                echo '[{'.sendEmail($LANG['forgot_pw_email_subject'], $textMail, $post_email, $textMailAlt).'}]';
475
            } else {
476
                // no one has this email ... alert
477
                echo '[{"error":"error_email" , "message":"'.$LANG['forgot_my_pw_error_email_not_exist'].'"}]';
478
            }
479
            break;
480
481
        // Send to user his new pw if key is conform
482
        case "generate_new_password":
483
            // decrypt and retreive data in JSON format
484
            $dataReceived = prepareExchangedData(
485
                filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES),
486
                "decode"
487
            );
488
489
            // Prepare variables
490
            $login = htmlspecialchars_decode($dataReceived['login']);
491
            $key = htmlspecialchars_decode($dataReceived['key']);
492
493
            // check if key is okay
494
            $data = DB::queryFirstRow(
495
                "SELECT valeur FROM ".prefix_table("misc")." WHERE intitule = %s AND type = %s",
496
                mysqli_escape_string($link, $login),
497
                "password_recovery"
498
            );
499
            if ($key == $data['valeur']) {
500
                // load passwordLib library
501
                $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
502
                $pwdlib->register();
503
                $pwdlib = new PasswordLib\PasswordLib();
504
505
                // generate key
506
                $newPwNotCrypted = $pwdlib->getRandomToken(10);
507
508
                // Prepare variables
509
                $newPw = $pwdlib->createPasswordHash(($newPwNotCrypted));
510
511
                // update DB
512
                DB::update(
513
                    prefix_table("users"),
514
                    array(
515
                        'pw' => $newPw
516
                        ),
517
                    "login = %s",
518
                    mysqli_escape_string($link, $login)
519
                );
520
                // Delete recovery in DB
521
                DB::delete(
522
                    prefix_table("misc"),
523
                    "type = %s AND intitule = %s AND valeur = %s",
524
                    "password_recovery",
525
                    mysqli_escape_string($link, $login),
526
                    $key
527
                );
528
                // Get email
529
                $dataUser = DB::queryFirstRow(
530
                    "SELECT email FROM ".prefix_table("users")." WHERE login = %s",
531
                    mysqli_escape_string($link, $login)
532
                );
533
534
                $_SESSION['validite_pw'] = false;
535
                // send to user
536
                $ret = json_decode(
537
                    sendEmail(
538
                        $LANG['forgot_pw_email_subject_confirm'],
539
                        $LANG['forgot_pw_email_body']." ".$newPwNotCrypted,
540
                        $dataUser['email'],
541
                        strip_tags($LANG['forgot_pw_email_body'])." ".$newPwNotCrypted
542
                    )
543
                );
544
                // send email
545
                if (empty($ret['error'])) {
546
                    echo 'done';
547
                } else {
548
                    echo $ret['message'];
549
                }
550
            }
551
            break;
552
        /**
553
         * Store the personal saltkey
554
         */
555
        case "store_personal_saltkey":
556
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
557
                echo '[ { "error" : "key_not_conform" , "status" : "nok" } ]';
558
                break;
559
            }
560
561
            $err = "";
0 ignored issues
show
Unused Code introduced by
$err is not used, you could remove the assignment.

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

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

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

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

Loading history...
562
            $dataReceived = prepareExchangedData(
563
                filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES),
564
                "decode"
565
            );
566
            $filter_score = filter_var($dataReceived['score'], FILTER_SANITIZE_NUMBER_INT);
567
            $filter_psk = filter_var($dataReceived['psk'], FILTER_SANITIZE_STRING);
568
569
            // manage store
570
            if ($filter_psk !== "") {
571
                // store in session the cleartext for psk
572
                $_SESSION['user_settings']['clear_psk'] = $filter_psk;
573
574
                // check if encrypted_psk is in database. If not, add it
575
                if (!isset($_SESSION['user_settings']['encrypted_psk']) || (isset($_SESSION['user_settings']['encrypted_psk']) && empty($_SESSION['user_settings']['encrypted_psk']))) {
576
                    // Check if security level is reach (if enabled)
577 View Code Duplication
                    if (isset($SETTINGS['personal_saltkey_security_level']) === true) {
578
                        // Did we received the pass score
579
                        if (empty($filter_score) === false) {
580
                            if (intval($SETTINGS['personal_saltkey_security_level']) > $filter_score) {
581
                                echo '[ { "error" : "security_level_not_reached" , "status" : "" } ]';
582
                                break;
583
                            }
584
                        }
585
                    }
586
                    // generate it based upon clear psk
587
                    $_SESSION['user_settings']['encrypted_psk'] = defuse_generate_personal_key($filter_psk);
588
589
                    // store it in DB
590
                    DB::update(
591
                        prefix_table("users"),
592
                        array(
593
                            'encrypted_psk' => $_SESSION['user_settings']['encrypted_psk']
594
                            ),
595
                        "id = %i",
596
                        $_SESSION['user_id']
597
                    );
598
                }
599
600
                // check if psk is correct.
601
                $user_key_encoded = defuse_validate_personal_key(
602
                    $filter_psk,
603
                    $_SESSION['user_settings']['encrypted_psk']
604
                );
605
606
                if (strpos($user_key_encoded, "Error ") !== false) {
607
                    echo '[ { "error" : "psk_not_correct" , "status" : "" } ]';
608
                    break;
609
                } else {
610
                    // Check if security level is reach (if enabled)
611 View Code Duplication
                    if (isset($SETTINGS['personal_saltkey_security_level']) === true) {
612
                        // Did we received the pass score
613
                        if (empty($filter_score) === false) {
614
                            if (intval($SETTINGS['personal_saltkey_security_level']) > $filter_score) {
615
                                echo '[ { "error" : "" , "status" : "security_level_not_reached_but_psk_correct" } ]';
616
                                break;
617
                            }
618
                        }
619
                    }
620
                    // Store PSK
621
                    $_SESSION['user_settings']['session_psk'] = $user_key_encoded;
622
                    setcookie(
623
                        "TeamPass_PFSK_".md5($_SESSION['user_id']),
624
                        encrypt($filter_psk, ""),
625
                        (!isset($SETTINGS['personal_saltkey_cookie_duration']) || $SETTINGS['personal_saltkey_cookie_duration'] == 0) ? time() + 60 * 60 * 24 : time() + 60 * 60 * 24 * $SETTINGS['personal_saltkey_cookie_duration'],
626
                        '/'
627
                    );
628
                }
629
            } else {
630
                echo '[ { "error" : "psk_is_empty" , "status" : "" } ]';
631
                break;
632
            }
633
634
            echo '[ { "error" : "" , "status" : "ok" } ]';
635
636
            break;
637
        /**
638
         * Change the personal saltkey
639
         */
640
        case "change_personal_saltkey":
641
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
642
                echo '[{"error" : "something_wrong"}]';
643
                break;
644
            }
645
646
            //init
647
            $list = "";
648
            $number = 0;
649
650
            //decrypt and retreive data in JSON format
651
            $dataReceived = prepareExchangedData(
652
                filter_input(INPUT_POST, 'data_to_share', FILTER_SANITIZE_STRING),
653
                "decode"
654
            );
655
656
            //Prepare variables
657
            $newPersonalSaltkey = htmlspecialchars_decode($dataReceived['sk']);
658
            $oldPersonalSaltkey = htmlspecialchars_decode($dataReceived['old_sk']);
659
660
            // check old psk
661
            $user_key_encoded = defuse_validate_personal_key(
662
                $oldPersonalSaltkey,
663
                $_SESSION['user_settings']['encrypted_psk']
664
            );
665
            if (strpos($user_key_encoded, "Error ") !== false) {
666
                echo prepareExchangedData(
667
                    array(
668
                        "list" => $list,
669
                        "error" => $user_key_encoded,
670
                        "nb_total" => $number
671
                    ),
672
                    "encode"
673
                );
674
                break;
675
            } else {
676
                // Store PSK
677
                $_SESSION['user_settings']['encrypted_oldpsk'] = $user_key_encoded;
678
            }
679
680
            // generate the new encrypted psk based upon clear psk
681
            $_SESSION['user_settings']['encrypted_psk'] = defuse_generate_personal_key($newPersonalSaltkey);
682
683
            // store it in DB
684
            DB::update(
685
                prefix_table("users"),
686
                array(
687
                    'encrypted_psk' => $_SESSION['user_settings']['encrypted_psk']
688
                    ),
689
                "id = %i",
690
                $_SESSION['user_id']
691
            );
692
693
            $user_key_encoded = defuse_validate_personal_key(
694
                $newPersonalSaltkey,
695
                $_SESSION['user_settings']['encrypted_psk']
696
            );
697
            $_SESSION['user_settings']['session_psk'] = $user_key_encoded;
698
699
            // Change encryption
700
            // Build list of items to be re-encrypted
701
            $rows = DB::query(
702
                "SELECT i.id as id, i.pw as pw
703
                FROM ".prefix_table("items")." as i
704
                INNER JOIN ".prefix_table("log_items")." as l ON (i.id=l.id_item)
705
                WHERE i.perso = %i AND l.id_user= %i AND l.action = %s",
706
                "1",
707
                $_SESSION['user_id'],
708
                "at_creation"
709
            );
710
            $number = DB::count();
711
            foreach ($rows as $record) {
712 View Code Duplication
                if (!empty($record['pw'])) {
713
                    if (empty($list)) {
714
                        $list = $record['id'];
715
                    } else {
716
                        $list .= ",".$record['id'];
717
                    }
718
                }
719
            }
720
721
            // change salt
722
            setcookie(
723
                "TeamPass_PFSK_".md5($_SESSION['user_id']),
724
                encrypt($newPersonalSaltkey, ""),
725
                time() + 60 * 60 * 24 * $SETTINGS['personal_saltkey_cookie_duration'],
726
                '/'
727
            );
728
729
            echo prepareExchangedData(
730
                array(
731
                    "list" => $list,
732
                    "error" => "no",
733
                    "nb_total" => $number
734
                ),
735
                "encode"
736
            );
737
            break;
738
        /**
739
         * Reset the personal saltkey
740
         */
741
        case "reset_personal_saltkey":
742
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
743
                echo '[{"error" : "something_wrong"}]';
744
                break;
745
            }
746
747
            if (!empty($_SESSION['user_id'])) {
748
                // delete all previous items of this user
749
                $rows = DB::query(
750
                    "SELECT i.id as id
751
                    FROM ".prefix_table("items")." as i
752
                    INNER JOIN ".prefix_table("log_items")." as l ON (i.id=l.id_item)
753
                    WHERE i.perso = %i AND l.id_user= %i AND l.action = %s",
754
                    "1",
755
                    $_SESSION['user_id'],
756
                    "at_creation"
757
                );
758
                foreach ($rows as $record) {
759
                    // delete in ITEMS table
760
                    DB::delete(prefix_table("items"), "id = %i", $record['id']);
761
                    // delete in LOGS table
762
                    DB::delete(prefix_table("log_items"), "id_item = %i", $record['id']);
763
                    // delete from CACHE table
764
                    updateCacheTable("delete_value", $record['id']);
765
                }
766
767
                // remove from DB
768
                DB::update(
769
                    prefix_table("users"),
770
                    array(
771
                        'encrypted_psk' => ""
772
                        ),
773
                    "id = %i",
774
                    $_SESSION['user_id']
775
                );
776
777
                $_SESSION['user_settings']['session_psk'] = "";
778
            }
779
            break;
780
        /**
781
         * Change the user's language
782
         */
783
        case "change_user_language":
784
            if (!empty($_SESSION['user_id'])) {
785
                // decrypt and retreive data in JSON format
786
                $dataReceived = prepareExchangedData(
787
                    filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES),
788
                    "decode"
789
                );
790
                // Prepare variables
791
                $language = $dataReceived['lang'];
792
                // update DB
793
                DB::update(
794
                    prefix_table("users"),
795
                    array(
796
                        'user_language' => $language
797
                        ),
798
                    "id = %i",
799
                    $_SESSION['user_id']
800
                );
801
                $_SESSION['user_language'] = $language;
802
                echo "done";
803
            } else {
804
                $_SESSION['user_language'] = "";
805
                echo "done";
806
            }
807
            break;
808
        /**
809
         * Send emails not sent
810
         */
811
        case "send_waiting_emails":
812
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
813
                echo '[ { "error" : "key_not_conform" } ]';
814
                break;
815
            }
816
817
            if (isset($SETTINGS['enable_send_email_on_user_login'])
818
                && $SETTINGS['enable_send_email_on_user_login'] == 1
819
                && isset($_SESSION['key'])
820
            ) {
821
                $row = DB::queryFirstRow(
822
                    "SELECT valeur FROM ".prefix_table("misc")." WHERE type = %s AND intitule = %s",
823
                    "cron",
824
                    "sending_emails"
825
                );
826
                if ((time() - $row['valeur']) >= 300 || $row['valeur'] == 0) {
827
                    //load library
828
                    require $SETTINGS['cpassman_dir'].'/includes/libraries/Email/Phpmailer/PHPMailerAutoload.php';
829
                    // load PHPMailer
830
                    $mail = new PHPMailer();
831
832
                    $mail->setLanguage("en", "../includes/libraries/Email/Phpmailer/language");
833
                    $mail->isSmtp(); // send via SMTP
834
                    $mail->Host = $SETTINGS['email_smtp_server']; // SMTP servers
835
                    $mail->SMTPAuth = $SETTINGS['email_smtp_auth']; // turn on SMTP authentication
836
                    $mail->Username = $SETTINGS['email_auth_username']; // SMTP username
837
                    $mail->Password = $SETTINGS['email_auth_pwd']; // SMTP password
838
                    $mail->From = $SETTINGS['email_from'];
839
                    $mail->FromName = $SETTINGS['email_from_name'];
840
                    $mail->WordWrap = 80; // set word wrap
841
                    $mail->isHtml(true); // send as HTML
842
                    $rows = DB::query("SELECT * FROM ".prefix_table("emails")." WHERE status != %s", "sent");
843
                    foreach ($rows as $record) {
844
                        // send email
845
                        $ret = json_decode(
846
                            @sendEmail(
847
                                $record['subject'],
848
                                $record['body'],
849
                                $record['receivers']
850
                            )
851
                        );
852
853
                        if (!empty($ret['error'])) {
854
                            $status = "not_sent";
855
                        } else {
856
                            $status = "sent";
857
                        }
858
                        // update item_id in files table
859
                        DB::update(
860
                            prefix_table("emails"),
861
                            array(
862
                                'status' => $status
863
                                ),
864
                            "timestamp = %s",
865
                            $record['timestamp']
866
                        );
867
                        if ($status == "not_sent") {
868
                            break;
869
                        }
870
                    }
871
                }
872
                // update cron time
873
                DB::update(
874
                    prefix_table("misc"),
875
                    array(
876
                        'valeur' => time()
877
                        ),
878
                    "intitule = %s AND type = %s",
879
                    "sending_emails",
880
                    "cron"
881
                );
882
            }
883
            break;
884
885
        /**
886
         * Store error
887
         */
888
        case "store_error":
889
            if (!empty($_SESSION['user_id'])) {
890
                // update DB
891
                logEvents(
892
                    'error',
893
                    urldecode(filter_input(INPUT_POST, 'error', FILTER_SANITIZE_STRING)),
894
                    $_SESSION['user_id'],
895
                    $_SESSION['login']
896
                );
897
            }
898
            break;
899
900
        /**
901
         * Generate a password generic
902
         */
903
        case "generate_a_password":
904 View Code Duplication
            if (filter_input(INPUT_POST, 'size', FILTER_SANITIZE_NUMBER_INT) > $SETTINGS['pwd_maximum_length']) {
905
                echo prepareExchangedData(
906
                    array(
907
                        "error_msg" => "Password length is too long!",
908
                        "error" => "true"
909
                    ),
910
                    "encode"
911
                );
912
                break;
913
            }
914
915
            //Load PWGEN
916
            $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
917
            $pwgen->register();
918
            $pwgen = new Encryption\PwGen\pwgen();
919
920
            $pwgen->setLength(filter_input(INPUT_POST, 'size', FILTER_SANITIZE_NUMBER_INT));
921
            if (null !== filter_input(INPUT_POST, 'secure', FILTER_SANITIZE_STRING)
922
                && filter_input(INPUT_POST, 'secure', FILTER_SANITIZE_STRING) === "true"
923
            ) {
924
                $pwgen->setSecure(true);
925
                $pwgen->setSymbols(true);
926
                $pwgen->setCapitalize(true);
927
                $pwgen->setNumerals(true);
928
            } else {
929
                $pwgen->setSecure((filter_input(INPUT_POST, 'secure', FILTER_SANITIZE_STRING) === "true") ? true : false);
930
                $pwgen->setNumerals((filter_input(INPUT_POST, 'numerals', FILTER_SANITIZE_STRING) === "true") ? true : false);
931
                $pwgen->setCapitalize((filter_input(INPUT_POST, 'capitalize', FILTER_SANITIZE_STRING) === "true") ? true : false);
932
                $pwgen->setSymbols((filter_input(INPUT_POST, 'symbols', FILTER_SANITIZE_STRING) === "true") ? true : false);
933
            }
934
935
            echo prepareExchangedData(
936
                array(
937
                    "key" => $pwgen->generate(),
938
                    "error" => ""
939
                ),
940
                "encode"
941
            );
942
            break;
943
        /**
944
         * Check if user exists and send back if psk is set
945
         */
946
        case "check_login_exists":
947
            $data = DB::query(
948
                "SELECT login, psk FROM ".prefix_table("users")."
949
                WHERE login = %i",
950
                mysqli_escape_string($link, stripslashes(filter_input(INPUT_POST, 'userId', FILTER_SANITIZE_NUMBER_INT)))
951
            );
952
            if (empty($data['login'])) {
953
                $userOk = false;
954
            } else {
955
                $userOk = true;
956
            }
957
            if (isset($SETTINGS['psk_authentication']) && $SETTINGS['psk_authentication'] == 1
958
                && !empty($data['psk'])
959
            ) {
960
                $pskSet = true;
961
            } else {
962
                $pskSet = false;
963
            }
964
965
            echo '[{"login" : "'.$userOk.'", "psk":"'.$pskSet.'"}]';
966
            break;
967
        /**
968
         * Make statistics on item
969
         */
970
        case "item_stat":
971
            if (null !== filter_input(INPUT_POST, 'scope', FILTER_SANITIZE_STRING)
972
                && filter_input(INPUT_POST, 'scope', FILTER_SANITIZE_STRING) === "item"
973
            ) {
974
                $data = DB::queryfirstrow(
975
                    "SELECT view FROM ".prefix_table("statistics")." WHERE scope = %s AND item_id = %i",
976
                    'item',
977
                    filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)
978
                );
979
                $counter = DB::count();
980
                if ($counter == 0) {
981
                    DB::insert(
982
                        prefix_table("statistics"),
983
                        array(
984
                            'scope' => 'item',
985
                            'view' => '1',
986
                            'item_id' => filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)
987
                        )
988
                    );
989
                } else {
990
                    DB::update(
991
                        prefix_table("statistics"),
992
                        array(
993
                            'scope' => 'item',
994
                            'view' => $data['view'] + 1
995
                        ),
996
                        "item_id = %i",
997
                        filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT)
998
                    );
999
                }
1000
            }
1001
1002
            break;
1003
        /**
1004
         * Refresh list of last items seen
1005
         */
1006
        case "refresh_list_items_seen":
1007
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
1008
                echo '[ { "error" : "key_not_conform" } ]';
1009
                break;
1010
            }
1011
1012
            // get list of last items seen
1013
            $x_counter = 1;
1014
            $return = "";
0 ignored issues
show
Unused Code introduced by
$return is not used, you could remove the assignment.

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

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

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

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

Loading history...
1015
            $arrTmp = array();
1016
            $arr_html = array();
1017
            $rows = DB::query(
1018
                "SELECT i.id AS id, i.label AS label, i.id_tree AS id_tree, l.date
1019
                FROM ".prefix_table("log_items")." AS l
1020
                RIGHT JOIN ".prefix_table("items")." AS i ON (l.id_item = i.id)
1021
                WHERE l.action = %s AND l.id_user = %i
1022
                ORDER BY l.date DESC
1023
                LIMIT 0, 100",
1024
                "at_shown",
1025
                $_SESSION['user_id']
1026
            );
1027
            if (DB::count() > 0) {
1028
                foreach ($rows as $record) {
1029
                    if (!in_array($record['id'], $arrTmp)) {
1030
                        array_push(
1031
                            $arr_html,
1032
                            array(
1033
                                "id" => $record['id'],
1034
                                "label" => htmlspecialchars(stripslashes(htmlspecialchars_decode($record['label'], ENT_QUOTES)), ENT_QUOTES),
1035
                                "tree_id" => $record['id_tree']
1036
                            )
1037
                        );
1038
                        $x_counter++;
1039
                        array_push($arrTmp, $record['id']);
1040
                        if ($x_counter >= 10) {
1041
                            break;
1042
                        }
1043
                    }
1044
                }
1045
            }
1046
1047
            // get wainting suggestions
1048
            $nb_suggestions_waiting = 0;
1049
            if (isset($SETTINGS['enable_suggestion']) && $SETTINGS['enable_suggestion'] == 1
1050
                && ($_SESSION['user_admin'] == 1 || $_SESSION['user_manager'] == 1)
1051
            ) {
1052
                DB::query("SELECT * FROM ".prefix_table("suggestion"));
1053
                $nb_suggestions_waiting = DB::count();
1054
            }
1055
1056
            echo json_encode(
1057
                array(
1058
                    "error" => "",
1059
                    "existing_suggestions" => $nb_suggestions_waiting,
1060
                    "html_json" => $arr_html
1061
                ),
1062
                JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
1063
            );
1064
            break;
1065
1066
        /**
1067
         * Generates a KEY with CRYPT
1068
         */
1069
        case "generate_new_key":
1070
            // load passwordLib library
1071
            $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
1072
            $pwdlib->register();
1073
            $pwdlib = new PasswordLib\PasswordLib();
1074
            // generate key
1075
            $key = $pwdlib->getRandomToken(filter_input(INPUT_POST, 'size', FILTER_SANITIZE_NUMBER_INT));
1076
            echo '[{"key" : "'.htmlentities($key, ENT_QUOTES).'"}]';
1077
            break;
1078
1079
        /**
1080
         * Generates a TOKEN with CRYPT
1081
         */
1082
        case "save_token":
1083
            $token = GenerateCryptKey(
1084
                null !== filter_input(INPUT_POST, 'size', FILTER_SANITIZE_NUMBER_INT) ? filter_input(INPUT_POST, 'size', FILTER_SANITIZE_NUMBER_INT) : 20,
1085
                null !== filter_input(INPUT_POST, 'secure', FILTER_SANITIZE_STRING) ? filter_input(INPUT_POST, 'secure', FILTER_SANITIZE_STRING) : false,
1086
                null !== filter_input(INPUT_POST, 'capital', FILTER_SANITIZE_STRING) ? filter_input(INPUT_POST, 'capital', FILTER_SANITIZE_STRING) : false,
1087
                null !== filter_input(INPUT_POST, 'numeric', FILTER_SANITIZE_STRING) ? filter_input(INPUT_POST, 'numeric', FILTER_SANITIZE_STRING) : false,
1088
                null !== filter_input(INPUT_POST, 'ambiguous', FILTER_SANITIZE_STRING) ? filter_input(INPUT_POST, 'ambiguous', FILTER_SANITIZE_STRING) : false,
1089
                null !== filter_input(INPUT_POST, 'symbols', FILTER_SANITIZE_STRING) ? filter_input(INPUT_POST, 'symbols', FILTER_SANITIZE_STRING) : false
1090
            );
1091
1092
            // store in DB
1093
            DB::insert(
1094
                prefix_table("tokens"),
1095
                array(
1096
                    'user_id' => $_SESSION['user_id'],
1097
                    'token' => $token,
1098
                    'reason' => filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_STRING),
1099
                    'creation_timestamp' => time(),
1100
                    'end_timestamp' => time() + filter_input(INPUT_POST, 'duration', FILTER_SANITIZE_NUMBER_INT)    // in secs
1101
                )
1102
            );
1103
1104
            echo '[{"token" : "'.$token.'"}]';
1105
            break;
1106
1107
        /**
1108
         * Create list of timezones
1109
         */
1110
        case "generate_timezones_list":
1111
            $array = array();
1112
            foreach (timezone_identifiers_list() as $zone) {
1113
                $array[$zone] = $zone;
1114
            }
1115
1116
            echo json_encode($array);
1117
            break;
1118
1119
        /**
1120
         * Check if suggestions are existing
1121
         */
1122
        case "is_existings_suggestions":
1123
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
1124
                echo '[ { "error" : "key_not_conform" } ]';
1125
                break;
1126
            }
1127
1128
            if ($_SESSION['user_manager'] === "1" || $_SESSION['is_admin'] === "1") {
1129
                $count = 0;
1130
                DB::query("SELECT * FROM ".$pre."items_change");
1131
                $count += DB::count();
1132
                DB::query("SELECT * FROM ".$pre."suggestion");
1133
                $count += DB::count();
1134
1135
                echo '[ { "error" : "" , "count" : "'.$count.'" , "show_sug_in_menu" : "0"} ]';
1136
            } elseif (isset($_SESSION['nb_item_change_proposals']) && $_SESSION['nb_item_change_proposals'] > 0) {
1137
                echo '[ { "error" : "" , "count" : "'.$_SESSION['nb_item_change_proposals'].'" , "show_sug_in_menu" : "1"} ]';
1138
            } else {
1139
                echo '[ { "error" : "" , "count" : "" , "show_sug_in_menu" : "0"} ]';
1140
            }
1141
1142
            break;
1143
1144
        /**
1145
         * Check if suggestions are existing
1146
         */
1147
        case "sending_statistics":
1148
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
1149
                echo '[ { "error" : "key_not_conform" } ]';
1150
                break;
1151
            }
1152
1153
            if (isset($SETTINGS['send_statistics_items']) && isset($SETTINGS['send_stats']) && isset($SETTINGS['send_stats_time'])
1154
                && $SETTINGS['send_stats'] === "1"
1155
                && ($SETTINGS['send_stats_time'] + $SETTINGS_EXT['one_day_seconds']) > time()
0 ignored issues
show
Bug introduced by
The variable $SETTINGS_EXT does not exist. Did you mean $SETTINGS?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1156
            ) {
1157
                // get statistics data
1158
                $stats_data = getStatisticsData();
1159
1160
1161
                // get statistics items to share
1162
                $statsToSend = [];
1163
                $statsToSend['ip'] = $_SERVER['SERVER_ADDR'];
1164
                $statsToSend['timestamp'] = time();
1165
                foreach (array_filter(explode(";", $SETTINGS['send_statistics_items'])) as $data) {
1166
                    if ($data === "stat_languages") {
1167
                        $tmp = "";
1168 View Code Duplication
                        foreach ($stats_data[$data] as $key => $value) {
1169
                            if (empty($tmp)) {
1170
                                $tmp = $key."-".$value;
1171
                            } else {
1172
                                $tmp .= ",".$key."-".$value;
1173
                            }
1174
                        }
1175
                        $statsToSend[$data] = $tmp;
1176
                    } elseif ($data === "stat_country") {
1177
                        $tmp = "";
1178 View Code Duplication
                        foreach ($stats_data[$data] as $key => $value) {
1179
                            if (empty($tmp)) {
1180
                                $tmp = $key."-".$value;
1181
                            } else {
1182
                                $tmp .= ",".$key."-".$value;
1183
                            }
1184
                        }
1185
                        $statsToSend[$data] = $tmp;
1186
                    } else {
1187
                        $statsToSend[$data] = $stats_data[$data];
1188
                    }
1189
                }
1190
1191
                // connect to Teampass Statistics database
1192
                db::debugmode(true);
1193
                $link2 = new MeekroDB(
1194
                    "sql11.freemysqlhosting.net",
1195
                    "sql11197223",
1196
                    "3QzpXYQ9dZ",
1197
                    "sql11197223",
1198
                    "3306",
1199
                    "utf8"
1200
                );
1201
1202
                $link2->insert(
1203
                    "statistics",
1204
                    $statsToSend
1205
                );
1206
1207
                // update table misc with current timestamp
1208
                DB::update(
1209
                    prefix_table("misc"),
1210
                    array(
1211
                        'valeur' => time()
1212
                        ),
1213
                    "type = %s AND intitule = %s",
1214
                    'admin',
1215
                    'send_stats_time'
1216
                );
1217
1218
1219
                //permits to test only once by session
1220
                $_SESSION['temporary']['send_stats_done'] = true;
1221
                $SETTINGS['send_stats_time'] = time();
1222
1223
                // save change in config file
1224
                handleConfigFile("update", 'send_stats_time', $SETTINGS['send_stats_time']);
1225
1226
                echo '[ { "error" : "" , "done" : "1"} ]';
1227
            } else {
1228
                echo '[ { "error" : "" , "done" : "0"} ]';
1229
            }
1230
1231
            break;
1232
1233
        /**
1234
         * delete a file
1235
         */
1236
        case "file_deletion":
1237
            if (filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING) !== $_SESSION['key']) {
1238
                echo '[ { "error" : "key_not_conform" } ]';
1239
                break;
1240
            }
1241
1242
            fileDelete(filter_input(INPUT_POST, 'filename', FILTER_SANITIZE_STRING));
1243
1244
            break;
1245
    }
1246
}
1247