Passed
Push — master ( 4526a3...260d60 )
by Nils
05:31
created

checkIdsExist()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 3
dl 0
loc 20
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Teampass - a collaborative passwords manager.
7
 * ---
8
 * This file is part of the TeamPass project.
9
 * 
10
 * TeamPass is free software: you can redistribute it and/or modify it
11
 * under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation, version 3 of the License.
13
 * 
14
 * TeamPass is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU General Public License for more details.
18
 * 
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 * 
22
 * Certain components of this file may be under different licenses. For
23
 * details, see the `licenses` directory or individual file headers.
24
 * ---
25
 * @file      main.functions.php
26
 * @author    Nils Laumaillé ([email protected])
27
 * @copyright 2009-2024 Teampass.net
28
 * @license   GPL-3.0
29
 * @see       https://www.teampass.net
30
 */
31
32
use LdapRecord\Connection;
33
use ForceUTF8\Encoding;
34
use Elegant\Sanitizer\Sanitizer;
35
use voku\helper\AntiXSS;
36
use Hackzilla\PasswordGenerator\Generator\ComputerPasswordGenerator;
37
use Hackzilla\PasswordGenerator\RandomGenerator\Php7RandomGenerator;
38
use TeampassClasses\SessionManager\SessionManager;
39
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
40
use TeampassClasses\Language\Language;
41
use TeampassClasses\NestedTree\NestedTree;
42
use Defuse\Crypto\Key;
43
use Defuse\Crypto\Crypto;
44
use Defuse\Crypto\KeyProtectedByPassword;
45
use Defuse\Crypto\File as CryptoFile;
46
use Defuse\Crypto\Exception as CryptoException;
47
use Elegant\Sanitizer\Filters\Uppercase;
48
use PHPMailer\PHPMailer\PHPMailer;
49
use TeampassClasses\PasswordManager\PasswordManager;
50
use Symfony\Component\Process\Exception\ProcessFailedException;
51
use Symfony\Component\Process\Process;
52
use Symfony\Component\Process\PhpExecutableFinder;
53
use TeampassClasses\Encryption\Encryption;
54
use TeampassClasses\ConfigManager\ConfigManager;
55
use TeampassClasses\EmailService\EmailService;
56
use TeampassClasses\EmailService\EmailSettings;
57
58
header('Content-type: text/html; charset=utf-8');
59
header('Cache-Control: no-cache, must-revalidate');
60
61
loadClasses('DB');
62
$session = SessionManager::getSession();
63
64
// Load config if $SETTINGS not defined
65
$configManager = new ConfigManager($session);
66
$SETTINGS = $configManager->getAllSettings();
67
68
/**
69
 * genHash().
70
 *
71
 * Generate a hash for user login
72
 *
73
 * @param string $password What password
74
 * @param string $cost     What cost
75
 *
76
 * @return string|void
77
 */
78
/* TODO - Remove this function
79
function bCrypt(
80
    string $password,
81
    string $cost
82
): ?string
83
{
84
    $salt = sprintf('$2y$%02d$', $cost);
85
    if (function_exists('openssl_random_pseudo_bytes')) {
86
        $salt .= bin2hex(openssl_random_pseudo_bytes(11));
87
    } else {
88
        $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
89
        for ($i = 0; $i < 22; ++$i) {
90
            $salt .= $chars[mt_rand(0, 63)];
91
        }
92
    }
93
94
    return crypt($password, $salt);
95
}
96
*/
97
98
/**
99
 * Checks if a string is hex encoded
100
 *
101
 * @param string $str
102
 * @return boolean
103
 */
104
function isHex(string $str): bool
105
{
106
    if (str_starts_with(strtolower($str), '0x')) {
107
        $str = substr($str, 2);
108
    }
109
110
    return ctype_xdigit($str);
111
}
112
113
/**
114
 * Defuse cryption function.
115
 *
116
 * @param string $message   what to de/crypt
117
 * @param string $ascii_key key to use
118
 * @param string $type      operation to perform
119
 * @param array  $SETTINGS  Teampass settings
120
 *
121
 * @return array
122
 */
123
function cryption(string $message, string $ascii_key, string $type, ?array $SETTINGS = []): array
124
{
125
    $ascii_key = empty($ascii_key) === true ? file_get_contents(SECUREPATH.'/'.SECUREFILE) : $ascii_key;
126
    $err = false;
127
    
128
    // convert KEY
129
    $key = Key::loadFromAsciiSafeString($ascii_key);
130
    try {
131
        if ($type === 'encrypt') {
132
            $text = Crypto::encrypt($message, $key);
133
        } elseif ($type === 'decrypt') {
134
            $text = Crypto::decrypt($message, $key);
135
        }
136
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
137
        $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.';
138
    } catch (CryptoException\BadFormatException $ex) {
139
        $err = $ex;
140
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
141
        $err = $ex;
142
    } catch (CryptoException\CryptoException $ex) {
143
        $err = $ex;
144
    } catch (CryptoException\IOException $ex) {
145
        $err = $ex;
146
    }
147
148
    return [
149
        'string' => $text ?? '',
150
        'error' => $err,
151
    ];
152
}
153
154
/**
155
 * Generating a defuse key.
156
 *
157
 * @return string
158
 */
159
function defuse_generate_key()
160
{
161
    $key = Key::createNewRandomKey();
162
    $key = $key->saveToAsciiSafeString();
163
    return $key;
164
}
165
166
/**
167
 * Generate a Defuse personal key.
168
 *
169
 * @param string $psk psk used
170
 *
171
 * @return string
172
 */
173
function defuse_generate_personal_key(string $psk): string
174
{
175
    $protected_key = KeyProtectedByPassword::createRandomPasswordProtectedKey($psk);
176
    return $protected_key->saveToAsciiSafeString(); // save this in user table
177
}
178
179
/**
180
 * Validate persoanl key with defuse.
181
 *
182
 * @param string $psk                   the user's psk
183
 * @param string $protected_key_encoded special key
184
 *
185
 * @return string
186
 */
187
function defuse_validate_personal_key(string $psk, string $protected_key_encoded): string
188
{
189
    try {
190
        $protected_key_encoded = KeyProtectedByPassword::loadFromAsciiSafeString($protected_key_encoded);
191
        $user_key = $protected_key_encoded->unlockKey($psk);
192
        $user_key_encoded = $user_key->saveToAsciiSafeString();
193
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
194
        return 'Error - Major issue as the encryption is broken.';
195
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
196
        return 'Error - The saltkey is not the correct one.';
197
    }
198
199
    return $user_key_encoded;
200
    // store it in session once user has entered his psk
201
}
202
203
/**
204
 * Decrypt a defuse string if encrypted.
205
 *
206
 * @param string $value Encrypted string
207
 *
208
 * @return string Decrypted string
209
 */
210
function defuseReturnDecrypted(string $value, $SETTINGS): string
211
{
212
    if (substr($value, 0, 3) === 'def') {
213
        $value = cryption($value, '', 'decrypt', $SETTINGS)['string'];
214
    }
215
216
    return $value;
217
}
218
219
/**
220
 * Trims a string depending on a specific string.
221
 *
222
 * @param string|array $chaine  what to trim
223
 * @param string       $element trim on what
224
 *
225
 * @return string
226
 */
227
function trimElement($chaine, string $element): string
228
{
229
    if (! empty($chaine)) {
230
        if (is_array($chaine) === true) {
231
            $chaine = implode(';', $chaine);
232
        }
233
        $chaine = trim($chaine);
234
        if (substr($chaine, 0, 1) === $element) {
235
            $chaine = substr($chaine, 1);
236
        }
237
        if (substr($chaine, strlen($chaine) - 1, 1) === $element) {
238
            $chaine = substr($chaine, 0, strlen($chaine) - 1);
239
        }
240
    }
241
242
    return $chaine;
243
}
244
245
/**
246
 * Permits to suppress all "special" characters from string.
247
 *
248
 * @param string $string  what to clean
249
 * @param bool   $special use of special chars?
250
 *
251
 * @return string
252
 */
253
function cleanString(string $string, bool $special = false): string
254
{
255
    // Create temporary table for special characters escape
256
    $tabSpecialChar = [];
257
    for ($i = 0; $i <= 31; ++$i) {
258
        $tabSpecialChar[] = chr($i);
259
    }
260
    array_push($tabSpecialChar, '<br />');
261
    if ((int) $special === 1) {
262
        $tabSpecialChar = array_merge($tabSpecialChar, ['</li>', '<ul>', '<ol>']);
263
    }
264
265
    return str_replace($tabSpecialChar, "\n", $string);
266
}
267
268
/**
269
 * Erro manager for DB.
270
 *
271
 * @param array $params output from query
272
 *
273
 * @return void
274
 */
275
function db_error_handler(array $params): void
276
{
277
    echo 'Error: ' . $params['error'] . "<br>\n";
278
    echo 'Query: ' . $params['query'] . "<br>\n";
279
    throw new Exception('Error - Query', 1);
280
}
281
282
/**
283
 * Identify user's rights
284
 *
285
 * @param string|array $groupesVisiblesUser  [description]
286
 * @param string|array $groupesInterditsUser [description]
287
 * @param string       $isAdmin              [description]
288
 * @param string       $idFonctions          [description]
289
 *
290
 * @return bool
291
 */
292
function identifyUserRights(
293
    $groupesVisiblesUser,
294
    $groupesInterditsUser,
295
    $isAdmin,
296
    $idFonctions,
297
    $SETTINGS
298
) {
299
    $session = SessionManager::getSession();
300
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
301
302
    // Check if user is ADMINISTRATOR    
303
    (int) $isAdmin === 1 ?
304
        identAdmin(
305
            $idFonctions,
306
            $SETTINGS, /** @scrutinizer ignore-type */
307
            $tree
308
        )
309
        :
310
        identUser(
311
            $groupesVisiblesUser,
312
            $groupesInterditsUser,
313
            $idFonctions,
314
            $SETTINGS, /** @scrutinizer ignore-type */
315
            $tree
316
        );
317
318
    // update user's timestamp
319
    DB::update(
320
        prefixTable('users'),
321
        [
322
            'timestamp' => time(),
323
        ],
324
        'id=%i',
325
        $session->get('user-id')
326
    );
327
328
    return true;
329
}
330
331
/**
332
 * Identify administrator.
333
 *
334
 * @param string $idFonctions Roles of user
335
 * @param array  $SETTINGS    Teampass settings
336
 * @param object $tree        Tree of folders
337
 *
338
 * @return bool
339
 */
340
function identAdmin($idFonctions, $SETTINGS, $tree)
341
{
342
    
343
    $session = SessionManager::getSession();
344
    $groupesVisibles = [];
345
    $session->set('user-personal_folders', []);
346
    $session->set('user-accessible_folders', []);
347
    $session->set('user-no_access_folders', []);
348
    $session->set('user-personal_visible_folders', []);
349
    $session->set('user-read_only_folders', []);
350
    $session->set('system-list_restricted_folders_for_items', []);
351
    $session->set('system-list_folders_editable_by_role', []);
352
    $session->set('user-list_folders_limited', []);
353
    $session->set('user-forbiden_personal_folders', []);
354
    
355
    // Get list of Folders
356
    $rows = DB::query('SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i', 0);
357
    foreach ($rows as $record) {
358
        array_push($groupesVisibles, $record['id']);
359
    }
360
    $session->set('user-accessible_folders', $groupesVisibles);
361
    $session->set('user-all_non_personal_folders', $groupesVisibles);
362
363
    // get complete list of ROLES
364
    $tmp = explode(';', $idFonctions);
365
    $rows = DB::query(
366
        'SELECT * FROM ' . prefixTable('roles_title') . '
367
        ORDER BY title ASC'
368
    );
369
    foreach ($rows as $record) {
370
        if (! empty($record['id']) && ! in_array($record['id'], $tmp)) {
371
            array_push($tmp, $record['id']);
372
        }
373
    }
374
    $session->set('user-roles', implode(';', $tmp));
375
    $session->set('user-admin', 1);
376
    // Check if admin has created Folders and Roles
377
    DB::query('SELECT * FROM ' . prefixTable('nested_tree') . '');
378
    $session->set('user-nb_folders', DB::count());
379
    DB::query('SELECT * FROM ' . prefixTable('roles_title'));
380
    $session->set('user-nb_roles', DB::count());
381
382
    return true;
383
}
384
385
/**
386
 * Permits to convert an element to array.
387
 *
388
 * @param string|array $element Any value to be returned as array
389
 *
390
 * @return array
391
 */
392
function convertToArray($element): ?array
393
{
394
    if (is_string($element) === true) {
395
        if (empty($element) === true) {
396
            return [];
397
        }
398
        return explode(
399
            ';',
400
            trimElement($element, ';')
401
        );
402
    }
403
    return $element;
404
}
405
406
/**
407
 * Defines the rights the user has.
408
 *
409
 * @param string|array $allowedFolders  Allowed folders
410
 * @param string|array $noAccessFolders Not allowed folders
411
 * @param string|array $userRoles       Roles of user
412
 * @param array        $SETTINGS        Teampass settings
413
 * @param object       $tree            Tree of folders
414
 * 
415
 * @return bool
416
 */
417
function identUser(
418
    $allowedFolders,
419
    $noAccessFolders,
420
    $userRoles,
421
    array $SETTINGS,
422
    object $tree
423
) {
424
    $session = SessionManager::getSession();
425
    // Init
426
    $session->set('user-accessible_folders', []);
427
    $session->set('user-personal_folders', []);
428
    $session->set('user-no_access_folders', []);
429
    $session->set('user-personal_visible_folders', []);
430
    $session->set('user-read_only_folders', []);
431
    $session->set('user-user-roles', $userRoles);
432
    $session->set('user-admin', 0);
433
    // init
434
    $personalFolders = [];
435
    $readOnlyFolders = [];
436
    $noAccessPersonalFolders = [];
437
    $restrictedFoldersForItems = [];
438
    $foldersLimited = [];
439
    $foldersLimitedFull = [];
440
    $allowedFoldersByRoles = [];
441
    $globalsUserId = $session->get('user-id');
442
    $globalsPersonalFolders = $session->get('user-personal_folder_enabled');
443
    // Ensure consistency in array format
444
    $noAccessFolders = convertToArray($noAccessFolders);
445
    $userRoles = convertToArray($userRoles);
446
    $allowedFolders = convertToArray($allowedFolders);
447
    $session->set('user-allowed_folders_by_definition', $allowedFolders);
448
    
449
    // Get list of folders depending on Roles
450
    $arrays = identUserGetFoldersFromRoles(
451
        $userRoles,
452
        $allowedFoldersByRoles,
453
        $readOnlyFolders,
454
        $allowedFolders
455
    );
456
    $allowedFoldersByRoles = $arrays['allowedFoldersByRoles'];
457
    $readOnlyFolders = $arrays['readOnlyFolders'];
458
459
    // Does this user is allowed to see other items
460
    $inc = 0;
461
    $rows = DB::query(
462
        'SELECT id, id_tree FROM ' . prefixTable('items') . '
463
            WHERE restricted_to LIKE %ss AND inactif = %s'.
464
            (count($allowedFolders) > 0 ? ' AND id_tree NOT IN ('.implode(',', $allowedFolders).')' : ''),
465
        $globalsUserId,
466
        '0'
467
    );
468
    foreach ($rows as $record) {
469
        // Exclude restriction on item if folder is fully accessible
470
        //if (in_array($record['id_tree'], $allowedFolders) === false) {
471
            $restrictedFoldersForItems[$record['id_tree']][$inc] = $record['id'];
472
            ++$inc;
473
        //}
474
    }
475
476
    // Check for the users roles if some specific rights exist on items
477
    $rows = DB::query(
478
        'SELECT i.id_tree, r.item_id
479
        FROM ' . prefixTable('items') . ' as i
480
        INNER JOIN ' . prefixTable('restriction_to_roles') . ' as r ON (r.item_id=i.id)
481
        WHERE i.id_tree <> "" '.
482
        (count($userRoles) > 0 ? 'AND r.role_id IN %li ' : '').
483
        'ORDER BY i.id_tree ASC',
484
        $userRoles
485
    );
486
    $inc = 0;
487
    foreach ($rows as $record) {
488
        //if (isset($record['id_tree'])) {
489
            $foldersLimited[$record['id_tree']][$inc] = $record['item_id'];
490
            array_push($foldersLimitedFull, $record['id_tree']);
491
            ++$inc;
492
        //}
493
    }
494
495
    // Get list of Personal Folders
496
    $arrays = identUserGetPFList(
497
        $globalsPersonalFolders,
498
        $allowedFolders,
499
        $globalsUserId,
500
        $personalFolders,
501
        $noAccessPersonalFolders,
502
        $foldersLimitedFull,
503
        $allowedFoldersByRoles,
504
        array_keys($restrictedFoldersForItems),
505
        $readOnlyFolders,
506
        $noAccessFolders,
507
        isset($SETTINGS['enable_pf_feature']) === true ? $SETTINGS['enable_pf_feature'] : 0,
508
        $tree
509
    );
510
    $allowedFolders = $arrays['allowedFolders'];
511
    $personalFolders = $arrays['personalFolders'];
512
    $noAccessPersonalFolders = $arrays['noAccessPersonalFolders'];
513
514
    // Return data
515
    $session->set('user-all_non_personal_folders', $allowedFolders);
516
    $session->set('user-accessible_folders', array_unique(array_merge($allowedFolders, $personalFolders), SORT_NUMERIC));
517
    $session->set('user-read_only_folders', $readOnlyFolders);
518
    $session->set('user-no_access_folders', $noAccessFolders);
519
    $session->set('user-personal_folders', $personalFolders);
520
    $session->set('user-list_folders_limited', $foldersLimited);
521
    $session->set('system-list_folders_editable_by_role', $allowedFoldersByRoles, 'SESSION');
522
    $session->set('system-list_restricted_folders_for_items', $restrictedFoldersForItems);
523
    $session->set('user-forbiden_personal_folders', $noAccessPersonalFolders);
524
    $session->set(
525
        'all_folders_including_no_access',
526
        array_unique(array_merge(
527
            $allowedFolders,
528
            $personalFolders,
529
            $noAccessFolders,
530
            $readOnlyFolders
531
        ), SORT_NUMERIC)
532
    );
533
    // Folders and Roles numbers
534
    DB::queryfirstrow('SELECT id FROM ' . prefixTable('nested_tree') . '');
535
    $session->set('user-nb_folders', DB::count());
536
    DB::queryfirstrow('SELECT id FROM ' . prefixTable('roles_title'));
537
    $session->set('user-nb_roles', DB::count());
538
    // check if change proposals on User's items
539
    if (isset($SETTINGS['enable_suggestion']) === true && (int) $SETTINGS['enable_suggestion'] === 1) {
540
        $countNewItems = DB::query(
541
            'SELECT COUNT(*)
542
            FROM ' . prefixTable('items_change') . ' AS c
543
            LEFT JOIN ' . prefixTable('log_items') . ' AS i ON (c.item_id = i.id_item)
544
            WHERE i.action = %s AND i.id_user = %i',
545
            'at_creation',
546
            $globalsUserId
547
        );
548
        $session->set('user-nb_item_change_proposals', $countNewItems);
549
    } else {
550
        $session->set('user-nb_item_change_proposals', 0);
551
    }
552
553
    return true;
554
}
555
556
/**
557
 * Get list of folders depending on Roles
558
 * 
559
 * @param array $userRoles
560
 * @param array $allowedFoldersByRoles
561
 * @param array $readOnlyFolders
562
 * @param array $allowedFolders
563
 * 
564
 * @return array
565
 */
566
function identUserGetFoldersFromRoles($userRoles, $allowedFoldersByRoles, $readOnlyFolders, $allowedFolders) : array
567
{
568
    $rows = DB::query(
569
        'SELECT *
570
        FROM ' . prefixTable('roles_values') . '
571
        WHERE type IN %ls'.(count($userRoles) > 0 ? ' AND role_id IN %li' : ''),
572
        ['W', 'ND', 'NE', 'NDNE', 'R'],
573
        $userRoles,
574
    );
575
    foreach ($rows as $record) {
576
        if ($record['type'] === 'R') {
577
            array_push($readOnlyFolders, $record['folder_id']);
578
        } elseif (in_array($record['folder_id'], $allowedFolders) === false) {
579
            array_push($allowedFoldersByRoles, $record['folder_id']);
580
        }
581
    }
582
    $allowedFoldersByRoles = array_unique($allowedFoldersByRoles);
583
    $readOnlyFolders = array_unique($readOnlyFolders);
584
    
585
    // Clean arrays
586
    foreach ($allowedFoldersByRoles as $value) {
587
        $key = array_search($value, $readOnlyFolders);
588
        if ($key !== false) {
589
            unset($readOnlyFolders[$key]);
590
        }
591
    }
592
    return [
593
        'readOnlyFolders' => $readOnlyFolders,
594
        'allowedFoldersByRoles' => $allowedFoldersByRoles
595
    ];
596
}
597
598
/**
599
 * Get list of Personal Folders
600
 * 
601
 * @param int $globalsPersonalFolders
602
 * @param array $allowedFolders
603
 * @param int $globalsUserId
604
 * @param array $personalFolders
605
 * @param array $noAccessPersonalFolders
606
 * @param array $foldersLimitedFull
607
 * @param array $allowedFoldersByRoles
608
 * @param array $restrictedFoldersForItems
609
 * @param array $readOnlyFolders
610
 * @param array $noAccessFolders
611
 * @param int $enablePfFeature
612
 * @param object $tree
613
 * 
614
 * @return array
615
 */
616
function identUserGetPFList(
617
    $globalsPersonalFolders,
618
    $allowedFolders,
619
    $globalsUserId,
620
    $personalFolders,
621
    $noAccessPersonalFolders,
622
    $foldersLimitedFull,
623
    $allowedFoldersByRoles,
624
    $restrictedFoldersForItems,
625
    $readOnlyFolders,
626
    $noAccessFolders,
627
    $enablePfFeature,
628
    $tree
629
)
630
{
631
    if (
632
        (int) $enablePfFeature === 1
633
        && (int) $globalsPersonalFolders === 1
634
    ) {
635
        $persoFld = DB::queryfirstrow(
636
            'SELECT id
637
            FROM ' . prefixTable('nested_tree') . '
638
            WHERE title = %s AND personal_folder = %i'.
639
            (count($allowedFolders) > 0 ? ' AND id NOT IN ('.implode(',', $allowedFolders).')' : ''),
640
            $globalsUserId,
641
            1
642
        );
643
        if (empty($persoFld['id']) === false) {
644
            array_push($personalFolders, $persoFld['id']);
645
            array_push($allowedFolders, $persoFld['id']);
646
            // get all descendants
647
            $ids = $tree->getDescendants($persoFld['id'], false, false, true);
648
            foreach ($ids as $id) {
649
                //array_push($allowedFolders, $id);
650
                array_push($personalFolders, $id);
651
            }
652
        }
653
    }
654
    
655
    // Exclude all other PF
656
    $where = new WhereClause('and');
657
    $where->add('personal_folder=%i', 1);
658
    if (count($personalFolders) > 0) {
659
        $where->add('id NOT IN ('.implode(',', $personalFolders).')');
660
    }
661
    if (
662
        (int) $enablePfFeature === 1
663
        && (int) $globalsPersonalFolders === 1
664
    ) {
665
        $where->add('title=%s', $globalsUserId);
666
        $where->negateLast();
667
    }
668
    $persoFlds = DB::query(
669
        'SELECT id
670
        FROM ' . prefixTable('nested_tree') . '
671
        WHERE %l',
672
        $where
673
    );
674
    foreach ($persoFlds as $persoFldId) {
675
        array_push($noAccessPersonalFolders, $persoFldId['id']);
676
    }
677
678
    // All folders visibles
679
    $allowedFolders = array_unique(array_merge(
680
        $allowedFolders,
681
        $foldersLimitedFull,
682
        $allowedFoldersByRoles,
683
        $restrictedFoldersForItems,
684
        $readOnlyFolders
685
    ), SORT_NUMERIC);
686
    // Exclude from allowed folders all the specific user forbidden folders
687
    if (count($noAccessFolders) > 0) {
688
        $allowedFolders = array_diff($allowedFolders, $noAccessFolders);
689
    }
690
691
    return [
692
        'allowedFolders' => array_diff(array_diff($allowedFolders, $noAccessPersonalFolders), $personalFolders),
693
        'personalFolders' => $personalFolders,
694
        'noAccessPersonalFolders' => $noAccessPersonalFolders
695
    ];
696
}
697
698
699
/**
700
 * Update the CACHE table.
701
 *
702
 * @param string $action   What to do
703
 * @param array  $SETTINGS Teampass settings
704
 * @param int    $ident    Ident format
705
 * 
706
 * @return void
707
 */
708
function updateCacheTable(string $action, ?int $ident = null): void
709
{
710
    if ($action === 'reload') {
711
        // Rebuild full cache table
712
        cacheTableRefresh();
713
    } elseif ($action === 'update_value' && is_null($ident) === false) {
714
        // UPDATE an item
715
        cacheTableUpdate($ident);
716
    } elseif ($action === 'add_value' && is_null($ident) === false) {
717
        // ADD an item
718
        cacheTableAdd($ident);
719
    } elseif ($action === 'delete_value' && is_null($ident) === false) {
720
        // DELETE an item
721
        DB::delete(prefixTable('cache'), 'id = %i', $ident);
722
    }
723
}
724
725
/**
726
 * Cache table - refresh.
727
 *
728
 * @return void
729
 */
730
function cacheTableRefresh(): void
731
{
732
    // Load class DB
733
    loadClasses('DB');
734
735
    //Load Tree
736
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
737
    // truncate table
738
    DB::query('TRUNCATE TABLE ' . prefixTable('cache'));
739
    // reload date
740
    $rows = DB::query(
741
        'SELECT *
742
        FROM ' . prefixTable('items') . ' as i
743
        INNER JOIN ' . prefixTable('log_items') . ' as l ON (l.id_item = i.id)
744
        AND l.action = %s
745
        AND i.inactif = %i',
746
        'at_creation',
747
        0
748
    );
749
    foreach ($rows as $record) {
750
        if (empty($record['id_tree']) === false) {
751
            // Get all TAGS
752
            $tags = '';
753
            $itemTags = DB::query(
754
                'SELECT tag
755
                FROM ' . prefixTable('tags') . '
756
                WHERE item_id = %i AND tag != ""',
757
                $record['id']
758
            );
759
            foreach ($itemTags as $itemTag) {
760
                $tags .= $itemTag['tag'] . ' ';
761
            }
762
763
            // Get renewal period
764
            $resNT = DB::queryfirstrow(
765
                'SELECT renewal_period
766
                FROM ' . prefixTable('nested_tree') . '
767
                WHERE id = %i',
768
                $record['id_tree']
769
            );
770
            // form id_tree to full foldername
771
            $folder = [];
772
            $arbo = $tree->getPath($record['id_tree'], true);
773
            foreach ($arbo as $elem) {
774
                // Check if title is the ID of a user
775
                if (is_numeric($elem->title) === true) {
776
                    // Is this a User id?
777
                    $user = DB::queryfirstrow(
778
                        'SELECT id, login
779
                        FROM ' . prefixTable('users') . '
780
                        WHERE id = %i',
781
                        $elem->title
782
                    );
783
                    if (count($user) > 0) {
784
                        $elem->title = $user['login'];
785
                    }
786
                }
787
                // Build path
788
                array_push($folder, stripslashes($elem->title));
789
            }
790
            // store data
791
            DB::insert(
792
                prefixTable('cache'),
793
                [
794
                    'id' => $record['id'],
795
                    'label' => $record['label'],
796
                    'description' => $record['description'] ?? '',
797
                    'url' => isset($record['url']) && ! empty($record['url']) ? $record['url'] : '0',
798
                    'tags' => $tags,
799
                    'id_tree' => $record['id_tree'],
800
                    'perso' => $record['perso'],
801
                    'restricted_to' => isset($record['restricted_to']) && ! empty($record['restricted_to']) ? $record['restricted_to'] : '0',
802
                    'login' => $record['login'] ?? '',
803
                    'folder' => implode(' > ', $folder),
804
                    'author' => $record['id_user'],
805
                    'renewal_period' => $resNT['renewal_period'] ?? '0',
806
                    'timestamp' => $record['date'],
807
                ]
808
            );
809
        }
810
    }
811
}
812
813
/**
814
 * Cache table - update existing value.
815
 *
816
 * @param int    $ident    Ident format
817
 * 
818
 * @return void
819
 */
820
function cacheTableUpdate(?int $ident = null): void
821
{
822
    $session = SessionManager::getSession();
823
    loadClasses('DB');
824
825
    //Load Tree
826
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
827
    // get new value from db
828
    $data = DB::queryfirstrow(
829
        'SELECT label, description, id_tree, perso, restricted_to, login, url
830
        FROM ' . prefixTable('items') . '
831
        WHERE id=%i',
832
        $ident
833
    );
834
    // Get all TAGS
835
    $tags = '';
836
    $itemTags = DB::query(
837
        'SELECT tag
838
            FROM ' . prefixTable('tags') . '
839
            WHERE item_id = %i AND tag != ""',
840
        $ident
841
    );
842
    foreach ($itemTags as $itemTag) {
843
        $tags .= $itemTag['tag'] . ' ';
844
    }
845
    // form id_tree to full foldername
846
    $folder = [];
847
    $arbo = $tree->getPath($data['id_tree'], true);
848
    foreach ($arbo as $elem) {
849
        // Check if title is the ID of a user
850
        if (is_numeric($elem->title) === true) {
851
            // Is this a User id?
852
            $user = DB::queryfirstrow(
853
                'SELECT id, login
854
                FROM ' . prefixTable('users') . '
855
                WHERE id = %i',
856
                $elem->title
857
            );
858
            if (count($user) > 0) {
859
                $elem->title = $user['login'];
860
            }
861
        }
862
        // Build path
863
        array_push($folder, stripslashes($elem->title));
864
    }
865
    // finaly update
866
    DB::update(
867
        prefixTable('cache'),
868
        [
869
            'label' => $data['label'],
870
            'description' => $data['description'],
871
            'tags' => $tags,
872
            'url' => isset($data['url']) && ! empty($data['url']) ? $data['url'] : '0',
873
            'id_tree' => $data['id_tree'],
874
            'perso' => $data['perso'],
875
            'restricted_to' => isset($data['restricted_to']) && ! empty($data['restricted_to']) ? $data['restricted_to'] : '0',
876
            'login' => $data['login'] ?? '',
877
            'folder' => implode(' » ', $folder),
878
            'author' => $session->get('user-id'),
879
        ],
880
        'id = %i',
881
        $ident
882
    );
883
}
884
885
/**
886
 * Cache table - add new value.
887
 *
888
 * @param int    $ident    Ident format
889
 * 
890
 * @return void
891
 */
892
function cacheTableAdd(?int $ident = null): void
893
{
894
    $session = SessionManager::getSession();
895
    $globalsUserId = $session->get('user-id');
896
897
    // Load class DB
898
    loadClasses('DB');
899
900
    //Load Tree
901
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
902
    // get new value from db
903
    $data = DB::queryFirstRow(
904
        'SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login, i.url, l.date
905
        FROM ' . prefixTable('items') . ' as i
906
        INNER JOIN ' . prefixTable('log_items') . ' as l ON (l.id_item = i.id)
907
        WHERE i.id = %i
908
        AND l.action = %s',
909
        $ident,
910
        'at_creation'
911
    );
912
    // Get all TAGS
913
    $tags = '';
914
    $itemTags = DB::query(
915
        'SELECT tag
916
            FROM ' . prefixTable('tags') . '
917
            WHERE item_id = %i AND tag != ""',
918
        $ident
919
    );
920
    foreach ($itemTags as $itemTag) {
921
        $tags .= $itemTag['tag'] . ' ';
922
    }
923
    // form id_tree to full foldername
924
    $folder = [];
925
    $arbo = $tree->getPath($data['id_tree'], true);
926
    foreach ($arbo as $elem) {
927
        // Check if title is the ID of a user
928
        if (is_numeric($elem->title) === true) {
929
            // Is this a User id?
930
            $user = DB::queryfirstrow(
931
                'SELECT id, login
932
                FROM ' . prefixTable('users') . '
933
                WHERE id = %i',
934
                $elem->title
935
            );
936
            if (count($user) > 0) {
937
                $elem->title = $user['login'];
938
            }
939
        }
940
        // Build path
941
        array_push($folder, stripslashes($elem->title));
942
    }
943
    // finaly update
944
    DB::insert(
945
        prefixTable('cache'),
946
        [
947
            'id' => $data['id'],
948
            'label' => $data['label'],
949
            'description' => $data['description'],
950
            'tags' => isset($tags) && empty($tags) === false ? $tags : 'None',
951
            'url' => isset($data['url']) && ! empty($data['url']) ? $data['url'] : '0',
952
            'id_tree' => $data['id_tree'],
953
            'perso' => isset($data['perso']) && empty($data['perso']) === false && $data['perso'] !== 'None' ? $data['perso'] : '0',
954
            'restricted_to' => isset($data['restricted_to']) && empty($data['restricted_to']) === false ? $data['restricted_to'] : '0',
955
            'login' => $data['login'] ?? '',
956
            'folder' => implode(' » ', $folder),
957
            'author' => $globalsUserId,
958
            'timestamp' => $data['date'],
959
        ]
960
    );
961
}
962
963
/**
964
 * Do statistics.
965
 *
966
 * @param array $SETTINGS Teampass settings
967
 *
968
 * @return array
969
 */
970
function getStatisticsData(array $SETTINGS): array
971
{
972
    DB::query(
973
        'SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i',
974
        0
975
    );
976
    $counter_folders = DB::count();
977
    DB::query(
978
        'SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i',
979
        1
980
    );
981
    $counter_folders_perso = DB::count();
982
    DB::query(
983
        'SELECT id FROM ' . prefixTable('items') . ' WHERE perso = %i',
984
        0
985
    );
986
    $counter_items = DB::count();
987
        DB::query(
988
        'SELECT id FROM ' . prefixTable('items') . ' WHERE perso = %i',
989
        1
990
    );
991
    $counter_items_perso = DB::count();
992
        DB::query(
993
        'SELECT id FROM ' . prefixTable('users') . ' WHERE login NOT IN (%s, %s, %s)',
994
        'OTV', 'TP', 'API'
995
    );
996
    $counter_users = DB::count();
997
        DB::query(
998
        'SELECT id FROM ' . prefixTable('users') . ' WHERE admin = %i',
999
        1
1000
    );
1001
    $admins = DB::count();
1002
    DB::query(
1003
        'SELECT id FROM ' . prefixTable('users') . ' WHERE gestionnaire = %i',
1004
        1
1005
    );
1006
    $managers = DB::count();
1007
    DB::query(
1008
        'SELECT id FROM ' . prefixTable('users') . ' WHERE read_only = %i',
1009
        1
1010
    );
1011
    $readOnly = DB::count();
1012
    // list the languages
1013
    $usedLang = [];
1014
    $tp_languages = DB::query(
1015
        'SELECT name FROM ' . prefixTable('languages')
1016
    );
1017
    foreach ($tp_languages as $tp_language) {
1018
        DB::query(
1019
            'SELECT * FROM ' . prefixTable('users') . ' WHERE user_language = %s',
1020
            $tp_language['name']
1021
        );
1022
        $usedLang[$tp_language['name']] = round((DB::count() * 100 / $counter_users), 0);
1023
    }
1024
1025
    // get list of ips
1026
    $usedIp = [];
1027
    $tp_ips = DB::query(
1028
        'SELECT user_ip FROM ' . prefixTable('users')
1029
    );
1030
    foreach ($tp_ips as $ip) {
1031
        if (array_key_exists($ip['user_ip'], $usedIp)) {
1032
            $usedIp[$ip['user_ip']] += $usedIp[$ip['user_ip']];
1033
        } elseif (! empty($ip['user_ip']) && $ip['user_ip'] !== 'none') {
1034
            $usedIp[$ip['user_ip']] = 1;
1035
        }
1036
    }
1037
1038
    return [
1039
        'error' => '',
1040
        'stat_phpversion' => phpversion(),
1041
        'stat_folders' => $counter_folders,
1042
        'stat_folders_shared' => intval($counter_folders) - intval($counter_folders_perso),
1043
        'stat_items' => $counter_items,
1044
        'stat_items_shared' => intval($counter_items) - intval($counter_items_perso),
1045
        'stat_users' => $counter_users,
1046
        'stat_admins' => $admins,
1047
        'stat_managers' => $managers,
1048
        'stat_ro' => $readOnly,
1049
        'stat_kb' => $SETTINGS['enable_kb'],
1050
        'stat_pf' => $SETTINGS['enable_pf_feature'],
1051
        'stat_fav' => $SETTINGS['enable_favourites'],
1052
        'stat_teampassversion' => TP_VERSION,
1053
        'stat_ldap' => $SETTINGS['ldap_mode'],
1054
        'stat_agses' => $SETTINGS['agses_authentication_enabled'],
1055
        'stat_duo' => $SETTINGS['duo'],
1056
        'stat_suggestion' => $SETTINGS['enable_suggestion'],
1057
        'stat_api' => $SETTINGS['api'],
1058
        'stat_customfields' => $SETTINGS['item_extra_fields'],
1059
        'stat_syslog' => $SETTINGS['syslog_enable'],
1060
        'stat_2fa' => $SETTINGS['google_authentication'],
1061
        'stat_stricthttps' => $SETTINGS['enable_sts'],
1062
        'stat_mysqlversion' => DB::serverVersion(),
1063
        'stat_languages' => $usedLang,
1064
        'stat_country' => $usedIp,
1065
    ];
1066
}
1067
1068
/**
1069
 * Permits to prepare the way to send the email
1070
 * 
1071
 * @param string $subject       email subject
1072
 * @param string $body          email message
1073
 * @param string $email         email
1074
 * @param string $receiverName  Receiver name
1075
 * @param string $encryptedUserPassword      encryptedUserPassword
1076
 *
1077
 * @return void
1078
 */
1079
function prepareSendingEmail(
1080
    $subject,
1081
    $body,
1082
    $email,
1083
    $receiverName = '',
1084
    $encryptedUserPassword = ''
1085
): void 
1086
{
1087
    DB::insert(
1088
        prefixTable('background_tasks'),
1089
        array(
1090
            'created_at' => time(),
1091
            'process_type' => 'send_email',
1092
            'arguments' => json_encode([
1093
                'subject' => $subject,
1094
                'receivers' => $email,
1095
                'body' => $body,
1096
                'receiver_name' => $receiverName,
1097
                'encryptedUserPassword' => $encryptedUserPassword,
1098
            ], JSON_HEX_QUOT | JSON_HEX_TAG),
1099
        )
1100
    );
1101
}
1102
1103
/**
1104
 * Returns the email body.
1105
 *
1106
 * @param string $textMail Text for the email
1107
 */
1108
function emailBody(string $textMail): string
1109
{
1110
    return '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.=
1111
    w3.org/TR/html4/loose.dtd"><html>
1112
    <head><title>Email Template</title>
1113
    <style type="text/css">
1114
    body { background-color: #f0f0f0; padding: 10px 0; margin:0 0 10px =0; }
1115
    </style></head>
1116
    <body style="-ms-text-size-adjust: none; size-adjust: none; margin: 0; padding: 10px 0; background-color: #f0f0f0;" bgcolor="#f0f0f0" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
1117
    <table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#f0f0f0" style="border-spacing: 0;">
1118
    <tr><td style="border-collapse: collapse;"><br>
1119
        <table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#17357c" style="border-spacing: 0; margin-bottom: 25px;">
1120
        <tr><td style="border-collapse: collapse; padding: 11px 20px;">
1121
            <div style="max-width:150px; max-height:34px; color:#f0f0f0; font-weight:bold;">Teampass</div>
1122
        </td></tr></table></td>
1123
    </tr>
1124
    <tr><td align="center" valign="top" bgcolor="#f0f0f0" style="border-collapse: collapse; background-color: #f0f0f0;">
1125
        <table width="600" cellpadding="0" cellspacing="0" border="0" class="container" bgcolor="#ffffff" style="border-spacing: 0; border-bottom: 1px solid #e0e0e0; box-shadow: 0 0 3px #ddd; color: #434343; font-family: Helvetica, Verdana, sans-serif;">
1126
        <tr><td class="container-padding" bgcolor="#ffffff" style="border-collapse: collapse; border-left: 1px solid #e0e0e0; background-color: #ffffff; padding-left: 30px; padding-right: 30px;">
1127
        <br><div style="float:right;">' .
1128
        $textMail .
1129
        '<br><br></td></tr></table>
1130
    </td></tr></table>
1131
    <br></body></html>';
1132
}
1133
1134
/**
1135
 * Convert date to timestamp.
1136
 *
1137
 * @param string $date        The date
1138
 * @param string $date_format Date format
1139
 *
1140
 * @return int
1141
 */
1142
function dateToStamp(string $date, string $date_format): int
1143
{
1144
    $date = date_parse_from_format($date_format, $date);
1145
    if ((int) $date['warning_count'] === 0 && (int) $date['error_count'] === 0) {
1146
        return mktime(
1147
            empty($date['hour']) === false ? $date['hour'] : 23,
1148
            empty($date['minute']) === false ? $date['minute'] : 59,
1149
            empty($date['second']) === false ? $date['second'] : 59,
1150
            $date['month'],
1151
            $date['day'],
1152
            $date['year']
1153
        );
1154
    }
1155
    return 0;
1156
}
1157
1158
/**
1159
 * Is this a date.
1160
 *
1161
 * @param string $date Date
1162
 *
1163
 * @return bool
1164
 */
1165
function isDate(string $date): bool
1166
{
1167
    return strtotime($date) !== false;
1168
}
1169
1170
/**
1171
 * Check if isUTF8().
1172
 *
1173
 * @param string|array $string Is the string
1174
 *
1175
 * @return int is the string in UTF8 format
1176
 */
1177
function isUTF8($string): int
1178
{
1179
    if (is_array($string) === true) {
1180
        $string = $string['string'];
1181
    }
1182
1183
    return preg_match(
1184
        '%^(?:
1185
        [\x09\x0A\x0D\x20-\x7E] # ASCII
1186
        | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
1187
        | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
1188
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
1189
        | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
1190
        | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1191
        | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1192
        | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1193
        )*$%xs',
1194
        $string
1195
    );
1196
}
1197
1198
/**
1199
 * Prepare an array to UTF8 format before JSON_encode.
1200
 *
1201
 * @param array $array Array of values
1202
 *
1203
 * @return array
1204
 */
1205
function utf8Converter(array $array): array
1206
{
1207
    array_walk_recursive(
1208
        $array,
1209
        static function (&$item): void {
1210
            if (mb_detect_encoding((string) $item, 'utf-8', true) === false) {
1211
                $item = mb_convert_encoding($item, 'ISO-8859-1', 'UTF-8');
1212
            }
1213
        }
1214
    );
1215
    return $array;
1216
}
1217
1218
/**
1219
 * Permits to prepare data to be exchanged.
1220
 *
1221
 * @param array|string $data Text
1222
 * @param string       $type Parameter
1223
 * @param string       $key  Optional key
1224
 *
1225
 * @return string|array
1226
 */
1227
function prepareExchangedData($data, string $type, ?string $key = null)
1228
{
1229
    $session = SessionManager::getSession();
1230
    $key = empty($key) ? $session->get('key') : $key;
1231
    
1232
    // Perform
1233
    if ($type === 'encode' && is_array($data) === true) {
1234
        // json encoding
1235
        $data = json_encode(
1236
            $data,
1237
            JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
1238
        );
1239
1240
        // Now encrypt
1241
        if ($session->get('encryptClientServer') === 1) {
1242
            $data = Encryption::encrypt(
1243
                $data,
1244
                $key
1245
            );
1246
        }
1247
1248
        return $data;
1249
    }
1250
1251
    if ($type === 'decode' && is_array($data) === false) {
1252
        // Decrypt if needed
1253
        if ($session->get('encryptClientServer') === 1) {
1254
            $data = (string) Encryption::decrypt(
1255
                (string) $data,
1256
                $key
1257
            );
1258
        } else {
1259
            // Double html encoding received
1260
            $data = html_entity_decode(html_entity_decode(/** @scrutinizer ignore-type */$data)); // @codeCoverageIgnore Is always a string (not an array)
1261
        }
1262
1263
        // Check if $data is a valid string before json_decode
1264
        if (is_string($data) && !empty($data)) {
1265
            // Return data array
1266
            return json_decode($data, true);
1267
        }
1268
    }
1269
1270
    return '';
1271
}
1272
1273
1274
/**
1275
 * Create a thumbnail.
1276
 *
1277
 * @param string  $src           Source
1278
 * @param string  $dest          Destination
1279
 * @param int $desired_width Size of width
1280
 * 
1281
 * @return void|string|bool
1282
 */
1283
function makeThumbnail(string $src, string $dest, int $desired_width)
1284
{
1285
    /* read the source image */
1286
    if (is_file($src) === true && mime_content_type($src) === 'image/png') {
1287
        $source_image = imagecreatefrompng($src);
1288
        if ($source_image === false) {
1289
            return "Error: Not a valid PNG file! It's type is ".mime_content_type($src);
1290
        }
1291
    } else {
1292
        return "Error: Not a valid PNG file! It's type is ".mime_content_type($src);
1293
    }
1294
1295
    // Get height and width
1296
    $width = imagesx($source_image);
1297
    $height = imagesy($source_image);
1298
    /* find the "desired height" of this thumbnail, relative to the desired width  */
1299
    $desired_height = (int) floor($height * $desired_width / $width);
1300
    /* create a new, "virtual" image */
1301
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
1302
    if ($virtual_image === false) {
1303
        return false;
1304
    }
1305
    /* copy source image at a resized size */
1306
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
1307
    /* create the physical thumbnail image to its destination */
1308
    imagejpeg($virtual_image, $dest);
1309
}
1310
1311
/**
1312
 * Check table prefix in SQL query.
1313
 *
1314
 * @param string $table Table name
1315
 * 
1316
 * @return string
1317
 */
1318
function prefixTable(string $table): string
1319
{
1320
    $safeTable = htmlspecialchars(DB_PREFIX . $table);
1321
    if (empty($safeTable) === false) {
1322
        // sanitize string
1323
        return $safeTable;
1324
    }
1325
    // stop error no table
1326
    return 'table_not_exists';
1327
}
1328
1329
/**
1330
 * GenerateCryptKey
1331
 *
1332
 * @param int     $size      Length
1333
 * @param bool $secure Secure
1334
 * @param bool $numerals Numerics
1335
 * @param bool $uppercase Uppercase letters
1336
 * @param bool $symbols Symbols
1337
 * @param bool $lowercase Lowercase
1338
 * 
1339
 * @return string
1340
 */
1341
function GenerateCryptKey(
1342
    int $size = 20,
1343
    bool $secure = false,
1344
    bool $numerals = false,
1345
    bool $uppercase = false,
1346
    bool $symbols = false,
1347
    bool $lowercase = false
1348
): string {
1349
    $generator = new ComputerPasswordGenerator();
1350
    $generator->setRandomGenerator(new Php7RandomGenerator());
1351
    
1352
    // Manage size
1353
    $generator->setLength((int) $size);
1354
    if ($secure === true) {
1355
        $generator->setSymbols(true);
1356
        $generator->setLowercase(true);
1357
        $generator->setUppercase(true);
1358
        $generator->setNumbers(true);
1359
    } else {
1360
        $generator->setLowercase($lowercase);
1361
        $generator->setUppercase($uppercase);
1362
        $generator->setNumbers($numerals);
1363
        $generator->setSymbols($symbols);
1364
    }
1365
1366
    return $generator->generatePasswords()[0];
1367
}
1368
1369
/**
1370
 * GenerateGenericPassword
1371
 *
1372
 * @param int     $size      Length
1373
 * @param bool $secure Secure
1374
 * @param bool $numerals Numerics
1375
 * @param bool $uppercase Uppercase letters
1376
 * @param bool $symbols Symbols
1377
 * @param bool $lowercase Lowercase
1378
 * @param array   $SETTINGS  SETTINGS
1379
 * 
1380
 * @return string
1381
 */
1382
function generateGenericPassword(
1383
    int $size,
1384
    bool $secure,
1385
    bool $lowercase,
1386
    bool $capitalize,
1387
    bool $numerals,
1388
    bool $symbols,
1389
    array $SETTINGS
1390
): string
1391
{
1392
    if ((int) $size > (int) $SETTINGS['pwd_maximum_length']) {
1393
        return prepareExchangedData(
1394
            array(
1395
                'error_msg' => 'Password length is too long! ',
1396
                'error' => 'true',
1397
            ),
1398
            'encode'
1399
        );
1400
    }
1401
    // Load libraries
1402
    $generator = new ComputerPasswordGenerator();
1403
    $generator->setRandomGenerator(new Php7RandomGenerator());
1404
1405
    // Manage size
1406
    $generator->setLength(($size <= 0) ? 10 : $size);
1407
1408
    if ($secure === true) {
1409
        $generator->setSymbols(true);
1410
        $generator->setLowercase(true);
1411
        $generator->setUppercase(true);
1412
        $generator->setNumbers(true);
1413
    } else {
1414
        $generator->setLowercase($lowercase);
1415
        $generator->setUppercase($capitalize);
1416
        $generator->setNumbers($numerals);
1417
        $generator->setSymbols($symbols);
1418
    }
1419
1420
    return prepareExchangedData(
1421
        array(
1422
            'key' => $generator->generatePasswords(),
1423
            'error' => '',
1424
        ),
1425
        'encode'
1426
    );
1427
}
1428
1429
/**
1430
 * Send sysLOG message
1431
 *
1432
 * @param string    $message
1433
 * @param string    $host
1434
 * @param int       $port
1435
 * @param string    $component
1436
 * 
1437
 * @return void
1438
*/
1439
function send_syslog($message, $host, $port, $component = 'teampass'): void
1440
{
1441
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1442
    $syslog_message = '<123>' . date('M d H:i:s ') . $component . ': ' . $message;
1443
    socket_sendto($sock, (string) $syslog_message, strlen($syslog_message), 0, (string) $host, (int) $port);
1444
    socket_close($sock);
1445
}
1446
1447
/**
1448
 * Permits to log events into DB
1449
 *
1450
 * @param array  $SETTINGS Teampass settings
1451
 * @param string $type     Type
1452
 * @param string $label    Label
1453
 * @param string $who      Who
1454
 * @param string $login    Login
1455
 * @param string|int $field_1  Field
1456
 * 
1457
 * @return void
1458
 */
1459
function logEvents(
1460
    array $SETTINGS, 
1461
    string $type, 
1462
    string $label, 
1463
    string $who, 
1464
    ?string $login = null, 
1465
    $field_1 = null
1466
): void
1467
{
1468
    if (empty($who)) {
1469
        $who = getClientIpServer();
1470
    }
1471
1472
    // Load class DB
1473
    loadClasses('DB');
1474
1475
    DB::insert(
1476
        prefixTable('log_system'),
1477
        [
1478
            'type' => $type,
1479
            'date' => time(),
1480
            'label' => $label,
1481
            'qui' => $who,
1482
            'field_1' => $field_1 === null ? '' : $field_1,
1483
        ]
1484
    );
1485
    // If SYSLOG
1486
    if (isset($SETTINGS['syslog_enable']) === true && (int) $SETTINGS['syslog_enable'] === 1) {
1487
        if ($type === 'user_mngt') {
1488
            send_syslog(
1489
                'action=' . str_replace('at_', '', $label) . ' attribute=user user=' . $who . ' userid="' . $login . '" change="' . $field_1 . '" ',
1490
                $SETTINGS['syslog_host'],
1491
                $SETTINGS['syslog_port'],
1492
                'teampass'
1493
            );
1494
        } else {
1495
            send_syslog(
1496
                'action=' . $type . ' attribute=' . $label . ' user=' . $who . ' userid="' . $login . '" ',
1497
                $SETTINGS['syslog_host'],
1498
                $SETTINGS['syslog_port'],
1499
                'teampass'
1500
            );
1501
        }
1502
    }
1503
}
1504
1505
/**
1506
 * Log events.
1507
 *
1508
 * @param array  $SETTINGS        Teampass settings
1509
 * @param int    $item_id         Item id
1510
 * @param string $item_label      Item label
1511
 * @param int    $id_user         User id
1512
 * @param string $action          Code for reason
1513
 * @param string $login           User login
1514
 * @param string $raison          Code for reason
1515
 * @param string $encryption_type Encryption on
1516
 * @param string $time Encryption Time
1517
 * @param string $old_value       Old value
1518
 * 
1519
 * @return void
1520
 */
1521
function logItems(
1522
    array $SETTINGS,
1523
    int $item_id,
1524
    string $item_label,
1525
    int $id_user,
1526
    string $action,
1527
    ?string $login = null,
1528
    ?string $raison = null,
1529
    ?string $encryption_type = null,
1530
    ?string $time = null,
1531
    ?string $old_value = null
1532
): void {
1533
    // Load class DB
1534
    loadClasses('DB');
1535
1536
    // Insert log in DB
1537
    DB::insert(
1538
        prefixTable('log_items'),
1539
        [
1540
            'id_item' => $item_id,
1541
            'date' => is_null($time) === true ? time() : $time,
1542
            'id_user' => $id_user,
1543
            'action' => $action,
1544
            'raison' => $raison,
1545
            'old_value' => $old_value,
1546
            'encryption_type' => is_null($encryption_type) === true ? TP_ENCRYPTION_NAME : $encryption_type,
1547
        ]
1548
    );
1549
    // Timestamp the last change
1550
    if (in_array($action, ['at_creation', 'at_modifiation', 'at_delete', 'at_import'], true)) {
1551
        DB::update(
1552
            prefixTable('misc'),
1553
            [
1554
                'valeur' => time(),
1555
                'updated_at' => time(),
1556
            ],
1557
            'type = %s AND intitule = %s',
1558
            'timestamp',
1559
            'last_item_change'
1560
        );
1561
    }
1562
1563
    // SYSLOG
1564
    if (isset($SETTINGS['syslog_enable']) === true && (int) $SETTINGS['syslog_enable'] === 1) {
1565
        // Extract reason
1566
        $attribute = is_null($raison) === true ? Array('') : explode(' : ', $raison);
1567
        // Get item info if not known
1568
        if (empty($item_label) === true) {
1569
            $dataItem = DB::queryfirstrow(
1570
                'SELECT id, id_tree, label
1571
                FROM ' . prefixTable('items') . '
1572
                WHERE id = %i',
1573
                $item_id
1574
            );
1575
            $item_label = $dataItem['label'];
1576
        }
1577
1578
        send_syslog(
1579
            'action=' . str_replace('at_', '', $action) .
1580
                ' attribute=' . str_replace('at_', '', $attribute[0]) .
1581
                ' itemno=' . $item_id .
1582
                ' user=' . (is_null($login) === true ? '' : addslashes((string) $login)) .
1583
                ' itemname="' . addslashes($item_label) . '"',
1584
            $SETTINGS['syslog_host'],
1585
            $SETTINGS['syslog_port'],
1586
            'teampass'
1587
        );
1588
    }
1589
1590
    // send notification if enabled
1591
    //notifyOnChange($item_id, $action, $SETTINGS);
1592
}
1593
1594
/**
1595
 * Prepare notification email to subscribers.
1596
 *
1597
 * @param int    $item_id  Item id
1598
 * @param string $label    Item label
1599
 * @param array  $changes  List of changes
1600
 * @param array  $SETTINGS Teampass settings
1601
 * 
1602
 * @return void
1603
 */
1604
function notifyChangesToSubscribers(int $item_id, string $label, array $changes, array $SETTINGS): void
1605
{
1606
    $session = SessionManager::getSession();
1607
    $lang = new Language($session->get('user-language') ?? 'english');
1608
    $globalsUserId = $session->get('user-id');
1609
    $globalsLastname = $session->get('user-lastname');
1610
    $globalsName = $session->get('user-name');
1611
    // send email to user that what to be notified
1612
    $notification = DB::queryOneColumn(
1613
        'email',
1614
        'SELECT *
1615
        FROM ' . prefixTable('notification') . ' AS n
1616
        INNER JOIN ' . prefixTable('users') . ' AS u ON (n.user_id = u.id)
1617
        WHERE n.item_id = %i AND n.user_id != %i',
1618
        $item_id,
1619
        $globalsUserId
1620
    );
1621
    if (DB::count() > 0) {
1622
        // Prepare path
1623
        $path = geItemReadablePath($item_id, '', $SETTINGS);
1624
        // Get list of changes
1625
        $htmlChanges = '<ul>';
1626
        foreach ($changes as $change) {
1627
            $htmlChanges .= '<li>' . $change . '</li>';
1628
        }
1629
        $htmlChanges .= '</ul>';
1630
        // send email
1631
        DB::insert(
1632
            prefixTable('emails'),
1633
            [
1634
                'timestamp' => time(),
1635
                'subject' => $lang->get('email_subject_item_updated'),
1636
                'body' => str_replace(
1637
                    ['#item_label#', '#folder_name#', '#item_id#', '#url#', '#name#', '#lastname#', '#changes#'],
1638
                    [$label, $path, $item_id, $SETTINGS['cpassman_url'], $globalsName, $globalsLastname, $htmlChanges],
1639
                    $lang->get('email_body_item_updated')
1640
                ),
1641
                'receivers' => implode(',', $notification),
1642
                'status' => '',
1643
            ]
1644
        );
1645
    }
1646
}
1647
1648
/**
1649
 * Returns the Item + path.
1650
 *
1651
 * @param int    $id_tree  Node id
1652
 * @param string $label    Label
1653
 * @param array  $SETTINGS TP settings
1654
 * 
1655
 * @return string
1656
 */
1657
function geItemReadablePath(int $id_tree, string $label, array $SETTINGS): string
1658
{
1659
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
1660
    $arbo = $tree->getPath($id_tree, true);
1661
    $path = '';
1662
    foreach ($arbo as $elem) {
1663
        if (empty($path) === true) {
1664
            $path = htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES) . ' ';
1665
        } else {
1666
            $path .= '&#8594; ' . htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES);
1667
        }
1668
    }
1669
1670
    // Build text to show user
1671
    if (empty($label) === false) {
1672
        return empty($path) === true ? addslashes($label) : addslashes($label) . ' (' . $path . ')';
1673
    }
1674
    return empty($path) === true ? '' : $path;
1675
}
1676
1677
/**
1678
 * Get the client ip address.
1679
 *
1680
 * @return string IP address
1681
 */
1682
function getClientIpServer(): string
1683
{
1684
    if (getenv('HTTP_CLIENT_IP')) {
1685
        $ipaddress = getenv('HTTP_CLIENT_IP');
1686
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
1687
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
1688
    } elseif (getenv('HTTP_X_FORWARDED')) {
1689
        $ipaddress = getenv('HTTP_X_FORWARDED');
1690
    } elseif (getenv('HTTP_FORWARDED_FOR')) {
1691
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
1692
    } elseif (getenv('HTTP_FORWARDED')) {
1693
        $ipaddress = getenv('HTTP_FORWARDED');
1694
    } elseif (getenv('REMOTE_ADDR')) {
1695
        $ipaddress = getenv('REMOTE_ADDR');
1696
    } else {
1697
        $ipaddress = 'UNKNOWN';
1698
    }
1699
1700
    return $ipaddress;
1701
}
1702
1703
/**
1704
 * Escape all HTML, JavaScript, and CSS.
1705
 *
1706
 * @param string $input    The input string
1707
 * @param string $encoding Which character encoding are we using?
1708
 * 
1709
 * @return string
1710
 */
1711
function noHTML(string $input, string $encoding = 'UTF-8'): string
1712
{
1713
    return htmlspecialchars($input, ENT_QUOTES | ENT_XHTML, $encoding, false);
1714
}
1715
1716
/**
1717
 * Rebuilds the Teampass config file.
1718
 *
1719
 * @param string $configFilePath Path to the config file.
1720
 * @param array  $settings       Teampass settings.
1721
 *
1722
 * @return string|bool
1723
 */
1724
function rebuildConfigFile(string $configFilePath, array $settings)
1725
{
1726
    // Perform a copy if the file exists
1727
    if (file_exists($configFilePath)) {
1728
        $backupFilePath = $configFilePath . '.' . date('Y_m_d_His', time());
1729
        if (!copy($configFilePath, $backupFilePath)) {
1730
            return "ERROR: Could not copy file '$configFilePath'";
1731
        }
1732
    }
1733
1734
    // Regenerate the config file
1735
    $data = ["<?php\n", "global \$SETTINGS;\n", "\$SETTINGS = array (\n"];
1736
    $rows = DB::query('SELECT * FROM ' . prefixTable('misc') . ' WHERE type=%s', 'admin');
1737
    foreach ($rows as $record) {
1738
        $value = getEncryptedValue($record['valeur'], $record['is_encrypted']);
1739
        $data[] = "    '{$record['intitule']}' => '". htmlspecialchars_decode($value, ENT_COMPAT) . "',\n";
1740
    }
1741
    $data[] = ");\n";
1742
    $data = array_unique($data);
1743
1744
    // Update the file
1745
    file_put_contents($configFilePath, implode('', $data));
1746
1747
    return true;
1748
}
1749
1750
/**
1751
 * Returns the encrypted value if needed.
1752
 *
1753
 * @param string $value       Value to encrypt.
1754
 * @param int   $isEncrypted Is the value encrypted?
1755
 *
1756
 * @return string
1757
 */
1758
function getEncryptedValue(string $value, int $isEncrypted): string
1759
{
1760
    return $isEncrypted ? cryption($value, '', 'encrypt')['string'] : $value;
1761
}
1762
1763
/**
1764
 * Permits to replace &#92; to permit correct display
1765
 *
1766
 * @param string $input Some text
1767
 * 
1768
 * @return string
1769
 */
1770
function handleBackslash(string $input): string
1771
{
1772
    return str_replace('&amp;#92;', '&#92;', $input);
1773
}
1774
1775
/**
1776
 * Permits to load settings
1777
 * 
1778
 * @return void
1779
*/
1780
function loadSettings(): void
1781
{
1782
    global $SETTINGS;
1783
    /* LOAD CPASSMAN SETTINGS */
1784
    if (! isset($SETTINGS['loaded']) || $SETTINGS['loaded'] !== 1) {
1785
        $SETTINGS = [];
1786
        $SETTINGS['duplicate_folder'] = 0;
1787
        //by default, this is set to 0;
1788
        $SETTINGS['duplicate_item'] = 0;
1789
        //by default, this is set to 0;
1790
        $SETTINGS['number_of_used_pw'] = 5;
1791
        //by default, this value is set to 5;
1792
        $settings = [];
1793
        $rows = DB::query(
1794
            'SELECT * FROM ' . prefixTable('misc') . ' WHERE type=%s_type OR type=%s_type2',
1795
            [
1796
                'type' => 'admin',
1797
                'type2' => 'settings',
1798
            ]
1799
        );
1800
        foreach ($rows as $record) {
1801
            if ($record['type'] === 'admin') {
1802
                $SETTINGS[$record['intitule']] = $record['valeur'];
1803
            } else {
1804
                $settings[$record['intitule']] = $record['valeur'];
1805
            }
1806
        }
1807
        $SETTINGS['loaded'] = 1;
1808
        $SETTINGS['default_session_expiration_time'] = 5;
1809
    }
1810
}
1811
1812
/**
1813
 * check if folder has custom fields.
1814
 * Ensure that target one also has same custom fields
1815
 * 
1816
 * @param int $source_id
1817
 * @param int $target_id 
1818
 * 
1819
 * @return bool
1820
*/
1821
function checkCFconsistency(int $source_id, int $target_id): bool
1822
{
1823
    $source_cf = [];
1824
    $rows = DB::QUERY(
1825
        'SELECT id_category
1826
            FROM ' . prefixTable('categories_folders') . '
1827
            WHERE id_folder = %i',
1828
        $source_id
1829
    );
1830
    foreach ($rows as $record) {
1831
        array_push($source_cf, $record['id_category']);
1832
    }
1833
1834
    $target_cf = [];
1835
    $rows = DB::QUERY(
1836
        'SELECT id_category
1837
            FROM ' . prefixTable('categories_folders') . '
1838
            WHERE id_folder = %i',
1839
        $target_id
1840
    );
1841
    foreach ($rows as $record) {
1842
        array_push($target_cf, $record['id_category']);
1843
    }
1844
1845
    $cf_diff = array_diff($source_cf, $target_cf);
1846
    if (count($cf_diff) > 0) {
1847
        return false;
1848
    }
1849
1850
    return true;
1851
}
1852
1853
/**
1854
 * Will encrypte/decrypt a fil eusing Defuse.
1855
 *
1856
 * @param string $type        can be either encrypt or decrypt
1857
 * @param string $source_file path to source file
1858
 * @param string $target_file path to target file
1859
 * @param array  $SETTINGS    Settings
1860
 * @param string $password    A password
1861
 *
1862
 * @return string|bool
1863
 */
1864
function prepareFileWithDefuse(
1865
    string $type,
1866
    string $source_file,
1867
    string $target_file,
1868
    array $SETTINGS,
1869
    string $password = null
1870
) {
1871
    // Load AntiXSS
1872
    $antiXss = new AntiXSS();
1873
    // Protect against bad inputs
1874
    if (is_array($source_file) === true || is_array($target_file) === true) {
1875
        return 'error_cannot_be_array';
1876
    }
1877
1878
    // Sanitize
1879
    $source_file = $antiXss->xss_clean($source_file);
1880
    $target_file = $antiXss->xss_clean($target_file);
1881
    if (empty($password) === true || is_null($password) === true) {
1882
        // get KEY to define password
1883
        $ascii_key = file_get_contents(SECUREPATH.'/'.SECUREFILE);
1884
        $password = Key::loadFromAsciiSafeString($ascii_key);
1885
    }
1886
1887
    $err = '';
1888
    if ($type === 'decrypt') {
1889
        // Decrypt file
1890
        $err = defuseFileDecrypt(
1891
            $source_file,
1892
            $target_file,
1893
            $SETTINGS, /** @scrutinizer ignore-type */
1894
            $password
1895
        );
1896
    } elseif ($type === 'encrypt') {
1897
        // Encrypt file
1898
        $err = defuseFileEncrypt(
1899
            $source_file,
1900
            $target_file,
1901
            $SETTINGS, /** @scrutinizer ignore-type */
1902
            $password
1903
        );
1904
    }
1905
1906
    // return error
1907
    return $err === true ? $err : '';
1908
}
1909
1910
/**
1911
 * Encrypt a file with Defuse.
1912
 *
1913
 * @param string $source_file path to source file
1914
 * @param string $target_file path to target file
1915
 * @param array  $SETTINGS    Settings
1916
 * @param string $password    A password
1917
 *
1918
 * @return string|bool
1919
 */
1920
function defuseFileEncrypt(
1921
    string $source_file,
1922
    string $target_file,
1923
    array $SETTINGS,
1924
    string $password = null
1925
) {
1926
    try {
1927
        CryptoFile::encryptFileWithPassword(
1928
            $source_file,
1929
            $target_file,
1930
            $password
1931
        );
1932
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1933
        $err = 'wrong_key';
1934
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1935
        $err = $ex;
1936
    } catch (CryptoException\IOException $ex) {
1937
        $err = $ex;
1938
    }
1939
1940
    // return error
1941
    return empty($err) === false ? $err : true;
1942
}
1943
1944
/**
1945
 * Decrypt a file with Defuse.
1946
 *
1947
 * @param string $source_file path to source file
1948
 * @param string $target_file path to target file
1949
 * @param array  $SETTINGS    Settings
1950
 * @param string $password    A password
1951
 *
1952
 * @return string|bool
1953
 */
1954
function defuseFileDecrypt(
1955
    string $source_file,
1956
    string $target_file,
1957
    array $SETTINGS,
1958
    string $password = null
1959
) {
1960
    try {
1961
        CryptoFile::decryptFileWithPassword(
1962
            $source_file,
1963
            $target_file,
1964
            $password
1965
        );
1966
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1967
        $err = 'wrong_key';
1968
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1969
        $err = $ex;
1970
    } catch (CryptoException\IOException $ex) {
1971
        $err = $ex;
1972
    }
1973
1974
    // return error
1975
    return empty($err) === false ? $err : true;
1976
}
1977
1978
/*
1979
* NOT TO BE USED
1980
*/
1981
/**
1982
 * Undocumented function.
1983
 *
1984
 * @param string $text Text to debug
1985
 */
1986
function debugTeampass(string $text): void
1987
{
1988
    $debugFile = fopen('D:/wamp64/www/TeamPass/debug.txt', 'r+');
1989
    if ($debugFile !== false) {
1990
        fputs($debugFile, $text);
1991
        fclose($debugFile);
1992
    }
1993
}
1994
1995
/**
1996
 * DELETE the file with expected command depending on server type.
1997
 *
1998
 * @param string $file     Path to file
1999
 * @param array  $SETTINGS Teampass settings
2000
 *
2001
 * @return void
2002
 */
2003
function fileDelete(string $file, array $SETTINGS): void
2004
{
2005
    // Load AntiXSS
2006
    $antiXss = new AntiXSS();
2007
    $file = $antiXss->xss_clean($file);
2008
    if (is_file($file)) {
2009
        unlink($file);
2010
    }
2011
}
2012
2013
/**
2014
 * Permits to extract the file extension.
2015
 *
2016
 * @param string $file File name
2017
 *
2018
 * @return string
2019
 */
2020
function getFileExtension(string $file): string
2021
{
2022
    if (strpos($file, '.') === false) {
2023
        return $file;
2024
    }
2025
2026
    return substr($file, strrpos($file, '.') + 1);
2027
}
2028
2029
/**
2030
 * Chmods files and folders with different permissions.
2031
 *
2032
 * This is an all-PHP alternative to using: \n
2033
 * <tt>exec("find ".$path." -type f -exec chmod 644 {} \;");</tt> \n
2034
 * <tt>exec("find ".$path." -type d -exec chmod 755 {} \;");</tt>
2035
 *
2036
 * @author Jeppe Toustrup (tenzer at tenzer dot dk)
2037
  *
2038
 * @param string $path      An either relative or absolute path to a file or directory which should be processed.
2039
 * @param int    $filePerm The permissions any found files should get.
2040
 * @param int    $dirPerm  The permissions any found folder should get.
2041
 *
2042
 * @return bool Returns TRUE if the path if found and FALSE if not.
2043
 *
2044
 * @warning The permission levels has to be entered in octal format, which
2045
 * normally means adding a zero ("0") in front of the permission level. \n
2046
 * More info at: http://php.net/chmod.
2047
*/
2048
2049
function recursiveChmod(
2050
    string $path,
2051
    int $filePerm = 0644,
2052
    int  $dirPerm = 0755
2053
) {
2054
    // Check if the path exists
2055
    $path = basename($path);
2056
    if (! file_exists($path)) {
2057
        return false;
2058
    }
2059
2060
    // See whether this is a file
2061
    if (is_file($path)) {
2062
        // Chmod the file with our given filepermissions
2063
        try {
2064
            chmod($path, $filePerm);
2065
        } catch (Exception $e) {
2066
            return false;
2067
        }
2068
    // If this is a directory...
2069
    } elseif (is_dir($path)) {
2070
        // Then get an array of the contents
2071
        $foldersAndFiles = scandir($path);
2072
        // Remove "." and ".." from the list
2073
        $entries = array_slice($foldersAndFiles, 2);
2074
        // Parse every result...
2075
        foreach ($entries as $entry) {
2076
            // And call this function again recursively, with the same permissions
2077
            recursiveChmod($path.'/'.$entry, $filePerm, $dirPerm);
2078
        }
2079
2080
        // When we are done with the contents of the directory, we chmod the directory itself
2081
        try {
2082
            chmod($path, $filePerm);
2083
        } catch (Exception $e) {
2084
            return false;
2085
        }
2086
    }
2087
2088
    // Everything seemed to work out well, return true
2089
    return true;
2090
}
2091
2092
/**
2093
 * Check if user can access to this item.
2094
 *
2095
 * @param int   $item_id ID of item
2096
 * @param array $SETTINGS
2097
 *
2098
 * @return bool|string
2099
 */
2100
function accessToItemIsGranted(int $item_id, array $SETTINGS)
2101
{
2102
    
2103
    $session = SessionManager::getSession();
2104
    $session_groupes_visibles = $session->get('user-accessible_folders');
2105
    $session_list_restricted_folders_for_items = $session->get('system-list_restricted_folders_for_items');
2106
    // Load item data
2107
    $data = DB::queryFirstRow(
2108
        'SELECT id_tree
2109
        FROM ' . prefixTable('items') . '
2110
        WHERE id = %i',
2111
        $item_id
2112
    );
2113
    // Check if user can access this folder
2114
    if (in_array($data['id_tree'], $session_groupes_visibles) === false) {
2115
        // Now check if this folder is restricted to user
2116
        if (isset($session_list_restricted_folders_for_items[$data['id_tree']]) === true
2117
            && in_array($item_id, $session_list_restricted_folders_for_items[$data['id_tree']]) === false
2118
        ) {
2119
            return 'ERR_FOLDER_NOT_ALLOWED';
2120
        }
2121
    }
2122
2123
    return true;
2124
}
2125
2126
/**
2127
 * Creates a unique key.
2128
 *
2129
 * @param int $lenght Key lenght
2130
 *
2131
 * @return string
2132
 */
2133
function uniqidReal(int $lenght = 13): string
2134
{
2135
    if (function_exists('random_bytes')) {
2136
        $bytes = random_bytes(intval(ceil($lenght / 2)));
2137
    } elseif (function_exists('openssl_random_pseudo_bytes')) {
2138
        $bytes = openssl_random_pseudo_bytes(intval(ceil($lenght / 2)));
2139
    } else {
2140
        throw new Exception('no cryptographically secure random function available');
2141
    }
2142
2143
    return substr(bin2hex($bytes), 0, $lenght);
2144
}
2145
2146
/**
2147
 * Obfuscate an email.
2148
 *
2149
 * @param string $email Email address
2150
 *
2151
 * @return string
2152
 */
2153
function obfuscateEmail(string $email): string
2154
{
2155
    $email = explode("@", $email);
2156
    $name = $email[0];
2157
    if (strlen($name) > 3) {
2158
        $name = substr($name, 0, 2);
2159
        for ($i = 0; $i < strlen($email[0]) - 3; $i++) {
2160
            $name .= "*";
2161
        }
2162
        $name .= substr($email[0], -1, 1);
2163
    }
2164
    $host = explode(".", $email[1])[0];
2165
    if (strlen($host) > 3) {
2166
        $host = substr($host, 0, 1);
2167
        for ($i = 0; $i < strlen(explode(".", $email[1])[0]) - 2; $i++) {
2168
            $host .= "*";
2169
        }
2170
        $host .= substr(explode(".", $email[1])[0], -1, 1);
2171
    }
2172
    $email = $name . "@" . $host . "." . explode(".", $email[1])[1];
2173
    return $email;
2174
}
2175
2176
/**
2177
 * Get id and title from role_titles table.
2178
 *
2179
 * @return array
2180
 */
2181
function getRolesTitles(): array
2182
{
2183
    // Load class DB
2184
    loadClasses('DB');
2185
    
2186
    // Insert log in DB
2187
    return DB::query(
2188
        'SELECT id, title
2189
        FROM ' . prefixTable('roles_title')
2190
    );
2191
}
2192
2193
/**
2194
 * Undocumented function.
2195
 *
2196
 * @param int $bytes Size of file
2197
 *
2198
 * @return string
2199
 */
2200
function formatSizeUnits(int $bytes): string
2201
{
2202
    if ($bytes >= 1073741824) {
2203
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
2204
    } elseif ($bytes >= 1048576) {
2205
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
2206
    } elseif ($bytes >= 1024) {
2207
        $bytes = number_format($bytes / 1024, 2) . ' KB';
2208
    } elseif ($bytes > 1) {
2209
        $bytes .= ' bytes';
2210
    } elseif ($bytes === 1) {
2211
        $bytes .= ' byte';
2212
    } else {
2213
        $bytes = '0 bytes';
2214
    }
2215
2216
    return $bytes;
2217
}
2218
2219
/**
2220
 * Generate user pair of keys.
2221
 *
2222
 * @param string $userPwd User password
2223
 *
2224
 * @return array
2225
 */
2226
function generateUserKeys(string $userPwd): array
2227
{
2228
    // Sanitize
2229
    $antiXss = new AntiXSS();
2230
    $userPwd = $antiXss->xss_clean($userPwd);
2231
    // Load classes
2232
    $rsa = new Crypt_RSA();
2233
    $cipher = new Crypt_AES();
2234
    // Create the private and public key
2235
    $res = $rsa->createKey(4096);
2236
    // Encrypt the privatekey
2237
    $cipher->setPassword($userPwd);
2238
    $privatekey = $cipher->encrypt($res['privatekey']);
2239
    return [
2240
        'private_key' => base64_encode($privatekey),
2241
        'public_key' => base64_encode($res['publickey']),
2242
        'private_key_clear' => base64_encode($res['privatekey']),
2243
    ];
2244
}
2245
2246
/**
2247
 * Permits to decrypt the user's privatekey.
2248
 *
2249
 * @param string $userPwd        User password
2250
 * @param string $userPrivateKey User private key
2251
 *
2252
 * @return string|object
2253
 */
2254
function decryptPrivateKey(string $userPwd, string $userPrivateKey)
2255
{
2256
    // Sanitize
2257
    $antiXss = new AntiXSS();
2258
    $userPwd = $antiXss->xss_clean($userPwd);
2259
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2260
2261
    if (empty($userPwd) === false) {
2262
        // Load classes
2263
        $cipher = new Crypt_AES();
2264
        // Encrypt the privatekey
2265
        $cipher->setPassword($userPwd);
2266
        try {
2267
            return base64_encode((string) $cipher->decrypt(base64_decode($userPrivateKey)));
2268
        } catch (Exception $e) {
2269
            return $e;
2270
        }
2271
    }
2272
    return '';
2273
}
2274
2275
/**
2276
 * Permits to encrypt the user's privatekey.
2277
 *
2278
 * @param string $userPwd        User password
2279
 * @param string $userPrivateKey User private key
2280
 *
2281
 * @return string
2282
 */
2283
function encryptPrivateKey(string $userPwd, string $userPrivateKey): string
2284
{
2285
    // Sanitize
2286
    $antiXss = new AntiXSS();
2287
    $userPwd = $antiXss->xss_clean($userPwd);
2288
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2289
2290
    if (empty($userPwd) === false) {
2291
        // Load classes
2292
        $cipher = new Crypt_AES();
2293
        // Encrypt the privatekey
2294
        $cipher->setPassword($userPwd);        
2295
        try {
2296
            return base64_encode($cipher->encrypt(base64_decode($userPrivateKey)));
2297
        } catch (Exception $e) {
2298
            return $e;
2299
        }
2300
    }
2301
    return '';
2302
}
2303
2304
/**
2305
 * Encrypts a string using AES.
2306
 *
2307
 * @param string $data String to encrypt
2308
 * @param string $key
2309
 *
2310
 * @return array
2311
 */
2312
function doDataEncryption(string $data, string $key = NULL): array
2313
{
2314
    // Sanitize
2315
    $antiXss = new AntiXSS();
2316
    $data = $antiXss->xss_clean($data);
2317
    
2318
    // Load classes
2319
    $cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
2320
    // Generate an object key
2321
    $objectKey = is_null($key) === true ? uniqidReal(KEY_LENGTH) : $antiXss->xss_clean($key);
2322
    // Set it as password
2323
    $cipher->setPassword($objectKey);
2324
    return [
2325
        'encrypted' => base64_encode($cipher->encrypt($data)),
2326
        'objectKey' => base64_encode($objectKey),
2327
    ];
2328
}
2329
2330
/**
2331
 * Decrypts a string using AES.
2332
 *
2333
 * @param string $data Encrypted data
2334
 * @param string $key  Key to uncrypt
2335
 *
2336
 * @return string
2337
 */
2338
function doDataDecryption(string $data, string $key): string
2339
{
2340
    // Sanitize
2341
    $antiXss = new AntiXSS();
2342
    $data = $antiXss->xss_clean($data);
2343
    $key = $antiXss->xss_clean($key);
2344
2345
    // Load classes
2346
    $cipher = new Crypt_AES();
2347
    // Set the object key
2348
    $cipher->setPassword(base64_decode($key));
2349
    return base64_encode((string) $cipher->decrypt(base64_decode($data)));
2350
}
2351
2352
/**
2353
 * Encrypts using RSA a string using a public key.
2354
 *
2355
 * @param string $key       Key to be encrypted
2356
 * @param string $publicKey User public key
2357
 *
2358
 * @return string
2359
 */
2360
function encryptUserObjectKey(string $key, string $publicKey): string
2361
{
2362
    // Sanitize
2363
    $antiXss = new AntiXSS();
2364
    $publicKey = $antiXss->xss_clean($publicKey);
2365
    // Load classes
2366
    $rsa = new Crypt_RSA();
2367
    // Load the public key
2368
    $decodedPublicKey = base64_decode($publicKey, true);
2369
    if ($decodedPublicKey === false) {
2370
        throw new InvalidArgumentException("Error while decoding key.");
2371
    }
2372
    $rsa->loadKey($decodedPublicKey);
2373
    // Encrypt
2374
    $encrypted = $rsa->encrypt(base64_decode($key));
2375
    if (empty($encrypted)) {  // Check if key is empty or null
2376
        throw new RuntimeException("Error while encrypting key.");
2377
    }
2378
    // Return
2379
    return base64_encode($encrypted);
2380
}
2381
2382
/**
2383
 * Decrypts using RSA an encrypted string using a private key.
2384
 *
2385
 * @param string $key        Encrypted key
2386
 * @param string $privateKey User private key
2387
 *
2388
 * @return string
2389
 */
2390
function decryptUserObjectKey(string $key, string $privateKey): string
2391
{
2392
    // Sanitize
2393
    $antiXss = new AntiXSS();
2394
    $privateKey = $antiXss->xss_clean($privateKey);
2395
2396
    // Load classes
2397
    $rsa = new Crypt_RSA();
2398
    // Load the private key
2399
    $decodedPrivateKey = base64_decode($privateKey, true);
2400
    if ($decodedPrivateKey === false) {
2401
        throw new InvalidArgumentException("Error while decoding private key.");
2402
    }
2403
2404
    $rsa->loadKey($decodedPrivateKey);
2405
2406
    // Decrypt
2407
    try {
2408
        $decodedKey = base64_decode($key, true);
2409
        if ($decodedKey === false) {
2410
            throw new InvalidArgumentException("Error while decoding key.");
2411
        }
2412
2413
        // This check is needed as decrypt() in version 2 can return false in case of error
2414
        $tmpValue = $rsa->decrypt($decodedKey);
2415
        if ($tmpValue !== false) {
0 ignored issues
show
introduced by
The condition $tmpValue !== false is always true.
Loading history...
2416
            return base64_encode($tmpValue);
2417
        } else {
2418
            return '';
2419
        }
2420
    } catch (Exception $e) {
2421
        if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2422
            error_log('TEAMPASS Error - ldap - '.$e->getMessage());
2423
        }
2424
        return 'Exception: could not decrypt object';
2425
    }
2426
}
2427
2428
/**
2429
 * Encrypts a file.
2430
 *
2431
 * @param string $fileInName File name
2432
 * @param string $fileInPath Path to file
2433
 *
2434
 * @return array
2435
 */
2436
function encryptFile(string $fileInName, string $fileInPath): array
2437
{
2438
    if (defined('FILE_BUFFER_SIZE') === false) {
2439
        define('FILE_BUFFER_SIZE', 128 * 1024);
2440
    }
2441
2442
    // Load classes
2443
    $cipher = new Crypt_AES();
2444
2445
    // Generate an object key
2446
    $objectKey = uniqidReal(32);
2447
    // Set it as password
2448
    $cipher->setPassword($objectKey);
2449
    // Prevent against out of memory
2450
    $cipher->enableContinuousBuffer();
2451
2452
    // Encrypt the file content
2453
    $filePath = filter_var($fileInPath . '/' . $fileInName, FILTER_SANITIZE_URL);
2454
    $fileContent = file_get_contents($filePath);
2455
    $plaintext = $fileContent;
2456
    $ciphertext = $cipher->encrypt($plaintext);
2457
2458
    // Save new file
2459
    // deepcode ignore InsecureHash: is simply used to get a unique name
2460
    $hash = md5($plaintext);
2461
    $fileOut = $fileInPath . '/' . TP_FILE_PREFIX . $hash;
2462
    file_put_contents($fileOut, $ciphertext);
2463
    unlink($fileInPath . '/' . $fileInName);
2464
    return [
2465
        'fileHash' => base64_encode($hash),
2466
        'objectKey' => base64_encode($objectKey),
2467
    ];
2468
}
2469
2470
/**
2471
 * Decrypt a file.
2472
 *
2473
 * @param string $fileName File name
2474
 * @param string $filePath Path to file
2475
 * @param string $key      Key to use
2476
 *
2477
 * @return string|array
2478
 */
2479
function decryptFile(string $fileName, string $filePath, string $key): string|array
2480
{
2481
    if (! defined('FILE_BUFFER_SIZE')) {
2482
        define('FILE_BUFFER_SIZE', 128 * 1024);
2483
    }
2484
    
2485
    // Load classes
2486
    $cipher = new Crypt_AES();
2487
    $antiXSS = new AntiXSS();
2488
    
2489
    // Get file name
2490
    $safeFileName = $antiXSS->xss_clean(base64_decode($fileName));
2491
2492
    // Set the object key
2493
    $cipher->setPassword(base64_decode($key));
2494
    // Prevent against out of memory
2495
    $cipher->enableContinuousBuffer();
2496
    $cipher->disablePadding();
2497
    // Get file content
2498
    $safeFilePath = realpath($filePath . '/' . TP_FILE_PREFIX . $safeFileName);
2499
    if ($safeFilePath !== false && file_exists($safeFilePath)) {
2500
        $ciphertext = file_get_contents(filter_var($safeFilePath, FILTER_SANITIZE_URL));
2501
    } else {
2502
        // Handle the error: file doesn't exist or path is invalid
2503
        return [
2504
            'error' => true,
2505
            'message' => 'This file has not been found.',
2506
        ];
2507
    }
2508
2509
    if (WIP) error_log('DEBUG: File image url -> '.filter_var($safeFilePath, FILTER_SANITIZE_URL));
2510
2511
    // Decrypt file content and return
2512
    return base64_encode($cipher->decrypt($ciphertext));
2513
}
2514
2515
/**
2516
 * Generate a simple password
2517
 *
2518
 * @param int $length Length of string
2519
 * @param bool $symbolsincluded Allow symbols
2520
 *
2521
 * @return string
2522
 */
2523
function generateQuickPassword(int $length = 16, bool $symbolsincluded = true): string
2524
{
2525
    // Generate new user password
2526
    $small_letters = range('a', 'z');
2527
    $big_letters = range('A', 'Z');
2528
    $digits = range(0, 9);
2529
    $symbols = $symbolsincluded === true ?
2530
        ['#', '_', '-', '@', '$', '+', '!'] : [];
2531
    $res = array_merge($small_letters, $big_letters, $digits, $symbols);
2532
    $count = count($res);
2533
    // first variant
2534
2535
    $random_string = '';
2536
    for ($i = 0; $i < $length; ++$i) {
2537
        $random_string .= $res[random_int(0, $count - 1)];
2538
    }
2539
2540
    return $random_string;
2541
}
2542
2543
/**
2544
 * Permit to store the sharekey of an object for users.
2545
 *
2546
 * @param string $object_name             Type for table selection
2547
 * @param int    $post_folder_is_personal Personal
2548
 * @param int    $post_object_id          Object
2549
 * @param string $objectKey               Object key
2550
 * @param array  $SETTINGS                Teampass settings
2551
 * @param int    $user_id                 User ID if needed
2552
 * @param bool   $onlyForUser             If is TRUE, then the sharekey is only for the user
2553
 * @param bool   $deleteAll               If is TRUE, then all existing entries are deleted
2554
 * @param array  $objectKeyArray          Array of objects
2555
 * @param int    $all_users_except_id     All users except this one
2556
 * @param int    $apiUserId               API User ID
2557
 *
2558
 * @return void
2559
 */
2560
function storeUsersShareKey(
2561
    string $object_name,
2562
    int $post_folder_is_personal,
2563
    int $post_object_id,
2564
    string $objectKey,
2565
    bool $onlyForUser = false,
2566
    bool $deleteAll = true,
2567
    array $objectKeyArray = [],
2568
    int $all_users_except_id = -1,
2569
    int $apiUserId = -1
2570
): void {
2571
    
2572
    $session = SessionManager::getSession();
2573
    loadClasses('DB');
2574
2575
    // Delete existing entries for this object
2576
    if ($deleteAll === true) {
2577
        DB::delete(
2578
            $object_name,
2579
            'object_id = %i',
2580
            $post_object_id
2581
        );
2582
    }
2583
2584
    // Get the user ID
2585
    $userId = ($apiUserId === -1) ? (int) $session->get('user-id') : $apiUserId;
2586
    
2587
    // $onlyForUser is only dynamically set by external calls
2588
    if (
2589
        $onlyForUser === true || (int) $post_folder_is_personal === 1
2590
    ) {
2591
        // Only create the sharekey for a user
2592
        $user = DB::queryFirstRow(
2593
            'SELECT public_key
2594
            FROM ' . prefixTable('users') . '
2595
            WHERE id = %i
2596
            AND public_key != ""',
2597
            $userId
2598
        );
2599
2600
        if (empty($objectKey) === false) {
2601
            DB::insert(
2602
                $object_name,
2603
                [
2604
                    'object_id' => (int) $post_object_id,
2605
                    'user_id' => $userId,
2606
                    'share_key' => encryptUserObjectKey(
2607
                        $objectKey,
2608
                        $user['public_key']
2609
                    ),
2610
                ]
2611
            );
2612
        } else if (count($objectKeyArray) > 0) {
2613
            foreach ($objectKeyArray as $object) {
2614
                DB::insert(
2615
                    $object_name,
2616
                    [
2617
                        'object_id' => (int) $object['objectId'],
2618
                        'user_id' => $userId,
2619
                        'share_key' => encryptUserObjectKey(
2620
                            $object['objectKey'],
2621
                            $user['public_key']
2622
                        ),
2623
                    ]
2624
                );
2625
            }
2626
        }
2627
    } else {
2628
        // Create sharekey for each user
2629
        $user_ids = [OTV_USER_ID, SSH_USER_ID, API_USER_ID];
2630
        if ($all_users_except_id !== -1) {
2631
            array_push($user_ids, $all_users_except_id . '"');
2632
        }
2633
        $users = DB::query(
2634
            'SELECT id, public_key
2635
            FROM ' . prefixTable('users') . '
2636
            WHERE id NOT IN (%li)
2637
            AND public_key != ""',
2638
            $user_ids
2639
        );
2640
        //DB::debugmode(false);
2641
        foreach ($users as $user) {
2642
            // Insert in DB the new object key for this item by user
2643
            if (count($objectKeyArray) === 0) {
2644
                if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case1 - ' . $object_name . ' - ' . $post_object_id . ' - ' . $user['id'] . ' - ' . $objectKey);
2645
                DB::insert(
2646
                    $object_name,
2647
                    [
2648
                        'object_id' => $post_object_id,
2649
                        'user_id' => (int) $user['id'],
2650
                        'share_key' => encryptUserObjectKey(
2651
                            $objectKey,
2652
                            $user['public_key']
2653
                        ),
2654
                    ]
2655
                );
2656
            } else {
2657
                foreach ($objectKeyArray as $object) {
2658
                    if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case2 - ' . $object_name . ' - ' . $object['objectId'] . ' - ' . $user['id'] . ' - ' . $object['objectKey']);
2659
                    DB::insert(
2660
                        $object_name,
2661
                        [
2662
                            'object_id' => (int) $object['objectId'],
2663
                            'user_id' => (int) $user['id'],
2664
                            'share_key' => encryptUserObjectKey(
2665
                                $object['objectKey'],
2666
                                $user['public_key']
2667
                            ),
2668
                        ]
2669
                    );
2670
                }
2671
            }
2672
        }
2673
    }
2674
}
2675
2676
/**
2677
 * Is this string base64 encoded?
2678
 *
2679
 * @param string $str Encoded string?
2680
 *
2681
 * @return bool
2682
 */
2683
function isBase64(string $str): bool
2684
{
2685
    $str = (string) trim($str);
2686
    if (! isset($str[0])) {
2687
        return false;
2688
    }
2689
2690
    $base64String = (string) base64_decode($str, true);
2691
    if ($base64String && base64_encode($base64String) === $str) {
2692
        return true;
2693
    }
2694
2695
    return false;
2696
}
2697
2698
/**
2699
 * Undocumented function
2700
 *
2701
 * @param string $field Parameter
2702
 *
2703
 * @return array|bool|resource|string
2704
 */
2705
function filterString(string $field)
2706
{
2707
    // Sanitize string
2708
    $field = filter_var(trim($field), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
2709
    if (empty($field) === false) {
2710
        // Load AntiXSS
2711
        $antiXss = new AntiXSS();
2712
        // Return
2713
        return $antiXss->xss_clean($field);
2714
    }
2715
2716
    return false;
2717
}
2718
2719
/**
2720
 * CHeck if provided credentials are allowed on server
2721
 *
2722
 * @param string $login    User Login
2723
 * @param string $password User Pwd
2724
 * @param array  $SETTINGS Teampass settings
2725
 *
2726
 * @return bool
2727
 */
2728
function ldapCheckUserPassword(string $login, string $password, array $SETTINGS): bool
2729
{
2730
    // Build ldap configuration array
2731
    $config = [
2732
        // Mandatory Configuration Options
2733
        'hosts' => [$SETTINGS['ldap_hosts']],
2734
        'base_dn' => $SETTINGS['ldap_bdn'],
2735
        'username' => $SETTINGS['ldap_username'],
2736
        'password' => $SETTINGS['ldap_password'],
2737
2738
        // Optional Configuration Options
2739
        'port' => $SETTINGS['ldap_port'],
2740
        'use_ssl' => (int) $SETTINGS['ldap_ssl'] === 1 ? true : false,
2741
        'use_tls' => (int) $SETTINGS['ldap_tls'] === 1 ? true : false,
2742
        'version' => 3,
2743
        'timeout' => 5,
2744
        'follow_referrals' => false,
2745
2746
        // Custom LDAP Options
2747
        'options' => [
2748
            // See: http://php.net/ldap_set_option
2749
            LDAP_OPT_X_TLS_REQUIRE_CERT => (isset($SETTINGS['ldap_tls_certiface_check']) ? $SETTINGS['ldap_tls_certiface_check'] : LDAP_OPT_X_TLS_HARD),
2750
        ],
2751
    ];
2752
    
2753
    $connection = new Connection($config);
2754
    // Connect to LDAP
2755
    try {
2756
        $connection->connect();
2757
    } catch (\LdapRecord\Auth\BindException $e) {
2758
        $error = $e->getDetailedError();
2759
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2760
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
2761
        }
2762
        // deepcode ignore ServerLeak: No important data is sent
2763
        echo 'An error occurred.';
2764
        return false;
2765
    }
2766
2767
    // Authenticate user
2768
    try {
2769
        if ($SETTINGS['ldap_type'] === 'ActiveDirectory') {
2770
            $connection->auth()->attempt($login, $password, $stayAuthenticated = true);
2771
        } else {
2772
            $connection->auth()->attempt($SETTINGS['ldap_user_attribute'].'='.$login.','.(isset($SETTINGS['ldap_dn_additional_user_dn']) && !empty($SETTINGS['ldap_dn_additional_user_dn']) ? $SETTINGS['ldap_dn_additional_user_dn'].',' : '').$SETTINGS['ldap_bdn'], $password, $stayAuthenticated = true);
2773
        }
2774
    } catch (\LdapRecord\Auth\BindException $e) {
2775
        $error = $e->getDetailedError();
2776
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2777
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
2778
        }
2779
        // deepcode ignore ServerLeak: No important data is sent
2780
        echo 'An error occurred.';
2781
        return false;
2782
    }
2783
2784
    return true;
2785
}
2786
2787
/**
2788
 * Removes from DB all sharekeys of this user
2789
 *
2790
 * @param int $userId User's id
2791
 * @param array   $SETTINGS Teampass settings
2792
 *
2793
 * @return bool
2794
 */
2795
function deleteUserObjetsKeys(int $userId, array $SETTINGS = []): bool
2796
{
2797
    // Load class DB
2798
    loadClasses('DB');
2799
2800
    // Remove all item sharekeys items
2801
    // expect if personal item
2802
    DB::delete(
2803
        prefixTable('sharekeys_items'),
2804
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2805
        $userId
2806
    );
2807
    // Remove all item sharekeys files
2808
    DB::delete(
2809
        prefixTable('sharekeys_files'),
2810
        'user_id = %i AND object_id NOT IN (
2811
            SELECT f.id 
2812
            FROM ' . prefixTable('items') . ' AS i 
2813
            INNER JOIN ' . prefixTable('files') . ' AS f ON f.id_item = i.id
2814
            WHERE i.perso = 1
2815
        )',
2816
        $userId
2817
    );
2818
    // Remove all item sharekeys fields
2819
    DB::delete(
2820
        prefixTable('sharekeys_fields'),
2821
        'user_id = %i AND object_id NOT IN (
2822
            SELECT c.id 
2823
            FROM ' . prefixTable('items') . ' AS i 
2824
            INNER JOIN ' . prefixTable('categories_items') . ' AS c ON c.item_id = i.id
2825
            WHERE i.perso = 1
2826
        )',
2827
        $userId
2828
    );
2829
    // Remove all item sharekeys logs
2830
    DB::delete(
2831
        prefixTable('sharekeys_logs'),
2832
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2833
        $userId
2834
    );
2835
    // Remove all item sharekeys suggestions
2836
    DB::delete(
2837
        prefixTable('sharekeys_suggestions'),
2838
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2839
        $userId
2840
    );
2841
    return false;
2842
}
2843
2844
/**
2845
 * Manage list of timezones   $SETTINGS Teampass settings
2846
 *
2847
 * @return array
2848
 */
2849
function timezone_list()
2850
{
2851
    static $timezones = null;
2852
    if ($timezones === null) {
2853
        $timezones = [];
2854
        $offsets = [];
2855
        $now = new DateTime('now', new DateTimeZone('UTC'));
2856
        foreach (DateTimeZone::listIdentifiers() as $timezone) {
2857
            $now->setTimezone(new DateTimeZone($timezone));
2858
            $offsets[] = $offset = $now->getOffset();
2859
            $timezones[$timezone] = '(' . format_GMT_offset($offset) . ') ' . format_timezone_name($timezone);
2860
        }
2861
2862
        array_multisort($offsets, $timezones);
2863
    }
2864
2865
    return $timezones;
2866
}
2867
2868
/**
2869
 * Provide timezone offset
2870
 *
2871
 * @param int $offset Timezone offset
2872
 *
2873
 * @return string
2874
 */
2875
function format_GMT_offset($offset): string
2876
{
2877
    $hours = intval($offset / 3600);
2878
    $minutes = abs(intval($offset % 3600 / 60));
2879
    return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
2880
}
2881
2882
/**
2883
 * Provides timezone name
2884
 *
2885
 * @param string $name Timezone name
2886
 *
2887
 * @return string
2888
 */
2889
function format_timezone_name($name): string
2890
{
2891
    $name = str_replace('/', ', ', $name);
2892
    $name = str_replace('_', ' ', $name);
2893
2894
    return str_replace('St ', 'St. ', $name);
2895
}
2896
2897
/**
2898
 * Provides info if user should use MFA based on roles
2899
 *
2900
 * @param string $userRolesIds  User roles ids
2901
 * @param string $mfaRoles      Roles for which MFA is requested
2902
 *
2903
 * @return bool
2904
 */
2905
function mfa_auth_requested_roles(string $userRolesIds, string $mfaRoles): bool
2906
{
2907
    if (empty($mfaRoles) === true) {
2908
        return true;
2909
    }
2910
2911
    $mfaRoles = array_values(json_decode($mfaRoles, true));
2912
    $userRolesIds = array_filter(explode(';', $userRolesIds));
2913
    if (count($mfaRoles) === 0 || count(array_intersect($mfaRoles, $userRolesIds)) > 0) {
2914
        return true;
2915
    }
2916
2917
    return false;
2918
}
2919
2920
/**
2921
 * Permits to clean a string for export purpose
2922
 *
2923
 * @param string $text
2924
 * @param bool $emptyCheckOnly
2925
 * 
2926
 * @return string
2927
 */
2928
function cleanStringForExport(string $text, bool $emptyCheckOnly = false): string
2929
{
2930
    if (is_null($text) === true || empty($text) === true) {
2931
        return '';
2932
    }
2933
    // only expected to check if $text was empty
2934
    elseif ($emptyCheckOnly === true) {
2935
        return $text;
2936
    }
2937
2938
    return strip_tags(
2939
        cleanString(
2940
            html_entity_decode($text, ENT_QUOTES | ENT_XHTML, 'UTF-8'),
2941
            true)
2942
        );
2943
}
2944
2945
/**
2946
 * Permits to check if user ID is valid
2947
 *
2948
 * @param integer $post_user_id
2949
 * @return bool
2950
 */
2951
function isUserIdValid($userId): bool
2952
{
2953
    if (is_null($userId) === false
2954
        && isset($userId) === true
2955
        && empty($userId) === false
2956
    ) {
2957
        return true;
2958
    }
2959
    return false;
2960
}
2961
2962
/**
2963
 * Check if a key exists and if its value equal the one expected
2964
 *
2965
 * @param string $key
2966
 * @param integer|string $value
2967
 * @param array $array
2968
 * 
2969
 * @return boolean
2970
 */
2971
function isKeyExistingAndEqual(
2972
    string $key,
2973
    /*PHP8 - integer|string*/$value,
2974
    array $array
2975
): bool
2976
{
2977
    if (isset($array[$key]) === true
2978
        && (is_int($value) === true ?
2979
            (int) $array[$key] === $value :
2980
            (string) $array[$key] === $value)
2981
    ) {
2982
        return true;
2983
    }
2984
    return false;
2985
}
2986
2987
/**
2988
 * Check if a variable is not set or equal to a value
2989
 *
2990
 * @param string|null $var
2991
 * @param integer|string $value
2992
 * 
2993
 * @return boolean
2994
 */
2995
function isKeyNotSetOrEqual(
2996
    /*PHP8 - string|null*/$var,
2997
    /*PHP8 - integer|string*/$value
2998
): bool
2999
{
3000
    if (isset($var) === false
3001
        || (is_int($value) === true ?
3002
            (int) $var === $value :
3003
            (string) $var === $value)
3004
    ) {
3005
        return true;
3006
    }
3007
    return false;
3008
}
3009
3010
/**
3011
 * Check if a key exists and if its value < to the one expected
3012
 *
3013
 * @param string $key
3014
 * @param integer $value
3015
 * @param array $array
3016
 * 
3017
 * @return boolean
3018
 */
3019
function isKeyExistingAndInferior(string $key, int $value, array $array): bool
3020
{
3021
    if (isset($array[$key]) === true && (int) $array[$key] < $value) {
3022
        return true;
3023
    }
3024
    return false;
3025
}
3026
3027
/**
3028
 * Check if a key exists and if its value > to the one expected
3029
 *
3030
 * @param string $key
3031
 * @param integer $value
3032
 * @param array $array
3033
 * 
3034
 * @return boolean
3035
 */
3036
function isKeyExistingAndSuperior(string $key, int $value, array $array): bool
3037
{
3038
    if (isset($array[$key]) === true && (int) $array[$key] > $value) {
3039
        return true;
3040
    }
3041
    return false;
3042
}
3043
3044
/**
3045
 * Check if values in array are set
3046
 * Return true if all set
3047
 * Return false if one of them is not set
3048
 *
3049
 * @param array $arrayOfValues
3050
 * @return boolean
3051
 */
3052
function isSetArrayOfValues(array $arrayOfValues): bool
3053
{
3054
    foreach($arrayOfValues as $value) {
3055
        if (isset($value) === false) {
3056
            return false;
3057
        }
3058
    }
3059
    return true;
3060
}
3061
3062
/**
3063
 * Check if values in array are set
3064
 * Return true if all set
3065
 * Return false if one of them is not set
3066
 *
3067
 * @param array $arrayOfValues
3068
 * @param integer|string $value
3069
 * @return boolean
3070
 */
3071
function isArrayOfVarsEqualToValue(
3072
    array $arrayOfVars,
3073
    /*PHP8 - integer|string*/$value
3074
) : bool
3075
{
3076
    foreach($arrayOfVars as $variable) {
3077
        if ($variable !== $value) {
3078
            return false;
3079
        }
3080
    }
3081
    return true;
3082
}
3083
3084
/**
3085
 * Checks if at least one variable in array is equal to value
3086
 *
3087
 * @param array $arrayOfValues
3088
 * @param integer|string $value
3089
 * @return boolean
3090
 */
3091
function isOneVarOfArrayEqualToValue(
3092
    array $arrayOfVars,
3093
    /*PHP8 - integer|string*/$value
3094
) : bool
3095
{
3096
    foreach($arrayOfVars as $variable) {
3097
        if ($variable === $value) {
3098
            return true;
3099
        }
3100
    }
3101
    return false;
3102
}
3103
3104
/**
3105
 * Checks is value is null, not set OR empty
3106
 *
3107
 * @param string|int|null $value
3108
 * @return boolean
3109
 */
3110
function isValueSetNullEmpty(/*PHP8 - string|int|null*/ $value) : bool
3111
{
3112
    if (is_null($value) === true || isset($value) === false || empty($value) === true) {
3113
        return true;
3114
    }
3115
    return false;
3116
}
3117
3118
/**
3119
 * Checks if value is set and if empty is equal to passed boolean
3120
 *
3121
 * @param string|int $value
3122
 * @param boolean $boolean
3123
 * @return boolean
3124
 */
3125
function isValueSetEmpty($value, $boolean = true) : bool
3126
{
3127
    if (isset($value) === true && empty($value) === $boolean) {
3128
        return true;
3129
    }
3130
    return false;
3131
}
3132
3133
/**
3134
 * Ensure Complexity is translated
3135
 *
3136
 * @return void
3137
 */
3138
function defineComplexity() : void
3139
{
3140
    // Load user's language
3141
    $session = SessionManager::getSession();
3142
    $lang = new Language($session->get('user-language') ?? 'english');
3143
    
3144
    if (defined('TP_PW_COMPLEXITY') === false) {
3145
        define(
3146
            'TP_PW_COMPLEXITY',
3147
            [
3148
                TP_PW_STRENGTH_1 => array(TP_PW_STRENGTH_1, $lang->get('complex_level1'), 'fas fa-thermometer-empty text-danger'),
3149
                TP_PW_STRENGTH_2 => array(TP_PW_STRENGTH_2, $lang->get('complex_level2'), 'fas fa-thermometer-quarter text-warning'),
3150
                TP_PW_STRENGTH_3 => array(TP_PW_STRENGTH_3, $lang->get('complex_level3'), 'fas fa-thermometer-half text-warning'),
3151
                TP_PW_STRENGTH_4 => array(TP_PW_STRENGTH_4, $lang->get('complex_level4'), 'fas fa-thermometer-three-quarters text-success'),
3152
                TP_PW_STRENGTH_5 => array(TP_PW_STRENGTH_5, $lang->get('complex_level5'), 'fas fa-thermometer-full text-success'),
3153
            ]
3154
        );
3155
    }
3156
}
3157
3158
/**
3159
 * Uses Sanitizer to perform data sanitization
3160
 *
3161
 * @param array     $data
3162
 * @param array     $filters
3163
 * @return array|string
3164
 */
3165
function dataSanitizer(array $data, array $filters): array|string
3166
{
3167
    // Load Sanitizer library
3168
    $sanitizer = new Sanitizer($data, $filters);
3169
3170
    // Load AntiXSS
3171
    $antiXss = new AntiXSS();
3172
3173
    // Sanitize post and get variables
3174
    return $antiXss->xss_clean($sanitizer->sanitize());
3175
}
3176
3177
/**
3178
 * Permits to manage the cache tree for a user
3179
 *
3180
 * @param integer $user_id
3181
 * @param string $data
3182
 * @param array $SETTINGS
3183
 * @param string $field_update
3184
 * @return void
3185
 */
3186
function cacheTreeUserHandler(int $user_id, string $data, array $SETTINGS, string $field_update = '')
3187
{
3188
    // Load class DB
3189
    loadClasses('DB');
3190
3191
    // Exists ?
3192
    $userCacheId = DB::queryfirstrow(
3193
        'SELECT increment_id
3194
        FROM ' . prefixTable('cache_tree') . '
3195
        WHERE user_id = %i',
3196
        $user_id
3197
    );
3198
    
3199
    if (is_null($userCacheId) === true || count($userCacheId) === 0) {
3200
        // insert in table
3201
        DB::insert(
3202
            prefixTable('cache_tree'),
3203
            array(
3204
                'data' => $data,
3205
                'timestamp' => time(),
3206
                'user_id' => $user_id,
3207
                'visible_folders' => '',
3208
            )
3209
        );
3210
    } else {
3211
        if (empty($field_update) === true) {
3212
            DB::update(
3213
                prefixTable('cache_tree'),
3214
                [
3215
                    'timestamp' => time(),
3216
                    'data' => $data,
3217
                ],
3218
                'increment_id = %i',
3219
                $userCacheId['increment_id']
3220
            );
3221
        /* USELESS
3222
        } else {
3223
            DB::update(
3224
                prefixTable('cache_tree'),
3225
                [
3226
                    $field_update => $data,
3227
                ],
3228
                'increment_id = %i',
3229
                $userCacheId['increment_id']
3230
            );*/
3231
        }
3232
    }
3233
}
3234
3235
/**
3236
 * Permits to calculate a %
3237
 *
3238
 * @param float $nombre
3239
 * @param float $total
3240
 * @param float $pourcentage
3241
 * @return float
3242
 */
3243
function pourcentage(float $nombre, float $total, float $pourcentage): float
3244
{ 
3245
    $resultat = ($nombre/$total) * $pourcentage;
3246
    return round($resultat);
3247
}
3248
3249
/**
3250
 * Load the folders list from the cache
3251
 *
3252
 * @param string $fieldName
3253
 * @param string $sessionName
3254
 * @param boolean $forceRefresh
3255
 * @return array
3256
 */
3257
function loadFoldersListByCache(
3258
    string $fieldName,
3259
    string $sessionName,
3260
    bool $forceRefresh = false
3261
): array
3262
{
3263
    // Case when refresh is EXPECTED / MANDATORY
3264
    if ($forceRefresh === true) {
3265
        return [
3266
            'state' => false,
3267
            'data' => [],
3268
        ];
3269
    }
3270
    
3271
    $session = SessionManager::getSession();
3272
3273
    // Get last folder update
3274
    $lastFolderChange = DB::queryfirstrow(
3275
        'SELECT valeur FROM ' . prefixTable('misc') . '
3276
        WHERE type = %s AND intitule = %s',
3277
        'timestamp',
3278
        'last_folder_change'
3279
    );
3280
    if (DB::count() === 0) {
3281
        $lastFolderChange['valeur'] = 0;
3282
    }
3283
3284
    // Case when an update in the tree has been done
3285
    // Refresh is then mandatory
3286
    if ((int) $lastFolderChange['valeur'] > (int) (null !== $session->get('user-tree_last_refresh_timestamp') ? $session->get('user-tree_last_refresh_timestamp') : 0)) {
3287
        return [
3288
            'state' => false,
3289
            'data' => [],
3290
        ];
3291
    }
3292
3293
    // Does this user has the tree structure in session?
3294
    // If yes then use it
3295
    if (count(null !== $session->get('user-folders_list') ? $session->get('user-folders_list') : []) > 0) {
3296
        return [
3297
            'state' => true,
3298
            'data' => json_encode($session->get('user-folders_list')[0]),
3299
            'extra' => 'to_be_parsed',
3300
        ];
3301
    }
3302
    
3303
    // Does this user has a tree cache
3304
    $userCacheTree = DB::queryfirstrow(
3305
        'SELECT '.$fieldName.'
3306
        FROM ' . prefixTable('cache_tree') . '
3307
        WHERE user_id = %i',
3308
        $session->get('user-id')
3309
    );
3310
    if (empty($userCacheTree[$fieldName]) === false && $userCacheTree[$fieldName] !== '[]') {
3311
        SessionManager::addRemoveFromSessionAssociativeArray(
3312
            'user-folders_list',
3313
            [$userCacheTree[$fieldName]],
3314
            'add'
3315
        );
3316
        return [
3317
            'state' => true,
3318
            'data' => $userCacheTree[$fieldName],
3319
            'extra' => '',
3320
        ];
3321
    }
3322
3323
    return [
3324
        'state' => false,
3325
        'data' => [],
3326
    ];
3327
}
3328
3329
3330
/**
3331
 * Permits to refresh the categories of folders
3332
 *
3333
 * @param array $folderIds
3334
 * @return void
3335
 */
3336
function handleFoldersCategories(
3337
    array $folderIds
3338
)
3339
{
3340
    // Load class DB
3341
    loadClasses('DB');
3342
3343
    $arr_data = array();
3344
3345
    // force full list of folders
3346
    if (count($folderIds) === 0) {
3347
        $folderIds = DB::queryFirstColumn(
3348
            'SELECT id
3349
            FROM ' . prefixTable('nested_tree') . '
3350
            WHERE personal_folder=%i',
3351
            0
3352
        );
3353
    }
3354
3355
    // Get complexity
3356
    defineComplexity();
3357
3358
    // update
3359
    foreach ($folderIds as $folder) {
3360
        // Do we have Categories
3361
        // get list of associated Categories
3362
        $arrCatList = array();
3363
        $rows_tmp = DB::query(
3364
            'SELECT c.id, c.title, c.level, c.type, c.masked, c.order, c.encrypted_data, c.role_visibility, c.is_mandatory,
3365
            f.id_category AS category_id
3366
            FROM ' . prefixTable('categories_folders') . ' AS f
3367
            INNER JOIN ' . prefixTable('categories') . ' AS c ON (f.id_category = c.parent_id)
3368
            WHERE id_folder=%i',
3369
            $folder
3370
        );
3371
        if (DB::count() > 0) {
3372
            foreach ($rows_tmp as $row) {
3373
                $arrCatList[$row['id']] = array(
3374
                    'id' => $row['id'],
3375
                    'title' => $row['title'],
3376
                    'level' => $row['level'],
3377
                    'type' => $row['type'],
3378
                    'masked' => $row['masked'],
3379
                    'order' => $row['order'],
3380
                    'encrypted_data' => $row['encrypted_data'],
3381
                    'role_visibility' => $row['role_visibility'],
3382
                    'is_mandatory' => $row['is_mandatory'],
3383
                    'category_id' => $row['category_id'],
3384
                );
3385
            }
3386
        }
3387
        $arr_data['categories'] = $arrCatList;
3388
3389
        // Now get complexity
3390
        $valTemp = '';
3391
        $data = DB::queryFirstRow(
3392
            'SELECT valeur
3393
            FROM ' . prefixTable('misc') . '
3394
            WHERE type = %s AND intitule=%i',
3395
            'complex',
3396
            $folder
3397
        );
3398
        if (DB::count() > 0 && empty($data['valeur']) === false) {
3399
            $valTemp = array(
3400
                'value' => $data['valeur'],
3401
                'text' => TP_PW_COMPLEXITY[$data['valeur']][1],
3402
            );
3403
        }
3404
        $arr_data['complexity'] = $valTemp;
3405
3406
        // Now get Roles
3407
        $valTemp = '';
3408
        $rows_tmp = DB::query(
3409
            'SELECT t.title
3410
            FROM ' . prefixTable('roles_values') . ' as v
3411
            INNER JOIN ' . prefixTable('roles_title') . ' as t ON (v.role_id = t.id)
3412
            WHERE v.folder_id = %i
3413
            GROUP BY title',
3414
            $folder
3415
        );
3416
        foreach ($rows_tmp as $record) {
3417
            $valTemp .= (empty($valTemp) === true ? '' : ' - ') . $record['title'];
3418
        }
3419
        $arr_data['visibilityRoles'] = $valTemp;
3420
3421
        // now save in DB
3422
        DB::update(
3423
            prefixTable('nested_tree'),
3424
            array(
3425
                'categories' => json_encode($arr_data),
3426
            ),
3427
            'id = %i',
3428
            $folder
3429
        );
3430
    }
3431
}
3432
3433
/**
3434
 * List all users that have specific roles
3435
 *
3436
 * @param array $roles
3437
 * @return array
3438
 */
3439
function getUsersWithRoles(
3440
    array $roles
3441
): array
3442
{
3443
    $session = SessionManager::getSession();
3444
    $arrUsers = array();
3445
3446
    foreach ($roles as $role) {
3447
        // loop on users and check if user has this role
3448
        $rows = DB::query(
3449
            'SELECT id, fonction_id
3450
            FROM ' . prefixTable('users') . '
3451
            WHERE id != %i AND admin = 0 AND fonction_id IS NOT NULL AND fonction_id != ""',
3452
            $session->get('user-id')
3453
        );
3454
        foreach ($rows as $user) {
3455
            $userRoles = is_null($user['fonction_id']) === false && empty($user['fonction_id']) === false ? explode(';', $user['fonction_id']) : [];
3456
            if (in_array($role, $userRoles, true) === true) {
3457
                array_push($arrUsers, $user['id']);
3458
            }
3459
        }
3460
    }
3461
3462
    return $arrUsers;
3463
}
3464
3465
3466
/**
3467
 * Get all users informations
3468
 *
3469
 * @param integer $userId
3470
 * @return array
3471
 */
3472
function getFullUserInfos(
3473
    int $userId
3474
): array
3475
{
3476
    if (empty($userId) === true) {
3477
        return array();
3478
    }
3479
3480
    $val = DB::queryfirstrow(
3481
        'SELECT *
3482
        FROM ' . prefixTable('users') . '
3483
        WHERE id = %i',
3484
        $userId
3485
    );
3486
3487
    return $val;
3488
}
3489
3490
/**
3491
 * Is required an upgrade
3492
 *
3493
 * @return boolean
3494
 */
3495
function upgradeRequired(): bool
3496
{
3497
    // Get settings.php
3498
    include_once __DIR__. '/../includes/config/settings.php';
3499
3500
    // Get timestamp in DB
3501
    $val = DB::queryfirstrow(
3502
        'SELECT valeur
3503
        FROM ' . prefixTable('misc') . '
3504
        WHERE type = %s AND intitule = %s',
3505
        'admin',
3506
        'upgrade_timestamp'
3507
    );
3508
3509
    // Check if upgrade is required
3510
    return (
3511
        is_null($val) || count($val) === 0 || !defined('UPGRADE_MIN_DATE') || 
3512
        empty($val['valeur']) || (int) $val['valeur'] < (int) UPGRADE_MIN_DATE
3513
    );
3514
}
3515
3516
/**
3517
 * Permits to change the user keys on his demand
3518
 *
3519
 * @param integer $userId
3520
 * @param string $passwordClear
3521
 * @param integer $nbItemsToTreat
3522
 * @param string $encryptionKey
3523
 * @param boolean $deleteExistingKeys
3524
 * @param boolean $sendEmailToUser
3525
 * @param boolean $encryptWithUserPassword
3526
 * @param boolean $generate_user_new_password
3527
 * @param string $emailBody
3528
 * @param boolean $user_self_change
3529
 * @param string $recovery_public_key
3530
 * @param string $recovery_private_key
3531
 * @return string
3532
 */
3533
function handleUserKeys(
3534
    int $userId,
3535
    string $passwordClear,
3536
    int $nbItemsToTreat,
3537
    string $encryptionKey = '',
3538
    bool $deleteExistingKeys = false,
3539
    bool $sendEmailToUser = true,
3540
    bool $encryptWithUserPassword = false,
3541
    bool $generate_user_new_password = false,
3542
    string $emailBody = '',
3543
    bool $user_self_change = false,
3544
    string $recovery_public_key = '',
3545
    string $recovery_private_key = ''
3546
): string
3547
{
3548
    $session = SessionManager::getSession();
3549
    $lang = new Language($session->get('user-language') ?? 'english');
3550
3551
    // prepapre background tasks for item keys generation        
3552
    $userTP = DB::queryFirstRow(
3553
        'SELECT pw, public_key, private_key
3554
        FROM ' . prefixTable('users') . '
3555
        WHERE id = %i',
3556
        TP_USER_ID
3557
    );
3558
    if (DB::count() === 0) {
3559
        return prepareExchangedData(
3560
            array(
3561
                'error' => true,
3562
                'message' => 'User not exists',
3563
            ),
3564
            'encode'
3565
        );
3566
    }
3567
3568
    // Do we need to generate new user password
3569
    if ($generate_user_new_password === true) {
3570
        // Generate a new password
3571
        $passwordClear = GenerateCryptKey(20, false, true, true, false, true);
3572
    }
3573
3574
    // Create password hash
3575
    $passwordManager = new PasswordManager();
3576
    $hashedPassword = $passwordManager->hashPassword($passwordClear);
3577
    if ($passwordManager->verifyPassword($hashedPassword, $passwordClear) === false) {
3578
        return prepareExchangedData(
3579
            array(
3580
                'error' => true,
3581
                'message' => $lang->get('pw_hash_not_correct'),
3582
            ),
3583
            'encode'
3584
        );
3585
    }
3586
3587
    // Check if valid public/private keys
3588
    if ($recovery_public_key !== '' && $recovery_private_key !== '') {
3589
        try {
3590
            // Generate random string
3591
            $random_str = generateQuickPassword(12, false);
3592
            // Encrypt random string with user publick key
3593
            $encrypted = encryptUserObjectKey($random_str, $recovery_public_key);
3594
            // Decrypt $encrypted with private key
3595
            $decrypted = decryptUserObjectKey($encrypted, $recovery_private_key);
3596
            // Check if decryptUserObjectKey returns our random string
3597
            if ($decrypted !== $random_str) {
3598
                throw new Exception('Public/Private keypair invalid.');
3599
            }
3600
        } catch (Exception $e) {
3601
            // Show error message to user and log event
3602
            if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
3603
                error_log('ERROR: User '.$userId.' - '.$e->getMessage());
3604
            }
3605
            return prepareExchangedData([
3606
                    'error' => true,
3607
                    'message' => $lang->get('pw_encryption_error'),
3608
                ],
3609
                'encode'
3610
            );
3611
        }
3612
    }
3613
3614
    // Generate new keys
3615
    if ($user_self_change === true && empty($recovery_public_key) === false && empty($recovery_private_key) === false){
3616
        $userKeys = [
3617
            'public_key' => $recovery_public_key,
3618
            'private_key_clear' => $recovery_private_key,
3619
            'private_key' => encryptPrivateKey($passwordClear, $recovery_private_key),
3620
        ];
3621
    } else {
3622
        $userKeys = generateUserKeys($passwordClear);
3623
    }
3624
3625
    // Save in DB
3626
    DB::update(
3627
        prefixTable('users'),
3628
        array(
3629
            'pw' => $hashedPassword,
3630
            'public_key' => $userKeys['public_key'],
3631
            'private_key' => $userKeys['private_key'],
3632
            'keys_recovery_time' => NULL,
3633
        ),
3634
        'id=%i',
3635
        $userId
3636
    );
3637
3638
    // update session too
3639
    if ($userId === $session->get('user-id')) {
3640
        $session->set('user-private_key', $userKeys['private_key_clear']);
3641
        $session->set('user-public_key', $userKeys['public_key']);
3642
        // Notify user that he must re download his keys:
3643
        $session->set('user-keys_recovery_time', NULL);
3644
    }
3645
3646
    // Manage empty encryption key
3647
    // Let's take the user's password if asked and if no encryption key provided
3648
    $encryptionKey = $encryptWithUserPassword === true && empty($encryptionKey) === true ? $passwordClear : $encryptionKey;
3649
3650
    // Create process
3651
    DB::insert(
3652
        prefixTable('background_tasks'),
3653
        array(
3654
            'created_at' => time(),
3655
            'process_type' => 'create_user_keys',
3656
            'arguments' => json_encode([
3657
                'new_user_id' => (int) $userId,
3658
                'new_user_pwd' => cryption($passwordClear, '','encrypt')['string'],
3659
                'new_user_code' => cryption(empty($encryptionKey) === true ? uniqidReal(20) : $encryptionKey, '','encrypt')['string'],
3660
                'owner_id' => (int) TP_USER_ID,
3661
                'creator_pwd' => $userTP['pw'],
3662
                'send_email' => $sendEmailToUser === true ? 1 : 0,
3663
                'otp_provided_new_value' => 1,
3664
                'email_body' => empty($emailBody) === true ? '' : $lang->get($emailBody),
3665
                'user_self_change' => $user_self_change === true ? 1 : 0,
3666
            ]),
3667
        )
3668
    );
3669
    $processId = DB::insertId();
3670
3671
    // Delete existing keys
3672
    if ($deleteExistingKeys === true) {
3673
        deleteUserObjetsKeys(
3674
            (int) $userId,
3675
        );
3676
    }
3677
3678
    // Create tasks
3679
    createUserTasks($processId, $nbItemsToTreat);
3680
3681
    // update user's new status
3682
    DB::update(
3683
        prefixTable('users'),
3684
        [
3685
            'is_ready_for_usage' => 0,
3686
            'otp_provided' => 1,
3687
            'ongoing_process_id' => $processId,
3688
            'special' => 'generate-keys',
3689
        ],
3690
        'id=%i',
3691
        $userId
3692
    );
3693
3694
    return prepareExchangedData(
3695
        array(
3696
            'error' => false,
3697
            'message' => '',
3698
            'user_password' => $generate_user_new_password === true ? $passwordClear : '',
3699
        ),
3700
        'encode'
3701
    );
3702
}
3703
3704
/**
3705
 * Permits to generate a new password for a user
3706
 *
3707
 * @param integer $processId
3708
 * @param integer $nbItemsToTreat
3709
 * @return void
3710
 
3711
 */
3712
function createUserTasks($processId, $nbItemsToTreat): void
3713
{
3714
    DB::insert(
3715
        prefixTable('background_subtasks'),
3716
        array(
3717
            'task_id' => $processId,
3718
            'created_at' => time(),
3719
            'task' => json_encode([
3720
                'step' => 'step0',
3721
                'index' => 0,
3722
                'nb' => $nbItemsToTreat,
3723
            ]),
3724
        )
3725
    );
3726
3727
    DB::insert(
3728
        prefixTable('background_subtasks'),
3729
        array(
3730
            'task_id' => $processId,
3731
            'created_at' => time(),
3732
            'task' => json_encode([
3733
                'step' => 'step10',
3734
                'index' => 0,
3735
                'nb' => $nbItemsToTreat,
3736
            ]),
3737
        )
3738
    );
3739
3740
    DB::insert(
3741
        prefixTable('background_subtasks'),
3742
        array(
3743
            'task_id' => $processId,
3744
            'created_at' => time(),
3745
            'task' => json_encode([
3746
                'step' => 'step20',
3747
                'index' => 0,
3748
                'nb' => $nbItemsToTreat,
3749
            ]),
3750
        )
3751
    );
3752
3753
    DB::insert(
3754
        prefixTable('background_subtasks'),
3755
        array(
3756
            'task_id' => $processId,
3757
            'created_at' => time(),
3758
            'task' => json_encode([
3759
                'step' => 'step30',
3760
                'index' => 0,
3761
                'nb' => $nbItemsToTreat,
3762
            ]),
3763
        )
3764
    );
3765
3766
    DB::insert(
3767
        prefixTable('background_subtasks'),
3768
        array(
3769
            'task_id' => $processId,
3770
            'created_at' => time(),
3771
            'task' => json_encode([
3772
                'step' => 'step40',
3773
                'index' => 0,
3774
                'nb' => $nbItemsToTreat,
3775
            ]),
3776
        )
3777
    );
3778
3779
    DB::insert(
3780
        prefixTable('background_subtasks'),
3781
        array(
3782
            'task_id' => $processId,
3783
            'created_at' => time(),
3784
            'task' => json_encode([
3785
                'step' => 'step50',
3786
                'index' => 0,
3787
                'nb' => $nbItemsToTreat,
3788
            ]),
3789
        )
3790
    );
3791
3792
    DB::insert(
3793
        prefixTable('background_subtasks'),
3794
        array(
3795
            'task_id' => $processId,
3796
            'created_at' => time(),
3797
            'task' => json_encode([
3798
                'step' => 'step60',
3799
                'index' => 0,
3800
                'nb' => $nbItemsToTreat,
3801
            ]),
3802
        )
3803
    );
3804
}
3805
3806
/**
3807
 * Permeits to check the consistency of date versus columns definition
3808
 *
3809
 * @param string $table
3810
 * @param array $dataFields
3811
 * @return array
3812
 */
3813
function validateDataFields(
3814
    string $table,
3815
    array $dataFields
3816
): array
3817
{
3818
    // Get table structure
3819
    $result = DB::query(
3820
        "SELECT `COLUMN_NAME`, `CHARACTER_MAXIMUM_LENGTH` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '%l' AND TABLE_NAME = '%l';",
3821
        DB_NAME,
3822
        $table
3823
    );
3824
3825
    foreach ($result as $row) {
3826
        $field = $row['COLUMN_NAME'];
3827
        $maxLength = is_null($row['CHARACTER_MAXIMUM_LENGTH']) === false ? (int) $row['CHARACTER_MAXIMUM_LENGTH'] : '';
3828
3829
        if (isset($dataFields[$field]) === true && is_array($dataFields[$field]) === false && empty($maxLength) === false) {
3830
            if (strlen((string) $dataFields[$field]) > $maxLength) {
3831
                return [
3832
                    'state' => false,
3833
                    'field' => $field,
3834
                    'maxLength' => $maxLength,
3835
                    'currentLength' => strlen((string) $dataFields[$field]),
3836
                ];
3837
            }
3838
        }
3839
    }
3840
    
3841
    return [
3842
        'state' => true,
3843
        'message' => '',
3844
    ];
3845
}
3846
3847
/**
3848
 * Adapt special characters sanitized during filter_var with option FILTER_SANITIZE_SPECIAL_CHARS operation
3849
 *
3850
 * @param string $string
3851
 * @return string
3852
 */
3853
function filterVarBack(string $string): string
3854
{
3855
    $arr = [
3856
        '&#060;' => '<',
3857
        '&#062;' => '>',
3858
        '&#034;' => '"',
3859
        '&#039;' => "'",
3860
        '&#038;' => '&',
3861
    ];
3862
3863
    foreach ($arr as $key => $value) {
3864
        $string = str_replace($key, $value, $string);
3865
    }
3866
3867
    return $string;
3868
}
3869
3870
/**
3871
 * 
3872
 */
3873
function storeTask(
3874
    string $taskName,
3875
    int $user_id,
3876
    int $is_personal_folder,
3877
    int $folder_destination_id,
3878
    int $item_id,
3879
    string $object_keys,
3880
    array $fields_keys = [],
3881
    array $files_keys = []
3882
)
3883
{
3884
    if (in_array($taskName, ['item_copy', 'new_item', 'update_item'])) {
3885
        // Create process
3886
        DB::insert(
3887
            prefixTable('background_tasks'),
3888
            array(
3889
                'created_at' => time(),
3890
                'process_type' => $taskName,
3891
                'arguments' => json_encode([
3892
                    'item_id' => $item_id,
3893
                    'object_key' => $object_keys,
3894
                ]),
3895
                'item_id' => $item_id,
3896
            )
3897
        );
3898
        $processId = DB::insertId();
3899
3900
        // Create tasks
3901
        // 1- Create password sharekeys for users of this new ITEM
3902
        DB::insert(
3903
            prefixTable('background_subtasks'),
3904
            array(
3905
                'task_id' => $processId,
3906
                'created_at' => time(),
3907
                'task' => json_encode([
3908
                    'step' => 'create_users_pwd_key',
3909
                    'index' => 0,
3910
                ]),
3911
            )
3912
        );
3913
3914
        // 2- Create fields sharekeys for users of this new ITEM
3915
        DB::insert(
3916
            prefixTable('background_subtasks'),
3917
            array(
3918
                'task_id' => $processId,
3919
                'created_at' => time(),
3920
                'task' => json_encode([
3921
                    'step' => 'create_users_fields_key',
3922
                    'index' => 0,
3923
                    'fields_keys' => $fields_keys,
3924
                ]),
3925
            )
3926
        );
3927
3928
        // 3- Create files sharekeys for users of this new ITEM
3929
        DB::insert(
3930
            prefixTable('background_subtasks'),
3931
            array(
3932
                'task_id' => $processId,
3933
                'created_at' => time(),
3934
                'task' => json_encode([
3935
                    'step' => 'create_users_files_key',
3936
                    'index' => 0,
3937
                    'files_keys' => $files_keys,
3938
                ]),
3939
            )
3940
        );
3941
    }
3942
}
3943
3944
/**
3945
 * 
3946
 */
3947
function createTaskForItem(
3948
    string $processType,
3949
    string|array $taskName,
3950
    int $itemId,
3951
    int $userId,
3952
    string $objectKey,
3953
    int $parentId = -1,
3954
    array $fields_keys = [],
3955
    array $files_keys = []
3956
)
3957
{
3958
    // 1- Create main process
3959
    // ---
3960
    
3961
    // Create process
3962
    DB::insert(
3963
        prefixTable('background_tasks'),
3964
        array(
3965
            'created_at' => time(),
3966
            'process_type' => $processType,
3967
            'arguments' => json_encode([
3968
                'all_users_except_id' => (int) $userId,
3969
                'item_id' => (int) $itemId,
3970
                'object_key' => $objectKey,
3971
                'author' => (int) $userId,
3972
            ]),
3973
            'item_id' => (int) $parentId !== -1 ?  $parentId : null,
3974
        )
3975
    );
3976
    $processId = DB::insertId();
3977
3978
    // 2- Create expected tasks
3979
    // ---
3980
    if (is_array($taskName) === false) {
0 ignored issues
show
introduced by
The condition is_array($taskName) === false is always false.
Loading history...
3981
        $taskName = [$taskName];
3982
    }
3983
    foreach($taskName as $task) {
3984
        if (WIP === true) error_log('createTaskForItem - task: '.$task);
3985
        switch ($task) {
3986
            case 'item_password':
3987
                
3988
                DB::insert(
3989
                    prefixTable('background_subtasks'),
3990
                    array(
3991
                        'task_id' => $processId,
3992
                        'created_at' => time(),
3993
                        'task' => json_encode([
3994
                            'step' => 'create_users_pwd_key',
3995
                            'index' => 0,
3996
                        ]),
3997
                    )
3998
                );
3999
4000
                break;
4001
            case 'item_field':
4002
                
4003
                DB::insert(
4004
                    prefixTable('background_subtasks'),
4005
                    array(
4006
                        'task_id' => $processId,
4007
                        'created_at' => time(),
4008
                        'task' => json_encode([
4009
                            'step' => 'create_users_fields_key',
4010
                            'index' => 0,
4011
                            'fields_keys' => $fields_keys,
4012
                        ]),
4013
                    )
4014
                );
4015
4016
                break;
4017
            case 'item_file':
4018
4019
                DB::insert(
4020
                    prefixTable('background_subtasks'),
4021
                    array(
4022
                        'task_id' => $processId,
4023
                        'created_at' => time(),
4024
                        'task' => json_encode([
4025
                            'step' => 'create_users_files_key',
4026
                            'index' => 0,
4027
                            'fields_keys' => $files_keys,
4028
                        ]),
4029
                    )
4030
                );
4031
                break;
4032
            default:
4033
                # code...
4034
                break;
4035
        }
4036
    }
4037
}
4038
4039
4040
function deleteProcessAndRelatedTasks(int $processId)
4041
{
4042
    // Delete process
4043
    DB::delete(
4044
        prefixTable('background_tasks'),
4045
        'id=%i',
4046
        $processId
4047
    );
4048
4049
    // Delete tasks
4050
    DB::delete(
4051
        prefixTable('background_subtasks'),
4052
        'task_id=%i',
4053
        $processId
4054
    );
4055
4056
}
4057
4058
/**
4059
 * Return PHP binary path
4060
 *
4061
 * @return string
4062
 */
4063
function getPHPBinary(): string
4064
{
4065
    // Get PHP binary path
4066
    $phpBinaryFinder = new PhpExecutableFinder();
4067
    $phpBinaryPath = $phpBinaryFinder->find();
4068
    return $phpBinaryPath === false ? 'false' : $phpBinaryPath;
4069
}
4070
4071
4072
4073
/**
4074
 * Delete unnecessary keys for personal items
4075
 *
4076
 * @param boolean $allUsers
4077
 * @param integer $user_id
4078
 * @return void
4079
 */
4080
function purgeUnnecessaryKeys(bool $allUsers = true, int $user_id=0)
4081
{
4082
    if ($allUsers === true) {
4083
        // Load class DB
4084
        if (class_exists('DB') === false) {
4085
            loadClasses('DB');
4086
        }
4087
4088
        $users = DB::query(
4089
            'SELECT id
4090
            FROM ' . prefixTable('users') . '
4091
            WHERE id NOT IN ('.OTV_USER_ID.', '.TP_USER_ID.', '.SSH_USER_ID.', '.API_USER_ID.')
4092
            ORDER BY login ASC'
4093
        );
4094
        foreach ($users as $user) {
4095
            purgeUnnecessaryKeysForUser((int) $user['id']);
4096
        }
4097
    } else {
4098
        purgeUnnecessaryKeysForUser((int) $user_id);
4099
    }
4100
}
4101
4102
/**
4103
 * Delete unnecessary keys for personal items
4104
 *
4105
 * @param integer $user_id
4106
 * @return void
4107
 */
4108
function purgeUnnecessaryKeysForUser(int $user_id=0)
4109
{
4110
    if ($user_id === 0) {
4111
        return;
4112
    }
4113
4114
    // Load class DB
4115
    loadClasses('DB');
4116
4117
    $personalItems = DB::queryFirstColumn(
4118
        'SELECT id
4119
        FROM ' . prefixTable('items') . ' AS i
4120
        INNER JOIN ' . prefixTable('log_items') . ' AS li ON li.id_item = i.id
4121
        WHERE i.perso = 1 AND li.action = "at_creation" AND li.id_user IN (%i, '.TP_USER_ID.')',
4122
        $user_id
4123
    );
4124
    if (count($personalItems) > 0) {
4125
        // Item keys
4126
        DB::delete(
4127
            prefixTable('sharekeys_items'),
4128
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4129
            $personalItems,
4130
            $user_id
4131
        );
4132
        // Files keys
4133
        DB::delete(
4134
            prefixTable('sharekeys_files'),
4135
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4136
            $personalItems,
4137
            $user_id
4138
        );
4139
        // Fields keys
4140
        DB::delete(
4141
            prefixTable('sharekeys_fields'),
4142
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4143
            $personalItems,
4144
            $user_id
4145
        );
4146
        // Logs keys
4147
        DB::delete(
4148
            prefixTable('sharekeys_logs'),
4149
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4150
            $personalItems,
4151
            $user_id
4152
        );
4153
    }
4154
}
4155
4156
/**
4157
 * Generate recovery keys file
4158
 *
4159
 * @param integer $userId
4160
 * @param array $SETTINGS
4161
 * @return string
4162
 */
4163
function handleUserRecoveryKeysDownload(int $userId, array $SETTINGS):string
4164
{
4165
    $session = SessionManager::getSession();
4166
    // Check if user exists
4167
    $userInfo = DB::queryFirstRow(
4168
        'SELECT login
4169
        FROM ' . prefixTable('users') . '
4170
        WHERE id = %i',
4171
        $userId
4172
    );
4173
4174
    if (DB::count() > 0) {
4175
        $now = (int) time();
4176
        // Prepare file content
4177
        $export_value = file_get_contents(__DIR__."/../includes/core/teampass_ascii.txt")."\n".
4178
            "Generation date: ".date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now)."\n\n".
4179
            "RECOVERY KEYS - Not to be shared - To be store safely\n\n".
4180
            "Public Key:\n".$session->get('user-public_key')."\n\n".
4181
            "Private Key:\n".$session->get('user-private_key')."\n\n";
4182
4183
        // Update user's keys_recovery_time
4184
        DB::update(
4185
            prefixTable('users'),
4186
            [
4187
                'keys_recovery_time' => $now,
4188
            ],
4189
            'id=%i',
4190
            $userId
4191
        );
4192
        $session->set('user-keys_recovery_time', $now);
4193
4194
        //Log into DB the user's disconnection
4195
        logEvents($SETTINGS, 'user_mngt', 'at_user_keys_download', (string) $userId, $userInfo['login']);
4196
        
4197
        // Return data
4198
        return prepareExchangedData(
4199
            array(
4200
                'error' => false,
4201
                'datetime' => date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now),
4202
                'timestamp' => $now,
4203
                'content' => base64_encode($export_value),
4204
                'login' => $userInfo['login'],
4205
            ),
4206
            'encode'
4207
        );
4208
    }
4209
4210
    return prepareExchangedData(
4211
        array(
4212
            'error' => true,
4213
            'datetime' => '',
4214
        ),
4215
        'encode'
4216
    );
4217
}
4218
4219
/**
4220
 * Permits to load expected classes
4221
 *
4222
 * @param string $className
4223
 * @return void
4224
 */
4225
function loadClasses(string $className = ''): void
4226
{
4227
    require_once __DIR__. '/../includes/config/include.php';
4228
    require_once __DIR__. '/../includes/config/settings.php';
4229
    require_once __DIR__.'/../vendor/autoload.php';
4230
4231
    if (defined('DB_PASSWD_CLEAR') === false) {
4232
        define('DB_PASSWD_CLEAR', defuseReturnDecrypted(DB_PASSWD, []));
4233
    }
4234
4235
    if (empty($className) === false) {
4236
        // Load class DB
4237
        if ((string) $className === 'DB') {
4238
            //Connect to DB
4239
            DB::$host = DB_HOST;
4240
            DB::$user = DB_USER;
4241
            DB::$password = DB_PASSWD_CLEAR;
4242
            DB::$dbName = DB_NAME;
4243
            DB::$port = DB_PORT;
4244
            DB::$encoding = DB_ENCODING;
4245
            DB::$ssl = DB_SSL;
4246
            DB::$connect_options = DB_CONNECT_OPTIONS;
4247
        }
4248
    }
4249
}
4250
4251
/**
4252
 * Returns the page the user is visiting.
4253
 *
4254
 * @return string The page name
4255
 */
4256
function getCurrectPage($SETTINGS)
4257
{
4258
    
4259
    $request = SymfonyRequest::createFromGlobals();
4260
4261
    // Parse the url
4262
    parse_str(
4263
        substr(
4264
            (string) $request->getRequestUri(),
4265
            strpos((string) $request->getRequestUri(), '?') + 1
4266
        ),
4267
        $result
4268
    );
4269
4270
    return $result['page'];
4271
}
4272
4273
/**
4274
 * Permits to return value if set
4275
 *
4276
 * @param string|int $value
4277
 * @param string|int|null $retFalse
4278
 * @param string|int $retTrue
4279
 * @return mixed
4280
 */
4281
function returnIfSet($value, $retFalse = '', $retTrue = null): mixed
4282
{
4283
4284
    return isset($value) === true ? ($retTrue === null ? $value : $retTrue) : $retFalse;
4285
}
4286
4287
4288
/**
4289
 * SEnd email to user
4290
 *
4291
 * @param string $post_receipt
4292
 * @param string $post_body
4293
 * @param string $post_subject
4294
 * @param array $post_replace
4295
 * @param boolean $immediate_email
4296
 * @param string $encryptedUserPassword
4297
 * @return string
4298
 */
4299
function sendMailToUser(
4300
    string $post_receipt,
4301
    string $post_body,
4302
    string $post_subject,
4303
    array $post_replace,
4304
    bool $immediate_email = false,
4305
    $encryptedUserPassword = ''
4306
): ?string {
4307
    global $SETTINGS;
4308
    $emailSettings = new EmailSettings($SETTINGS);
4309
    $emailService = new EmailService();
4310
4311
    // Sanitize inputs
4312
    $post_receipt = filter_var($post_receipt, FILTER_SANITIZE_EMAIL);
4313
    $post_subject = htmlspecialchars($post_subject, ENT_QUOTES, 'UTF-8');
4314
    $post_body = htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8');
4315
4316
    if (count($post_replace) > 0) {
4317
        $post_body = str_replace(
4318
            array_keys($post_replace),
4319
            array_values($post_replace),
4320
            $post_body
4321
        );
4322
    }
4323
4324
    // Remove newlines to prevent header injection
4325
    $post_body = str_replace(array("\r", "\n"), '', $post_body);    
4326
4327
    if ($immediate_email === true) {
4328
        // Send email
4329
        $ret = $emailService->sendMail(
4330
            $post_subject,
4331
            $post_body,
0 ignored issues
show
Security File Manipulation introduced by
$post_body can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

6 paths for user data to reach this point

  1. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 80
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 80
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  2. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 76
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 76
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  3. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 79
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 79
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  4. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 78
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 78
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  5. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 81
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 81
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  6. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 77
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 77
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325

Used in path-write context

  1. EmailService::sendMail() is called
    in sources/main.functions.php on line 4357
  2. Enters via parameter $textMail
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 98
  3. Data is passed through sanitizeEmailBody()
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 113
  4. $this->sanitizeEmailBody($textMail) is assigned to $textMail
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 113
  5. Data is passed through emailBody()
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 119
  6. emailBody($textMail) is assigned to property PHPMailer::$Body
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 119
  7. Read from property PHPMailer::$Body
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  8. Data is passed through encodeString()
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  9. $this->encodeString($this->Body, $this->Encoding) is assigned to $body
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  10. file_put_contents() is called
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3092

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...
Security File Manipulation introduced by
$post_body can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

6 paths for user data to reach this point

  1. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 78
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 78
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  2. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 80
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 80
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  3. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 76
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 76
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  4. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 79
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 79
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  5. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 77
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 77
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325
  6. Path: Read from $_SERVER in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 81
  1. Read from $_SERVER
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 81
  2. array('subTaskId' => $_SERVER['argv'][1], 'index' => $_SERVER['argv'][2], 'nb' => $_SERVER['argv'][3], 'step' => $_SERVER['argv'][4], 'taskArguments' => $_SERVER['argv'][5], 'taskId' => $_SERVER['argv'][6]) is assigned to $inputData
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 75
  3. Data is passed through json_decode(), and json_decode($inputData['taskArguments'], true) is assigned to $taskArgs
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 93
  4. performUserCreationKeys() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 118
  5. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 152
  6. cronContinueReEncryptingUserSharekeysStep10() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 185
  7. Enters via parameter $extra_arguments
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 841
  8. sendMailToUser() is called
    in scripts/background_tasks___userKeysCreation_subtaskHdl.php on line 882
  9. Enters via parameter $post_body
    in sources/main.functions.php on line 4301
  10. Data is passed through htmlspecialchars(), and htmlspecialchars($post_body, ENT_QUOTES, 'UTF-8') is assigned to $post_body
    in sources/main.functions.php on line 4314
  11. Data is passed through str_replace(), and ``str_replace(array(' ', ' '), '', $post_body)`` is assigned to $post_body
    in sources/main.functions.php on line 4325

Used in path-write context

  1. EmailService::sendMail() is called
    in sources/main.functions.php on line 4357
  2. Enters via parameter $textMail
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 98
  3. Data is passed through sanitizeEmailBody()
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 113
  4. $this->sanitizeEmailBody($textMail) is assigned to $textMail
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 113
  5. Data is passed through emailBody()
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 119
  6. emailBody($textMail) is assigned to property PHPMailer::$Body
    in vendor/teampassclasses/emailservice/src/EmailService.php on line 119
  7. Read from property PHPMailer::$Body
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  8. Data is passed through encodeString()
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  9. $this->encodeString($this->Body, $this->Encoding) is assigned to $body
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3075
  10. $body is returned
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 3135
  11. $this->createBody() is assigned to property PHPMailer::$MIMEBody
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1622
  12. Read from property PHPMailer::$MIMEBody
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1687
  13. PHPMailer::sendmailSend() is called
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1687
  14. Enters via parameter $body
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1726
  15. fwrite() is called
    in vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1803

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...
4332
            $post_receipt,
4333
            $emailSettings,
4334
            '',
4335
            false
4336
        );
4337
    
4338
        $ret = json_decode($ret, true);
4339
    
4340
        return prepareExchangedData(
4341
            array(
4342
                'error' => empty($ret['error']) === true ? false : true,
4343
                'message' => $ret['message'],
4344
            ),
4345
            'encode'
4346
        );
4347
    } else {
4348
        // Send through task handler
4349
        prepareSendingEmail(
4350
            $post_subject,
4351
            $post_body,
4352
            $post_receipt,
4353
            "",
4354
            $encryptedUserPassword,
4355
        );
4356
    }
4357
4358
    return null;
4359
}
4360
4361
/**
4362
 * Converts a password strengh value to zxcvbn level
4363
 * 
4364
 * @param integer $passwordStrength
4365
 * 
4366
 * @return integer
4367
 */
4368
function convertPasswordStrength($passwordStrength): int
4369
{
4370
    if ($passwordStrength === 0) {
4371
        return TP_PW_STRENGTH_1;
4372
    } else if ($passwordStrength === 1) {
4373
        return TP_PW_STRENGTH_2;
4374
    } else if ($passwordStrength === 2) {
4375
        return TP_PW_STRENGTH_3;
4376
    } else if ($passwordStrength === 3) {
4377
        return TP_PW_STRENGTH_4;
4378
    } else {
4379
        return TP_PW_STRENGTH_5;
4380
    }
4381
}
4382
4383
/**
4384
 * Check that a password is strong. The password needs to have at least :
4385
 *   - length >= 10.
4386
 *   - Uppercase and lowercase chars.
4387
 *   - Number or special char.
4388
 *   - Not contain username, name or mail part.
4389
 *   - Different from previous password.
4390
 * 
4391
 * @param string $password - Password to ckeck.
4392
 * @return bool - true if the password is strong, false otherwise.
4393
 */
4394
function isPasswordStrong($password) {
4395
    $session = SessionManager::getSession();
4396
4397
    // Password can't contain login, name or lastname
4398
    $forbiddenWords = [
4399
        $session->get('user-login'),
4400
        $session->get('user-name'),
4401
        $session->get('user-lastname'),
4402
    ];
4403
4404
    // Cut out the email
4405
    if ($email = $session->get('user-email')) {
4406
        $emailParts = explode('@', $email);
4407
4408
        if (count($emailParts) === 2) {
4409
            // Mail username (removed @domain.tld)
4410
            $forbiddenWords[] = $emailParts[0];
4411
4412
            // Organisation name (removed username@ and .tld)
4413
            $domain = explode('.', $emailParts[1]);
4414
            if (count($domain) > 1)
4415
                $forbiddenWords[] = $domain[0];
4416
        }
4417
    }
4418
4419
    // Search forbidden words in password
4420
    foreach ($forbiddenWords as $word) {
4421
        if (empty($word))
4422
            continue;
4423
4424
        // Stop if forbidden word found in password
4425
        if (stripos($password, $word) !== false)
4426
            return false;
4427
    }
4428
4429
    // Get password complexity
4430
    $length = strlen($password);
4431
    $hasUppercase = preg_match('/[A-Z]/', $password);
4432
    $hasLowercase = preg_match('/[a-z]/', $password);
4433
    $hasNumber = preg_match('/[0-9]/', $password);
4434
    $hasSpecialChar = preg_match('/[\W_]/', $password);
4435
4436
    // Get current user hash
4437
    $userHash = DB::queryFirstRow(
4438
        "SELECT pw FROM " . prefixtable('users') . " WHERE id = %d;",
4439
        $session->get('user-id')
4440
    )['pw'];
4441
4442
    $passwordManager = new PasswordManager();
4443
    
4444
    return $length >= 8
4445
           && $hasUppercase
4446
           && $hasLowercase
4447
           && ($hasNumber || $hasSpecialChar)
4448
           && !$passwordManager->verifyPassword($userHash, $password);
4449
}
4450