Passed
Pull Request — master (#4676)
by Nils
05:33
created

createUserTasks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 22
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 37
rs 9.568
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-2025 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
        error_log('TEAMPASS-Error-Wrong key or modified ciphertext: ' . $ex->getMessage());
138
        $err = 'wrong_key_or_modified_ciphertext';
139
    } catch (CryptoException\BadFormatException $ex) {
140
        error_log('TEAMPASS-Error-Bad format exception: ' . $ex->getMessage());
141
        $err = 'bad_format';
142
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
143
        error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage());
144
        $err = 'environment_error';
145
    } catch (CryptoException\IOException $ex) {
146
        error_log('TEAMPASS-Error-IO: ' . $ex->getMessage());
147
        $err = 'io_error';
148
    } catch (Exception $ex) {
149
        error_log('TEAMPASS-Error-Unexpected exception: ' . $ex->getMessage());
150
        $err = 'unexpected_error';
151
    }
152
153
    return [
154
        'string' => $text ?? '',
155
        'error' => $err,
156
    ];
157
}
158
159
/**
160
 * Generating a defuse key.
161
 *
162
 * @return string
163
 */
164
function defuse_generate_key()
165
{
166
    $key = Key::createNewRandomKey();
167
    $key = $key->saveToAsciiSafeString();
168
    return $key;
169
}
170
171
/**
172
 * Generate a Defuse personal key.
173
 *
174
 * @param string $psk psk used
175
 *
176
 * @return string
177
 */
178
function defuse_generate_personal_key(string $psk): string
179
{
180
    $protected_key = KeyProtectedByPassword::createRandomPasswordProtectedKey($psk);
181
    return $protected_key->saveToAsciiSafeString(); // save this in user table
182
}
183
184
/**
185
 * Validate persoanl key with defuse.
186
 *
187
 * @param string $psk                   the user's psk
188
 * @param string $protected_key_encoded special key
189
 *
190
 * @return string
191
 */
192
function defuse_validate_personal_key(string $psk, string $protected_key_encoded): string
193
{
194
    try {
195
        $protected_key_encoded = KeyProtectedByPassword::loadFromAsciiSafeString($protected_key_encoded);
196
        $user_key = $protected_key_encoded->unlockKey($psk);
197
        $user_key_encoded = $user_key->saveToAsciiSafeString();
198
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
199
        return 'Error - Major issue as the encryption is broken.';
200
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
201
        return 'Error - The saltkey is not the correct one.';
202
    }
203
204
    return $user_key_encoded;
205
    // store it in session once user has entered his psk
206
}
207
208
/**
209
 * Decrypt a defuse string if encrypted.
210
 *
211
 * @param string $value Encrypted string
212
 *
213
 * @return string Decrypted string
214
 */
215
function defuseReturnDecrypted(string $value, $SETTINGS): string
216
{
217
    if (substr($value, 0, 3) === 'def') {
218
        $value = cryption($value, '', 'decrypt', $SETTINGS)['string'];
219
    }
220
221
    return $value;
222
}
223
224
/**
225
 * Trims a string depending on a specific string.
226
 *
227
 * @param string|array $chaine  what to trim
228
 * @param string       $element trim on what
229
 *
230
 * @return string
231
 */
232
function trimElement($chaine, string $element): string
233
{
234
    if (! empty($chaine)) {
235
        if (is_array($chaine) === true) {
236
            $chaine = implode(';', $chaine);
237
        }
238
        $chaine = trim($chaine);
239
        if (substr($chaine, 0, 1) === $element) {
240
            $chaine = substr($chaine, 1);
241
        }
242
        if (substr($chaine, strlen($chaine) - 1, 1) === $element) {
243
            $chaine = substr($chaine, 0, strlen($chaine) - 1);
244
        }
245
    }
246
247
    return $chaine;
248
}
249
250
/**
251
 * Permits to suppress all "special" characters from string.
252
 *
253
 * @param string $string  what to clean
254
 * @param bool   $special use of special chars?
255
 *
256
 * @return string
257
 */
258
function cleanString(string $string, bool $special = false): string
259
{
260
    // Create temporary table for special characters escape
261
    $tabSpecialChar = [];
262
    for ($i = 0; $i <= 31; ++$i) {
263
        $tabSpecialChar[] = chr($i);
264
    }
265
    array_push($tabSpecialChar, '<br />');
266
    if ((int) $special === 1) {
267
        $tabSpecialChar = array_merge($tabSpecialChar, ['</li>', '<ul>', '<ol>']);
268
    }
269
270
    return str_replace($tabSpecialChar, "\n", $string);
271
}
272
273
/**
274
 * Erro manager for DB.
275
 *
276
 * @param array $params output from query
277
 *
278
 * @return void
279
 */
280
function db_error_handler(array $params): void
281
{
282
    echo 'Error: ' . $params['error'] . "<br>\n";
283
    echo 'Query: ' . $params['query'] . "<br>\n";
284
    throw new Exception('Error - Query', 1);
285
}
286
287
/**
288
 * Identify user's rights
289
 *
290
 * @param string|array $groupesVisiblesUser  [description]
291
 * @param string|array $groupesInterditsUser [description]
292
 * @param string       $isAdmin              [description]
293
 * @param string       $idFonctions          [description]
294
 *
295
 * @return bool
296
 */
297
function identifyUserRights(
298
    $groupesVisiblesUser,
299
    $groupesInterditsUser,
300
    $isAdmin,
301
    $idFonctions,
302
    $SETTINGS
303
) {
304
    $session = SessionManager::getSession();
305
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
306
307
    // Check if user is ADMINISTRATOR    
308
    (int) $isAdmin === 1 ?
309
        identAdmin(
310
            $idFonctions,
311
            $SETTINGS, /** @scrutinizer ignore-type */
312
            $tree
313
        )
314
        :
315
        identUser(
316
            $groupesVisiblesUser,
317
            $groupesInterditsUser,
318
            $idFonctions,
319
            $SETTINGS, /** @scrutinizer ignore-type */
320
            $tree
321
        );
322
323
    // update user's timestamp
324
    DB::update(
325
        prefixTable('users'),
326
        [
327
            'timestamp' => time(),
328
        ],
329
        'id=%i',
330
        $session->get('user-id')
331
    );
332
333
    return true;
334
}
335
336
/**
337
 * Identify administrator.
338
 *
339
 * @param string $idFonctions Roles of user
340
 * @param array  $SETTINGS    Teampass settings
341
 * @param object $tree        Tree of folders
342
 *
343
 * @return bool
344
 */
345
function identAdmin($idFonctions, $SETTINGS, $tree)
346
{
347
    
348
    $session = SessionManager::getSession();
349
    $groupesVisibles = [];
350
    $session->set('user-personal_folders', []);
351
    $session->set('user-accessible_folders', []);
352
    $session->set('user-no_access_folders', []);
353
    $session->set('user-personal_visible_folders', []);
354
    $session->set('user-read_only_folders', []);
355
    $session->set('system-list_restricted_folders_for_items', []);
356
    $session->set('system-list_folders_editable_by_role', []);
357
    $session->set('user-list_folders_limited', []);
358
    $session->set('user-forbiden_personal_folders', []);
359
    
360
    // Get list of Folders
361
    $rows = DB::query('SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i', 0);
362
    foreach ($rows as $record) {
363
        array_push($groupesVisibles, $record['id']);
364
    }
365
    $session->set('user-accessible_folders', $groupesVisibles);
366
    $session->set('user-all_non_personal_folders', $groupesVisibles);
367
368
    // get complete list of ROLES
369
    $tmp = explode(';', $idFonctions);
370
    $rows = DB::query(
371
        'SELECT * FROM ' . prefixTable('roles_title') . '
372
        ORDER BY title ASC'
373
    );
374
    foreach ($rows as $record) {
375
        if (! empty($record['id']) && ! in_array($record['id'], $tmp)) {
376
            array_push($tmp, $record['id']);
377
        }
378
    }
379
    $session->set('user-roles', implode(';', $tmp));
380
    $session->set('user-admin', 1);
381
    // Check if admin has created Folders and Roles
382
    DB::query('SELECT * FROM ' . prefixTable('nested_tree') . '');
383
    $session->set('user-nb_folders', DB::count());
384
    DB::query('SELECT * FROM ' . prefixTable('roles_title'));
385
    $session->set('user-nb_roles', DB::count());
386
387
    return true;
388
}
389
390
/**
391
 * Permits to convert an element to array.
392
 *
393
 * @param string|array $element Any value to be returned as array
394
 *
395
 * @return array
396
 */
397
function convertToArray($element): ?array
398
{
399
    if (is_string($element) === true) {
400
        if (empty($element) === true) {
401
            return [];
402
        }
403
        return explode(
404
            ';',
405
            trimElement($element, ';')
406
        );
407
    }
408
    return $element;
409
}
410
411
/**
412
 * Defines the rights the user has.
413
 *
414
 * @param string|array $allowedFolders  Allowed folders
415
 * @param string|array $noAccessFolders Not allowed folders
416
 * @param string|array $userRoles       Roles of user
417
 * @param array        $SETTINGS        Teampass settings
418
 * @param object       $tree            Tree of folders
419
 * 
420
 * @return bool
421
 */
422
function identUser(
423
    $allowedFolders,
424
    $noAccessFolders,
425
    $userRoles,
426
    array $SETTINGS,
427
    object $tree
428
) {
429
    $session = SessionManager::getSession();
430
    // Init
431
    $session->set('user-accessible_folders', []);
432
    $session->set('user-personal_folders', []);
433
    $session->set('user-no_access_folders', []);
434
    $session->set('user-personal_visible_folders', []);
435
    $session->set('user-read_only_folders', []);
436
    $session->set('user-user-roles', $userRoles);
437
    $session->set('user-admin', 0);
438
    // init
439
    $personalFolders = [];
440
    $readOnlyFolders = [];
441
    $noAccessPersonalFolders = [];
442
    $restrictedFoldersForItems = [];
443
    $foldersLimited = [];
444
    $foldersLimitedFull = [];
445
    $allowedFoldersByRoles = [];
446
    $globalsUserId = $session->get('user-id');
447
    $globalsPersonalFolders = $session->get('user-personal_folder_enabled');
448
    // Ensure consistency in array format
449
    $noAccessFolders = convertToArray($noAccessFolders);
450
    $userRoles = convertToArray($userRoles);
451
    $allowedFolders = convertToArray($allowedFolders);
452
    $session->set('user-allowed_folders_by_definition', $allowedFolders);
453
    
454
    // Get list of folders depending on Roles
455
    $arrays = identUserGetFoldersFromRoles(
456
        $userRoles,
457
        $allowedFoldersByRoles,
458
        $readOnlyFolders,
459
        $allowedFolders
460
    );
461
    $allowedFoldersByRoles = $arrays['allowedFoldersByRoles'];
462
    $readOnlyFolders = $arrays['readOnlyFolders'];
463
464
    // Does this user is allowed to see other items
465
    $inc = 0;
466
    $rows = DB::query(
467
        'SELECT id, id_tree FROM ' . prefixTable('items') . '
468
            WHERE restricted_to LIKE %ss AND inactif = %s'.
469
            (count($allowedFolders) > 0 ? ' AND id_tree NOT IN ('.implode(',', $allowedFolders).')' : ''),
470
        $globalsUserId,
471
        '0'
472
    );
473
    foreach ($rows as $record) {
474
        // Exclude restriction on item if folder is fully accessible
475
        //if (in_array($record['id_tree'], $allowedFolders) === false) {
476
            $restrictedFoldersForItems[$record['id_tree']][$inc] = $record['id'];
477
            ++$inc;
478
        //}
479
    }
480
481
    // Check for the users roles if some specific rights exist on items
482
    $rows = DB::query(
483
        'SELECT i.id_tree, r.item_id
484
        FROM ' . prefixTable('items') . ' as i
485
        INNER JOIN ' . prefixTable('restriction_to_roles') . ' as r ON (r.item_id=i.id)
486
        WHERE i.id_tree <> "" '.
487
        (count($userRoles) > 0 ? 'AND r.role_id IN %li ' : '').
488
        'ORDER BY i.id_tree ASC',
489
        $userRoles
490
    );
491
    $inc = 0;
492
    foreach ($rows as $record) {
493
        //if (isset($record['id_tree'])) {
494
            $foldersLimited[$record['id_tree']][$inc] = $record['item_id'];
495
            array_push($foldersLimitedFull, $record['id_tree']);
496
            ++$inc;
497
        //}
498
    }
499
500
    // Get list of Personal Folders
501
    $arrays = identUserGetPFList(
502
        $globalsPersonalFolders,
503
        $allowedFolders,
504
        $globalsUserId,
505
        $personalFolders,
506
        $noAccessPersonalFolders,
507
        $foldersLimitedFull,
508
        $allowedFoldersByRoles,
509
        array_keys($restrictedFoldersForItems),
510
        $readOnlyFolders,
511
        $noAccessFolders,
512
        isset($SETTINGS['enable_pf_feature']) === true ? $SETTINGS['enable_pf_feature'] : 0,
513
        $tree
514
    );
515
    $allowedFolders = $arrays['allowedFolders'];
516
    $personalFolders = $arrays['personalFolders'];
517
    $noAccessPersonalFolders = $arrays['noAccessPersonalFolders'];
518
519
    // Return data
520
    $session->set('user-all_non_personal_folders', $allowedFolders);
521
    $session->set('user-accessible_folders', array_unique(array_merge($allowedFolders, $personalFolders), SORT_NUMERIC));
522
    $session->set('user-read_only_folders', $readOnlyFolders);
523
    $session->set('user-no_access_folders', $noAccessFolders);
524
    $session->set('user-personal_folders', $personalFolders);
525
    $session->set('user-list_folders_limited', $foldersLimited);
526
    $session->set('system-list_folders_editable_by_role', $allowedFoldersByRoles, 'SESSION');
527
    $session->set('system-list_restricted_folders_for_items', $restrictedFoldersForItems);
528
    $session->set('user-forbiden_personal_folders', $noAccessPersonalFolders);
529
    $session->set(
530
        'all_folders_including_no_access',
531
        array_unique(array_merge(
532
            $allowedFolders,
533
            $personalFolders,
534
            $noAccessFolders,
535
            $readOnlyFolders
536
        ), SORT_NUMERIC)
537
    );
538
    // Folders and Roles numbers
539
    DB::queryFirstRow('SELECT id FROM ' . prefixTable('nested_tree') . '');
540
    $session->set('user-nb_folders', DB::count());
541
    DB::queryFirstRow('SELECT id FROM ' . prefixTable('roles_title'));
542
    $session->set('user-nb_roles', DB::count());
543
    // check if change proposals on User's items
544
    if (isset($SETTINGS['enable_suggestion']) === true && (int) $SETTINGS['enable_suggestion'] === 1) {
545
        $countNewItems = DB::query(
546
            'SELECT COUNT(*)
547
            FROM ' . prefixTable('items_change') . ' AS c
548
            LEFT JOIN ' . prefixTable('log_items') . ' AS i ON (c.item_id = i.id_item)
549
            WHERE i.action = %s AND i.id_user = %i',
550
            'at_creation',
551
            $globalsUserId
552
        );
553
        $session->set('user-nb_item_change_proposals', $countNewItems);
554
    } else {
555
        $session->set('user-nb_item_change_proposals', 0);
556
    }
557
558
    return true;
559
}
560
561
/**
562
 * Get list of folders depending on Roles
563
 * 
564
 * @param array $userRoles
565
 * @param array $allowedFoldersByRoles
566
 * @param array $readOnlyFolders
567
 * @param array $allowedFolders
568
 * 
569
 * @return array
570
 */
571
function identUserGetFoldersFromRoles(array $userRoles, array $allowedFoldersByRoles = [], array $readOnlyFolders = [], array $allowedFolders = []) : array
572
{
573
    $rows = DB::query(
574
        'SELECT *
575
        FROM ' . prefixTable('roles_values') . '
576
        WHERE type IN %ls'.(count($userRoles) > 0 ? ' AND role_id IN %li' : ''),
577
        ['W', 'ND', 'NE', 'NDNE', 'R'],
578
        $userRoles,
579
    );
580
    foreach ($rows as $record) {
581
        if ($record['type'] === 'R') {
582
            array_push($readOnlyFolders, $record['folder_id']);
583
        } elseif (in_array($record['folder_id'], $allowedFolders) === false) {
584
            array_push($allowedFoldersByRoles, $record['folder_id']);
585
        }
586
    }
587
    $allowedFoldersByRoles = array_unique($allowedFoldersByRoles);
588
    $readOnlyFolders = array_unique($readOnlyFolders);
589
    
590
    // Clean arrays
591
    foreach ($allowedFoldersByRoles as $value) {
592
        $key = array_search($value, $readOnlyFolders);
593
        if ($key !== false) {
594
            unset($readOnlyFolders[$key]);
595
        }
596
    }
597
    return [
598
        'readOnlyFolders' => $readOnlyFolders,
599
        'allowedFoldersByRoles' => $allowedFoldersByRoles
600
    ];
601
}
602
603
/**
604
 * Get list of Personal Folders
605
 * 
606
 * @param int $globalsPersonalFolders
607
 * @param array $allowedFolders
608
 * @param int $globalsUserId
609
 * @param array $personalFolders
610
 * @param array $noAccessPersonalFolders
611
 * @param array $foldersLimitedFull
612
 * @param array $allowedFoldersByRoles
613
 * @param array $restrictedFoldersForItems
614
 * @param array $readOnlyFolders
615
 * @param array $noAccessFolders
616
 * @param int $enablePfFeature
617
 * @param object $tree
618
 * 
619
 * @return array
620
 */
621
function identUserGetPFList(
622
    $globalsPersonalFolders,
623
    $allowedFolders,
624
    $globalsUserId,
625
    $personalFolders,
626
    $noAccessPersonalFolders,
627
    $foldersLimitedFull,
628
    $allowedFoldersByRoles,
629
    $restrictedFoldersForItems,
630
    $readOnlyFolders,
631
    $noAccessFolders,
632
    $enablePfFeature,
633
    $tree
634
)
635
{
636
    if (
637
        (int) $enablePfFeature === 1
638
        && (int) $globalsPersonalFolders === 1
639
    ) {
640
        $persoFld = DB::queryFirstRow(
641
            'SELECT id
642
            FROM ' . prefixTable('nested_tree') . '
643
            WHERE title = %s AND personal_folder = %i'.
644
            (count($allowedFolders) > 0 ? ' AND id NOT IN ('.implode(',', $allowedFolders).')' : ''),
645
            $globalsUserId,
646
            1
647
        );
648
        if (empty($persoFld['id']) === false) {
649
            array_push($personalFolders, $persoFld['id']);
650
            array_push($allowedFolders, $persoFld['id']);
651
            // get all descendants
652
            $ids = $tree->getDescendants($persoFld['id'], false, false, true);
653
            foreach ($ids as $id) {
654
                //array_push($allowedFolders, $id);
655
                array_push($personalFolders, $id);
656
            }
657
        }
658
    }
659
    
660
    // Exclude all other PF
661
    $where = new WhereClause('and');
662
    $where->add('personal_folder=%i', 1);
663
    if (count($personalFolders) > 0) {
664
        $where->add('id NOT IN ('.implode(',', $personalFolders).')');
665
    }
666
    if (
667
        (int) $enablePfFeature === 1
668
        && (int) $globalsPersonalFolders === 1
669
    ) {
670
        $where->add('title=%s', $globalsUserId);
671
        $where->negateLast();
672
    }
673
    $persoFlds = DB::query(
674
        'SELECT id
675
        FROM ' . prefixTable('nested_tree') . '
676
        WHERE %l',
677
        $where
678
    );
679
    foreach ($persoFlds as $persoFldId) {
680
        array_push($noAccessPersonalFolders, $persoFldId['id']);
681
    }
682
683
    // All folders visibles
684
    $allowedFolders = array_unique(array_merge(
685
        $allowedFolders,
686
        $foldersLimitedFull,
687
        $allowedFoldersByRoles,
688
        $restrictedFoldersForItems,
689
        $readOnlyFolders
690
    ), SORT_NUMERIC);
691
    // Exclude from allowed folders all the specific user forbidden folders
692
    if (count($noAccessFolders) > 0) {
693
        $allowedFolders = array_diff($allowedFolders, $noAccessFolders);
694
    }
695
696
    return [
697
        'allowedFolders' => array_diff(array_diff($allowedFolders, $noAccessPersonalFolders), $personalFolders),
698
        'personalFolders' => $personalFolders,
699
        'noAccessPersonalFolders' => $noAccessPersonalFolders
700
    ];
701
}
702
703
704
/**
705
 * Update the CACHE table.
706
 *
707
 * @param string $action   What to do
708
 * @param array  $SETTINGS Teampass settings
709
 * @param int    $ident    Ident format
710
 * 
711
 * @return void
712
 */
713
function updateCacheTable(string $action, ?int $ident = null): void
714
{
715
    if ($action === 'reload') {
716
        // Rebuild full cache table
717
        cacheTableRefresh();
718
    } elseif ($action === 'update_value' && is_null($ident) === false) {
719
        // UPDATE an item
720
        cacheTableUpdate($ident);
721
    } elseif ($action === 'add_value' && is_null($ident) === false) {
722
        // ADD an item
723
        cacheTableAdd($ident);
724
    } elseif ($action === 'delete_value' && is_null($ident) === false) {
725
        // DELETE an item
726
        DB::delete(prefixTable('cache'), 'id = %i', $ident);
727
    }
728
}
729
730
/**
731
 * Cache table - refresh.
732
 *
733
 * @return void
734
 */
735
function cacheTableRefresh(): void
736
{
737
    // Load class DB
738
    loadClasses('DB');
739
740
    //Load Tree
741
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
742
    // truncate table
743
    DB::query('TRUNCATE TABLE ' . prefixTable('cache'));
744
    // reload date
745
    $rows = DB::query(
746
        'SELECT *
747
        FROM ' . prefixTable('items') . ' as i
748
        INNER JOIN ' . prefixTable('log_items') . ' as l ON (l.id_item = i.id)
749
        AND l.action = %s
750
        AND i.inactif = %i',
751
        'at_creation',
752
        0
753
    );
754
    foreach ($rows as $record) {
755
        if (empty($record['id_tree']) === false) {
756
            // Get all TAGS
757
            $tags = '';
758
            $itemTags = DB::query(
759
                'SELECT tag
760
                FROM ' . prefixTable('tags') . '
761
                WHERE item_id = %i AND tag != ""',
762
                $record['id']
763
            );
764
            foreach ($itemTags as $itemTag) {
765
                $tags .= $itemTag['tag'] . ' ';
766
            }
767
768
            // Get renewal period
769
            $resNT = DB::queryFirstRow(
770
                'SELECT renewal_period
771
                FROM ' . prefixTable('nested_tree') . '
772
                WHERE id = %i',
773
                $record['id_tree']
774
            );
775
            // form id_tree to full foldername
776
            $folder = [];
777
            $arbo = $tree->getPath($record['id_tree'], true);
778
            foreach ($arbo as $elem) {
779
                // Check if title is the ID of a user
780
                if (is_numeric($elem->title) === true) {
781
                    // Is this a User id?
782
                    $user = DB::queryFirstRow(
783
                        'SELECT id, login
784
                        FROM ' . prefixTable('users') . '
785
                        WHERE id = %i',
786
                        $elem->title
787
                    );
788
                    if (count($user) > 0) {
789
                        $elem->title = $user['login'];
790
                    }
791
                }
792
                // Build path
793
                array_push($folder, stripslashes($elem->title));
794
            }
795
            // store data
796
            DB::insert(
797
                prefixTable('cache'),
798
                [
799
                    'id' => $record['id'],
800
                    'label' => $record['label'],
801
                    'description' => $record['description'] ?? '',
802
                    'url' => isset($record['url']) && ! empty($record['url']) ? $record['url'] : '0',
803
                    'tags' => $tags,
804
                    'id_tree' => $record['id_tree'],
805
                    'perso' => $record['perso'],
806
                    'restricted_to' => isset($record['restricted_to']) && ! empty($record['restricted_to']) ? $record['restricted_to'] : '0',
807
                    'login' => $record['login'] ?? '',
808
                    'folder' => implode(' > ', $folder),
809
                    'author' => $record['id_user'],
810
                    'renewal_period' => $resNT['renewal_period'] ?? '0',
811
                    'timestamp' => $record['date'],
812
                ]
813
            );
814
        }
815
    }
816
}
817
818
/**
819
 * Cache table - update existing value.
820
 *
821
 * @param int    $ident    Ident format
822
 * 
823
 * @return void
824
 */
825
function cacheTableUpdate(?int $ident = null): void
826
{
827
    $session = SessionManager::getSession();
828
    loadClasses('DB');
829
830
    //Load Tree
831
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
832
    // get new value from db
833
    $data = DB::queryFirstRow(
834
        'SELECT label, description, id_tree, perso, restricted_to, login, url
835
        FROM ' . prefixTable('items') . '
836
        WHERE id=%i',
837
        $ident
838
    );
839
    // Get all TAGS
840
    $tags = '';
841
    $itemTags = DB::query(
842
        'SELECT tag
843
            FROM ' . prefixTable('tags') . '
844
            WHERE item_id = %i AND tag != ""',
845
        $ident
846
    );
847
    foreach ($itemTags as $itemTag) {
848
        $tags .= $itemTag['tag'] . ' ';
849
    }
850
    // form id_tree to full foldername
851
    $folder = [];
852
    $arbo = $tree->getPath($data['id_tree'], true);
853
    foreach ($arbo as $elem) {
854
        // Check if title is the ID of a user
855
        if (is_numeric($elem->title) === true) {
856
            // Is this a User id?
857
            $user = DB::queryFirstRow(
858
                'SELECT id, login
859
                FROM ' . prefixTable('users') . '
860
                WHERE id = %i',
861
                $elem->title
862
            );
863
            if (count($user) > 0) {
864
                $elem->title = $user['login'];
865
            }
866
        }
867
        // Build path
868
        array_push($folder, stripslashes($elem->title));
869
    }
870
    // finaly update
871
    DB::update(
872
        prefixTable('cache'),
873
        [
874
            'label' => $data['label'],
875
            'description' => $data['description'],
876
            'tags' => $tags,
877
            'url' => isset($data['url']) && ! empty($data['url']) ? $data['url'] : '0',
878
            'id_tree' => $data['id_tree'],
879
            'perso' => $data['perso'],
880
            'restricted_to' => isset($data['restricted_to']) && ! empty($data['restricted_to']) ? $data['restricted_to'] : '0',
881
            'login' => $data['login'] ?? '',
882
            'folder' => implode(' » ', $folder),
883
            'author' => $session->get('user-id'),
884
        ],
885
        'id = %i',
886
        $ident
887
    );
888
}
889
890
/**
891
 * Cache table - add new value.
892
 *
893
 * @param int    $ident    Ident format
894
 * 
895
 * @return void
896
 */
897
function cacheTableAdd(?int $ident = null): void
898
{
899
    $session = SessionManager::getSession();
900
    $globalsUserId = $session->get('user-id');
901
902
    // Load class DB
903
    loadClasses('DB');
904
905
    //Load Tree
906
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
907
    // get new value from db
908
    $data = DB::queryFirstRow(
909
        'SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login, i.url, l.date
910
        FROM ' . prefixTable('items') . ' as i
911
        INNER JOIN ' . prefixTable('log_items') . ' as l ON (l.id_item = i.id)
912
        WHERE i.id = %i
913
        AND l.action = %s',
914
        $ident,
915
        'at_creation'
916
    );
917
    // Get all TAGS
918
    $tags = '';
919
    $itemTags = DB::query(
920
        'SELECT tag
921
            FROM ' . prefixTable('tags') . '
922
            WHERE item_id = %i AND tag != ""',
923
        $ident
924
    );
925
    foreach ($itemTags as $itemTag) {
926
        $tags .= $itemTag['tag'] . ' ';
927
    }
928
    // form id_tree to full foldername
929
    $folder = [];
930
    $arbo = $tree->getPath($data['id_tree'], true);
931
    foreach ($arbo as $elem) {
932
        // Check if title is the ID of a user
933
        if (is_numeric($elem->title) === true) {
934
            // Is this a User id?
935
            $user = DB::queryFirstRow(
936
                'SELECT id, login
937
                FROM ' . prefixTable('users') . '
938
                WHERE id = %i',
939
                $elem->title
940
            );
941
            if (count($user) > 0) {
942
                $elem->title = $user['login'];
943
            }
944
        }
945
        // Build path
946
        array_push($folder, stripslashes($elem->title));
947
    }
948
    // finaly update
949
    DB::insert(
950
        prefixTable('cache'),
951
        [
952
            'id' => $data['id'],
953
            'label' => $data['label'],
954
            'description' => $data['description'],
955
            'tags' => empty($tags) === false ? $tags : 'None',
956
            'url' => isset($data['url']) && ! empty($data['url']) ? $data['url'] : '0',
957
            'id_tree' => $data['id_tree'],
958
            'perso' => isset($data['perso']) && empty($data['perso']) === false && $data['perso'] !== 'None' ? $data['perso'] : '0',
959
            'restricted_to' => isset($data['restricted_to']) && empty($data['restricted_to']) === false ? $data['restricted_to'] : '0',
960
            'login' => $data['login'] ?? '',
961
            'folder' => implode(' » ', $folder),
962
            'author' => $globalsUserId,
963
            'timestamp' => $data['date'],
964
        ]
965
    );
966
}
967
968
/**
969
 * Do statistics.
970
 *
971
 * @param array $SETTINGS Teampass settings
972
 *
973
 * @return array
974
 */
975
function getStatisticsData(array $SETTINGS): array
976
{
977
    DB::query(
978
        'SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i',
979
        0
980
    );
981
    $counter_folders = DB::count();
982
    DB::query(
983
        'SELECT id FROM ' . prefixTable('nested_tree') . ' WHERE personal_folder = %i',
984
        1
985
    );
986
    $counter_folders_perso = DB::count();
987
    DB::query(
988
        'SELECT id FROM ' . prefixTable('items') . ' WHERE perso = %i',
989
        0
990
    );
991
    $counter_items = DB::count();
992
        DB::query(
993
        'SELECT id FROM ' . prefixTable('items') . ' WHERE perso = %i',
994
        1
995
    );
996
    $counter_items_perso = DB::count();
997
        DB::query(
998
        'SELECT id FROM ' . prefixTable('users') . ' WHERE login NOT IN (%s, %s, %s)',
999
        'OTV', 'TP', 'API'
1000
    );
1001
    $counter_users = DB::count();
1002
        DB::query(
1003
        'SELECT id FROM ' . prefixTable('users') . ' WHERE admin = %i',
1004
        1
1005
    );
1006
    $admins = DB::count();
1007
    DB::query(
1008
        'SELECT id FROM ' . prefixTable('users') . ' WHERE gestionnaire = %i',
1009
        1
1010
    );
1011
    $managers = DB::count();
1012
    DB::query(
1013
        'SELECT id FROM ' . prefixTable('users') . ' WHERE read_only = %i',
1014
        1
1015
    );
1016
    $readOnly = DB::count();
1017
    // list the languages
1018
    $usedLang = [];
1019
    $tp_languages = DB::query(
1020
        'SELECT name FROM ' . prefixTable('languages')
1021
    );
1022
    foreach ($tp_languages as $tp_language) {
1023
        DB::query(
1024
            'SELECT * FROM ' . prefixTable('users') . ' WHERE user_language = %s',
1025
            $tp_language['name']
1026
        );
1027
        $usedLang[$tp_language['name']] = round((DB::count() * 100 / $counter_users), 0);
1028
    }
1029
1030
    // get list of ips
1031
    $usedIp = [];
1032
    $tp_ips = DB::query(
1033
        'SELECT user_ip FROM ' . prefixTable('users')
1034
    );
1035
    foreach ($tp_ips as $ip) {
1036
        if (array_key_exists($ip['user_ip'], $usedIp)) {
1037
            $usedIp[$ip['user_ip']] += $usedIp[$ip['user_ip']];
1038
        } elseif (! empty($ip['user_ip']) && $ip['user_ip'] !== 'none') {
1039
            $usedIp[$ip['user_ip']] = 1;
1040
        }
1041
    }
1042
1043
    return [
1044
        'error' => '',
1045
        'stat_phpversion' => phpversion(),
1046
        'stat_folders' => $counter_folders,
1047
        'stat_folders_shared' => intval($counter_folders) - intval($counter_folders_perso),
1048
        'stat_items' => $counter_items,
1049
        'stat_items_shared' => intval($counter_items) - intval($counter_items_perso),
1050
        'stat_users' => $counter_users,
1051
        'stat_admins' => $admins,
1052
        'stat_managers' => $managers,
1053
        'stat_ro' => $readOnly,
1054
        'stat_kb' => $SETTINGS['enable_kb'],
1055
        'stat_pf' => $SETTINGS['enable_pf_feature'],
1056
        'stat_fav' => $SETTINGS['enable_favourites'],
1057
        'stat_teampassversion' => TP_VERSION,
1058
        'stat_ldap' => $SETTINGS['ldap_mode'],
1059
        'stat_agses' => $SETTINGS['agses_authentication_enabled'],
1060
        'stat_duo' => $SETTINGS['duo'],
1061
        'stat_suggestion' => $SETTINGS['enable_suggestion'],
1062
        'stat_api' => $SETTINGS['api'],
1063
        'stat_customfields' => $SETTINGS['item_extra_fields'],
1064
        'stat_syslog' => $SETTINGS['syslog_enable'],
1065
        'stat_2fa' => $SETTINGS['google_authentication'],
1066
        'stat_stricthttps' => $SETTINGS['enable_sts'],
1067
        'stat_mysqlversion' => DB::serverVersion(),
1068
        'stat_languages' => $usedLang,
1069
        'stat_country' => $usedIp,
1070
    ];
1071
}
1072
1073
/**
1074
 * Permits to prepare the way to send the email
1075
 * 
1076
 * @param string $subject       email subject
1077
 * @param string $body          email message
1078
 * @param string $email         email
1079
 * @param string $receiverName  Receiver name
1080
 * @param string $encryptedUserPassword      encryptedUserPassword
1081
 *
1082
 * @return void
1083
 */
1084
function prepareSendingEmail(
1085
    $subject,
1086
    $body,
1087
    $email,
1088
    $receiverName = '',
1089
    $encryptedUserPassword = ''
1090
): void 
1091
{
1092
    DB::insert(
1093
        prefixTable('background_tasks'),
1094
        array(
1095
            'created_at' => time(),
1096
            'process_type' => 'send_email',
1097
            'arguments' => json_encode([
1098
                'subject' => $subject,
1099
                'receivers' => $email,
1100
                'body' => $body,
1101
                'receiver_name' => $receiverName,
1102
                'encryptedUserPassword' => $encryptedUserPassword,
1103
            ], JSON_HEX_QUOT | JSON_HEX_TAG),
1104
        )
1105
    );
1106
}
1107
1108
/**
1109
 * Returns the email body.
1110
 *
1111
 * @param string $textMail Text for the email
1112
 */
1113
function emailBody(string $textMail): string
1114
{
1115
    return '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.=
1116
    w3.org/TR/html4/loose.dtd"><html>
1117
    <head><title>Email Template</title>
1118
    <style type="text/css">
1119
    body { background-color: #f0f0f0; padding: 10px 0; margin:0 0 10px =0; }
1120
    </style></head>
1121
    <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">
1122
    <table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#f0f0f0" style="border-spacing: 0;">
1123
    <tr><td style="border-collapse: collapse;"><br>
1124
        <table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#17357c" style="border-spacing: 0; margin-bottom: 25px;">
1125
        <tr><td style="border-collapse: collapse; padding: 11px 20px;">
1126
            <div style="max-width:150px; max-height:34px; color:#f0f0f0; font-weight:bold;">Teampass</div>
1127
        </td></tr></table></td>
1128
    </tr>
1129
    <tr><td align="center" valign="top" bgcolor="#f0f0f0" style="border-collapse: collapse; background-color: #f0f0f0;">
1130
        <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;">
1131
        <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;">
1132
        <br><div style="float:right;">' .
1133
        $textMail .
1134
        '<br><br></td></tr></table>
1135
    </td></tr></table>
1136
    <br></body></html>';
1137
}
1138
1139
/**
1140
 * Convert date to timestamp.
1141
 *
1142
 * @param string $date        The date
1143
 * @param string $date_format Date format
1144
 *
1145
 * @return int
1146
 */
1147
function dateToStamp(string $date, string $date_format): int
1148
{
1149
    $date = date_parse_from_format($date_format, $date);
1150
    if ((int) $date['warning_count'] === 0 && (int) $date['error_count'] === 0) {
1151
        return mktime(
1152
            empty($date['hour']) === false ? $date['hour'] : 23,
1153
            empty($date['minute']) === false ? $date['minute'] : 59,
1154
            empty($date['second']) === false ? $date['second'] : 59,
1155
            $date['month'],
1156
            $date['day'],
1157
            $date['year']
1158
        );
1159
    }
1160
    return 0;
1161
}
1162
1163
/**
1164
 * Is this a date.
1165
 *
1166
 * @param string $date Date
1167
 *
1168
 * @return bool
1169
 */
1170
function isDate(string $date): bool
1171
{
1172
    return strtotime($date) !== false;
1173
}
1174
1175
/**
1176
 * Check if isUTF8().
1177
 *
1178
 * @param string|array $string Is the string
1179
 *
1180
 * @return int is the string in UTF8 format
1181
 */
1182
function isUTF8($string): int
1183
{
1184
    if (is_array($string) === true) {
1185
        $string = $string['string'];
1186
    }
1187
1188
    return preg_match(
1189
        '%^(?:
1190
        [\x09\x0A\x0D\x20-\x7E] # ASCII
1191
        | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
1192
        | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
1193
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
1194
        | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
1195
        | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1196
        | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1197
        | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1198
        )*$%xs',
1199
        $string
1200
    );
1201
}
1202
1203
/**
1204
 * Prepare an array to UTF8 format before JSON_encode.
1205
 *
1206
 * @param array $array Array of values
1207
 *
1208
 * @return array
1209
 */
1210
function utf8Converter(array $array): array
1211
{
1212
    array_walk_recursive(
1213
        $array,
1214
        static function (&$item): void {
1215
            if (mb_detect_encoding((string) $item, 'utf-8', true) === false) {
1216
                $item = mb_convert_encoding($item, 'ISO-8859-1', 'UTF-8');
1217
            }
1218
        }
1219
    );
1220
    return $array;
1221
}
1222
1223
/**
1224
 * Permits to prepare data to be exchanged.
1225
 *
1226
 * @param array|string $data Text
1227
 * @param string       $type Parameter
1228
 * @param string       $key  Optional key
1229
 *
1230
 * @return string|array
1231
 */
1232
function prepareExchangedData($data, string $type, ?string $key = null)
1233
{
1234
    $session = SessionManager::getSession();
1235
    $key = empty($key) ? $session->get('key') : $key;
1236
    
1237
    // Perform
1238
    if ($type === 'encode' && is_array($data) === true) {
1239
        // json encoding
1240
        $data = json_encode(
1241
            $data,
1242
            JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
1243
        );
1244
1245
        // Now encrypt
1246
        if ($session->get('encryptClientServer') === 1) {
1247
            $data = Encryption::encrypt(
1248
                $data,
1249
                $key
1250
            );
1251
        }
1252
1253
        return $data;
1254
    }
1255
1256
    if ($type === 'decode' && is_array($data) === false) {
1257
        // Decrypt if needed
1258
        if ($session->get('encryptClientServer') === 1) {
1259
            $data = (string) Encryption::decrypt(
1260
                (string) $data,
1261
                $key
1262
            );
1263
        } else {
1264
            // Double html encoding received
1265
            $data = html_entity_decode(html_entity_decode(/** @scrutinizer ignore-type */$data)); // @codeCoverageIgnore Is always a string (not an array)
1266
        }
1267
1268
        // Check if $data is a valid string before json_decode
1269
        if (is_string($data) && !empty($data)) {
1270
            // Return data array
1271
            return json_decode($data, true);
1272
        }
1273
    }
1274
1275
    return '';
1276
}
1277
1278
1279
/**
1280
 * Create a thumbnail.
1281
 *
1282
 * @param string  $src           Source
1283
 * @param string  $dest          Destination
1284
 * @param int $desired_width Size of width
1285
 * 
1286
 * @return void|string|bool
1287
 */
1288
function makeThumbnail(string $src, string $dest, int $desired_width)
1289
{
1290
    /* read the source image */
1291
    if (is_file($src) === true && mime_content_type($src) === 'image/png') {
1292
        $source_image = imagecreatefrompng($src);
1293
        if ($source_image === false) {
1294
            return "Error: Not a valid PNG file! It's type is ".mime_content_type($src);
1295
        }
1296
    } else {
1297
        return "Error: Not a valid PNG file! It's type is ".mime_content_type($src);
1298
    }
1299
1300
    // Get height and width
1301
    $width = imagesx($source_image);
1302
    $height = imagesy($source_image);
1303
    /* find the "desired height" of this thumbnail, relative to the desired width  */
1304
    $desired_height = (int) floor($height * $desired_width / $width);
1305
    /* create a new, "virtual" image */
1306
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
1307
    if ($virtual_image === false) {
1308
        return false;
1309
    }
1310
    /* copy source image at a resized size */
1311
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
1312
    /* create the physical thumbnail image to its destination */
1313
    imagejpeg($virtual_image, $dest);
1314
}
1315
1316
/**
1317
 * Check table prefix in SQL query.
1318
 *
1319
 * @param string $table Table name
1320
 * 
1321
 * @return string
1322
 */
1323
function prefixTable(string $table): string
1324
{
1325
    $safeTable = htmlspecialchars(DB_PREFIX . $table);
1326
    if (empty($safeTable) === false) {
1327
        // sanitize string
1328
        return $safeTable;
1329
    }
1330
    // stop error no table
1331
    return 'table_not_exists';
1332
}
1333
1334
/**
1335
 * GenerateCryptKey
1336
 *
1337
 * @param int     $size      Length
1338
 * @param bool $secure Secure
1339
 * @param bool $numerals Numerics
1340
 * @param bool $uppercase Uppercase letters
1341
 * @param bool $symbols Symbols
1342
 * @param bool $lowercase Lowercase
1343
 * 
1344
 * @return string
1345
 */
1346
function GenerateCryptKey(
1347
    int $size = 20,
1348
    bool $secure = false,
1349
    bool $numerals = false,
1350
    bool $uppercase = false,
1351
    bool $symbols = false,
1352
    bool $lowercase = false
1353
): string {
1354
    $generator = new ComputerPasswordGenerator();
1355
    $generator->setRandomGenerator(new Php7RandomGenerator());
1356
    
1357
    // Manage size
1358
    $generator->setLength((int) $size);
1359
    if ($secure === true) {
1360
        $generator->setSymbols(true);
1361
        $generator->setLowercase(true);
1362
        $generator->setUppercase(true);
1363
        $generator->setNumbers(true);
1364
    } else {
1365
        $generator->setLowercase($lowercase);
1366
        $generator->setUppercase($uppercase);
1367
        $generator->setNumbers($numerals);
1368
        $generator->setSymbols($symbols);
1369
    }
1370
1371
    return $generator->generatePasswords()[0];
1372
}
1373
1374
/**
1375
 * GenerateGenericPassword
1376
 *
1377
 * @param int     $size      Length
1378
 * @param bool $secure Secure
1379
 * @param bool $numerals Numerics
1380
 * @param bool $uppercase Uppercase letters
1381
 * @param bool $symbols Symbols
1382
 * @param bool $lowercase Lowercase
1383
 * @param array   $SETTINGS  SETTINGS
1384
 * 
1385
 * @return string
1386
 */
1387
function generateGenericPassword(
1388
    int $size,
1389
    bool $secure,
1390
    bool $lowercase,
1391
    bool $capitalize,
1392
    bool $numerals,
1393
    bool $symbols,
1394
    array $SETTINGS
1395
): string
1396
{
1397
    if ((int) $size > (int) $SETTINGS['pwd_maximum_length']) {
1398
        return prepareExchangedData(
1399
            array(
1400
                'error_msg' => 'Password length is too long! ',
1401
                'error' => 'true',
1402
            ),
1403
            'encode'
1404
        );
1405
    }
1406
    // Load libraries
1407
    $generator = new ComputerPasswordGenerator();
1408
    $generator->setRandomGenerator(new Php7RandomGenerator());
1409
1410
    // Manage size
1411
    $generator->setLength(($size <= 0) ? 10 : $size);
1412
1413
    if ($secure === true) {
1414
        $generator->setSymbols(true);
1415
        $generator->setLowercase(true);
1416
        $generator->setUppercase(true);
1417
        $generator->setNumbers(true);
1418
    } else {
1419
        $generator->setLowercase($lowercase);
1420
        $generator->setUppercase($capitalize);
1421
        $generator->setNumbers($numerals);
1422
        $generator->setSymbols($symbols);
1423
    }
1424
1425
    return prepareExchangedData(
1426
        array(
1427
            'key' => $generator->generatePasswords(),
1428
            'error' => '',
1429
        ),
1430
        'encode'
1431
    );
1432
}
1433
1434
/**
1435
 * Send sysLOG message
1436
 *
1437
 * @param string    $message
1438
 * @param string    $host
1439
 * @param int       $port
1440
 * @param string    $component
1441
 * 
1442
 * @return void
1443
*/
1444
function send_syslog($message, $host, $port, $component = 'teampass'): void
1445
{
1446
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1447
    $syslog_message = '<123>' . date('M d H:i:s ') . $component . ': ' . $message;
1448
    socket_sendto($sock, (string) $syslog_message, strlen($syslog_message), 0, (string) $host, (int) $port);
1449
    socket_close($sock);
1450
}
1451
1452
/**
1453
 * Permits to log events into DB
1454
 *
1455
 * @param array  $SETTINGS Teampass settings
1456
 * @param string $type     Type
1457
 * @param string $label    Label
1458
 * @param string $who      Who
1459
 * @param string $login    Login
1460
 * @param string|int $field_1  Field
1461
 * 
1462
 * @return void
1463
 */
1464
function logEvents(
1465
    array $SETTINGS, 
1466
    string $type, 
1467
    string $label, 
1468
    string $who, 
1469
    ?string $login = null, 
1470
    $field_1 = null
1471
): void
1472
{
1473
    if (empty($who)) {
1474
        $who = getClientIpServer();
1475
    }
1476
1477
    // Load class DB
1478
    loadClasses('DB');
1479
1480
    DB::insert(
1481
        prefixTable('log_system'),
1482
        [
1483
            'type' => $type,
1484
            'date' => time(),
1485
            'label' => $label,
1486
            'qui' => $who,
1487
            'field_1' => $field_1 === null ? '' : $field_1,
1488
        ]
1489
    );
1490
    // If SYSLOG
1491
    if (isset($SETTINGS['syslog_enable']) === true && (int) $SETTINGS['syslog_enable'] === 1) {
1492
        if ($type === 'user_mngt') {
1493
            send_syslog(
1494
                'action=' . str_replace('at_', '', $label) . ' attribute=user user=' . $who . ' userid="' . $login . '" change="' . $field_1 . '" ',
1495
                $SETTINGS['syslog_host'],
1496
                $SETTINGS['syslog_port'],
1497
                'teampass'
1498
            );
1499
        } else {
1500
            send_syslog(
1501
                'action=' . $type . ' attribute=' . $label . ' user=' . $who . ' userid="' . $login . '" ',
1502
                $SETTINGS['syslog_host'],
1503
                $SETTINGS['syslog_port'],
1504
                'teampass'
1505
            );
1506
        }
1507
    }
1508
}
1509
1510
/**
1511
 * Log events.
1512
 *
1513
 * @param array  $SETTINGS        Teampass settings
1514
 * @param int    $item_id         Item id
1515
 * @param string $item_label      Item label
1516
 * @param int    $id_user         User id
1517
 * @param string $action          Code for reason
1518
 * @param string $login           User login
1519
 * @param string $raison          Code for reason
1520
 * @param string $encryption_type Encryption on
1521
 * @param string $time Encryption Time
1522
 * @param string $old_value       Old value
1523
 * 
1524
 * @return void
1525
 */
1526
function logItems(
1527
    array $SETTINGS,
1528
    int $item_id,
1529
    string $item_label,
1530
    int $id_user,
1531
    string $action,
1532
    ?string $login = null,
1533
    ?string $raison = null,
1534
    ?string $encryption_type = null,
1535
    ?string $time = null,
1536
    ?string $old_value = null
1537
): void {
1538
    // Load class DB
1539
    loadClasses('DB');
1540
1541
    // Insert log in DB
1542
    DB::insert(
1543
        prefixTable('log_items'),
1544
        [
1545
            'id_item' => $item_id,
1546
            'date' => is_null($time) === true ? time() : $time,
1547
            'id_user' => $id_user,
1548
            'action' => $action,
1549
            'raison' => $raison,
1550
            'old_value' => $old_value,
1551
            'encryption_type' => is_null($encryption_type) === true ? TP_ENCRYPTION_NAME : $encryption_type,
1552
        ]
1553
    );
1554
    // Timestamp the last change
1555
    if (in_array($action, ['at_creation', 'at_modifiation', 'at_delete', 'at_import'], true)) {
1556
        DB::update(
1557
            prefixTable('misc'),
1558
            [
1559
                'valeur' => time(),
1560
                'updated_at' => time(),
1561
            ],
1562
            'type = %s AND intitule = %s',
1563
            'timestamp',
1564
            'last_item_change'
1565
        );
1566
    }
1567
1568
    // SYSLOG
1569
    if (isset($SETTINGS['syslog_enable']) === true && (int) $SETTINGS['syslog_enable'] === 1) {
1570
        // Extract reason
1571
        $attribute = is_null($raison) === true ? Array('') : explode(' : ', $raison);
1572
        // Get item info if not known
1573
        if (empty($item_label) === true) {
1574
            $dataItem = DB::queryFirstRow(
1575
                'SELECT id, id_tree, label
1576
                FROM ' . prefixTable('items') . '
1577
                WHERE id = %i',
1578
                $item_id
1579
            );
1580
            $item_label = $dataItem['label'];
1581
        }
1582
1583
        send_syslog(
1584
            'action=' . str_replace('at_', '', $action) .
1585
                ' attribute=' . str_replace('at_', '', $attribute[0]) .
1586
                ' itemno=' . $item_id .
1587
                ' user=' . (is_null($login) === true ? '' : addslashes((string) $login)) .
1588
                ' itemname="' . addslashes($item_label) . '"',
1589
            $SETTINGS['syslog_host'],
1590
            $SETTINGS['syslog_port'],
1591
            'teampass'
1592
        );
1593
    }
1594
1595
    // send notification if enabled
1596
    //notifyOnChange($item_id, $action, $SETTINGS);
1597
}
1598
1599
/**
1600
 * Prepare notification email to subscribers.
1601
 *
1602
 * @param int    $item_id  Item id
1603
 * @param string $label    Item label
1604
 * @param array  $changes  List of changes
1605
 * @param array  $SETTINGS Teampass settings
1606
 * 
1607
 * @return void
1608
 */
1609
function notifyChangesToSubscribers(int $item_id, string $label, array $changes, array $SETTINGS): void
1610
{
1611
    $session = SessionManager::getSession();
1612
    $lang = new Language($session->get('user-language') ?? 'english');
1613
    $globalsUserId = $session->get('user-id');
1614
    $globalsLastname = $session->get('user-lastname');
1615
    $globalsName = $session->get('user-name');
1616
    // send email to user that what to be notified
1617
    $notification = DB::queryFirstColumn(
1618
        'SELECT email
1619
        FROM ' . prefixTable('notification') . ' AS n
1620
        INNER JOIN ' . prefixTable('users') . ' AS u ON (n.user_id = u.id)
1621
        WHERE n.item_id = %i AND n.user_id != %i',
1622
        $item_id,
1623
        $globalsUserId
1624
    );
1625
    if (DB::count() > 0) {
1626
        // Prepare path
1627
        $path = geItemReadablePath($item_id, '', $SETTINGS);
1628
        // Get list of changes
1629
        $htmlChanges = '<ul>';
1630
        foreach ($changes as $change) {
1631
            $htmlChanges .= '<li>' . $change . '</li>';
1632
        }
1633
        $htmlChanges .= '</ul>';
1634
        // send email
1635
        DB::insert(
1636
            prefixTable('emails'),
1637
            [
1638
                'timestamp' => time(),
1639
                'subject' => $lang->get('email_subject_item_updated'),
1640
                'body' => str_replace(
1641
                    ['#item_label#', '#folder_name#', '#item_id#', '#url#', '#name#', '#lastname#', '#changes#'],
1642
                    [$label, $path, $item_id, $SETTINGS['cpassman_url'], $globalsName, $globalsLastname, $htmlChanges],
1643
                    $lang->get('email_body_item_updated')
1644
                ),
1645
                'receivers' => implode(',', $notification),
1646
                'status' => '',
1647
            ]
1648
        );
1649
    }
1650
}
1651
1652
/**
1653
 * Returns the Item + path.
1654
 *
1655
 * @param int    $id_tree  Node id
1656
 * @param string $label    Label
1657
 * @param array  $SETTINGS TP settings
1658
 * 
1659
 * @return string
1660
 */
1661
function geItemReadablePath(int $id_tree, string $label, array $SETTINGS): string
1662
{
1663
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
1664
    $arbo = $tree->getPath($id_tree, true);
1665
    $path = '';
1666
    foreach ($arbo as $elem) {
1667
        if (empty($path) === true) {
1668
            $path = htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES) . ' ';
1669
        } else {
1670
            $path .= '&#8594; ' . htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES);
1671
        }
1672
    }
1673
1674
    // Build text to show user
1675
    if (empty($label) === false) {
1676
        return empty($path) === true ? addslashes($label) : addslashes($label) . ' (' . $path . ')';
1677
    }
1678
    return empty($path) === true ? '' : $path;
1679
}
1680
1681
/**
1682
 * Get the client ip address.
1683
 *
1684
 * @return string IP address
1685
 */
1686
function getClientIpServer(): string
1687
{
1688
    if (getenv('HTTP_CLIENT_IP')) {
1689
        $ipaddress = getenv('HTTP_CLIENT_IP');
1690
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
1691
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
1692
    } elseif (getenv('HTTP_X_FORWARDED')) {
1693
        $ipaddress = getenv('HTTP_X_FORWARDED');
1694
    } elseif (getenv('HTTP_FORWARDED_FOR')) {
1695
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
1696
    } elseif (getenv('HTTP_FORWARDED')) {
1697
        $ipaddress = getenv('HTTP_FORWARDED');
1698
    } elseif (getenv('REMOTE_ADDR')) {
1699
        $ipaddress = getenv('REMOTE_ADDR');
1700
    } else {
1701
        $ipaddress = 'UNKNOWN';
1702
    }
1703
1704
    return $ipaddress;
1705
}
1706
1707
/**
1708
 * Escape all HTML, JavaScript, and CSS.
1709
 *
1710
 * @param string $input    The input string
1711
 * @param string $encoding Which character encoding are we using?
1712
 * 
1713
 * @return string
1714
 */
1715
function noHTML(string $input, string $encoding = 'UTF-8'): string
1716
{
1717
    return htmlspecialchars($input, ENT_QUOTES | ENT_XHTML, $encoding, false);
1718
}
1719
1720
/**
1721
 * Rebuilds the Teampass config file.
1722
 *
1723
 * @param string $configFilePath Path to the config file.
1724
 * @param array  $settings       Teampass settings.
1725
 *
1726
 * @return string|bool
1727
 */
1728
function rebuildConfigFile(string $configFilePath, array $settings)
1729
{
1730
    // Perform a copy if the file exists
1731
    if (file_exists($configFilePath)) {
1732
        $backupFilePath = $configFilePath . '.' . date('Y_m_d_His', time());
1733
        if (!copy($configFilePath, $backupFilePath)) {
1734
            return "ERROR: Could not copy file '$configFilePath'";
1735
        }
1736
    }
1737
1738
    // Regenerate the config file
1739
    $data = ["<?php\n", "global \$SETTINGS;\n", "\$SETTINGS = array (\n"];
1740
    $rows = DB::query('SELECT * FROM ' . prefixTable('misc') . ' WHERE type=%s', 'admin');
1741
    foreach ($rows as $record) {
1742
        $value = getEncryptedValue($record['valeur'], $record['is_encrypted']);
1743
        $data[] = "    '{$record['intitule']}' => '". htmlspecialchars_decode($value, ENT_COMPAT) . "',\n";
1744
    }
1745
    $data[] = ");\n";
1746
    $data = array_unique($data);
1747
1748
    // Update the file
1749
    file_put_contents($configFilePath, implode('', $data));
1750
1751
    return true;
1752
}
1753
1754
/**
1755
 * Returns the encrypted value if needed.
1756
 *
1757
 * @param string $value       Value to encrypt.
1758
 * @param int   $isEncrypted Is the value encrypted?
1759
 *
1760
 * @return string
1761
 */
1762
function getEncryptedValue(string $value, int $isEncrypted): string
1763
{
1764
    return $isEncrypted ? cryption($value, '', 'encrypt')['string'] : $value;
1765
}
1766
1767
/**
1768
 * Permits to replace &#92; to permit correct display
1769
 *
1770
 * @param string $input Some text
1771
 * 
1772
 * @return string
1773
 */
1774
function handleBackslash(string $input): string
1775
{
1776
    return str_replace('&amp;#92;', '&#92;', $input);
1777
}
1778
1779
/**
1780
 * Permits to load settings
1781
 * 
1782
 * @return void
1783
*/
1784
function loadSettings(): void
1785
{
1786
    global $SETTINGS;
1787
    /* LOAD CPASSMAN SETTINGS */
1788
    if (! isset($SETTINGS['loaded']) || $SETTINGS['loaded'] !== 1) {
1789
        $SETTINGS = [];
1790
        $SETTINGS['duplicate_folder'] = 0;
1791
        //by default, this is set to 0;
1792
        $SETTINGS['duplicate_item'] = 0;
1793
        //by default, this is set to 0;
1794
        $SETTINGS['number_of_used_pw'] = 5;
1795
        //by default, this value is set to 5;
1796
        $settings = [];
1797
        $rows = DB::query(
1798
            'SELECT * FROM ' . prefixTable('misc') . ' WHERE type=%s_type OR type=%s_type2',
1799
            [
1800
                'type' => 'admin',
1801
                'type2' => 'settings',
1802
            ]
1803
        );
1804
        foreach ($rows as $record) {
1805
            if ($record['type'] === 'admin') {
1806
                $SETTINGS[$record['intitule']] = $record['valeur'];
1807
            } else {
1808
                $settings[$record['intitule']] = $record['valeur'];
1809
            }
1810
        }
1811
        $SETTINGS['loaded'] = 1;
1812
        $SETTINGS['default_session_expiration_time'] = 5;
1813
    }
1814
}
1815
1816
/**
1817
 * check if folder has custom fields.
1818
 * Ensure that target one also has same custom fields
1819
 * 
1820
 * @param int $source_id
1821
 * @param int $target_id 
1822
 * 
1823
 * @return bool
1824
*/
1825
function checkCFconsistency(int $source_id, int $target_id): bool
1826
{
1827
    $source_cf = [];
1828
    $rows = DB::query(
1829
        'SELECT id_category
1830
            FROM ' . prefixTable('categories_folders') . '
1831
            WHERE id_folder = %i',
1832
        $source_id
1833
    );
1834
    foreach ($rows as $record) {
1835
        array_push($source_cf, $record['id_category']);
1836
    }
1837
1838
    $target_cf = [];
1839
    $rows = DB::QUERY(
1840
        'SELECT id_category
1841
            FROM ' . prefixTable('categories_folders') . '
1842
            WHERE id_folder = %i',
1843
        $target_id
1844
    );
1845
    foreach ($rows as $record) {
1846
        array_push($target_cf, $record['id_category']);
1847
    }
1848
1849
    $cf_diff = array_diff($source_cf, $target_cf);
1850
    if (count($cf_diff) > 0) {
1851
        return false;
1852
    }
1853
1854
    return true;
1855
}
1856
1857
/**
1858
 * Will encrypte/decrypt a fil eusing Defuse.
1859
 *
1860
 * @param string $type        can be either encrypt or decrypt
1861
 * @param string $source_file path to source file
1862
 * @param string $target_file path to target file
1863
 * @param array  $SETTINGS    Settings
1864
 * @param string $password    A password
1865
 *
1866
 * @return string|bool
1867
 */
1868
function prepareFileWithDefuse(
1869
    string $type,
1870
    string $source_file,
1871
    string $target_file,
1872
    string $password = null
1873
) {
1874
    // Load AntiXSS
1875
    $antiXss = new AntiXSS();
1876
    // Protect against bad inputs
1877
    if (is_array($source_file) === true || is_array($target_file) === true) {
1878
        return 'error_cannot_be_array';
1879
    }
1880
1881
    // Sanitize
1882
    $source_file = $antiXss->xss_clean($source_file);
1883
    $target_file = $antiXss->xss_clean($target_file);
1884
    if (empty($password) === true || is_null($password) === true) {
1885
        // get KEY to define password
1886
        $ascii_key = file_get_contents(SECUREPATH.'/'.SECUREFILE);
1887
        $password = Key::loadFromAsciiSafeString($ascii_key);
1888
    }
1889
1890
    $err = '';
1891
    if ($type === 'decrypt') {
1892
        // Decrypt file
1893
        $err = defuseFileDecrypt(
1894
            $source_file,
1895
            $target_file,
1896
            $password
0 ignored issues
show
Bug introduced by
It seems like $password can also be of type Defuse\Crypto\Key; however, parameter $password of defuseFileDecrypt() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1896
            /** @scrutinizer ignore-type */ $password
Loading history...
1897
        );
1898
    } elseif ($type === 'encrypt') {
1899
        // Encrypt file
1900
        $err = defuseFileEncrypt(
1901
            $source_file,
1902
            $target_file,
1903
            $password
0 ignored issues
show
Bug introduced by
It seems like $password can also be of type Defuse\Crypto\Key; however, parameter $password of defuseFileEncrypt() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1903
            /** @scrutinizer ignore-type */ $password
Loading history...
1904
        );
1905
    }
1906
1907
    // return error
1908
    return $err === true ? $err : '';
1909
}
1910
1911
/**
1912
 * Encrypt a file with Defuse.
1913
 *
1914
 * @param string $source_file path to source file
1915
 * @param string $target_file path to target file
1916
 * @param array  $SETTINGS    Settings
1917
 * @param string $password    A password
1918
 *
1919
 * @return string|bool
1920
 */
1921
function defuseFileEncrypt(
1922
    string $source_file,
1923
    string $target_file,
1924
    string $password = null
1925
) {
1926
    $err = '';
1927
    try {
1928
        CryptoFile::encryptFileWithPassword(
1929
            $source_file,
1930
            $target_file,
1931
            $password
1932
        );
1933
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1934
        $err = 'wrong_key';
1935
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1936
        error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage());
1937
        $err = 'environment_error';
1938
    } catch (CryptoException\IOException $ex) {
1939
        error_log('TEAMPASS-Error-General: ' . $ex->getMessage());
1940
        $err = 'general_error';
1941
    }
1942
1943
    // return error
1944
    return empty($err) === false ? $err : true;
1945
}
1946
1947
/**
1948
 * Decrypt a file with Defuse.
1949
 *
1950
 * @param string $source_file path to source file
1951
 * @param string $target_file path to target file
1952
 * @param array  $SETTINGS    Settings
1953
 * @param string $password    A password
1954
 *
1955
 * @return string|bool
1956
 */
1957
function defuseFileDecrypt(
1958
    string $source_file,
1959
    string $target_file,
1960
    string $password = null
1961
) {
1962
    $err = '';
1963
    try {
1964
        CryptoFile::decryptFileWithPassword(
1965
            $source_file,
1966
            $target_file,
1967
            $password
1968
        );
1969
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1970
        $err = 'wrong_key';
1971
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1972
        error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage());
1973
        $err = 'environment_error';
1974
    } catch (CryptoException\IOException $ex) {
1975
        error_log('TEAMPASS-Error-General: ' . $ex->getMessage());
1976
        $err = 'general_error';
1977
    }
1978
1979
    // return error
1980
    return empty($err) === false ? $err : true;
1981
}
1982
1983
/*
1984
* NOT TO BE USED
1985
*/
1986
/**
1987
 * Undocumented function.
1988
 *
1989
 * @param string $text Text to debug
1990
 */
1991
function debugTeampass(string $text): void
1992
{
1993
    $debugFile = fopen('D:/wamp64/www/TeamPass/debug.txt', 'r+');
1994
    if ($debugFile !== false) {
1995
        fputs($debugFile, $text);
1996
        fclose($debugFile);
1997
    }
1998
}
1999
2000
/**
2001
 * DELETE the file with expected command depending on server type.
2002
 *
2003
 * @param string $file     Path to file
2004
 * @param array  $SETTINGS Teampass settings
2005
 *
2006
 * @return void
2007
 */
2008
function fileDelete(string $file, array $SETTINGS): void
2009
{
2010
    // Load AntiXSS
2011
    $antiXss = new AntiXSS();
2012
    $file = $antiXss->xss_clean($file);
2013
    if (is_file($file)) {
2014
        unlink($file);
2015
    }
2016
}
2017
2018
/**
2019
 * Permits to extract the file extension.
2020
 *
2021
 * @param string $file File name
2022
 *
2023
 * @return string
2024
 */
2025
function getFileExtension(string $file): string
2026
{
2027
    if (strpos($file, '.') === false) {
2028
        return $file;
2029
    }
2030
2031
    return substr($file, strrpos($file, '.') + 1);
2032
}
2033
2034
/**
2035
 * Chmods files and folders with different permissions.
2036
 *
2037
 * This is an all-PHP alternative to using: \n
2038
 * <tt>exec("find ".$path." -type f -exec chmod 644 {} \;");</tt> \n
2039
 * <tt>exec("find ".$path." -type d -exec chmod 755 {} \;");</tt>
2040
 *
2041
 * @author Jeppe Toustrup (tenzer at tenzer dot dk)
2042
  *
2043
 * @param string $path      An either relative or absolute path to a file or directory which should be processed.
2044
 * @param int    $filePerm The permissions any found files should get.
2045
 * @param int    $dirPerm  The permissions any found folder should get.
2046
 *
2047
 * @return bool Returns TRUE if the path if found and FALSE if not.
2048
 *
2049
 * @warning The permission levels has to be entered in octal format, which
2050
 * normally means adding a zero ("0") in front of the permission level. \n
2051
 * More info at: http://php.net/chmod.
2052
*/
2053
2054
function recursiveChmod(
2055
    string $path,
2056
    int $filePerm = 0644,
2057
    int  $dirPerm = 0755
2058
) {
2059
    // Check if the path exists
2060
    $path = basename($path);
2061
    if (! file_exists($path)) {
2062
        return false;
2063
    }
2064
2065
    // See whether this is a file
2066
    if (is_file($path)) {
2067
        // Chmod the file with our given filepermissions
2068
        try {
2069
            chmod($path, $filePerm);
2070
        } catch (Exception $e) {
2071
            return false;
2072
        }
2073
    // If this is a directory...
2074
    } elseif (is_dir($path)) {
2075
        // Then get an array of the contents
2076
        $foldersAndFiles = scandir($path);
2077
        // Remove "." and ".." from the list
2078
        $entries = array_slice($foldersAndFiles, 2);
2079
        // Parse every result...
2080
        foreach ($entries as $entry) {
2081
            // And call this function again recursively, with the same permissions
2082
            recursiveChmod($path.'/'.$entry, $filePerm, $dirPerm);
2083
        }
2084
2085
        // When we are done with the contents of the directory, we chmod the directory itself
2086
        try {
2087
            chmod($path, $filePerm);
2088
        } catch (Exception $e) {
2089
            return false;
2090
        }
2091
    }
2092
2093
    // Everything seemed to work out well, return true
2094
    return true;
2095
}
2096
2097
/**
2098
 * Check if user can access to this item.
2099
 *
2100
 * @param int   $item_id ID of item
2101
 * @param array $SETTINGS
2102
 *
2103
 * @return bool|string
2104
 */
2105
function accessToItemIsGranted(int $item_id, array $SETTINGS)
2106
{
2107
    
2108
    $session = SessionManager::getSession();
2109
    $session_groupes_visibles = $session->get('user-accessible_folders');
2110
    $session_list_restricted_folders_for_items = $session->get('system-list_restricted_folders_for_items');
2111
    // Load item data
2112
    $data = DB::queryFirstRow(
2113
        'SELECT id_tree
2114
        FROM ' . prefixTable('items') . '
2115
        WHERE id = %i',
2116
        $item_id
2117
    );
2118
    // Check if user can access this folder
2119
    if (in_array($data['id_tree'], $session_groupes_visibles) === false) {
2120
        // Now check if this folder is restricted to user
2121
        if (isset($session_list_restricted_folders_for_items[$data['id_tree']]) === true
2122
            && in_array($item_id, $session_list_restricted_folders_for_items[$data['id_tree']]) === false
2123
        ) {
2124
            return 'ERR_FOLDER_NOT_ALLOWED';
2125
        }
2126
    }
2127
2128
    return true;
2129
}
2130
2131
/**
2132
 * Creates a unique key.
2133
 *
2134
 * @param int $lenght Key lenght
2135
 *
2136
 * @return string
2137
 */
2138
function uniqidReal(int $lenght = 13): string
2139
{
2140
    if (function_exists('random_bytes')) {
2141
        $bytes = random_bytes(intval(ceil($lenght / 2)));
2142
    } elseif (function_exists('openssl_random_pseudo_bytes')) {
2143
        $bytes = openssl_random_pseudo_bytes(intval(ceil($lenght / 2)));
2144
    } else {
2145
        throw new Exception('no cryptographically secure random function available');
2146
    }
2147
2148
    return substr(bin2hex($bytes), 0, $lenght);
2149
}
2150
2151
/**
2152
 * Obfuscate an email.
2153
 *
2154
 * @param string $email Email address
2155
 *
2156
 * @return string
2157
 */
2158
function obfuscateEmail(string $email): string
2159
{
2160
    $email = explode("@", $email);
2161
    $name = $email[0];
2162
    if (strlen($name) > 3) {
2163
        $name = substr($name, 0, 2);
2164
        for ($i = 0; $i < strlen($email[0]) - 3; $i++) {
2165
            $name .= "*";
2166
        }
2167
        $name .= substr($email[0], -1, 1);
2168
    }
2169
    $host = explode(".", $email[1])[0];
2170
    if (strlen($host) > 3) {
2171
        $host = substr($host, 0, 1);
2172
        for ($i = 0; $i < strlen(explode(".", $email[1])[0]) - 2; $i++) {
2173
            $host .= "*";
2174
        }
2175
        $host .= substr(explode(".", $email[1])[0], -1, 1);
2176
    }
2177
    $email = $name . "@" . $host . "." . explode(".", $email[1])[1];
2178
    return $email;
2179
}
2180
2181
/**
2182
 * Get id and title from role_titles table.
2183
 *
2184
 * @return array
2185
 */
2186
function getRolesTitles(): array
2187
{
2188
    // Load class DB
2189
    loadClasses('DB');
2190
    
2191
    // Insert log in DB
2192
    return DB::query(
2193
        'SELECT id, title
2194
        FROM ' . prefixTable('roles_title')
2195
    );
2196
}
2197
2198
/**
2199
 * Undocumented function.
2200
 *
2201
 * @param int $bytes Size of file
2202
 *
2203
 * @return string
2204
 */
2205
function formatSizeUnits(int $bytes): string
2206
{
2207
    if ($bytes >= 1073741824) {
2208
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
2209
    } elseif ($bytes >= 1048576) {
2210
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
2211
    } elseif ($bytes >= 1024) {
2212
        $bytes = number_format($bytes / 1024, 2) . ' KB';
2213
    } elseif ($bytes > 1) {
2214
        $bytes .= ' bytes';
2215
    } elseif ($bytes === 1) {
2216
        $bytes .= ' byte';
2217
    } else {
2218
        $bytes = '0 bytes';
2219
    }
2220
2221
    return $bytes;
2222
}
2223
2224
/**
2225
 * Generate user pair of keys.
2226
 *
2227
 * @param string $userPwd User password
2228
 *
2229
 * @return array
2230
 */
2231
function generateUserKeys(string $userPwd): array
2232
{
2233
    // Sanitize
2234
    $antiXss = new AntiXSS();
2235
    $userPwd = $antiXss->xss_clean($userPwd);
2236
    // Load classes
2237
    $rsa = new Crypt_RSA();
2238
    $cipher = new Crypt_AES();
2239
    // Create the private and public key
2240
    $res = $rsa->createKey(4096);
2241
    // Encrypt the privatekey
2242
    $cipher->setPassword($userPwd);
2243
    $privatekey = $cipher->encrypt($res['privatekey']);
2244
    return [
2245
        'private_key' => base64_encode($privatekey),
2246
        'public_key' => base64_encode($res['publickey']),
2247
        'private_key_clear' => base64_encode($res['privatekey']),
2248
    ];
2249
}
2250
2251
/**
2252
 * Permits to decrypt the user's privatekey.
2253
 *
2254
 * @param string $userPwd        User password
2255
 * @param string $userPrivateKey User private key
2256
 *
2257
 * @return string|object
2258
 */
2259
function decryptPrivateKey(string $userPwd, string $userPrivateKey)
2260
{
2261
    // Sanitize
2262
    $antiXss = new AntiXSS();
2263
    $userPwd = $antiXss->xss_clean($userPwd);
2264
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2265
2266
    if (empty($userPwd) === false) {
2267
        // Load classes
2268
        $cipher = new Crypt_AES();
2269
        // Encrypt the privatekey
2270
        $cipher->setPassword($userPwd);
2271
        try {
2272
            return base64_encode((string) $cipher->decrypt(base64_decode($userPrivateKey)));
2273
        } catch (Exception $e) {
2274
            return $e;
2275
        }
2276
    }
2277
    return '';
2278
}
2279
2280
/**
2281
 * Permits to encrypt the user's privatekey.
2282
 *
2283
 * @param string $userPwd        User password
2284
 * @param string $userPrivateKey User private key
2285
 *
2286
 * @return string
2287
 */
2288
function encryptPrivateKey(string $userPwd, string $userPrivateKey): string
2289
{
2290
    // Sanitize
2291
    $antiXss = new AntiXSS();
2292
    $userPwd = $antiXss->xss_clean($userPwd);
2293
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2294
2295
    if (empty($userPwd) === false) {
2296
        // Load classes
2297
        $cipher = new Crypt_AES();
2298
        // Encrypt the privatekey
2299
        $cipher->setPassword($userPwd);        
2300
        try {
2301
            return base64_encode($cipher->encrypt(base64_decode($userPrivateKey)));
2302
        } catch (Exception $e) {
2303
            return $e->getMessage();
2304
        }
2305
    }
2306
    return '';
2307
}
2308
2309
/**
2310
 * Encrypts a string using AES.
2311
 *
2312
 * @param string $data String to encrypt
2313
 * @param string $key
2314
 *
2315
 * @return array
2316
 */
2317
function doDataEncryption(string $data, string $key = NULL): array
2318
{
2319
    // Sanitize
2320
    $antiXss = new AntiXSS();
2321
    $data = $antiXss->xss_clean($data);
2322
    
2323
    // Load classes
2324
    $cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
2325
    // Generate an object key
2326
    $objectKey = is_null($key) === true ? uniqidReal(KEY_LENGTH) : $antiXss->xss_clean($key);
2327
    // Set it as password
2328
    $cipher->setPassword($objectKey);
2329
    return [
2330
        'encrypted' => base64_encode($cipher->encrypt($data)),
2331
        'objectKey' => base64_encode($objectKey),
2332
    ];
2333
}
2334
2335
/**
2336
 * Decrypts a string using AES.
2337
 *
2338
 * @param string $data Encrypted data
2339
 * @param string $key  Key to uncrypt
2340
 *
2341
 * @return string
2342
 */
2343
function doDataDecryption(string $data, string $key): string
2344
{
2345
    // Sanitize
2346
    $antiXss = new AntiXSS();
2347
    $data = $antiXss->xss_clean($data);
2348
    $key = $antiXss->xss_clean($key);
2349
2350
    // Load classes
2351
    $cipher = new Crypt_AES();
2352
    // Set the object key
2353
    $cipher->setPassword(base64_decode($key));
2354
    return base64_encode((string) $cipher->decrypt(base64_decode($data)));
2355
}
2356
2357
/**
2358
 * Encrypts using RSA a string using a public key.
2359
 *
2360
 * @param string $key       Key to be encrypted
2361
 * @param string $publicKey User public key
2362
 *
2363
 * @return string
2364
 */
2365
function encryptUserObjectKey(string $key, string $publicKey): string
2366
{
2367
    // Empty password
2368
    if (empty($key)) return '';
2369
2370
    // Sanitize
2371
    $antiXss = new AntiXSS();
2372
    $publicKey = $antiXss->xss_clean($publicKey);
2373
    // Load classes
2374
    $rsa = new Crypt_RSA();
2375
    // Load the public key
2376
    $decodedPublicKey = base64_decode($publicKey, true);
2377
    if ($decodedPublicKey === false) {
2378
        throw new InvalidArgumentException("Error while decoding key.");
2379
    }
2380
    $rsa->loadKey($decodedPublicKey);
2381
    // Encrypt
2382
    $encrypted = $rsa->encrypt(base64_decode($key));
2383
    if (empty($encrypted)) {  // Check if key is empty or null
2384
        throw new RuntimeException("Error while encrypting key.");
2385
    }
2386
    // Return
2387
    return base64_encode($encrypted);
2388
}
2389
2390
/**
2391
 * Decrypts using RSA an encrypted string using a private key.
2392
 *
2393
 * @param string $key        Encrypted key
2394
 * @param string $privateKey User private key
2395
 *
2396
 * @return string
2397
 */
2398
function decryptUserObjectKey(string $key, string $privateKey): string
2399
{
2400
    // Sanitize
2401
    $antiXss = new AntiXSS();
2402
    $privateKey = $antiXss->xss_clean($privateKey);
2403
2404
    // Load classes
2405
    $rsa = new Crypt_RSA();
2406
    // Load the private key
2407
    $decodedPrivateKey = base64_decode($privateKey, true);
2408
    if ($decodedPrivateKey === false) {
2409
        throw new InvalidArgumentException("Error while decoding private key.");
2410
    }
2411
2412
    $rsa->loadKey($decodedPrivateKey);
2413
2414
    // Decrypt
2415
    try {
2416
        $decodedKey = base64_decode($key, true);
2417
        if ($decodedKey === false) {
2418
            throw new InvalidArgumentException("Error while decoding key.");
2419
        }
2420
2421
        // This check is needed as decrypt() in version 2 can return false in case of error
2422
        $tmpValue = $rsa->decrypt($decodedKey);
2423
        if ($tmpValue !== false) {
0 ignored issues
show
introduced by
The condition $tmpValue !== false is always true.
Loading history...
2424
            return base64_encode($tmpValue);
2425
        } else {
2426
            return '';
2427
        }
2428
    } catch (Exception $e) {
2429
        if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2430
            error_log('TEAMPASS Error - ldap - '.$e->getMessage());
2431
        }
2432
        return 'Exception: could not decrypt object';
2433
    }
2434
}
2435
2436
/**
2437
 * Encrypts a file.
2438
 *
2439
 * @param string $fileInName File name
2440
 * @param string $fileInPath Path to file
2441
 *
2442
 * @return array
2443
 */
2444
function encryptFile(string $fileInName, string $fileInPath): array
2445
{
2446
    if (defined('FILE_BUFFER_SIZE') === false) {
2447
        define('FILE_BUFFER_SIZE', 128 * 1024);
2448
    }
2449
2450
    // Load classes
2451
    $cipher = new Crypt_AES();
2452
2453
    // Generate an object key
2454
    $objectKey = uniqidReal(32);
2455
    // Set it as password
2456
    $cipher->setPassword($objectKey);
2457
    // Prevent against out of memory
2458
    $cipher->enableContinuousBuffer();
2459
2460
    // Encrypt the file content
2461
    $filePath = filter_var($fileInPath . '/' . $fileInName, FILTER_SANITIZE_URL);
2462
    $fileContent = file_get_contents($filePath);
2463
    $plaintext = $fileContent;
2464
    $ciphertext = $cipher->encrypt($plaintext);
2465
2466
    // Save new file
2467
    // deepcode ignore InsecureHash: is simply used to get a unique name
2468
    $hash = uniqid('', true);
2469
    $fileOut = $fileInPath . '/' . TP_FILE_PREFIX . $hash;
2470
    file_put_contents($fileOut, $ciphertext);
2471
    unlink($fileInPath . '/' . $fileInName);
2472
    return [
2473
        'fileHash' => base64_encode($hash),
2474
        'objectKey' => base64_encode($objectKey),
2475
    ];
2476
}
2477
2478
/**
2479
 * Decrypt a file.
2480
 *
2481
 * @param string $fileName File name
2482
 * @param string $filePath Path to file
2483
 * @param string $key      Key to use
2484
 *
2485
 * @return string|array
2486
 */
2487
function decryptFile(string $fileName, string $filePath, string $key): string|array
2488
{
2489
    if (! defined('FILE_BUFFER_SIZE')) {
2490
        define('FILE_BUFFER_SIZE', 128 * 1024);
2491
    }
2492
    
2493
    // Load classes
2494
    $cipher = new Crypt_AES();
2495
    $antiXSS = new AntiXSS();
2496
    
2497
    // Get file name
2498
    $safeFileName = $antiXSS->xss_clean(base64_decode($fileName));
2499
2500
    // Set the object key
2501
    $cipher->setPassword(base64_decode($key));
2502
    // Prevent against out of memory
2503
    $cipher->enableContinuousBuffer();
2504
    $cipher->disablePadding();
2505
    // Get file content
2506
    $safeFilePath = realpath($filePath . '/' . TP_FILE_PREFIX . $safeFileName);
2507
    if ($safeFilePath !== false && file_exists($safeFilePath)) {
2508
        $ciphertext = file_get_contents(filter_var($safeFilePath, FILTER_SANITIZE_URL));
2509
    } else {
2510
        // Handle the error: file doesn't exist or path is invalid
2511
        return [
2512
            'error' => true,
2513
            'message' => 'This file has not been found.',
2514
        ];
2515
    }
2516
2517
    if (WIP) error_log('DEBUG: File image url -> '.filter_var($safeFilePath, FILTER_SANITIZE_URL));
2518
2519
    // Decrypt file content and return
2520
    return base64_encode($cipher->decrypt($ciphertext));
2521
}
2522
2523
/**
2524
 * Generate a simple password
2525
 *
2526
 * @param int $length Length of string
2527
 * @param bool $symbolsincluded Allow symbols
2528
 *
2529
 * @return string
2530
 */
2531
function generateQuickPassword(int $length = 16, bool $symbolsincluded = true): string
2532
{
2533
    // Generate new user password
2534
    $small_letters = range('a', 'z');
2535
    $big_letters = range('A', 'Z');
2536
    $digits = range(0, 9);
2537
    $symbols = $symbolsincluded === true ?
2538
        ['#', '_', '-', '@', '$', '+', '!'] : [];
2539
    $res = array_merge($small_letters, $big_letters, $digits, $symbols);
2540
    $count = count($res);
2541
    // first variant
2542
2543
    $random_string = '';
2544
    for ($i = 0; $i < $length; ++$i) {
2545
        $random_string .= $res[random_int(0, $count - 1)];
2546
    }
2547
2548
    return $random_string;
2549
}
2550
2551
/**
2552
 * Permit to store the sharekey of an object for users.
2553
 *
2554
 * @param string $object_name             Type for table selection
2555
 * @param int    $post_folder_is_personal Personal
2556
 * @param int    $post_object_id          Object
2557
 * @param string $objectKey               Object key
2558
 * @param array  $SETTINGS                Teampass settings
2559
 * @param int    $user_id                 User ID if needed
2560
 * @param bool   $onlyForUser             If is TRUE, then the sharekey is only for the user
2561
 * @param bool   $deleteAll               If is TRUE, then all existing entries are deleted
2562
 * @param array  $objectKeyArray          Array of objects
2563
 * @param int    $all_users_except_id     All users except this one
2564
 * @param int    $apiUserId               API User ID
2565
 *
2566
 * @return void
2567
 */
2568
function storeUsersShareKey(
2569
    string $object_name,
2570
    int $post_folder_is_personal,
2571
    int $post_object_id,
2572
    string $objectKey,
2573
    bool $onlyForUser = false,
2574
    bool $deleteAll = true,
2575
    array $objectKeyArray = [],
2576
    int $all_users_except_id = -1,
2577
    int $apiUserId = -1
2578
): void {
2579
    
2580
    $session = SessionManager::getSession();
2581
    loadClasses('DB');
2582
2583
    // Delete existing entries for this object
2584
    if ($deleteAll === true) {
2585
        DB::delete(
2586
            $object_name,
2587
            'object_id = %i',
2588
            $post_object_id
2589
        );
2590
    }
2591
2592
    // Get the user ID
2593
    $userId = ($apiUserId === -1) ? (int) $session->get('user-id') : $apiUserId;
2594
    
2595
    // $onlyForUser is only dynamically set by external calls
2596
    if (
2597
        $onlyForUser === true || (int) $post_folder_is_personal === 1
2598
    ) {
2599
        // Only create the sharekey for a user
2600
        $user = DB::queryFirstRow(
2601
            'SELECT public_key
2602
            FROM ' . prefixTable('users') . '
2603
            WHERE id = %i
2604
            AND public_key != ""',
2605
            $userId
2606
        );
2607
2608
        if (empty($objectKey) === false) {
2609
            DB::insert(
2610
                $object_name,
2611
                [
2612
                    'object_id' => (int) $post_object_id,
2613
                    'user_id' => $userId,
2614
                    'share_key' => encryptUserObjectKey(
2615
                        $objectKey,
2616
                        $user['public_key']
2617
                    ),
2618
                ]
2619
            );
2620
        } else if (count($objectKeyArray) > 0) {
2621
            foreach ($objectKeyArray as $object) {
2622
                DB::insert(
2623
                    $object_name,
2624
                    [
2625
                        'object_id' => (int) $object['objectId'],
2626
                        'user_id' => $userId,
2627
                        'share_key' => encryptUserObjectKey(
2628
                            $object['objectKey'],
2629
                            $user['public_key']
2630
                        ),
2631
                    ]
2632
                );
2633
            }
2634
        }
2635
    } else {
2636
        // Create sharekey for each user
2637
        $user_ids = [OTV_USER_ID, SSH_USER_ID, API_USER_ID];
2638
        if ($all_users_except_id !== -1) {
2639
            array_push($user_ids, (int) $all_users_except_id);
2640
        }
2641
        $users = DB::query(
2642
            'SELECT id, public_key
2643
            FROM ' . prefixTable('users') . '
2644
            WHERE id NOT IN %li
2645
            AND public_key != ""',
2646
            $user_ids
2647
        );
2648
        //DB::debugmode(false);
2649
        foreach ($users as $user) {
2650
            // Insert in DB the new object key for this item by user
2651
            if (count($objectKeyArray) === 0) {
2652
                if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case1 - ' . $object_name . ' - ' . $post_object_id . ' - ' . $user['id'] . ' - ' . $objectKey);
2653
                DB::insert(
2654
                    $object_name,
2655
                    [
2656
                        'object_id' => $post_object_id,
2657
                        'user_id' => (int) $user['id'],
2658
                        'share_key' => encryptUserObjectKey(
2659
                            $objectKey,
2660
                            $user['public_key']
2661
                        ),
2662
                    ]
2663
                );
2664
            } else {
2665
                foreach ($objectKeyArray as $object) {
2666
                    if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case2 - ' . $object_name . ' - ' . $object['objectId'] . ' - ' . $user['id'] . ' - ' . $object['objectKey']);
2667
                    DB::insert(
2668
                        $object_name,
2669
                        [
2670
                            'object_id' => (int) $object['objectId'],
2671
                            'user_id' => (int) $user['id'],
2672
                            'share_key' => encryptUserObjectKey(
2673
                                $object['objectKey'],
2674
                                $user['public_key']
2675
                            ),
2676
                        ]
2677
                    );
2678
                }
2679
            }
2680
        }
2681
    }
2682
}
2683
2684
/**
2685
 * Is this string base64 encoded?
2686
 *
2687
 * @param string $str Encoded string?
2688
 *
2689
 * @return bool
2690
 */
2691
function isBase64(string $str): bool
2692
{
2693
    $str = (string) trim($str);
2694
    if (! isset($str[0])) {
2695
        return false;
2696
    }
2697
2698
    $base64String = (string) base64_decode($str, true);
2699
    if ($base64String && base64_encode($base64String) === $str) {
2700
        return true;
2701
    }
2702
2703
    return false;
2704
}
2705
2706
/**
2707
 * Undocumented function
2708
 *
2709
 * @param string $field Parameter
2710
 *
2711
 * @return array|bool|resource|string
2712
 */
2713
function filterString(string $field)
2714
{
2715
    // Sanitize string
2716
    $field = filter_var(trim($field), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
2717
    if (empty($field) === false) {
2718
        // Load AntiXSS
2719
        $antiXss = new AntiXSS();
2720
        // Return
2721
        return $antiXss->xss_clean($field);
2722
    }
2723
2724
    return false;
2725
}
2726
2727
/**
2728
 * CHeck if provided credentials are allowed on server
2729
 *
2730
 * @param string $login    User Login
2731
 * @param string $password User Pwd
2732
 * @param array  $SETTINGS Teampass settings
2733
 *
2734
 * @return bool
2735
 */
2736
function ldapCheckUserPassword(string $login, string $password, array $SETTINGS): bool
2737
{
2738
    // Build ldap configuration array
2739
    $config = [
2740
        // Mandatory Configuration Options
2741
        'hosts' => [$SETTINGS['ldap_hosts']],
2742
        'base_dn' => $SETTINGS['ldap_bdn'],
2743
        'username' => $SETTINGS['ldap_username'],
2744
        'password' => $SETTINGS['ldap_password'],
2745
2746
        // Optional Configuration Options
2747
        'port' => $SETTINGS['ldap_port'],
2748
        'use_ssl' => (int) $SETTINGS['ldap_ssl'] === 1 ? true : false,
2749
        'use_tls' => (int) $SETTINGS['ldap_tls'] === 1 ? true : false,
2750
        'version' => 3,
2751
        'timeout' => 5,
2752
        'follow_referrals' => false,
2753
2754
        // Custom LDAP Options
2755
        'options' => [
2756
            // See: http://php.net/ldap_set_option
2757
            LDAP_OPT_X_TLS_REQUIRE_CERT => (isset($SETTINGS['ldap_tls_certiface_check']) ? $SETTINGS['ldap_tls_certiface_check'] : LDAP_OPT_X_TLS_HARD),
2758
        ],
2759
    ];
2760
    
2761
    $connection = new Connection($config);
2762
    // Connect to LDAP
2763
    try {
2764
        $connection->connect();
2765
    } catch (\LdapRecord\Auth\BindException $e) {
2766
        $error = $e->getDetailedError();
2767
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2768
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
2769
        }
2770
        // deepcode ignore ServerLeak: No important data is sent
2771
        echo 'An error occurred.';
2772
        return false;
2773
    }
2774
2775
    // Authenticate user
2776
    try {
2777
        if ($SETTINGS['ldap_type'] === 'ActiveDirectory') {
2778
            $connection->auth()->attempt($login, $password, $stayAuthenticated = true);
2779
        } else {
2780
            $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);
2781
        }
2782
    } catch (\LdapRecord\Auth\BindException $e) {
2783
        $error = $e->getDetailedError();
2784
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2785
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
2786
        }
2787
        // deepcode ignore ServerLeak: No important data is sent
2788
        echo 'An error occurred.';
2789
        return false;
2790
    }
2791
2792
    return true;
2793
}
2794
2795
/**
2796
 * Removes from DB all sharekeys of this user
2797
 *
2798
 * @param int $userId User's id
2799
 * @param array   $SETTINGS Teampass settings
2800
 *
2801
 * @return bool
2802
 */
2803
function deleteUserObjetsKeys(int $userId, array $SETTINGS = []): bool
2804
{
2805
    // Load class DB
2806
    loadClasses('DB');
2807
2808
    // Remove all item sharekeys items
2809
    // expect if personal item
2810
    DB::delete(
2811
        prefixTable('sharekeys_items'),
2812
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2813
        $userId
2814
    );
2815
    // Remove all item sharekeys files
2816
    DB::delete(
2817
        prefixTable('sharekeys_files'),
2818
        'user_id = %i AND object_id NOT IN (
2819
            SELECT f.id 
2820
            FROM ' . prefixTable('items') . ' AS i 
2821
            INNER JOIN ' . prefixTable('files') . ' AS f ON f.id_item = i.id
2822
            WHERE i.perso = 1
2823
        )',
2824
        $userId
2825
    );
2826
    // Remove all item sharekeys fields
2827
    DB::delete(
2828
        prefixTable('sharekeys_fields'),
2829
        'user_id = %i AND object_id NOT IN (
2830
            SELECT c.id 
2831
            FROM ' . prefixTable('items') . ' AS i 
2832
            INNER JOIN ' . prefixTable('categories_items') . ' AS c ON c.item_id = i.id
2833
            WHERE i.perso = 1
2834
        )',
2835
        $userId
2836
    );
2837
    // Remove all item sharekeys logs
2838
    DB::delete(
2839
        prefixTable('sharekeys_logs'),
2840
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2841
        $userId
2842
    );
2843
    // Remove all item sharekeys suggestions
2844
    DB::delete(
2845
        prefixTable('sharekeys_suggestions'),
2846
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
2847
        $userId
2848
    );
2849
    return false;
2850
}
2851
2852
/**
2853
 * Manage list of timezones   $SETTINGS Teampass settings
2854
 *
2855
 * @return array
2856
 */
2857
function timezone_list()
2858
{
2859
    static $timezones = null;
2860
    if ($timezones === null) {
2861
        $timezones = [];
2862
        $offsets = [];
2863
        $now = new DateTime('now', new DateTimeZone('UTC'));
2864
        foreach (DateTimeZone::listIdentifiers() as $timezone) {
2865
            $now->setTimezone(new DateTimeZone($timezone));
2866
            $offsets[] = $offset = $now->getOffset();
2867
            $timezones[$timezone] = '(' . format_GMT_offset($offset) . ') ' . format_timezone_name($timezone);
2868
        }
2869
2870
        array_multisort($offsets, $timezones);
2871
    }
2872
2873
    return $timezones;
2874
}
2875
2876
/**
2877
 * Provide timezone offset
2878
 *
2879
 * @param int $offset Timezone offset
2880
 *
2881
 * @return string
2882
 */
2883
function format_GMT_offset($offset): string
2884
{
2885
    $hours = intval($offset / 3600);
2886
    $minutes = abs(intval($offset % 3600 / 60));
2887
    return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
2888
}
2889
2890
/**
2891
 * Provides timezone name
2892
 *
2893
 * @param string $name Timezone name
2894
 *
2895
 * @return string
2896
 */
2897
function format_timezone_name($name): string
2898
{
2899
    $name = str_replace('/', ', ', $name);
2900
    $name = str_replace('_', ' ', $name);
2901
2902
    return str_replace('St ', 'St. ', $name);
2903
}
2904
2905
/**
2906
 * Provides info if user should use MFA based on roles
2907
 *
2908
 * @param string $userRolesIds  User roles ids
2909
 * @param string $mfaRoles      Roles for which MFA is requested
2910
 *
2911
 * @return bool
2912
 */
2913
function mfa_auth_requested_roles(string $userRolesIds, string $mfaRoles): bool
2914
{
2915
    if (empty($mfaRoles) === true) {
2916
        return true;
2917
    }
2918
2919
    $mfaRoles = array_values(json_decode($mfaRoles, true));
2920
    $userRolesIds = array_filter(explode(';', $userRolesIds));
2921
    if (count($mfaRoles) === 0 || count(array_intersect($mfaRoles, $userRolesIds)) > 0) {
2922
        return true;
2923
    }
2924
2925
    return false;
2926
}
2927
2928
/**
2929
 * Permits to clean a string for export purpose
2930
 *
2931
 * @param string $text
2932
 * @param bool $emptyCheckOnly
2933
 * 
2934
 * @return string
2935
 */
2936
function cleanStringForExport(string $text, bool $emptyCheckOnly = false): string
2937
{
2938
    if (is_null($text) === true || empty($text) === true) {
2939
        return '';
2940
    }
2941
    // only expected to check if $text was empty
2942
    elseif ($emptyCheckOnly === true) {
2943
        return $text;
2944
    }
2945
2946
    return strip_tags(
2947
        cleanString(
2948
            html_entity_decode($text, ENT_QUOTES | ENT_XHTML, 'UTF-8'),
2949
            true)
2950
        );
2951
}
2952
2953
/**
2954
 * Permits to check if user ID is valid
2955
 *
2956
 * @param integer $post_user_id
2957
 * @return bool
2958
 */
2959
function isUserIdValid($userId): bool
2960
{
2961
    if (is_null($userId) === false
2962
        && isset($userId) === true
2963
        && empty($userId) === false
2964
    ) {
2965
        return true;
2966
    }
2967
    return false;
2968
}
2969
2970
/**
2971
 * Check if a key exists and if its value equal the one expected
2972
 *
2973
 * @param string $key
2974
 * @param integer|string $value
2975
 * @param array $array
2976
 * 
2977
 * @return boolean
2978
 */
2979
function isKeyExistingAndEqual(
2980
    string $key,
2981
    /*PHP8 - integer|string*/$value,
2982
    array $array
2983
): bool
2984
{
2985
    if (isset($array[$key]) === true
2986
        && (is_int($value) === true ?
2987
            (int) $array[$key] === $value :
2988
            (string) $array[$key] === $value)
2989
    ) {
2990
        return true;
2991
    }
2992
    return false;
2993
}
2994
2995
/**
2996
 * Check if a variable is not set or equal to a value
2997
 *
2998
 * @param string|null $var
2999
 * @param integer|string $value
3000
 * 
3001
 * @return boolean
3002
 */
3003
function isKeyNotSetOrEqual(
3004
    /*PHP8 - string|null*/$var,
3005
    /*PHP8 - integer|string*/$value
3006
): bool
3007
{
3008
    if (isset($var) === false
3009
        || (is_int($value) === true ?
3010
            (int) $var === $value :
3011
            (string) $var === $value)
3012
    ) {
3013
        return true;
3014
    }
3015
    return false;
3016
}
3017
3018
/**
3019
 * Check if a key exists and if its value < to the one expected
3020
 *
3021
 * @param string $key
3022
 * @param integer $value
3023
 * @param array $array
3024
 * 
3025
 * @return boolean
3026
 */
3027
function isKeyExistingAndInferior(string $key, int $value, array $array): bool
3028
{
3029
    if (isset($array[$key]) === true && (int) $array[$key] < $value) {
3030
        return true;
3031
    }
3032
    return false;
3033
}
3034
3035
/**
3036
 * Check if a key exists and if its value > to the one expected
3037
 *
3038
 * @param string $key
3039
 * @param integer $value
3040
 * @param array $array
3041
 * 
3042
 * @return boolean
3043
 */
3044
function isKeyExistingAndSuperior(string $key, int $value, array $array): bool
3045
{
3046
    if (isset($array[$key]) === true && (int) $array[$key] > $value) {
3047
        return true;
3048
    }
3049
    return false;
3050
}
3051
3052
/**
3053
 * Check if values in array are set
3054
 * Return true if all set
3055
 * Return false if one of them is not set
3056
 *
3057
 * @param array $arrayOfValues
3058
 * @return boolean
3059
 */
3060
function isSetArrayOfValues(array $arrayOfValues): bool
3061
{
3062
    foreach($arrayOfValues as $value) {
3063
        if (isset($value) === false) {
3064
            return false;
3065
        }
3066
    }
3067
    return true;
3068
}
3069
3070
/**
3071
 * Check if values in array are set
3072
 * Return true if all set
3073
 * Return false if one of them is not set
3074
 *
3075
 * @param array $arrayOfValues
3076
 * @param integer|string $value
3077
 * @return boolean
3078
 */
3079
function isArrayOfVarsEqualToValue(
3080
    array $arrayOfVars,
3081
    /*PHP8 - integer|string*/$value
3082
) : bool
3083
{
3084
    foreach($arrayOfVars as $variable) {
3085
        if ($variable !== $value) {
3086
            return false;
3087
        }
3088
    }
3089
    return true;
3090
}
3091
3092
/**
3093
 * Checks if at least one variable in array is equal to value
3094
 *
3095
 * @param array $arrayOfValues
3096
 * @param integer|string $value
3097
 * @return boolean
3098
 */
3099
function isOneVarOfArrayEqualToValue(
3100
    array $arrayOfVars,
3101
    /*PHP8 - integer|string*/$value
3102
) : bool
3103
{
3104
    foreach($arrayOfVars as $variable) {
3105
        if ($variable === $value) {
3106
            return true;
3107
        }
3108
    }
3109
    return false;
3110
}
3111
3112
/**
3113
 * Checks is value is null, not set OR empty
3114
 *
3115
 * @param string|int|null $value
3116
 * @return boolean
3117
 */
3118
function isValueSetNullEmpty(/*PHP8 - string|int|null*/ $value) : bool
3119
{
3120
    if (is_null($value) === true || isset($value) === false || empty($value) === true) {
3121
        return true;
3122
    }
3123
    return false;
3124
}
3125
3126
/**
3127
 * Checks if value is set and if empty is equal to passed boolean
3128
 *
3129
 * @param string|int $value
3130
 * @param boolean $boolean
3131
 * @return boolean
3132
 */
3133
function isValueSetEmpty($value, $boolean = true) : bool
3134
{
3135
    if (isset($value) === true && empty($value) === $boolean) {
3136
        return true;
3137
    }
3138
    return false;
3139
}
3140
3141
/**
3142
 * Ensure Complexity is translated
3143
 *
3144
 * @return void
3145
 */
3146
function defineComplexity() : void
3147
{
3148
    // Load user's language
3149
    $session = SessionManager::getSession();
3150
    $lang = new Language($session->get('user-language') ?? 'english');
3151
    
3152
    if (defined('TP_PW_COMPLEXITY') === false) {
3153
        define(
3154
            'TP_PW_COMPLEXITY',
3155
            [
3156
                TP_PW_STRENGTH_1 => array(TP_PW_STRENGTH_1, $lang->get('complex_level1'), 'fas fa-thermometer-empty text-danger'),
3157
                TP_PW_STRENGTH_2 => array(TP_PW_STRENGTH_2, $lang->get('complex_level2'), 'fas fa-thermometer-quarter text-warning'),
3158
                TP_PW_STRENGTH_3 => array(TP_PW_STRENGTH_3, $lang->get('complex_level3'), 'fas fa-thermometer-half text-warning'),
3159
                TP_PW_STRENGTH_4 => array(TP_PW_STRENGTH_4, $lang->get('complex_level4'), 'fas fa-thermometer-three-quarters text-success'),
3160
                TP_PW_STRENGTH_5 => array(TP_PW_STRENGTH_5, $lang->get('complex_level5'), 'fas fa-thermometer-full text-success'),
3161
            ]
3162
        );
3163
    }
3164
}
3165
3166
/**
3167
 * Uses Sanitizer to perform data sanitization
3168
 *
3169
 * @param array     $data
3170
 * @param array     $filters
3171
 * @return array|string
3172
 */
3173
function dataSanitizer(array $data, array $filters): array|string
3174
{
3175
    // Load Sanitizer library
3176
    $sanitizer = new Sanitizer($data, $filters);
3177
3178
    // Load AntiXSS
3179
    $antiXss = new AntiXSS();
3180
3181
    // Sanitize post and get variables
3182
    return $antiXss->xss_clean($sanitizer->sanitize());
3183
}
3184
3185
/**
3186
 * Permits to manage the cache tree for a user
3187
 *
3188
 * @param integer $user_id
3189
 * @param string $data
3190
 * @param array $SETTINGS
3191
 * @param string $field_update
3192
 * @return void
3193
 */
3194
function cacheTreeUserHandler(int $user_id, string $data, array $SETTINGS, string $field_update = '')
3195
{
3196
    // Load class DB
3197
    loadClasses('DB');
3198
3199
    // Exists ?
3200
    $userCacheId = DB::queryFirstRow(
3201
        'SELECT increment_id
3202
        FROM ' . prefixTable('cache_tree') . '
3203
        WHERE user_id = %i',
3204
        $user_id
3205
    );
3206
    
3207
    if (is_null($userCacheId) === true || count($userCacheId) === 0) {
3208
        // insert in table
3209
        DB::insert(
3210
            prefixTable('cache_tree'),
3211
            array(
3212
                'data' => $data,
3213
                'timestamp' => time(),
3214
                'user_id' => $user_id,
3215
                'visible_folders' => '',
3216
            )
3217
        );
3218
    } else {
3219
        if (empty($field_update) === true) {
3220
            DB::update(
3221
                prefixTable('cache_tree'),
3222
                [
3223
                    'timestamp' => time(),
3224
                    'data' => $data,
3225
                ],
3226
                'increment_id = %i',
3227
                $userCacheId['increment_id']
3228
            );
3229
        /* USELESS
3230
        } else {
3231
            DB::update(
3232
                prefixTable('cache_tree'),
3233
                [
3234
                    $field_update => $data,
3235
                ],
3236
                'increment_id = %i',
3237
                $userCacheId['increment_id']
3238
            );*/
3239
        }
3240
    }
3241
}
3242
3243
/**
3244
 * Permits to calculate a %
3245
 *
3246
 * @param float $nombre
3247
 * @param float $total
3248
 * @param float $pourcentage
3249
 * @return float
3250
 */
3251
function pourcentage(float $nombre, float $total, float $pourcentage): float
3252
{ 
3253
    $resultat = ($nombre/$total) * $pourcentage;
3254
    return round($resultat);
3255
}
3256
3257
/**
3258
 * Load the folders list from the cache
3259
 *
3260
 * @param string $fieldName
3261
 * @param string $sessionName
3262
 * @param boolean $forceRefresh
3263
 * @return array
3264
 */
3265
function loadFoldersListByCache(
3266
    string $fieldName,
3267
    string $sessionName,
3268
    bool $forceRefresh = false
3269
): array
3270
{
3271
    // Case when refresh is EXPECTED / MANDATORY
3272
    if ($forceRefresh === true) {
3273
        return [
3274
            'state' => false,
3275
            'data' => [],
3276
        ];
3277
    }
3278
    
3279
    $session = SessionManager::getSession();
3280
3281
    // Get last folder update
3282
    $lastFolderChange = DB::queryFirstRow(
3283
        'SELECT valeur FROM ' . prefixTable('misc') . '
3284
        WHERE type = %s AND intitule = %s',
3285
        'timestamp',
3286
        'last_folder_change'
3287
    );
3288
    if (DB::count() === 0) {
3289
        $lastFolderChange['valeur'] = 0;
3290
    }
3291
3292
    // Case when an update in the tree has been done
3293
    // Refresh is then mandatory
3294
    if ((int) $lastFolderChange['valeur'] > (int) (null !== $session->get('user-tree_last_refresh_timestamp') ? $session->get('user-tree_last_refresh_timestamp') : 0)) {
3295
        return [
3296
            'state' => false,
3297
            'data' => [],
3298
        ];
3299
    }
3300
3301
    // Does this user has the tree structure in session?
3302
    // If yes then use it
3303
    if (count(null !== $session->get('user-folders_list') ? $session->get('user-folders_list') : []) > 0) {
3304
        return [
3305
            'state' => true,
3306
            'data' => json_encode($session->get('user-folders_list')[0]),
3307
            'extra' => 'to_be_parsed',
3308
        ];
3309
    }
3310
    
3311
    // Does this user has a tree cache
3312
    $userCacheTree = DB::queryFirstRow(
3313
        'SELECT '.$fieldName.'
3314
        FROM ' . prefixTable('cache_tree') . '
3315
        WHERE user_id = %i',
3316
        $session->get('user-id')
3317
    );
3318
    if (empty($userCacheTree[$fieldName]) === false && $userCacheTree[$fieldName] !== '[]') {
3319
        SessionManager::addRemoveFromSessionAssociativeArray(
3320
            'user-folders_list',
3321
            [$userCacheTree[$fieldName]],
3322
            'add'
3323
        );
3324
        return [
3325
            'state' => true,
3326
            'data' => $userCacheTree[$fieldName],
3327
            'extra' => '',
3328
        ];
3329
    }
3330
3331
    return [
3332
        'state' => false,
3333
        'data' => [],
3334
    ];
3335
}
3336
3337
3338
/**
3339
 * Permits to refresh the categories of folders
3340
 *
3341
 * @param array $folderIds
3342
 * @return void
3343
 */
3344
function handleFoldersCategories(
3345
    array $folderIds
3346
)
3347
{
3348
    // Load class DB
3349
    loadClasses('DB');
3350
3351
    $arr_data = array();
3352
3353
    // force full list of folders
3354
    if (count($folderIds) === 0) {
3355
        $folderIds = DB::queryFirstColumn(
3356
            'SELECT id
3357
            FROM ' . prefixTable('nested_tree') . '
3358
            WHERE personal_folder=%i',
3359
            0
3360
        );
3361
    }
3362
3363
    // Get complexity
3364
    defineComplexity();
3365
3366
    // update
3367
    foreach ($folderIds as $folder) {
3368
        // Do we have Categories
3369
        // get list of associated Categories
3370
        $arrCatList = array();
3371
        $rows_tmp = DB::query(
3372
            'SELECT c.id, c.title, c.level, c.type, c.masked, c.order, c.encrypted_data, c.role_visibility, c.is_mandatory,
3373
            f.id_category AS category_id
3374
            FROM ' . prefixTable('categories_folders') . ' AS f
3375
            INNER JOIN ' . prefixTable('categories') . ' AS c ON (f.id_category = c.parent_id)
3376
            WHERE id_folder=%i',
3377
            $folder
3378
        );
3379
        if (DB::count() > 0) {
3380
            foreach ($rows_tmp as $row) {
3381
                $arrCatList[$row['id']] = array(
3382
                    'id' => $row['id'],
3383
                    'title' => $row['title'],
3384
                    'level' => $row['level'],
3385
                    'type' => $row['type'],
3386
                    'masked' => $row['masked'],
3387
                    'order' => $row['order'],
3388
                    'encrypted_data' => $row['encrypted_data'],
3389
                    'role_visibility' => $row['role_visibility'],
3390
                    'is_mandatory' => $row['is_mandatory'],
3391
                    'category_id' => $row['category_id'],
3392
                );
3393
            }
3394
        }
3395
        $arr_data['categories'] = $arrCatList;
3396
3397
        // Now get complexity
3398
        $valTemp = '';
3399
        $data = DB::queryFirstRow(
3400
            'SELECT valeur
3401
            FROM ' . prefixTable('misc') . '
3402
            WHERE type = %s AND intitule=%i',
3403
            'complex',
3404
            $folder
3405
        );
3406
        if (DB::count() > 0 && empty($data['valeur']) === false) {
3407
            $valTemp = array(
3408
                'value' => $data['valeur'],
3409
                'text' => TP_PW_COMPLEXITY[$data['valeur']][1],
3410
            );
3411
        }
3412
        $arr_data['complexity'] = $valTemp;
3413
3414
        // Now get Roles
3415
        $valTemp = '';
3416
        $rows_tmp = DB::query(
3417
            'SELECT t.title
3418
            FROM ' . prefixTable('roles_values') . ' as v
3419
            INNER JOIN ' . prefixTable('roles_title') . ' as t ON (v.role_id = t.id)
3420
            WHERE v.folder_id = %i
3421
            GROUP BY title',
3422
            $folder
3423
        );
3424
        foreach ($rows_tmp as $record) {
3425
            $valTemp .= (empty($valTemp) === true ? '' : ' - ') . $record['title'];
3426
        }
3427
        $arr_data['visibilityRoles'] = $valTemp;
3428
3429
        // now save in DB
3430
        DB::update(
3431
            prefixTable('nested_tree'),
3432
            array(
3433
                'categories' => json_encode($arr_data),
3434
            ),
3435
            'id = %i',
3436
            $folder
3437
        );
3438
    }
3439
}
3440
3441
/**
3442
 * List all users that have specific roles
3443
 *
3444
 * @param array $roles
3445
 * @return array
3446
 */
3447
function getUsersWithRoles(
3448
    array $roles
3449
): array
3450
{
3451
    $session = SessionManager::getSession();
3452
    $arrUsers = array();
3453
3454
    foreach ($roles as $role) {
3455
        // loop on users and check if user has this role
3456
        $rows = DB::query(
3457
            'SELECT id, fonction_id
3458
            FROM ' . prefixTable('users') . '
3459
            WHERE id != %i AND admin = 0 AND fonction_id IS NOT NULL AND fonction_id != ""',
3460
            $session->get('user-id')
3461
        );
3462
        foreach ($rows as $user) {
3463
            $userRoles = is_null($user['fonction_id']) === false && empty($user['fonction_id']) === false ? explode(';', $user['fonction_id']) : [];
3464
            if (in_array($role, $userRoles, true) === true) {
3465
                array_push($arrUsers, $user['id']);
3466
            }
3467
        }
3468
    }
3469
3470
    return $arrUsers;
3471
}
3472
3473
3474
/**
3475
 * Get all users informations
3476
 *
3477
 * @param integer $userId
3478
 * @return array
3479
 */
3480
function getFullUserInfos(
3481
    int $userId
3482
): array
3483
{
3484
    if (empty($userId) === true) {
3485
        return array();
3486
    }
3487
3488
    $val = DB::queryFirstRow(
3489
        'SELECT *
3490
        FROM ' . prefixTable('users') . '
3491
        WHERE id = %i',
3492
        $userId
3493
    );
3494
3495
    return $val;
3496
}
3497
3498
/**
3499
 * Is required an upgrade
3500
 *
3501
 * @return boolean
3502
 */
3503
function upgradeRequired(): bool
3504
{
3505
    // Get settings.php
3506
    include_once __DIR__. '/../includes/config/settings.php';
3507
3508
    // Get timestamp in DB
3509
    $val = DB::queryFirstRow(
3510
        'SELECT valeur
3511
        FROM ' . prefixTable('misc') . '
3512
        WHERE type = %s AND intitule = %s',
3513
        'admin',
3514
        'upgrade_timestamp'
3515
    );
3516
3517
    // Check if upgrade is required
3518
    return (
3519
        is_null($val) || count($val) === 0 || !defined('UPGRADE_MIN_DATE') || 
3520
        empty($val['valeur']) || (int) $val['valeur'] < (int) UPGRADE_MIN_DATE
3521
    );
3522
}
3523
3524
/**
3525
 * Permits to change the user keys on his demand
3526
 *
3527
 * @param integer $userId
3528
 * @param string $passwordClear
3529
 * @param integer $nbItemsToTreat
3530
 * @param string $encryptionKey
3531
 * @param boolean $deleteExistingKeys
3532
 * @param boolean $sendEmailToUser
3533
 * @param boolean $encryptWithUserPassword
3534
 * @param boolean $generate_user_new_password
3535
 * @param string $emailBody
3536
 * @param boolean $user_self_change
3537
 * @param string $recovery_public_key
3538
 * @param string $recovery_private_key
3539
 * @return string
3540
 */
3541
function handleUserKeys(
3542
    int $userId,
3543
    string $passwordClear,
3544
    int $nbItemsToTreat,
3545
    string $encryptionKey = '',
3546
    bool $deleteExistingKeys = false,
3547
    bool $sendEmailToUser = true,
3548
    bool $encryptWithUserPassword = false,
3549
    bool $generate_user_new_password = false,
3550
    string $emailBody = '',
3551
    bool $user_self_change = false,
3552
    string $recovery_public_key = '',
3553
    string $recovery_private_key = ''
3554
): string
3555
{
3556
    $session = SessionManager::getSession();
3557
    $lang = new Language($session->get('user-language') ?? 'english');
3558
3559
    // prepapre background tasks for item keys generation        
3560
    $userTP = DB::queryFirstRow(
3561
        'SELECT pw, public_key, private_key
3562
        FROM ' . prefixTable('users') . '
3563
        WHERE id = %i',
3564
        TP_USER_ID
3565
    );
3566
    if (DB::count() === 0) {
3567
        return prepareExchangedData(
3568
            array(
3569
                'error' => true,
3570
                'message' => 'User not exists',
3571
            ),
3572
            'encode'
3573
        );
3574
    }
3575
3576
    // Do we need to generate new user password
3577
    if ($generate_user_new_password === true) {
3578
        // Generate a new password
3579
        $passwordClear = GenerateCryptKey(20, false, true, true, false, true);
3580
    }
3581
3582
    // Create password hash
3583
    $passwordManager = new PasswordManager();
3584
    $hashedPassword = $passwordManager->hashPassword($passwordClear);
3585
    if ($passwordManager->verifyPassword($hashedPassword, $passwordClear) === false) {
3586
        return prepareExchangedData(
3587
            array(
3588
                'error' => true,
3589
                'message' => $lang->get('pw_hash_not_correct'),
3590
            ),
3591
            'encode'
3592
        );
3593
    }
3594
3595
    // Check if valid public/private keys
3596
    if ($recovery_public_key !== '' && $recovery_private_key !== '') {
3597
        try {
3598
            // Generate random string
3599
            $random_str = generateQuickPassword(12, false);
3600
            // Encrypt random string with user publick key
3601
            $encrypted = encryptUserObjectKey($random_str, $recovery_public_key);
3602
            // Decrypt $encrypted with private key
3603
            $decrypted = decryptUserObjectKey($encrypted, $recovery_private_key);
3604
            // Check if decryptUserObjectKey returns our random string
3605
            if ($decrypted !== $random_str) {
3606
                throw new Exception('Public/Private keypair invalid.');
3607
            }
3608
        } catch (Exception $e) {
3609
            // Show error message to user and log event
3610
            if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
3611
                error_log('ERROR: User '.$userId.' - '.$e->getMessage());
3612
            }
3613
            return prepareExchangedData([
3614
                    'error' => true,
3615
                    'message' => $lang->get('pw_encryption_error'),
3616
                ],
3617
                'encode'
3618
            );
3619
        }
3620
    }
3621
3622
    // Generate new keys
3623
    if ($user_self_change === true && empty($recovery_public_key) === false && empty($recovery_private_key) === false){
3624
        $userKeys = [
3625
            'public_key' => $recovery_public_key,
3626
            'private_key_clear' => $recovery_private_key,
3627
            'private_key' => encryptPrivateKey($passwordClear, $recovery_private_key),
3628
        ];
3629
    } else {
3630
        $userKeys = generateUserKeys($passwordClear);
3631
    }
3632
3633
    // Save in DB
3634
    DB::update(
3635
        prefixTable('users'),
3636
        array(
3637
            'pw' => $hashedPassword,
3638
            'public_key' => $userKeys['public_key'],
3639
            'private_key' => $userKeys['private_key'],
3640
            'keys_recovery_time' => NULL,
3641
        ),
3642
        'id=%i',
3643
        $userId
3644
    );
3645
3646
    // update session too
3647
    if ($userId === $session->get('user-id')) {
3648
        $session->set('user-private_key', $userKeys['private_key_clear']);
3649
        $session->set('user-public_key', $userKeys['public_key']);
3650
        // Notify user that he must re download his keys:
3651
        $session->set('user-keys_recovery_time', NULL);
3652
    }
3653
3654
    // Manage empty encryption key
3655
    // Let's take the user's password if asked and if no encryption key provided
3656
    $encryptionKey = $encryptWithUserPassword === true && empty($encryptionKey) === true ? $passwordClear : $encryptionKey;
3657
3658
    // Create process
3659
    DB::insert(
3660
        prefixTable('background_tasks'),
3661
        array(
3662
            'created_at' => time(),
3663
            'process_type' => 'create_user_keys',
3664
            'arguments' => json_encode([
3665
                'new_user_id' => (int) $userId,
3666
                'new_user_pwd' => cryption($passwordClear, '','encrypt')['string'],
3667
                'new_user_code' => cryption(empty($encryptionKey) === true ? uniqidReal(20) : $encryptionKey, '','encrypt')['string'],
3668
                'owner_id' => (int) TP_USER_ID,
3669
                'creator_pwd' => $userTP['pw'],
3670
                'send_email' => $sendEmailToUser === true ? 1 : 0,
3671
                'otp_provided_new_value' => 1,
3672
                'email_body' => empty($emailBody) === true ? '' : $lang->get($emailBody),
3673
                'user_self_change' => $user_self_change === true ? 1 : 0,
3674
            ]),
3675
        )
3676
    );
3677
    $processId = DB::insertId();
3678
3679
    // Delete existing keys
3680
    if ($deleteExistingKeys === true) {
3681
        deleteUserObjetsKeys(
3682
            (int) $userId,
3683
        );
3684
    }
3685
3686
    // Create tasks
3687
    createUserTasks($processId, $nbItemsToTreat);
3688
3689
    // update user's new status
3690
    DB::update(
3691
        prefixTable('users'),
3692
        [
3693
            'is_ready_for_usage' => 0,
3694
            'otp_provided' => 1,
3695
            'ongoing_process_id' => $processId,
3696
            'special' => 'generate-keys',
3697
        ],
3698
        'id=%i',
3699
        $userId
3700
    );
3701
3702
    return prepareExchangedData(
3703
        array(
3704
            'error' => false,
3705
            'message' => '',
3706
            'user_password' => $generate_user_new_password === true ? $passwordClear : '',
3707
        ),
3708
        'encode'
3709
    );
3710
}
3711
3712
/**
3713
 * Permits to generate a new password for a user
3714
 *
3715
 * @param integer $processId
3716
 * @param integer $nbItemsToTreat
3717
 * @return void
3718
 
3719
 */
3720
function createUserTasks($processId, $nbItemsToTreat): void
3721
{
3722
    // Create subtask for step 0
3723
    DB::insert(
3724
        prefixTable('background_subtasks'),
3725
        array(
3726
            'task_id' => $processId,
3727
            'created_at' => time(),
3728
            'task' => json_encode([
3729
                'step' => 'step0',
3730
                'index' => 0,
3731
                'nb' => $nbItemsToTreat,
3732
            ]),
3733
        )
3734
    );
3735
3736
    // Prepare the subtask queries
3737
    $queries = [
3738
        'step20' => 'SELECT * FROM ' . prefixTable('items'),
3739
3740
        'step30' => 'SELECT * FROM ' . prefixTable('log_items') . 
3741
                    ' WHERE raison LIKE "at_pw :%" AND encryption_type = "teampass_aes"',
3742
3743
        'step40' => 'SELECT * FROM ' . prefixTable('categories_items') . 
3744
                    ' WHERE encryption_type = "teampass_aes"',
3745
3746
        'step50' => 'SELECT * FROM ' . prefixTable('suggestion'),
3747
3748
        'step60' => 'SELECT * FROM ' . prefixTable('files') . ' AS f
3749
                        INNER JOIN ' . prefixTable('items') . ' AS i ON i.id = f.id_item
3750
                        WHERE f.status = "' . TP_ENCRYPTION_NAME . '"'
3751
    ];
3752
3753
    // Perform loop on $queries to create sub-tasks
3754
    foreach ($queries as $step => $query) {
3755
        DB::query($query);
3756
        createAllSubTasks($step, DB::count(), $nbItemsToTreat, $processId);
3757
    }
3758
}
3759
3760
/**
3761
 * Create all subtasks for a given action
3762
 * @param string $action The action to be performed
3763
 * @param int $totalElements Total number of elements to process
3764
 * @param int $elementsPerIteration Number of elements per iteration
3765
 * @param int $taskId The ID of the task
3766
 */
3767
function createAllSubTasks($action, $totalElements, $elementsPerIteration, $taskId) {
3768
    // Calculate the number of iterations
3769
    $iterations = ceil($totalElements / $elementsPerIteration);
3770
3771
    // Create the subtasks
3772
    for ($i = 0; $i < $iterations; $i++) {
3773
        DB::insert(prefixTable('background_subtasks'), [
3774
            'task_id' => $taskId,
3775
            'created_at' => time(),
3776
            'task' => json_encode([
3777
                "step" => $action,
3778
                "index" => $i * $elementsPerIteration,
3779
                "nb" => $elementsPerIteration,
3780
            ]),
3781
        ]);
3782
    }
3783
}
3784
3785
/**
3786
 * Permeits to check the consistency of date versus columns definition
3787
 *
3788
 * @param string $table
3789
 * @param array $dataFields
3790
 * @return array
3791
 */
3792
function validateDataFields(
3793
    string $table,
3794
    array $dataFields
3795
): array
3796
{
3797
    // Get table structure
3798
    $result = DB::query(
3799
        "SELECT `COLUMN_NAME`, `CHARACTER_MAXIMUM_LENGTH` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '%l' AND TABLE_NAME = '%l';",
3800
        DB_NAME,
3801
        $table
3802
    );
3803
3804
    foreach ($result as $row) {
3805
        $field = $row['COLUMN_NAME'];
3806
        $maxLength = is_null($row['CHARACTER_MAXIMUM_LENGTH']) === false ? (int) $row['CHARACTER_MAXIMUM_LENGTH'] : '';
3807
3808
        if (isset($dataFields[$field]) === true && is_array($dataFields[$field]) === false && empty($maxLength) === false) {
3809
            if (strlen((string) $dataFields[$field]) > $maxLength) {
3810
                return [
3811
                    'state' => false,
3812
                    'field' => $field,
3813
                    'maxLength' => $maxLength,
3814
                    'currentLength' => strlen((string) $dataFields[$field]),
3815
                ];
3816
            }
3817
        }
3818
    }
3819
    
3820
    return [
3821
        'state' => true,
3822
        'message' => '',
3823
    ];
3824
}
3825
3826
/**
3827
 * Adapt special characters sanitized during filter_var with option FILTER_SANITIZE_SPECIAL_CHARS operation
3828
 *
3829
 * @param string $string
3830
 * @return string
3831
 */
3832
function filterVarBack(string $string): string
3833
{
3834
    $arr = [
3835
        '&#060;' => '<',
3836
        '&#062;' => '>',
3837
        '&#034;' => '"',
3838
        '&#039;' => "'",
3839
        '&#038;' => '&',
3840
    ];
3841
3842
    foreach ($arr as $key => $value) {
3843
        $string = str_replace($key, $value, $string);
3844
    }
3845
3846
    return $string;
3847
}
3848
3849
/**
3850
 * 
3851
 */
3852
function storeTask(
3853
    string $taskName,
3854
    int $user_id,
3855
    int $is_personal_folder,
3856
    int $folder_destination_id,
3857
    int $item_id,
3858
    string $object_keys,
3859
    array $fields_keys = [],
3860
    array $files_keys = []
3861
)
3862
{
3863
    if (in_array($taskName, ['item_copy', 'new_item', 'update_item'])) {
3864
        // Create process
3865
        DB::insert(
3866
            prefixTable('background_tasks'),
3867
            array(
3868
                'created_at' => time(),
3869
                'process_type' => $taskName,
3870
                'arguments' => json_encode([
3871
                    'item_id' => $item_id,
3872
                    'object_key' => $object_keys,
3873
                ]),
3874
                'item_id' => $item_id,
3875
            )
3876
        );
3877
        $processId = DB::insertId();
3878
3879
        // Create tasks
3880
        // 1- Create password sharekeys for users of this new ITEM
3881
        DB::insert(
3882
            prefixTable('background_subtasks'),
3883
            array(
3884
                'task_id' => $processId,
3885
                'created_at' => time(),
3886
                'task' => json_encode([
3887
                    'step' => 'create_users_pwd_key',
3888
                    'index' => 0,
3889
                ]),
3890
            )
3891
        );
3892
3893
        // 2- Create fields sharekeys for users of this new ITEM
3894
        DB::insert(
3895
            prefixTable('background_subtasks'),
3896
            array(
3897
                'task_id' => $processId,
3898
                'created_at' => time(),
3899
                'task' => json_encode([
3900
                    'step' => 'create_users_fields_key',
3901
                    'index' => 0,
3902
                    'fields_keys' => $fields_keys,
3903
                ]),
3904
            )
3905
        );
3906
3907
        // 3- Create files sharekeys for users of this new ITEM
3908
        DB::insert(
3909
            prefixTable('background_subtasks'),
3910
            array(
3911
                'task_id' => $processId,
3912
                'created_at' => time(),
3913
                'task' => json_encode([
3914
                    'step' => 'create_users_files_key',
3915
                    'index' => 0,
3916
                    'files_keys' => $files_keys,
3917
                ]),
3918
            )
3919
        );
3920
    }
3921
}
3922
3923
/**
3924
 * 
3925
 */
3926
function createTaskForItem(
3927
    string $processType,
3928
    string|array $taskName,
3929
    int $itemId,
3930
    int $userId,
3931
    string $objectKey,
3932
    int $parentId = -1,
3933
    array $fields_keys = [],
3934
    array $files_keys = []
3935
)
3936
{
3937
    // 1- Create main process
3938
    // ---
3939
    
3940
    // Create process
3941
    DB::insert(
3942
        prefixTable('background_tasks'),
3943
        array(
3944
            'created_at' => time(),
3945
            'process_type' => $processType,
3946
            'arguments' => json_encode([
3947
                'all_users_except_id' => (int) $userId,
3948
                'item_id' => (int) $itemId,
3949
                'object_key' => $objectKey,
3950
                'author' => (int) $userId,
3951
            ]),
3952
            'item_id' => (int) $parentId !== -1 ?  $parentId : null,
3953
        )
3954
    );
3955
    $processId = DB::insertId();
3956
3957
    // 2- Create expected tasks
3958
    // ---
3959
    if (is_array($taskName) === false) {
0 ignored issues
show
introduced by
The condition is_array($taskName) === false is always false.
Loading history...
3960
        $taskName = [$taskName];
3961
    }
3962
    foreach($taskName as $task) {
3963
        if (WIP === true) error_log('createTaskForItem - task: '.$task);
3964
        switch ($task) {
3965
            case 'item_password':
3966
                
3967
                DB::insert(
3968
                    prefixTable('background_subtasks'),
3969
                    array(
3970
                        'task_id' => $processId,
3971
                        'created_at' => time(),
3972
                        'task' => json_encode([
3973
                            'step' => 'create_users_pwd_key',
3974
                            'index' => 0,
3975
                        ]),
3976
                    )
3977
                );
3978
3979
                break;
3980
            case 'item_field':
3981
                
3982
                DB::insert(
3983
                    prefixTable('background_subtasks'),
3984
                    array(
3985
                        'task_id' => $processId,
3986
                        'created_at' => time(),
3987
                        'task' => json_encode([
3988
                            'step' => 'create_users_fields_key',
3989
                            'index' => 0,
3990
                            'fields_keys' => $fields_keys,
3991
                        ]),
3992
                    )
3993
                );
3994
3995
                break;
3996
            case 'item_file':
3997
3998
                DB::insert(
3999
                    prefixTable('background_subtasks'),
4000
                    array(
4001
                        'task_id' => $processId,
4002
                        'created_at' => time(),
4003
                        'task' => json_encode([
4004
                            'step' => 'create_users_files_key',
4005
                            'index' => 0,
4006
                            'fields_keys' => $files_keys,
4007
                        ]),
4008
                    )
4009
                );
4010
                break;
4011
            default:
4012
                # code...
4013
                break;
4014
        }
4015
    }
4016
}
4017
4018
4019
function deleteProcessAndRelatedTasks(int $processId)
4020
{
4021
    // Delete process
4022
    DB::delete(
4023
        prefixTable('background_tasks'),
4024
        'id=%i',
4025
        $processId
4026
    );
4027
4028
    // Delete tasks
4029
    DB::delete(
4030
        prefixTable('background_subtasks'),
4031
        'task_id=%i',
4032
        $processId
4033
    );
4034
4035
}
4036
4037
/**
4038
 * Return PHP binary path
4039
 *
4040
 * @return string
4041
 */
4042
function getPHPBinary(): string
4043
{
4044
    // Get PHP binary path
4045
    $phpBinaryFinder = new PhpExecutableFinder();
4046
    $phpBinaryPath = $phpBinaryFinder->find();
4047
    return $phpBinaryPath === false ? 'false' : $phpBinaryPath;
4048
}
4049
4050
4051
4052
/**
4053
 * Delete unnecessary keys for personal items
4054
 *
4055
 * @param boolean $allUsers
4056
 * @param integer $user_id
4057
 * @return void
4058
 */
4059
function purgeUnnecessaryKeys(bool $allUsers = true, int $user_id=0)
4060
{
4061
    if ($allUsers === true) {
4062
        // Load class DB
4063
        if (class_exists('DB') === false) {
4064
            loadClasses('DB');
4065
        }
4066
4067
        $users = DB::query(
4068
            'SELECT id
4069
            FROM ' . prefixTable('users') . '
4070
            WHERE id NOT IN ('.OTV_USER_ID.', '.TP_USER_ID.', '.SSH_USER_ID.', '.API_USER_ID.')
4071
            ORDER BY login ASC'
4072
        );
4073
        foreach ($users as $user) {
4074
            purgeUnnecessaryKeysForUser((int) $user['id']);
4075
        }
4076
    } else {
4077
        purgeUnnecessaryKeysForUser((int) $user_id);
4078
    }
4079
}
4080
4081
/**
4082
 * Delete unnecessary keys for personal items
4083
 *
4084
 * @param integer $user_id
4085
 * @return void
4086
 */
4087
function purgeUnnecessaryKeysForUser(int $user_id=0)
4088
{
4089
    if ($user_id === 0) {
4090
        return;
4091
    }
4092
4093
    // Load class DB
4094
    loadClasses('DB');
4095
4096
    $personalItems = DB::queryFirstColumn(
4097
        'SELECT id
4098
        FROM ' . prefixTable('items') . ' AS i
4099
        INNER JOIN ' . prefixTable('log_items') . ' AS li ON li.id_item = i.id
4100
        WHERE i.perso = 1 AND li.action = "at_creation" AND li.id_user IN (%i, '.TP_USER_ID.')',
4101
        $user_id
4102
    );
4103
    if (count($personalItems) > 0) {
4104
        // Item keys
4105
        DB::delete(
4106
            prefixTable('sharekeys_items'),
4107
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4108
            $personalItems,
4109
            $user_id
4110
        );
4111
        // Files keys
4112
        DB::delete(
4113
            prefixTable('sharekeys_files'),
4114
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4115
            $personalItems,
4116
            $user_id
4117
        );
4118
        // Fields keys
4119
        DB::delete(
4120
            prefixTable('sharekeys_fields'),
4121
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4122
            $personalItems,
4123
            $user_id
4124
        );
4125
        // Logs keys
4126
        DB::delete(
4127
            prefixTable('sharekeys_logs'),
4128
            'object_id IN %li AND user_id NOT IN (%i, '.TP_USER_ID.')',
4129
            $personalItems,
4130
            $user_id
4131
        );
4132
    }
4133
}
4134
4135
/**
4136
 * Generate recovery keys file
4137
 *
4138
 * @param integer $userId
4139
 * @param array $SETTINGS
4140
 * @return string
4141
 */
4142
function handleUserRecoveryKeysDownload(int $userId, array $SETTINGS):string
4143
{
4144
    $session = SessionManager::getSession();
4145
    // Check if user exists
4146
    $userInfo = DB::queryFirstRow(
4147
        'SELECT login
4148
        FROM ' . prefixTable('users') . '
4149
        WHERE id = %i',
4150
        $userId
4151
    );
4152
4153
    if (DB::count() > 0) {
4154
        $now = (int) time();
4155
        // Prepare file content
4156
        $export_value = file_get_contents(__DIR__."/../includes/core/teampass_ascii.txt")."\n".
4157
            "Generation date: ".date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now)."\n\n".
4158
            "RECOVERY KEYS - Not to be shared - To be store safely\n\n".
4159
            "Public Key:\n".$session->get('user-public_key')."\n\n".
4160
            "Private Key:\n".$session->get('user-private_key')."\n\n";
4161
4162
        // Update user's keys_recovery_time
4163
        DB::update(
4164
            prefixTable('users'),
4165
            [
4166
                'keys_recovery_time' => $now,
4167
            ],
4168
            'id=%i',
4169
            $userId
4170
        );
4171
        $session->set('user-keys_recovery_time', $now);
4172
4173
        //Log into DB the user's disconnection
4174
        logEvents($SETTINGS, 'user_mngt', 'at_user_keys_download', (string) $userId, $userInfo['login']);
4175
        
4176
        // Return data
4177
        return prepareExchangedData(
4178
            array(
4179
                'error' => false,
4180
                'datetime' => date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now),
4181
                'timestamp' => $now,
4182
                'content' => base64_encode($export_value),
4183
                'login' => $userInfo['login'],
4184
            ),
4185
            'encode'
4186
        );
4187
    }
4188
4189
    return prepareExchangedData(
4190
        array(
4191
            'error' => true,
4192
            'datetime' => '',
4193
        ),
4194
        'encode'
4195
    );
4196
}
4197
4198
/**
4199
 * Permits to load expected classes
4200
 *
4201
 * @param string $className
4202
 * @return void
4203
 */
4204
function loadClasses(string $className = ''): void
4205
{
4206
    require_once __DIR__. '/../includes/config/include.php';
4207
    require_once __DIR__. '/../includes/config/settings.php';
4208
    require_once __DIR__.'/../vendor/autoload.php';
4209
4210
    if (defined('DB_PASSWD_CLEAR') === false) {
4211
        define('DB_PASSWD_CLEAR', defuseReturnDecrypted(DB_PASSWD, []));
4212
    }
4213
4214
    if (empty($className) === false) {
4215
        // Load class DB
4216
        if ((string) $className === 'DB') {
4217
            //Connect to DB
4218
            DB::$host = DB_HOST;
4219
            DB::$user = DB_USER;
4220
            DB::$password = DB_PASSWD_CLEAR;
4221
            DB::$dbName = DB_NAME;
4222
            DB::$port = DB_PORT;
4223
            DB::$encoding = DB_ENCODING;
4224
            DB::$ssl = DB_SSL;
4225
            DB::$connect_options = DB_CONNECT_OPTIONS;
4226
        }
4227
    }
4228
}
4229
4230
/**
4231
 * Returns the page the user is visiting.
4232
 *
4233
 * @return string The page name
4234
 */
4235
function getCurrectPage($SETTINGS)
4236
{
4237
    
4238
    $request = SymfonyRequest::createFromGlobals();
4239
4240
    // Parse the url
4241
    parse_str(
4242
        substr(
4243
            (string) $request->getRequestUri(),
4244
            strpos((string) $request->getRequestUri(), '?') + 1
4245
        ),
4246
        $result
4247
    );
4248
4249
    return $result['page'];
4250
}
4251
4252
/**
4253
 * Permits to return value if set
4254
 *
4255
 * @param string|int $value
4256
 * @param string|int|null $retFalse
4257
 * @param string|int $retTrue
4258
 * @return mixed
4259
 */
4260
function returnIfSet($value, $retFalse = '', $retTrue = null): mixed
4261
{
4262
4263
    return isset($value) === true ? ($retTrue === null ? $value : $retTrue) : $retFalse;
4264
}
4265
4266
4267
/**
4268
 * SEnd email to user
4269
 *
4270
 * @param string $post_receipt
4271
 * @param string $post_body
4272
 * @param string $post_subject
4273
 * @param array $post_replace
4274
 * @param boolean $immediate_email
4275
 * @param string $encryptedUserPassword
4276
 * @return string
4277
 */
4278
function sendMailToUser(
4279
    string $post_receipt,
4280
    string $post_body,
4281
    string $post_subject,
4282
    array $post_replace,
4283
    bool $immediate_email = false,
4284
    $encryptedUserPassword = ''
4285
): ?string {
4286
    global $SETTINGS;
4287
    $emailSettings = new EmailSettings($SETTINGS);
4288
    $emailService = new EmailService();
4289
    $antiXss = new AntiXSS();
4290
4291
    // Sanitize inputs
4292
    $post_receipt = filter_var($post_receipt, FILTER_SANITIZE_EMAIL);
4293
    $post_subject = $antiXss->xss_clean($post_subject);
4294
    $post_body = $antiXss->xss_clean($post_body);
4295
4296
    if (count($post_replace) > 0) {
4297
        $post_body = str_replace(
4298
            array_keys($post_replace),
4299
            array_values($post_replace),
4300
            $post_body
4301
        );
4302
    }
4303
4304
    // Remove newlines to prevent header injection
4305
    $post_body = str_replace(array("\r", "\n"), '', $post_body);    
4306
4307
    if ($immediate_email === true) {
4308
        // Send email
4309
        $ret = $emailService->sendMail(
4310
            $post_subject,
4311
            $post_body,
4312
            $post_receipt,
4313
            $emailSettings,
4314
            '',
4315
            false
4316
        );
4317
    
4318
        $ret = json_decode($ret, true);
4319
    
4320
        return prepareExchangedData(
4321
            array(
4322
                'error' => empty($ret['error']) === true ? false : true,
4323
                'message' => $ret['message'],
4324
            ),
4325
            'encode'
4326
        );
4327
    } else {
4328
        // Send through task handler
4329
        prepareSendingEmail(
4330
            $post_subject,
4331
            $post_body,
4332
            $post_receipt,
4333
            "",
4334
            $encryptedUserPassword,
4335
        );
4336
    }
4337
4338
    return null;
4339
}
4340
4341
/**
4342
 * Converts a password strengh value to zxcvbn level
4343
 * 
4344
 * @param integer $passwordStrength
4345
 * 
4346
 * @return integer
4347
 */
4348
function convertPasswordStrength($passwordStrength): int
4349
{
4350
    if ($passwordStrength === 0) {
4351
        return TP_PW_STRENGTH_1;
4352
    } else if ($passwordStrength === 1) {
4353
        return TP_PW_STRENGTH_2;
4354
    } else if ($passwordStrength === 2) {
4355
        return TP_PW_STRENGTH_3;
4356
    } else if ($passwordStrength === 3) {
4357
        return TP_PW_STRENGTH_4;
4358
    } else {
4359
        return TP_PW_STRENGTH_5;
4360
    }
4361
}
4362
4363
/**
4364
 * Check that a password is strong. The password needs to have at least :
4365
 *   - length >= 10.
4366
 *   - Uppercase and lowercase chars.
4367
 *   - Number or special char.
4368
 *   - Not contain username, name or mail part.
4369
 *   - Different from previous password.
4370
 * 
4371
 * @param string $password - Password to ckeck.
4372
 * @return bool - true if the password is strong, false otherwise.
4373
 */
4374
function isPasswordStrong($password) {
4375
    $session = SessionManager::getSession();
4376
4377
    // Password can't contain login, name or lastname
4378
    $forbiddenWords = [
4379
        $session->get('user-login'),
4380
        $session->get('user-name'),
4381
        $session->get('user-lastname'),
4382
    ];
4383
4384
    // Cut out the email
4385
    if ($email = $session->get('user-email')) {
4386
        $emailParts = explode('@', $email);
4387
4388
        if (count($emailParts) === 2) {
4389
            // Mail username (removed @domain.tld)
4390
            $forbiddenWords[] = $emailParts[0];
4391
4392
            // Organisation name (removed username@ and .tld)
4393
            $domain = explode('.', $emailParts[1]);
4394
            if (count($domain) > 1)
4395
                $forbiddenWords[] = $domain[0];
4396
        }
4397
    }
4398
4399
    // Search forbidden words in password
4400
    foreach ($forbiddenWords as $word) {
4401
        if (empty($word))
4402
            continue;
4403
4404
        // Stop if forbidden word found in password
4405
        if (stripos($password, $word) !== false)
4406
            return false;
4407
    }
4408
4409
    // Get password complexity
4410
    $length = strlen($password);
4411
    $hasUppercase = preg_match('/[A-Z]/', $password);
4412
    $hasLowercase = preg_match('/[a-z]/', $password);
4413
    $hasNumber = preg_match('/[0-9]/', $password);
4414
    $hasSpecialChar = preg_match('/[\W_]/', $password);
4415
4416
    // Get current user hash
4417
    $userHash = DB::queryFirstRow(
4418
        "SELECT pw FROM " . prefixtable('users') . " WHERE id = %d;",
4419
        $session->get('user-id')
4420
    )['pw'];
4421
4422
    $passwordManager = new PasswordManager();
4423
    
4424
    return $length >= 8
4425
           && $hasUppercase
4426
           && $hasLowercase
4427
           && ($hasNumber || $hasSpecialChar)
4428
           && !$passwordManager->verifyPassword($userHash, $password);
4429
}
4430