Completed
Push — development ( a5a40b...b096dd )
by Nils
07:37
created

main.functions.php ➔ identifyUserRights()   F

Complexity

Conditions 49
Paths 612

Size

Total Lines 295
Code Lines 193

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 49
eloc 193
nc 612
nop 5
dl 0
loc 295
rs 2
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.functions.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
10
 */
11
12
//define pbkdf2 iteration count
13
define('ITCOUNT', '2072');
14
15
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
16
    die('Hacking attempt...');
17
}
18
19
// load phpCrypt
20
if (!isset($_SESSION['settings']['cpassman_dir']) || empty($_SESSION['settings']['cpassman_dir'])) {
21
    require_once '../includes/libraries/phpcrypt/phpCrypt.php';
22
    require_once '../includes/config/settings.php';
23
} else {
24
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/phpcrypt/phpCrypt.php';
25
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/config/settings.php';
26
}
27
use PHP_Crypt\PHP_Crypt as PHP_Crypt;
28
29
30
// prepare Encryption class calls
31
use \Defuse\Crypto\Crypto;
32
use \Defuse\Crypto\Exception as Ex;
33
34
//Generate N# of random bits for use as salt
35
/**
36
 * @param integer $n
37
 */
38
function getBits($n)
39
{
40
    $str = '';
41
    $x = $n + 10;
42
    for ($i = 0; $i < $x; $i++) {
43
        $str .= base_convert(mt_rand(1, 36), 10, 36);
44
    }
45
    return substr($str, 0, $n);
46
}
47
48
//generate pbkdf2 compliant hash
49 View Code Duplication
function strHashPbkdf2($p, $s, $c, $kl, $a = 'sha256', $st = 0)
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...
50
{
51
    $kb = $st + $kl; // Key blocks to compute
52
    $dk = ''; // Derived key
53
54
    for ($block = 1; $block <= $kb; $block++) { // Create key
55
        $ib = $h = hash_hmac($a, $s.pack('N', $block), $p, true); // Initial hash for this block
56
        for ($i = 1; $i < $c; $i++) { // Perform block iterations
57
            $ib ^= ($h = hash_hmac($a, $h, $p, true)); // XOR each iterate
58
        }
59
        $dk .= $ib; // Append iterated block
60
    }
61
    return substr($dk, $st, $kl); // Return derived key of correct length
62
}
63
64
/**
65
 * stringUtf8Decode()
66
 *
67
 * utf8_decode
68
 */
69
function stringUtf8Decode($string)
70
{
71
    return str_replace(" ", "+", utf8_decode($string));
72
}
73
74
/**
75
 * encryptOld()
76
 *
77
 * crypt a string
78
 * @param string $text
79
 */
80 View Code Duplication
function encryptOld($text, $personalSalt = "")
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...
81
{
82
    if (!empty($personalSalt)) {
83
        return trim(
84
            base64_encode(
85
                mcrypt_encrypt(
86
                    MCRYPT_RIJNDAEL_256,
87
                    $personalSalt,
88
                    $text,
89
                    MCRYPT_MODE_ECB,
90
                    mcrypt_create_iv(
91
                        mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
92
                        MCRYPT_RAND
93
                    )
94
                )
95
            )
96
        );
97
    } else {
98
        return trim(
99
            base64_encode(
100
                mcrypt_encrypt(
101
                    MCRYPT_RIJNDAEL_256,
102
                    SALT,
103
                    $text,
104
                    MCRYPT_MODE_ECB,
105
                    mcrypt_create_iv(
106
                        mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
107
                        MCRYPT_RAND
108
                    )
109
                )
110
            )
111
        );
112
    }
113
}
114
115
/**
116
 * decryptOld()
117
 *
118
 * decrypt a crypted string
119
 */
120 View Code Duplication
function decryptOld($text, $personalSalt = "")
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...
121
{
122
    if (!empty($personalSalt)) {
123
        return trim(
124
            mcrypt_decrypt(
125
                MCRYPT_RIJNDAEL_256,
126
                $personalSalt,
127
                base64_decode($text),
128
                MCRYPT_MODE_ECB,
129
                mcrypt_create_iv(
130
                    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
131
                    MCRYPT_RAND
132
                )
133
            )
134
        );
135
    } else {
136
        return trim(
137
            mcrypt_decrypt(
138
                MCRYPT_RIJNDAEL_256,
139
                SALT,
140
                base64_decode($text),
141
                MCRYPT_MODE_ECB,
142
                mcrypt_create_iv(
143
                    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
144
                    MCRYPT_RAND
145
                )
146
            )
147
        );
148
    }
149
}
150
151
/**
152
 * encrypt()
153
 *
154
 * crypt a string
155
 * @param string $decrypted
156
 */
157
function encrypt($decrypted, $personalSalt = "")
158
{
159 View Code Duplication
    if (!isset($_SESSION['settings']['cpassman_dir']) || empty($_SESSION['settings']['cpassman_dir'])) {
160
        require_once '../includes/libraries/Encryption/PBKDF2/PasswordHash.php';
161
    } else {
162
        require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Encryption/PBKDF2/PasswordHash.php';
163
    }
164
165
    if (!empty($personalSalt)) {
166
            $staticSalt = $personalSalt;
167
    } else {
168
            $staticSalt = SALT;
169
    }
170
171
    //set our salt to a variable
172
    // Get 64 random bits for the salt for pbkdf2
173
    $pbkdf2Salt = getBits(64);
174
    // generate a pbkdf2 key to use for the encryption.
175
    $key = substr(pbkdf2('sha256', $staticSalt, $pbkdf2Salt, ITCOUNT, 16 + 32, true), 32, 16);
176
    // Build $iv and $ivBase64.  We use a block size of 256 bits (AES compliant)
177
    // and CTR mode.  (Note: ECB mode is inadequate as IV is not used.)
178
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, 'ctr'), MCRYPT_RAND);
179
180
    //base64 trim
181
    if (strlen($ivBase64 = rtrim(base64_encode($iv), '=')) != 43) {
182
        return false;
183
    }
184
    // Encrypt $decrypted
185
    $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $decrypted, 'ctr', $iv);
186
    // MAC the encrypted text
187
    $mac = hash_hmac('sha256', $encrypted, $staticSalt);
188
    // We're done!
189
    return base64_encode($ivBase64.$encrypted.$mac.$pbkdf2Salt);
190
}
191
192
/**
193
 * decrypt()
194
 *
195
 * decrypt a crypted string
196
 */
197
function decrypt($encrypted, $personalSalt = "")
198
{
199 View Code Duplication
    if (!isset($_SESSION['settings']['cpassman_dir']) || empty($_SESSION['settings']['cpassman_dir'])) {
200
        require_once '../includes/libraries/Encryption/PBKDF2/PasswordHash.php';
201
    } else {
202
        require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Encryption/PBKDF2/PasswordHash.php';
203
    }
204
205
    if (!empty($personalSalt)) {
206
        $staticSalt = $personalSalt;
207
    } else {
208
        $staticSalt = SALT;
209
    }
210
    //base64 decode the entire payload
211
    $encrypted = base64_decode($encrypted);
212
    // get the salt
213
    $pbkdf2Salt = substr($encrypted, -64);
214
    //remove the salt from the string
215
    $encrypted = substr($encrypted, 0, -64);
216
    $key = substr(pbkdf2('sha256', $staticSalt, $pbkdf2Salt, ITCOUNT, 16 + 32, true), 32, 16);
217
    // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
218
    $iv = base64_decode(substr($encrypted, 0, 43).'==');
219
    // Remove $iv from $encrypted.
220
    $encrypted = substr($encrypted, 43);
221
    // Retrieve $mac which is the last 64 characters of $encrypted.
222
    $mac = substr($encrypted, -64);
223
    // Remove the last 64 chars from encrypted (remove MAC)
224
    $encrypted = substr($encrypted, 0, -64);
225
    //verify the sha256hmac from the encrypted data before even trying to decrypt it
226
    if (hash_hmac('sha256', $encrypted, $staticSalt) != $mac) {
227
        return false;
228
    }
229
    // Decrypt the data.
230
    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "\0\4");
231
    // Yay!
232
    return $decrypted;
233
}
234
235
236
/**
237
 * genHash()
238
 *
239
 * Generate a hash for user login
240
 * @param string $password
241
 */
242 View Code Duplication
function bCrypt($password, $cost)
0 ignored issues
show
Best Practice introduced by
The function bCrypt() has been defined more than once; this definition is ignored, only the first definition in install/install.queries.php (L58-70) 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...
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...
243
{
244
    $salt = sprintf('$2y$%02d$', $cost);
245
    if (function_exists('openssl_random_pseudo_bytes')) {
246
        $salt .= bin2hex(openssl_random_pseudo_bytes(11));
247
    } else {
248
        $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
249
        for ($i = 0; $i < 22; $i++) {
250
            $salt .= $chars[mt_rand(0, 63)];
251
        }
252
    }
253
    return crypt($password, $salt);
254
}
255
256
function cryption_before_defuse($message, $sk, $iv, $type = null, $scope = "public")
257
{
258
    if (DEFUSE_ENCRYPTION === TRUE) {
259
        if ($scope === "perso") {
260
            return defuse_crypto(
261
                $message,
262
                $sk,
263
                $type
264
            );
265
        } else {
266
            return defuse_crypto(
267
                $message,
268
                file_get_contents(SECUREPATH."/teampass-seckey.txt"),
269
                $type
270
            );
271
        }
272
    } else {
273
        return cryption_phpCrypt($message, $sk, $iv, $type);
274
    }
275
}
276
277
/*
278
 * cryption() - Encrypt and decrypt string based upon phpCrypt library
279
 *
280
 * Using AES_128 and mode CBC
281
 *
282
 * $key and $iv have to be given in hex format
283
 */
284
function cryption_phpCrypt($string, $key, $iv, $type)
285
{
286
    // manage key origin
287
    define('SALT', 'LEfzTjADMTzV6qHC');
288
289
    if ($key != SALT) {
290
        // check key (AES-128 requires a 16 bytes length key)
291
        if (strlen($key) < 16) {
292
            for ($x = strlen($key) + 1; $x <= 16; $x++) {
293
                $key .= chr(0);
294
            }
295
        } else if (strlen($key) > 16) {
296
            $key = substr($key, 16);
297
        }
298
    }
299
300
    // load crypt
301
    $crypt = new PHP_Crypt($key, PHP_Crypt::CIPHER_AES_128, PHP_Crypt::MODE_CBC);
302
303
    if ($type == "encrypt") {
304
        // generate IV and encrypt
305
        $iv = $crypt->createIV();
306
        $encrypt = $crypt->encrypt($string);
307
        // return
308
        return array(
309
            "string" => bin2hex($encrypt),
310
            "iv" => bin2hex($iv),
311
            "error" => empty($encrypt) ? "ERR_ENCRYPTION_NOT_CORRECT" : ""
312
        );
313
    } else if ($type == "decrypt") {
314
        // case if IV is empty
315
        if (empty($iv)) {
316
                    return array(
317
                'string' => "",
318
                'error' => "ERR_ENCRYPTION_NOT_CORRECT"
319
            );
320
        }
321
322
        // convert
323
        try {
324
            $string = testHex2Bin(trim($string));
325
            $iv = testHex2Bin($iv);
326
        } catch (Exception $e) {
327
            return array(
328
                'string' => "",
329
                'error' => "ERR_ENCRYPTION_NOT_CORRECT"
330
            );
331
        }
332
333
        // load IV
334
        $crypt->IV($iv);
335
        // decrypt
336
        $decrypt = $crypt->decrypt($string);
337
        // return
338
        return array(
339
            'string' => str_replace(chr(0), "", $decrypt),
340
            'error' => ""
341
        );
342
    }
343
}
344
345
function testHex2Bin($val)
346
{
347
    if (!@hex2bin($val)) {
348
        throw new Exception("ERROR");
349
    }
350
    return hex2bin($val);
351
}
352
353
/**
354
 * @param string $ascii_key
355
 * @param string $type
356
 */
357
function cryption($message, $ascii_key, $type) //defuse_crypto
358
{
359
    // load PhpEncryption library
360 View Code Duplication
    if (!isset($_SESSION['settings']['cpassman_dir']) || empty($_SESSION['settings']['cpassman_dir'])) {
361
        $path = '../includes/libraries/Encryption/Encryption/';
362
    } else {
363
        $path = $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Encryption/Encryption/';
364
    }
365
366
    require_once $path.'Crypto.php';
367
    require_once $path.'Encoding.php';
368
    require_once $path.'DerivedKeys.php';
369
    require_once $path.'Key.php';
370
    require_once $path.'KeyOrPassword.php';
371
    require_once $path.'File.php';
372
    require_once $path.'RuntimeTests.php';
373
    require_once $path.'KeyProtectedByPassword.php';
374
    require_once $path.'Core.php';
375
376
    // init
377
    $err = '';
378
    if (empty($ascii_key)) {
379
        $ascii_key = file_get_contents(SECUREPATH."/teampass-seckey.txt");
380
    }
381
382
    // convert KEY
383
    $key = \Defuse\Crypto\Key::loadFromAsciiSafeString($ascii_key);
384
385
    try {
386
        if ($type === "encrypt") {
387
            $text = \Defuse\Crypto\Crypto::encrypt($message, $key);
388
        } else if ($type === "decrypt") {
389
            $text = \Defuse\Crypto\Crypto::decrypt($message, $key);
390
        }
391
    } catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) {
392
        $err = "An attack! Either the wrong key was loaded, or the ciphertext has changed since it was created either corrupted in the database or intentionally modified by someone trying to carry out an attack.";
393
    } catch (Defuse\Crypto\Exception\BadFormatException $ex) {
394
        $err = $ex;
395
    } catch (Defuse\Crypto\Exception\EnvironmentIsBrokenException $ex) {
396
        $err = $ex;
397
    } catch (Defuse\Crypto\Exception\CryptoException $ex) {
398
        $err = $ex;
399
    } catch (Defuse\Crypto\Exception\IOException $ex) {
400
        $err = $ex;
401
    }
402
403
    return array(
404
        'string' => isset($text) ? $text : "",
405
        'error' => $err
406
    );
407
}
408
409
function defuse_generate_key() {
410
    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
411
    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
412
    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
413
    require_once '../includes/libraries/Encryption/Encryption/Key.php';
414
    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
415
    require_once '../includes/libraries/Encryption/Encryption/File.php';
416
    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
417
    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
418
    require_once '../includes/libraries/Encryption/Encryption/Core.php';
419
420
    $key = \Defuse\Crypto\Key::createNewRandomKey();
421
    $key = $key->saveToAsciiSafeString();
422
    return $key;
423
}
424
425
function defuse_generate_personal_key($psk) {
426
    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
427
    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
428
    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
429
    require_once '../includes/libraries/Encryption/Encryption/Key.php';
430
    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
431
    require_once '../includes/libraries/Encryption/Encryption/File.php';
432
    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
433
    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
434
    require_once '../includes/libraries/Encryption/Encryption/Core.php';
435
436
    $protected_key = \Defuse\Crypto\KeyProtectedByPassword::createRandomPasswordProtectedKey($psk);
437
    $protected_key_encoded = $protected_key->saveToAsciiSafeString();
438
439
    return $protected_key_encoded; // save this in user table
440
}
441
442
/**
443
 * @param string $psk
444
 */
445
function defuse_validate_personal_key($psk, $protected_key_encoded) {
446
    require_once '../includes/libraries/Encryption/Encryption/Crypto.php';
447
    require_once '../includes/libraries/Encryption/Encryption/Encoding.php';
448
    require_once '../includes/libraries/Encryption/Encryption/DerivedKeys.php';
449
    require_once '../includes/libraries/Encryption/Encryption/Key.php';
450
    require_once '../includes/libraries/Encryption/Encryption/KeyOrPassword.php';
451
    require_once '../includes/libraries/Encryption/Encryption/File.php';
452
    require_once '../includes/libraries/Encryption/Encryption/RuntimeTests.php';
453
    require_once '../includes/libraries/Encryption/Encryption/KeyProtectedByPassword.php';
454
    require_once '../includes/libraries/Encryption/Encryption/Core.php';
455
456
    try {
457
        $protected_key = \Defuse\Crypto\KeyProtectedByPassword::loadFromAsciiSafeString($protected_key_encoded);
458
        $user_key = $protected_key->unlockKey($psk);
459
        $user_key_encoded = $user_key->saveToAsciiSafeString();
460
    } catch (Defuse\Crypto\Exception\EnvironmentIsBrokenException $ex) {
461
        return "Error - Major issue as the encryption is broken.";
462
    } catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) {
463
        return "Error - The saltkey is not the correct one.";
464
    }
465
466
    return $user_key_encoded; // store it in session once user has entered his psk
467
}
468
469
/**
470
 * trimElement()
471
 *
472
 * trim a string depending on a specific string
473
 * @param string $element
474
 * @return string
475
 */
476
function trimElement($chaine, $element)
477
{
478
    if (!empty($chaine)) {
479
        $chaine = trim($chaine);
480
        if (substr($chaine, 0, 1) == $element) {
481
            $chaine = substr($chaine, 1);
482
        }
483
        if (substr($chaine, strlen($chaine) - 1, 1) == $element) {
484
            $chaine = substr($chaine, 0, strlen($chaine) - 1);
485
        }
486
    }
487
    return $chaine;
488
}
489
490
/**
491
 * cleanString()
492
 *
493
 * permits to suppress all "special" characters from string
494
 */
495
function cleanString($string, $special = false)
496
{
497
    // Create temporary table for special characters escape
498
    $tabSpecialChar = array();
499
    for ($i = 0; $i <= 31; $i++) {
500
        $tabSpecialChar[] = chr($i);
501
    }
502
    array_push($tabSpecialChar, "<br />");
503
    if ($special == "1") {
504
        $tabSpecialChar = array_merge($tabSpecialChar, array("</li>", "<ul>", "<ol>"));
505
    }
506
507
    return str_replace($tabSpecialChar, "\n", $string);
508
}
509
510
function db_error_handler($params) {
511
    echo "Error: ".$params['error']."<br>\n";
512
    echo "Query: ".$params['query']."<br>\n";
513
    die; // don't want to keep going if a query broke
514
}
515
516
/**
517
 * identifyUserRights()
518
 *
519
 * @return
520
 * @param boolean $refresh
521
 */
522
function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmin, $idFonctions, $refresh)
523
{
524
    global $server, $user, $pass, $database, $pre, $port, $encoding;
525
526
    //load ClassLoader
527
    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
528
529
    //Connect to DB
530
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
531
    DB::$host = $server;
532
    DB::$user = $user;
533
    DB::$password = $pass;
534
    DB::$dbName = $database;
535
    DB::$port = $port;
536
    DB::$encoding = $encoding;
537
    DB::$error_handler = true;
538
    $link = mysqli_connect($server, $user, $pass, $database, $port);
539
    $link->set_charset($encoding);
540
541
    //Build tree
542
    $tree = new SplClassLoader('Tree\NestedTree', $_SESSION['settings']['cpassman_dir'].'/includes/libraries');
543
    $tree->register();
544
    $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
545
546
    // Check if user is ADMINISTRATOR
547
    if ($isAdmin == 1) {
548
        $groupesVisibles = array();
549
        $_SESSION['personal_folders'] = array();
550
        $_SESSION['groupes_visibles'] = array();
551
        $_SESSION['groupes_interdits'] = array();
552
        $_SESSION['personal_visible_groups'] = array();
553
        $_SESSION['read_only_folders'] = array();
554
        $_SESSION['list_restricted_folders_for_items'] = array();
555
        $_SESSION['list_folders_editable_by_role'] = array();
556
        $_SESSION['list_folders_limited'] = array();
557
        $_SESSION['groupes_visibles_list'] = "";
558
        $_SESSION['list_folders_limited'] = "";
559
        $rows = DB::query("SELECT id FROM ".prefix_table("nested_tree")." WHERE personal_folder = %i", 0);
560
        foreach ($rows as $record) {
561
            array_push($groupesVisibles, $record['id']);
562
        }
563
        $_SESSION['groupes_visibles'] = $groupesVisibles;
564
        $_SESSION['all_non_personal_folders'] = $groupesVisibles;
565
        // Exclude all PF
566
        $_SESSION['forbiden_pfs'] = array();
567
        $where = new WhereClause('and'); // create a WHERE statement of pieces joined by ANDs
568
        $where->add('personal_folder=%i', 1);
569
        if (isset($_SESSION['settings']['enable_pf_feature']) && $_SESSION['settings']['enable_pf_feature'] == 1) {
570
            $where->add('title=%s', $_SESSION['user_id']);
571
            $where->negateLast();
572
        }
573
        // Get ID of personal folder
574
        $pf = DB::queryfirstrow(
575
            "SELECT id FROM ".prefix_table("nested_tree")." WHERE title = %s",
576
            $_SESSION['user_id']
577
        );
578
        if (!empty($pf['id'])) {
579
            if (!in_array($pf['id'], $_SESSION['groupes_visibles'])) {
580
                array_push($_SESSION['groupes_visibles'], $pf['id']);
581
                array_push($_SESSION['personal_visible_groups'], $pf['id']);
582
                // get all descendants
583
                $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title', 'personal_folder');
0 ignored issues
show
Unused Code introduced by
The call to NestedTree::__construct() has too many arguments starting with 'personal_folder'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
584
                $tree->rebuild();
585
                $tst = $tree->getDescendants($pf['id']);
586
                foreach ($tst as $t) {
587
                    array_push($_SESSION['groupes_visibles'], $t->id);
588
                    array_push($_SESSION['personal_visible_groups'], $t->id);
589
                }
590
            }
591
        }
592
593
        // get complete list of ROLES
594
        $tmp = explode(";", $_SESSION['fonction_id']);
595
        $rows = DB::query(
596
            "SELECT * FROM ".prefix_table("roles_title")."
597
            ORDER BY title ASC");
598
        foreach ($rows as $record) {
599
            if (!empty($record['id']) && !in_array($record['id'], $tmp)) {
600
                array_push($tmp, $record['id']);
601
            }
602
        }
603
        $_SESSION['fonction_id'] = implode(";", $tmp);
604
605
        $_SESSION['groupes_visibles_list'] = implode(',', $_SESSION['groupes_visibles']);
606
        $_SESSION['is_admin'] = $isAdmin;
607
        // Check if admin has created Folders and Roles
608
        DB::query("SELECT * FROM ".prefix_table("nested_tree")."");
609
        $_SESSION['nb_folders'] = DB::count();
610
        DB::query("SELECT * FROM ".prefix_table("roles_title"));
611
        $_SESSION['nb_roles'] = DB::count();
612
    } else {
613
        // init
614
        $_SESSION['groupes_visibles'] = array();
615
        $_SESSION['personal_folders'] = array();
616
        $_SESSION['groupes_interdits'] = array();
617
        $_SESSION['personal_visible_groups'] = array();
618
        $_SESSION['read_only_folders'] = array();
619
        $groupesInterdits = array();
620
        $groupesInterditsUser = explode(';', trimElement($groupesInterditsUser, ";"));
621
        if (!empty($groupesInterditsUser) && count($groupesInterditsUser) > 0) {
622
            $groupesInterdits = $groupesInterditsUser;
623
        }
624
        $_SESSION['is_admin'] = $isAdmin;
625
        $fonctionsAssociees = explode(';', trimElement($idFonctions, ";"));
626
627
        $listAllowedFolders = $listFoldersLimited = $listFoldersEditableByRole = $listRestrictedFoldersForItems = $listReadOnlyFolders = array();
628
629
        // rechercher tous les groupes visibles en fonction des roles de l'utilisateur
630
        foreach ($fonctionsAssociees as $roleId) {
631
            if (!empty($roleId)) {
632
                // Get allowed folders for each Role
633
                $rows = DB::query("SELECT folder_id FROM ".prefix_table("roles_values")." WHERE role_id=%i", $roleId);
634
635
                if (DB::count() > 0) {
636
                    $tmp = DB::queryfirstrow("SELECT allow_pw_change FROM ".prefix_table("roles_title")." WHERE id = %i", $roleId);
637
                    foreach ($rows as $record) {
638
                        if (isset($record['folder_id']) && !in_array($record['folder_id'], $listAllowedFolders)) {
639
                            array_push($listAllowedFolders, $record['folder_id']);
640
                        }
641
                        // Check if this group is allowed to modify any pw in allowed folders
642
                        if ($tmp['allow_pw_change'] == 1 && !in_array($record['folder_id'], $listFoldersEditableByRole)) {
643
                            array_push($listFoldersEditableByRole, $record['folder_id']);
644
                        }
645
                    }
646
                    // Check for the users roles if some specific rights exist on items
647
                    $rows = DB::query(
648
                        "SELECT i.id_tree, r.item_id
649
                        FROM ".prefix_table("items")." as i
650
                        INNER JOIN ".prefix_table("restriction_to_roles")." as r ON (r.item_id=i.id)
651
                        WHERE r.role_id=%i
652
                        ORDER BY i.id_tree ASC",
653
                        $roleId
654
                    );
655
                    $x = 0;
656
                    foreach ($rows as $record) {
657
                        if (isset($record['id_tree'])) {
658
                            $listFoldersLimited[$record['id_tree']][$x] = $record['item_id'];
659
                            $x++;
660
                        }
661
                    }
662
                }
663
            }
664
        }
665
666
        // Does this user is allowed to see other items
667
        $x = 0;
668
        $rows = DB::query(
669
            "SELECT id, id_tree FROM ".prefix_table("items")."
670
            WHERE restricted_to LIKE %ss AND inactif=%s",
671
            $_SESSION['user_id'].';',
672
            '0'
673
        );
674
        foreach ($rows as $record) {
675
            $listRestrictedFoldersForItems[$record['id_tree']][$x] = $record['id'];
676
            $x++;
677
        }
678
        // => Build final lists
679
        // Clean arrays
680
        $allowedFoldersTmp = array();
0 ignored issues
show
Unused Code introduced by
$allowedFoldersTmp 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...
681
        $listAllowedFolders = array_unique($listAllowedFolders);
682
        $groupesVisiblesUser = explode(';', trimElement($groupesVisiblesUser, ";"));
683
        // Add user allowed folders
684
        $allowedFoldersTmp = array_unique(
685
            array_merge($listAllowedFolders, $groupesVisiblesUser)
686
        );
687
        // Exclude from allowed folders all the specific user forbidden folders
688
        $allowedFolders = array();
689
        foreach ($allowedFoldersTmp as $id) {
690
            if (!in_array($id, $groupesInterditsUser) && !empty($id)) {
691
                array_push($allowedFolders, $id);
692
            }
693
        }
694
695
        // Clean array
696
        $listAllowedFolders = array_filter(array_unique($allowedFolders));
697
698
        // Exclude all PF
699
        $_SESSION['forbiden_pfs'] = array();
700
701
        $where = new WhereClause('and');
702
        $where->add('personal_folder=%i', 1);
703
        if (
704
            isset($_SESSION['settings']['enable_pf_feature']) &&
705
            $_SESSION['settings']['enable_pf_feature'] == 1 &&
706
            isset($_SESSION['personal_folder']) &&
707
            $_SESSION['personal_folder'] == 1
708
        ) {
709
            $where->add('title=%s', $_SESSION['user_id']);
710
            $where->negateLast();
711
        }
712
713
        $pfs = DB::query("SELECT id FROM ".prefix_table("nested_tree")." WHERE %l", $where);
714
        foreach ($pfs as $pfId) {
715
            array_push($_SESSION['forbiden_pfs'], $pfId['id']);
716
        }
717
        // Get IDs of personal folders
718
        if (
719
            isset($_SESSION['settings']['enable_pf_feature']) &&
720
            $_SESSION['settings']['enable_pf_feature'] == 1 &&
721
            isset($_SESSION['personal_folder']) &&
722
            $_SESSION['personal_folder'] == 1
723
        ) {
724
            $pf = DB::queryfirstrow("SELECT id FROM ".prefix_table("nested_tree")." WHERE title = %s", $_SESSION['user_id']);
725
            if (!empty($pf['id'])) {
726
                if (!in_array($pf['id'], $listAllowedFolders)) {
727
                    array_push($_SESSION['personal_folders'], $pf['id']);
728
                    // get all descendants
729
                    $ids = $tree->getDescendants($pf['id'], true, false);
730
                    foreach ($ids as $id) {
731
                        array_push($listAllowedFolders, $id->id);
732
                        array_push($_SESSION['personal_visible_groups'], $id->id);
733
                        array_push($_SESSION['personal_folders'], $id->id);
734
                    }
735
                }
736
            }
737
            // get list of readonly folders when pf is disabled.
738
            // rule - if one folder is set as W or N in one of the Role, then User has access as W
739
            foreach ($listAllowedFolders as $folderId) {
740
                if (!in_array($folderId, array_unique(array_merge($listReadOnlyFolders, $_SESSION['personal_folders'])))) {   //
741
                    DB::query(
742
                        "SELECT *
743
                        FROM ".prefix_table("roles_values")."
744
                        WHERE folder_id = %i AND role_id IN %li AND type IN %ls",
745
                        $folderId,
746
                        $fonctionsAssociees,
747
                        array("W", "ND", "NE", "NDNE")
748
749
                    );
750
                    if (DB::count() == 0 && !in_array($folderId, $groupesVisiblesUser)) {
751
                        array_push($listReadOnlyFolders, $folderId);
752
                    }
753
                }
754
            }
755
        } else {
756
            // get list of readonly folders when pf is disabled.
757
            // rule - if one folder is set as W in one of the Role, then User has access as W
758
            foreach ($listAllowedFolders as $folderId) {
759
                if (!in_array($folderId, $listReadOnlyFolders)) {
760
                    DB::query(
761
                        "SELECT *
762
                        FROM ".prefix_table("roles_values")."
763
                        WHERE folder_id = %i AND role_id IN %li AND type IN %ls",
764
                        $folderId,
765
                        $fonctionsAssociees,
766
                        array("W", "ND", "NE", "NDNE")
767
                    );
768
                    if (DB::count() == 0 && !in_array($folderId, $groupesVisiblesUser)) {
769
                        array_push($listReadOnlyFolders, $folderId);
770
                    }
771
                }
772
            }
773
        }
774
775
        // check if change proposals on User's items
776
        if (isset($_SESSION['settings']['enable_suggestion']) && $_SESSION['settings']['enable_suggestion'] == 1) {
777
            DB::query(
778
                "SELECT *
779
                FROM ".prefix_table("items_change")." AS c
780
                LEFT JOIN ".prefix_table("log_items")." AS i ON (c.item_id = i.id_item)
781
                WHERE i.action = %s AND i.id_user = %i",
782
                "at_creation",
783
                $_SESSION['user_id']
784
            );
785
            $_SESSION['nb_item_change_proposals'] = DB::count();
786
        } else {
787
            $_SESSION['nb_item_change_proposals'] = 0;
788
        }
789
790
        $_SESSION['all_non_personal_folders'] = $listAllowedFolders;
791
        $_SESSION['groupes_visibles'] = $listAllowedFolders;
792
        $_SESSION['groupes_visibles_list'] = implode(',', $listAllowedFolders);
793
        $_SESSION['personal_visible_groups_list'] = implode(',', $_SESSION['personal_visible_groups']);
794
        $_SESSION['read_only_folders'] = $listReadOnlyFolders;
795
        $_SESSION['no_access_folders'] = $groupesInterdits;
796
797
        $_SESSION['list_folders_limited'] = $listFoldersLimited;
798
        $_SESSION['list_folders_editable_by_role'] = $listFoldersEditableByRole;
799
        $_SESSION['list_restricted_folders_for_items'] = $listRestrictedFoldersForItems;
800
        // Folders and Roles numbers
801
        DB::queryfirstrow("SELECT id FROM ".prefix_table("nested_tree")."");
802
        $_SESSION['nb_folders'] = DB::count();
803
        DB::queryfirstrow("SELECT id FROM ".prefix_table("roles_title"));
804
        $_SESSION['nb_roles'] = DB::count();
805
    }
806
807
    // update user's timestamp
808
    DB::update(
809
        prefix_table('users'),
810
        array(
811
            'timestamp' => time()
812
        ),
813
        "id=%i",
814
        $_SESSION['user_id']
815
    );
816
}
817
818
/**
819
 * updateCacheTable()
820
 *
821
 * Update the CACHE table
822
 * @param string $action
823
 */
824
function updateCacheTable($action, $id = "")
825
{
826
    global $db, $server, $user, $pass, $database, $pre, $port, $encoding;
827
    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
828
829
    //Connect to DB
830
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
831
    DB::$host = $server;
832
    DB::$user = $user;
833
    DB::$password = $pass;
834
    DB::$dbName = $database;
835
    DB::$port = $port;
836
    DB::$encoding = $encoding;
837
    DB::$error_handler = true;
838
    $link = mysqli_connect($server, $user, $pass, $database, $port);
839
    $link->set_charset($encoding);
840
841
    //Load Tree
842
    $tree = new SplClassLoader('Tree\NestedTree', '../includes/libraries');
843
    $tree->register();
844
    $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
845
846
    // Rebuild full cache table
847
    if ($action === "reload") {
848
        // truncate table
849
        DB::query("TRUNCATE TABLE ".$pre."cache");
850
851
        // reload date
852
        $rows = DB::query(
853
            "SELECT *
854
            FROM ".$pre."items as i
855
            INNER JOIN ".$pre."log_items as l ON (l.id_item = i.id)
856
            AND l.action = %s
857
            AND i.inactif = %i",
858
            'at_creation',
859
            0
860
        );
861
        foreach ($rows as $record) {
862
            // Get all TAGS
863
            $tags = "";
864
            $itemTags = DB::query("SELECT tag FROM ".$pre."tags WHERE item_id=%i", $record['id']);
865
            foreach ($itemTags as $itemTag) {
866
                if (!empty($itemTag['tag'])) {
867
                    $tags .= $itemTag['tag']." ";
868
                }
869
            }
870
            // Get renewal period
871
            $resNT = DB::queryfirstrow("SELECT renewal_period FROM ".$pre."nested_tree WHERE id=%i", $record['id_tree']);
872
873
            // form id_tree to full foldername
874
            $folder = "";
875
            $arbo = $tree->getPath($record['id_tree'], true);
876 View Code Duplication
            foreach ($arbo as $elem) {
877
                if ($elem->title == $_SESSION['user_id'] && $elem->nlevel == 1) {
878
                    $elem->title = $_SESSION['login'];
879
                }
880
                if (empty($folder)) {
881
                    $folder = stripslashes($elem->title);
882
                } else {
883
                    $folder .= " » ".stripslashes($elem->title);
884
                }
885
            }
886
            // store data
887
            DB::insert(
888
                $pre."cache",
889
                array(
890
                    'id' => $record['id'],
891
                    'label' => $record['label'],
892
                    'description' => $record['description'],
893
                    'url' => (isset($record['url']) && !empty($record['url'])) ? $record['url'] : "0",
894
                    'tags' => $tags,
895
                    'id_tree' => $record['id_tree'],
896
                    'perso' => $record['perso'],
897
                    'restricted_to' => (isset($record['restricted_to']) && !empty($record['restricted_to'])) ? $record['restricted_to'] : "0",
898
                    'login' => isset($record['login']) ? $record['login'] : "",
899
                    'folder' => $folder,
900
                    'author' => $record['id_user'],
901
                    'renewal_period' => isset($resNT['renewal_period']) ? $resNT['renewal_period'] : "0",
902
                    'timestamp' => $record['date']
903
                    )
904
            );
905
        }
906
        // UPDATE an item
907
    } elseif ($action === "update_value") {
908
        // get new value from db
909
        $data = DB::queryfirstrow(
910
            "SELECT label, description, id_tree, perso, restricted_to, login, url
911
            FROM ".$pre."items
912
            WHERE id=%i", $id);
913
        // Get all TAGS
914
        $tags = "";
915
        $itemTags = DB::query("SELECT tag FROM ".$pre."tags WHERE item_id=%i", $id);
916
        foreach ($itemTags as $itemTag) {
917
            if (!empty($itemTag['tag'])) {
918
                $tags .= $itemTag['tag']." ";
919
            }
920
        }
921
        // form id_tree to full foldername
922
        $folder = "";
923
        $arbo = $tree->getPath($data['id_tree'], true);
924 View Code Duplication
        foreach ($arbo as $elem) {
925
            if ($elem->title == $_SESSION['user_id'] && $elem->nlevel == 1) {
926
                $elem->title = $_SESSION['login'];
927
            }
928
            if (empty($folder)) {
929
                $folder = stripslashes($elem->title);
930
            } else {
931
                $folder .= " » ".stripslashes($elem->title);
932
            }
933
        }
934
        // finaly update
935
        DB::update(
936
            $pre."cache",
937
            array(
938
                'label' => $data['label'],
939
                'description' => $data['description'],
940
                'tags' => $tags,
941
                'url' => (isset($data['url']) && !empty($data['url'])) ? $data['url'] : "0",
942
                'id_tree' => $data['id_tree'],
943
                'perso' => $data['perso'],
944
                'restricted_to' => $data['restricted_to'],
945
                'login' => isset($data['login']) ? $data['login'] : "",
946
                'folder' => $folder,
947
                'author' => $_SESSION['user_id'],
948
                ),
949
            "id = %i",
950
            $id
951
        );
952
        // ADD an item
953
    } elseif ($action === "add_value") {
954
        // get new value from db
955
        $data = DB::queryFirstRow(
956
            "SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login, i.url, l.date
957
            FROM ".$pre."items as i
958
            INNER JOIN ".$pre."log_items as l ON (l.id_item = i.id)
959
            WHERE i.id = %i
960
            AND l.action = %s",
961
            $id, 'at_creation'
962
        );
963
        // Get all TAGS
964
        $tags = "";
965
        $itemTags = DB::query("SELECT tag FROM ".$pre."tags WHERE item_id = %i", $id);
966
        foreach ($itemTags as $itemTag) {
967
            if (!empty($itemTag['tag'])) {
968
                $tags .= $itemTag['tag']." ";
969
            }
970
        }
971
        // form id_tree to full foldername
972
        $folder = "";
973
        $arbo = $tree->getPath($data['id_tree'], true);
974 View Code Duplication
        foreach ($arbo as $elem) {
975
            if ($elem->title == $_SESSION['user_id'] && $elem->nlevel == 1) {
976
                $elem->title = $_SESSION['login'];
977
            }
978
            if (empty($folder)) {
979
                $folder = stripslashes($elem->title);
980
            } else {
981
                $folder .= " » ".stripslashes($elem->title);
982
            }
983
        }
984
        // finaly update
985
        DB::insert(
986
            $pre."cache",
987
            array(
988
                'id' => $data['id'],
989
                'label' => $data['label'],
990
                'description' => $data['description'],
991
                'tags' => $tags,
992
                'url' => (isset($data['url']) && !empty($data['url'])) ? $data['url'] : "0",
993
                'url' => $data['url'],
994
                'id_tree' => $data['id_tree'],
995
                'perso' => $data['perso'],
996
                'restricted_to' => $data['restricted_to'],
997
                'login' => isset($data['login']) ? $data['login'] : "",
998
                'folder' => $folder,
999
                'author' => $_SESSION['user_id'],
1000
                'timestamp' => $data['date']
1001
                )
1002
        );
1003
        // DELETE an item
1004
    } elseif ($action === "delete_value") {
1005
        DB::delete($pre."cache", "id = %i", $id);
1006
    }
1007
}
1008
1009
/*
1010
*
1011
*/
1012
function getStatisticsData() {
1013
        DB::query(
1014
        "SELECT id FROM ".prefix_table("nested_tree")." WHERE personal_folder = %i",
1015
        0
1016
    );
1017
    $counter_folders = DB::count();
1018
1019
    DB::query(
1020
        "SELECT id FROM ".prefix_table("nested_tree")." WHERE personal_folder = %i",
1021
        1
1022
    );
1023
    $counter_folders_perso = DB::count();
1024
1025
    DB::query(
1026
        "SELECT id FROM ".prefix_table("items")." WHERE perso = %i",
1027
        0
1028
    );
1029
    $counter_items = DB::count();
1030
1031
    DB::query(
1032
        "SELECT id FROM ".prefix_table("items")." WHERE perso = %i",
1033
        1
1034
    );
1035
    $counter_items_perso = DB::count();
1036
1037
    DB::query(
1038
        "SELECT id FROM ".prefix_table("users").""
1039
    );
1040
    $counter_users = DB::count();
1041
1042
    DB::query(
1043
        "SELECT id FROM ".prefix_table("users")." WHERE admin = %i",
1044
        1
1045
    );
1046
    $admins = DB::count();
1047
1048
    DB::query(
1049
        "SELECT id FROM ".prefix_table("users")." WHERE gestionnaire = %i",
1050
        1
1051
    );
1052
    $managers = DB::count();
1053
1054
    DB::query(
1055
        "SELECT id FROM ".prefix_table("users")." WHERE read_only = %i",
1056
        1
1057
    );
1058
    $ro = DB::count();
1059
1060
    // list the languages
1061
    $usedLang = [];
1062
    $tp_languages = DB::query(
1063
        "SELECT name FROM ".prefix_table("languages")
1064
    );
1065
    foreach ($tp_languages as $tp_language) {
1066
        DB::query(
1067
            "SELECT * FROM ".prefix_table("users")." WHERE user_language = %s",
1068
            $tp_language['name']
1069
        );
1070
        $usedLang[$tp_language['name']] = round((DB::count() * 100 / $counter_users), 0);
1071
    }
1072
1073
    // get list of ips
1074
    $usedIp = [];
1075
    $tp_ips = DB::query(
1076
        "SELECT user_ip FROM ".prefix_table("users")
1077
    );
1078
    foreach ($tp_ips as $ip) {
1079
        if (array_key_exists($ip['user_ip'], $usedIp)) {
1080
            $usedIp[$ip['user_ip']] = $usedIp[$ip['user_ip']] + 1;
1081
        } else if (!empty($ip['user_ip']) && $ip['user_ip'] !== "none") {
1082
            $usedIp[$ip['user_ip']] = 1;
1083
        }
1084
    }
1085
1086
    return array(
1087
        "error" => "",
1088
        "stat_phpversion" => phpversion(),
1089
        "stat_folders" => $counter_folders,
1090
        "stat_folders_shared" => intval($counter_folders) - intval($counter_folders_perso),
1091
        "stat_items" => $counter_items,
1092
        "stat_items_shared" => intval($counter_items) - intval($counter_items_perso),
1093
        "stat_users" => $counter_users,
1094
        "stat_admins" => $admins,
1095
        "stat_managers" => $managers,
1096
        "stat_ro" => $ro,
1097
        "stat_kb" => $_SESSION['settings']['enable_kb'],
1098
        "stat_pf" => $_SESSION['settings']['enable_pf_feature'],
1099
        "stat_fav" => $_SESSION['settings']['enable_favourites'],
1100
        "stat_teampassversion" => $_SESSION['settings']['cpassman_version'],
1101
        "stat_ldap" => $_SESSION['settings']['ldap_mode'],
1102
        "stat_agses" => $_SESSION['settings']['agses_authentication_enabled'],
1103
        "stat_duo" => $_SESSION['settings']['duo'],
1104
        "stat_suggestion" => $_SESSION['settings']['enable_suggestion'],
1105
        "stat_api" => $_SESSION['settings']['api'],
1106
        "stat_customfields" => $_SESSION['settings']['item_extra_fields'],
1107
        "stat_syslog" => $_SESSION['settings']['syslog_enable'],
1108
        "stat_2fa" => $_SESSION['settings']['google_authentication'],
1109
        "stat_stricthttps" => $_SESSION['settings']['enable_sts'],
1110
        "stat_mysqlversion" => DB::serverVersion(),
1111
        "stat_languages" => $usedLang,
1112
        "stat_country" => $usedIp
1113
    );
1114
}
1115
1116
/**
1117
 * sendEmail()
1118
 *
1119
 * @return
1120
 */
1121
function sendEmail($subject, $textMail, $email, $textMailAlt = "")
1122
{
1123
    global $LANG;
1124
    include $_SESSION['settings']['cpassman_dir'].'/includes/config/settings.php';
1125
    //load library
1126
    $user_language = isset($_SESSION['user_language']) ? $_SESSION['user_language'] : "english";
1127
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$user_language.'.php';
1128
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Email/Phpmailer/PHPMailerAutoload.php';
1129
1130
    // load PHPMailer
1131
    $mail = new PHPMailer();
1132
1133
    // send to user
1134
    $mail->setLanguage("en", "../includes/libraries/Email/Phpmailer/language/");
1135
    $mail->SMTPDebug = 0; //value 1 can be used to debug
1136
    $mail->Port = $_SESSION['settings']['email_port']; //COULD BE USED
1137
    $mail->CharSet = "utf-8";
1138
    $smtp_security = $_SESSION['settings']['email_security'];
1139
    if ($smtp_security == "tls" || $smtp_security == "ssl") {
1140
        $mail->SMTPSecure = $smtp_security;
1141
    }
1142
    $mail->isSmtp(); // send via SMTP
1143
    $mail->Host = $_SESSION['settings']['email_smtp_server']; // SMTP servers
1144
    $mail->SMTPAuth = $_SESSION['settings']['email_smtp_auth'] == '1' ? true : false; // turn on SMTP authentication
1145
    $mail->Username = $_SESSION['settings']['email_auth_username']; // SMTP username
1146
    $mail->Password = $_SESSION['settings']['email_auth_pwd']; // SMTP password
1147
    $mail->From = $_SESSION['settings']['email_from'];
1148
    $mail->FromName = $_SESSION['settings']['email_from_name'];
1149
    $mail->addAddress($email); //Destinataire
1150
    $mail->WordWrap = 80; // set word wrap
1151
    $mail->isHtml(true); // send as HTML
1152
    $mail->Subject = $subject;
1153
    $mail->Body = $textMail;
1154
    $mail->AltBody = $textMailAlt;
1155
    // send email
1156
    if (!$mail->send()) {
1157
        return '"error":"error_mail_not_send" , "message":"'.str_replace(array("\n", "\t", "\r"), '', $mail->ErrorInfo).'"';
1158
    } else {
1159
        return '"error":"" , "message":"'.$LANG['forgot_my_pw_email_sent'].'"';
1160
    }
1161
}
1162
1163
/**
1164
 * generateKey()
1165
 *
1166
 * @return
1167
 */
1168
function generateKey()
1169
{
1170
    return substr(md5(rand().rand()), 0, 15);
1171
}
1172
1173
/**
1174
 * dateToStamp()
1175
 *
1176
 * @return
1177
 */
1178
function dateToStamp($date)
1179
{
1180
    $date = date_parse_from_format($_SESSION['settings']['date_format'], $date);
1181
    if ($date['warning_count'] == 0 && $date['error_count'] == 0) {
1182
        return mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
1183
    } else {
1184
        return false;
1185
    }
1186
}
1187
1188
function isDate($date)
1189
{
1190
    return (strtotime($date) !== false);
1191
}
1192
1193
/**
1194
 * isUTF8()
1195
 *
1196
 * @return integer is the string in UTF8 format.
1197
 */
1198
1199
function isUTF8($string)
1200
{
1201
    if (is_array($string) === true) {
1202
        $string = $string['string'];
1203
    }
1204
    return preg_match(
1205
        '%^(?:
1206
        [\x09\x0A\x0D\x20-\x7E] # ASCII
1207
        | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
1208
        | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
1209
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
1210
        | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
1211
        | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1212
        | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1213
        | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1214
        )*$%xs',
1215
        $string
1216
    );
1217
}
1218
1219
/*
1220
* FUNCTION
1221
* permits to prepare data to be exchanged
1222
*/
1223
/**
1224
 * @param string $type
1225
 */
1226
function prepareExchangedData($data, $type)
1227
{
1228
    //load ClassLoader
1229
    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
1230
    //Load AES
1231
    $aes = new SplClassLoader('Encryption\Crypt', '../includes/libraries');
1232
    $aes->register();
1233
1234
    if ($type == "encode") {
1235
        if (
1236
            isset($_SESSION['settings']['encryptClientServer'])
1237
            && $_SESSION['settings']['encryptClientServer'] == 0
1238
        ) {
1239
            return json_encode(
1240
                $data,
1241
                JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
1242
            );
1243
        } else {
1244
            return Encryption\Crypt\aesctr::encrypt(
1245
                json_encode(
1246
                    $data,
1247
                    JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
1248
                ),
1249
                $_SESSION['key'],
1250
                256
1251
            );
1252
        }
1253
    } elseif ($type == "decode") {
1254
        if (
1255
            isset($_SESSION['settings']['encryptClientServer'])
1256
            && $_SESSION['settings']['encryptClientServer'] == 0
1257
        ) {
1258
            return json_decode(
1259
                $data,
1260
                true
1261
            );
1262
        } else {
1263
            return json_decode(
1264
                Encryption\Crypt\aesctr::decrypt(
1265
                    $data,
1266
                    $_SESSION['key'],
1267
                    256
1268
                ),
1269
                true
1270
            );
1271
        }
1272
    }
1273
}
1274
1275
function make_thumb($src, $dest, $desired_width) {
1276
1277
    /* read the source image */
1278
    $source_image = imagecreatefrompng($src);
1279
    $width = imagesx($source_image);
1280
    $height = imagesy($source_image);
1281
1282
    /* find the "desired height" of this thumbnail, relative to the desired width  */
1283
    $desired_height = floor($height * ($desired_width / $width));
1284
1285
    /* create a new, "virtual" image */
1286
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
1287
1288
    /* copy source image at a resized size */
1289
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
1290
1291
    /* create the physical thumbnail image to its destination */
1292
    imagejpeg($virtual_image, $dest);
1293
}
1294
1295
/*
1296
** check table prefix in SQL query
1297
*/
1298
/**
1299
 * @param string $table
1300
 */
1301
function prefix_table($table)
1302
{
1303
    global $pre;
1304
    $safeTable = htmlspecialchars($pre.$table);
1305
    if (!empty($safeTable)) {
1306
        // sanitize string
1307
        return $safeTable;
1308
    } else {
1309
        // stop error no table
1310
        return "table_not_exists";
1311
    }
1312
}
1313
1314
/*
1315
 * Creates a KEY using PasswordLib
1316
 */
1317
function GenerateCryptKey($size = "", $secure = false, $numerals = false, $capitalize = false, $ambiguous = false, $symbols = false)
1318
{
1319
    // load library
1320
    $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
1321
    $pwgen->register();
1322
    $pwgen = new Encryption\PwGen\pwgen();
1323
1324
    // init
1325
    if (!empty($size)) {
1326
        $pwgen->setLength($size);
1327
    }
1328
    if (!empty($secure)) {
1329
        $pwgen->setSecure($secure);
1330
    }
1331
    if (!empty($numerals)) {
1332
        $pwgen->setNumerals($numerals);
1333
    }
1334
    if (!empty($capitalize)) {
1335
        $pwgen->setCapitalize($capitalize);
1336
    }
1337
    if (!empty($ambiguous)) {
1338
        $pwgen->setAmbiguous($ambiguous);
1339
    }
1340
    if (!empty($symbols)) {
1341
        $pwgen->setSymbols($symbols);
1342
    }
1343
1344
    // generate and send back
1345
    return $pwgen->generate();
1346
}
1347
1348
/*
1349
* Send sysLOG message
1350
*/
1351
/**
1352
 * @param string $message
1353
 */
1354
function send_syslog($message, $component = "teampass", $program = "php", $host, $port)
0 ignored issues
show
Unused Code introduced by
The parameter $program is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1355
{
1356
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1357
        //$syslog_message = "<123>" . date('M d H:i:s ') . " " .$host . " " . $component . ": " . $message;
1358
    $syslog_message = "<123>".date('M d H:i:s ').$component.": ".$message;
1359
        socket_sendto($sock, $syslog_message, strlen($syslog_message), 0, $host, $port);
1360
    socket_close($sock);
1361
}
1362
1363
1364
1365
/**
1366
 * logEvents()
1367
 *
1368
 * permits to log events into DB
1369
 * @param string $type
1370
 * @param string $label
1371
 * @param string $field_1
1372
 */
1373
function logEvents($type, $label, $who, $login = "", $field_1 = NULL)
1374
{
1375
    global $server, $user, $pass, $database, $pre, $port, $encoding;
1376
1377
    if (empty($who)) {
1378
        $who = get_client_ip_server();
1379
    }
1380
1381
    // include librairies & connect to DB
1382
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
1383
    DB::$host = $server;
1384
    DB::$user = $user;
1385
    DB::$password = $pass;
1386
    DB::$dbName = $database;
1387
    DB::$port = $port;
1388
    DB::$encoding = $encoding;
1389
    DB::$error_handler = true;
1390
    $link = mysqli_connect($server, $user, $pass, $database, $port);
1391
    $link->set_charset($encoding);
1392
1393
    DB::insert(
1394
        prefix_table("log_system"),
1395
        array(
1396
            'type' => $type,
1397
            'date' => time(),
1398
            'label' => $label,
1399
            'qui' => $who,
1400
            'field_1' => $field_1 === null ? "" : $field_1
1401
        )
1402
    );
1403
    if (isset($_SESSION['settings']['syslog_enable']) && $_SESSION['settings']['syslog_enable'] == 1) {
1404
        if ($type == "user_mngt") {
1405
            send_syslog("The User ".$login." perform the acction off ".$label." to the user ".$field_1." - ".$type, "teampass", "php", $_SESSION['settings']['syslog_host'], $_SESSION['settings']['syslog_port']);
1406
        } else {
1407
            send_syslog("The User ".$login." perform the acction off ".$label." - ".$type, "teampass", "php", $_SESSION['settings']['syslog_host'], $_SESSION['settings']['syslog_port']);
1408
        }
1409
    }
1410
}
1411
1412
/**
1413
 * @param string $item
1414
 * @param string $action
1415
 */
1416
function logItems($id, $item, $id_user, $action, $login = "", $raison = NULL, $raison_iv = NULL, $encryption_type = "")
1417
{
1418
    global $server, $user, $pass, $database, $pre, $port, $encoding;
1419
    // include librairies & connect to DB
1420
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
1421
    DB::$host = $server;
1422
    DB::$user = $user;
1423
    DB::$password = $pass;
1424
    DB::$dbName = $database;
1425
    DB::$port = $port;
1426
    DB::$encoding = $encoding;
1427
    DB::$error_handler = true;
1428
    $link = mysqli_connect($server, $user, $pass, $database, $port);
1429
    $link->set_charset($encoding);
1430
    DB::insert(
1431
        prefix_table(
1432
            "log_items"),
1433
            array(
1434
                'id_item' => $id,
1435
                'date' => time(),
1436
                'id_user' => $id_user,
1437
                'action' => $action,
1438
                'raison' => $raison,
1439
                'raison_iv' => $raison_iv,
1440
                'encryption_type' => $encryption_type
1441
            )
1442
        );
1443
        if (isset($_SESSION['settings']['syslog_enable']) && $_SESSION['settings']['syslog_enable'] == 1) {
1444
                send_syslog("The Item ".$item." was ".$action." by ".$login." ".$raison, "teampass", "php", $_SESSION['settings']['syslog_host'], $_SESSION['settings']['syslog_port']);
1445
        }
1446
}
1447
1448
/*
1449
* Function to get the client ip address
1450
 */
1451
function get_client_ip_server() {
1452
    if (getenv('HTTP_CLIENT_IP')) {
1453
            $ipaddress = getenv('HTTP_CLIENT_IP');
1454
    } else if (getenv('HTTP_X_FORWARDED_FOR')) {
1455
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
1456
    } else if (getenv('HTTP_X_FORWARDED')) {
1457
            $ipaddress = getenv('HTTP_X_FORWARDED');
1458
    } else if (getenv('HTTP_FORWARDED_FOR')) {
1459
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
1460
    } else if (getenv('HTTP_FORWARDED')) {
1461
            $ipaddress = getenv('HTTP_FORWARDED');
1462
    } else if (getenv('REMOTE_ADDR')) {
1463
            $ipaddress = getenv('REMOTE_ADDR');
1464
    } else {
1465
            $ipaddress = 'UNKNOWN';
1466
    }
1467
1468
    return $ipaddress;
1469
}
1470
1471
/**
1472
 * Escape all HTML, JavaScript, and CSS
1473
 *
1474
 * @param string $input The input string
1475
 * @param string $encoding Which character encoding are we using?
1476
 * @return string
1477
 */
1478
function noHTML($input, $encoding = 'UTF-8')
1479
{
1480
    return htmlspecialchars($input, ENT_QUOTES | ENT_XHTML, $encoding, false);
1481
}
1482
1483
/**
1484
 * handleConfigFile()
1485
 *
1486
 * permits to handle the Teampass config file
1487
 * $action accepts "rebuild" and "update"
1488
 */
1489
function handleConfigFile($action, $field = null, $value = null)
1490
{
1491
    global $server, $user, $pass, $database, $pre, $port, $encoding;
1492
    $tp_config_file = "../includes/config/tp.config.php";
1493
1494
    // include librairies & connect to DB
1495
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
1496
    DB::$host = $server;
1497
    DB::$user = $user;
1498
    DB::$password = $pass;
1499
    DB::$dbName = $database;
1500
    DB::$port = $port;
1501
    DB::$encoding = $encoding;
1502
    DB::$error_handler = true;
1503
    $link = mysqli_connect($server, $user, $pass, $database, $port);
1504
    $link->set_charset($encoding);
1505
1506
    if (!file_exists($tp_config_file) || $action == "rebuild") {
1507
        // perform a copy
1508
        if (file_exists($tp_config_file)) {
1509
            if (!copy($tp_config_file, $tp_config_file.'.'.date("Y_m_d_His", time()))) {
1510
                return "ERROR: Could not copy file '".$tp_config_file."'";
1511
            }
1512
        }
1513
1514
        // regenerate
1515
        $data = array();
1516
        $data[0] = "<?php\n";
1517
        $data[1] = "global \$SETTINGS;\n";
1518
        $data[2] = "\$SETTINGS = array (\n";
1519
        $rows = DB::query(
1520
            "SELECT * FROM ".prefix_table("misc")." WHERE type=%s",
1521
            "admin"
1522
        );
1523
        foreach ($rows as $record) {
1524
            array_push($data, "    '".$record['intitule']."' => '".$record['valeur']."',\n");
1525
        }
1526
        array_push($data, ");");
1527
        $data = array_unique($data);
1528
    } else if ($action == "update" && !empty($field)) {
1529
        $data = file($tp_config_file);
1530
        $x = 0;
1531
        $bFound = false;
1532
        foreach ($data as $line) {
1533
            if (stristr($line, ");")) {
1534
                break;
1535
            }
1536
            if (stristr($line, "'".$field."' => '")) {
1537
                $data[$x] = "    '".$field."' => '".$value."',\n";
1538
                $bFound = true;
1539
                break;
1540
            }
1541
            $x++;
1542
        }
1543
        if ($bFound === false) {
1544
            $data[($x - 1)] = "    '".$field."' => '".$value."',\n";
1545
        }
1546
    } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches 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 else branches can be removed.

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

could be turned into

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

This is much more concise to read.

Loading history...
1547
        // ERROR
1548
    }
1549
1550
    // update file
1551
    file_put_contents($tp_config_file, implode('', $data));
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Security File Manipulation introduced by
implode('', $data) can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_POST
    in sources/admin.queries.php on line 1793
  2. Data is decoded by json_decode()
    in vendor/sources/main.functions.php on line 1259
  3. $dataReceived is assigned
    in sources/admin.queries.php on line 1793
  4. $dataReceived['field'] is passed to handleConfigFile()
    in sources/admin.queries.php on line 1913
  5. $data is assigned
    in sources/main.functions.php on line 1544
  6. $data is passed through implode()
    in sources/main.functions.php on line 1551

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...
1552
1553
    return true;
1554
}
1555
1556
/*
1557
** Permits to replace &#92; to permit correct display
1558
*/
1559
function handleBackslash($input)
1560
{
1561
    return str_replace("&amp;#92;", "&#92;", $input);
1562
}
1563
1564
/*
1565
** Permits to loas settings
1566
*/
1567
function loadSettings()
1568
{
1569
    /* LOAD CPASSMAN SETTINGS */
1570 View Code Duplication
    if (!isset($_SESSION['settings']['loaded']) || $_SESSION['settings']['loaded'] != 1) {
1571
        $_SESSION['settings']['duplicate_folder'] = 0; //by default, this is false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
1572
        $_SESSION['settings']['duplicate_item'] = 0; //by default, this is false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
1573
        $_SESSION['settings']['number_of_used_pw'] = 5; //by default, this value is 5;
1574
        $settings = array();
1575
1576
        $rows = DB::query("SELECT * FROM ".prefix_table("misc")." WHERE type=%s_type OR type=%s_type2",
1577
            array(
1578
                'type' => "admin",
1579
                'type2' => "settings"
1580
            )
1581
        );
1582
        foreach ($rows as $record) {
1583
            if ($record['type'] == 'admin') {
1584
                $_SESSION['settings'][$record['intitule']] = $record['valeur'];
1585
            } else {
1586
                $settings[$record['intitule']] = $record['valeur'];
1587
            }
1588
        }
1589
        $_SESSION['settings']['loaded'] = 1;
1590
        $_SESSION['settings']['default_session_expiration_time'] = 5;
1591
    }
1592
}
1593
1594
/*
1595
** check if folder has custom fields.
1596
** Ensure that target one also has same custom fields
1597
*/
1598
function checkCFconsistency($source_id, $target_id) {
1599
    $source_cf = array();
1600
    $rows = DB::QUERY(
1601
        "SELECT id_category
1602
        FROM ".prefix_table("categories_folders")."
1603
        WHERE id_folder = %i",
1604
        $source_id
1605
    );
1606
    foreach ($rows as $record) {
1607
        array_push($source_cf, $record['id_category']);
1608
    }
1609
1610
    $target_cf = array();
1611
    $rows = DB::QUERY(
1612
        "SELECT id_category
1613
        FROM ".prefix_table("categories_folders")."
1614
        WHERE id_folder = %i",
1615
        $target_id
1616
    );
1617
    foreach ($rows as $record) {
1618
        array_push($target_cf, $record['id_category']);
1619
    }
1620
1621
    $cf_diff = array_diff($source_cf, $target_cf);
1622
    if (count($cf_diff) > 0) {
1623
        return false;
1624
    }
1625
1626
    return true;
1627
}
1628
1629
/*
1630
*
1631
*/
1632
function encrypt_or_decrypt_file($image_code, $image_status, $opts) {
1633
    global $server, $user, $pass, $database, $pre, $port, $encoding;
1634
1635
    // include librairies & connect to DB
1636
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
1637
    DB::$host = $server;
1638
    DB::$user = $user;
1639
    DB::$password = $pass;
1640
    DB::$dbName = $database;
1641
    DB::$port = $port;
1642
    DB::$encoding = $encoding;
1643
    DB::$error_handler = true;
1644
    $link = mysqli_connect($server, $user, $pass, $database, $port);
1645
    $link->set_charset($encoding);
1646
1647
    if (isset($_SESSION['settings']['enable_attachment_encryption']) && $_SESSION['settings']['enable_attachment_encryption'] === "1" && isset($image_status) && $image_status === "clear") {
1648
        // file needs to be encrypted
1649 View Code Duplication
        if (file_exists($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code)) {
1650
            // make a copy of file
1651
            if (!copy(
1652
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code,
1653
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".copy"
1654
            )) {
1655
                exit;
1656
            } else {
1657
                // do a bck
1658
                copy(
1659
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code,
1660
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".bck"
1661
                );
1662
            }
1663
1664
            // Open the file
1665
            unlink($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code);
1666
            $fp = fopen($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".copy", "rb");
1667
            $out = fopen($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code, 'wb');
1668
1669
            // ecnrypt
1670
            stream_filter_append($out, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
1671
1672
            // read file and create new one
1673
            while (($line = fgets($fp)) !== false) {
1674
                fputs($out, $line);
1675
            }
1676
            fclose($fp);
1677
            fclose($out);
1678
1679
            // update table
1680
            DB::update(
1681
                prefix_table('files'),
1682
                array(
1683
                    'status' => 'encrypted'
1684
                    ),
1685
                "id=%i",
1686
                substr($_POST['uri'], 1)
1687
            );
1688
        }
1689
    } elseif (isset($_SESSION['settings']['enable_attachment_encryption']) && $_SESSION['settings']['enable_attachment_encryption'] === "0" && isset($image_status) && $image_status === "encrypted") {
1690
        // file needs to be decrypted
1691 View Code Duplication
        if (file_exists($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code)) {
1692
            // make a copy of file
1693
            if (!copy(
1694
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code,
1695
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".copy"
1696
            )) {
1697
                $error = "Copy not possible";
0 ignored issues
show
Unused Code introduced by
$error 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...
1698
                exit;
1699
            } else {
1700
                // do a bck
1701
                copy(
1702
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code,
1703
                    $_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".bck"
1704
                );
1705
            }
1706
1707
            // Open the file
1708
            unlink($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code);
1709
            $fp = fopen($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code.".copy", "rb");
1710
            $out = fopen($_SESSION['settings']['path_to_upload_folder'].'/'.$image_code, 'wb');
1711
1712
            // ecnrypt
1713
            stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
1714
1715
            // read file and create new one
1716
            while (($line = fgets($fp)) !== false) {
1717
                fputs($out, $line);
1718
            }
1719
            fclose($fp);
1720
            fclose($out);
1721
1722
            // update table
1723
            DB::update(
1724
                prefix_table('files'),
1725
                array(
1726
                    'status' => 'clear'
1727
                    ),
1728
                "id=%i",
1729
                substr($_POST['uri'], 1)
1730
            );
1731
        }
1732
    }
1733
}
1734
1735
/*
1736
* NOT TO BE USED
1737
*/
1738
function debugTeampass($text) {
1739
    $debugFile = fopen('D:/wamp64/www/TeamPass/debug.txt', 'r+');
1740
    fputs($debugFile, $text);
1741
    fclose($debugFile);
1742
}
1743
1744
/*
1745
* DELETE the file with expected command depending on server type
1746
*/
1747
function fileDelete($file) {
1748
    if (is_file($file)) {
1749
        try {
1750
            close($file);
1751
        } catch(Exception $e){
1752
            print_r($e);
1753
        }
1754
        // define if we under Windows
1755
        if (strpos(dirname(__FILE__), '/', 0) !== false) {
1756
            unlink($file);
1757
        } else {
1758
            $lines = array();
1759
            exec("DEL /F/Q \"".$file."\"", $lines, $deleteError);
1760
        }
1761
    }
1762
}
1763
1764
/*
1765
* Permits to extract the file extension
1766
*/
1767
function getFileExtension($f)
1768
{
1769
    if (strpos($f, '.') === false) {
1770
        return $f;
1771
    }
1772
1773
    return substr($f, strrpos($f, '.') + 1);
1774
}