Passed
Pull Request — master (#4920)
by Nils
06:05
created

createUserMigrationTask()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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

1847
            /** @scrutinizer ignore-type */ $password
Loading history...
1848
        );
1849
    } elseif ($type === 'encrypt') {
1850
        // Encrypt file
1851
        $err = defuseFileEncrypt(
1852
            $source_file,
1853
            $target_file,
1854
            $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

1854
            /** @scrutinizer ignore-type */ $password
Loading history...
1855
        );
1856
    }
1857
1858
    // return error
1859
    return $err === true ? $err : '';
1860
}
1861
1862
/**
1863
 * Encrypt a file with Defuse.
1864
 *
1865
 * @param string $source_file path to source file
1866
 * @param string $target_file path to target file
1867
 * @param array  $SETTINGS    Settings
1868
 * @param string $password    A password
1869
 *
1870
 * @return string|bool
1871
 */
1872
function defuseFileEncrypt(
1873
    string $source_file,
1874
    string $target_file,
1875
    ?string $password = null
1876
) {
1877
    $err = '';
1878
    try {
1879
        CryptoFile::encryptFileWithPassword(
1880
            $source_file,
1881
            $target_file,
1882
            $password
1883
        );
1884
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1885
        $err = 'wrong_key';
1886
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1887
        error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage());
1888
        $err = 'environment_error';
1889
    } catch (CryptoException\IOException $ex) {
1890
        error_log('TEAMPASS-Error-General: ' . $ex->getMessage());
1891
        $err = 'general_error';
1892
    }
1893
1894
    // return error
1895
    return empty($err) === false ? $err : true;
1896
}
1897
1898
/**
1899
 * Decrypt a file with Defuse.
1900
 *
1901
 * @param string $source_file path to source file
1902
 * @param string $target_file path to target file
1903
 * @param string $password    A password
1904
 *
1905
 * @return string|bool
1906
 */
1907
function defuseFileDecrypt(
1908
    string $source_file,
1909
    string $target_file,
1910
    ?string $password = null
1911
) {
1912
    $err = '';
1913
    try {
1914
        CryptoFile::decryptFileWithPassword(
1915
            $source_file,
1916
            $target_file,
1917
            $password
1918
        );
1919
    } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) {
1920
        $err = 'wrong_key';
1921
    } catch (CryptoException\EnvironmentIsBrokenException $ex) {
1922
        error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage());
1923
        $err = 'environment_error';
1924
    } catch (CryptoException\IOException $ex) {
1925
        error_log('TEAMPASS-Error-General: ' . $ex->getMessage());
1926
        $err = 'general_error';
1927
    }
1928
1929
    // return error
1930
    return empty($err) === false ? $err : true;
1931
}
1932
1933
/*
1934
* NOT TO BE USED
1935
*/
1936
/**
1937
 * Undocumented function.
1938
 *
1939
 * @param string $text Text to debug
1940
 */
1941
function debugTeampass(string $text): void
1942
{
1943
    $debugFile = fopen('D:/wamp64/www/TeamPass/debug.txt', 'r+');
1944
    if ($debugFile !== false) {
1945
        fputs($debugFile, $text);
1946
        fclose($debugFile);
1947
    }
1948
}
1949
1950
/**
1951
 * DELETE the file with expected command depending on server type.
1952
 *
1953
 * @param string $file     Path to file
1954
 * @param array  $SETTINGS Teampass settings
1955
 *
1956
 * @return void
1957
 */
1958
function fileDelete(string $file, array $SETTINGS): void
1959
{
1960
    // Load AntiXSS
1961
    $antiXss = new AntiXSS();
1962
    $file = $antiXss->xss_clean($file);
1963
    if (is_file($file)) {
1964
        unlink($file);
1965
    }
1966
}
1967
1968
/**
1969
 * Permits to extract the file extension.
1970
 *
1971
 * @param string $file File name
1972
 *
1973
 * @return string
1974
 */
1975
function getFileExtension(string $file): string
1976
{
1977
    if (strpos($file, '.') === false) {
1978
        return $file;
1979
    }
1980
1981
    return substr($file, strrpos($file, '.') + 1);
1982
}
1983
1984
/**
1985
 * Chmods files and folders with different permissions.
1986
 *
1987
 * This is an all-PHP alternative to using: \n
1988
 * <tt>exec("find ".$path." -type f -exec chmod 644 {} \;");</tt> \n
1989
 * <tt>exec("find ".$path." -type d -exec chmod 755 {} \;");</tt>
1990
 *
1991
 * @author Jeppe Toustrup (tenzer at tenzer dot dk)
1992
  *
1993
 * @param string $path      An either relative or absolute path to a file or directory which should be processed.
1994
 * @param int    $filePerm The permissions any found files should get.
1995
 * @param int    $dirPerm  The permissions any found folder should get.
1996
 *
1997
 * @return bool Returns TRUE if the path if found and FALSE if not.
1998
 *
1999
 * @warning The permission levels has to be entered in octal format, which
2000
 * normally means adding a zero ("0") in front of the permission level. \n
2001
 * More info at: http://php.net/chmod.
2002
*/
2003
2004
function recursiveChmod(
2005
    string $path,
2006
    int $filePerm = 0644,
2007
    int  $dirPerm = 0755
2008
) {
2009
    // Check if the path exists
2010
    $path = basename($path);
2011
    if (! file_exists($path)) {
2012
        return false;
2013
    }
2014
2015
    // See whether this is a file
2016
    if (is_file($path)) {
2017
        // Chmod the file with our given filepermissions
2018
        try {
2019
            chmod($path, $filePerm);
2020
        } catch (Exception $e) {
2021
            return false;
2022
        }
2023
    // If this is a directory...
2024
    } elseif (is_dir($path)) {
2025
        // Then get an array of the contents
2026
        $foldersAndFiles = scandir($path);
2027
        // Remove "." and ".." from the list
2028
        $entries = array_slice($foldersAndFiles, 2);
2029
        // Parse every result...
2030
        foreach ($entries as $entry) {
2031
            // And call this function again recursively, with the same permissions
2032
            recursiveChmod($path.'/'.$entry, $filePerm, $dirPerm);
2033
        }
2034
2035
        // When we are done with the contents of the directory, we chmod the directory itself
2036
        try {
2037
            chmod($path, $filePerm);
2038
        } catch (Exception $e) {
2039
            return false;
2040
        }
2041
    }
2042
2043
    // Everything seemed to work out well, return true
2044
    return true;
2045
}
2046
2047
/**
2048
 * Check if user can access to this item.
2049
 *
2050
 * @param int   $item_id ID of item
2051
 * @param array $SETTINGS
2052
 *
2053
 * @return bool|string
2054
 */
2055
function accessToItemIsGranted(int $item_id, array $SETTINGS)
2056
{
2057
    
2058
    $session = SessionManager::getSession();
2059
    $session_groupes_visibles = $session->get('user-accessible_folders');
2060
    $session_list_restricted_folders_for_items = $session->get('system-list_restricted_folders_for_items');
2061
    // Load item data
2062
    $data = DB::queryFirstRow(
2063
        'SELECT id_tree
2064
        FROM ' . prefixTable('items') . '
2065
        WHERE id = %i',
2066
        $item_id
2067
    );
2068
    // Check if user can access this folder
2069
    if (in_array($data['id_tree'], $session_groupes_visibles) === false) {
2070
        // Now check if this folder is restricted to user
2071
        if (isset($session_list_restricted_folders_for_items[$data['id_tree']]) === true
2072
            && in_array($item_id, $session_list_restricted_folders_for_items[$data['id_tree']]) === false
2073
        ) {
2074
            return 'ERR_FOLDER_NOT_ALLOWED';
2075
        }
2076
    }
2077
2078
    return true;
2079
}
2080
2081
/**
2082
 * Creates a unique key.
2083
 *
2084
 * @param int $lenght Key lenght
2085
 *
2086
 * @return string
2087
 */
2088
function uniqidReal(int $lenght = 13): string
2089
{
2090
    if (function_exists('random_bytes')) {
2091
        $bytes = random_bytes(intval(ceil($lenght / 2)));
2092
    } elseif (function_exists('openssl_random_pseudo_bytes')) {
2093
        $bytes = openssl_random_pseudo_bytes(intval(ceil($lenght / 2)));
2094
    } else {
2095
        throw new Exception('no cryptographically secure random function available');
2096
    }
2097
2098
    return substr(bin2hex($bytes), 0, $lenght);
2099
}
2100
2101
/**
2102
 * Obfuscate an email.
2103
 *
2104
 * @param string $email Email address
2105
 *
2106
 * @return string
2107
 */
2108
function obfuscateEmail(string $email): string
2109
{
2110
    $email = explode("@", $email);
2111
    $name = $email[0];
2112
    if (strlen($name) > 3) {
2113
        $name = substr($name, 0, 2);
2114
        for ($i = 0; $i < strlen($email[0]) - 3; $i++) {
2115
            $name .= "*";
2116
        }
2117
        $name .= substr($email[0], -1, 1);
2118
    }
2119
    $host = explode(".", $email[1])[0];
2120
    if (strlen($host) > 3) {
2121
        $host = substr($host, 0, 1);
2122
        for ($i = 0; $i < strlen(explode(".", $email[1])[0]) - 2; $i++) {
2123
            $host .= "*";
2124
        }
2125
        $host .= substr(explode(".", $email[1])[0], -1, 1);
2126
    }
2127
    $email = $name . "@" . $host . "." . explode(".", $email[1])[1];
2128
    return $email;
2129
}
2130
2131
/**
2132
 * Get id and title from role_titles table.
2133
 *
2134
 * @return array
2135
 */
2136
function getRolesTitles(): array
2137
{
2138
    // Load class DB
2139
    loadClasses('DB');
2140
    
2141
    // Insert log in DB
2142
    return DB::query(
2143
        'SELECT id, title
2144
        FROM ' . prefixTable('roles_title')
2145
    );
2146
}
2147
2148
/**
2149
 * Undocumented function.
2150
 *
2151
 * @param int $bytes Size of file
2152
 *
2153
 * @return string
2154
 */
2155
function formatSizeUnits(int $bytes): string
2156
{
2157
    if ($bytes >= 1073741824) {
2158
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
2159
    } elseif ($bytes >= 1048576) {
2160
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
2161
    } elseif ($bytes >= 1024) {
2162
        $bytes = number_format($bytes / 1024, 2) . ' KB';
2163
    } elseif ($bytes > 1) {
2164
        $bytes .= ' bytes';
2165
    } elseif ($bytes === 1) {
2166
        $bytes .= ' byte';
2167
    } else {
2168
        $bytes = '0 bytes';
2169
    }
2170
2171
    return $bytes;
2172
}
2173
2174
/**
2175
 * Generate user pair of keys.
2176
 *
2177
 * @param string $userPwd User password
2178
 *
2179
 * @return array
2180
 */
2181
function generateUserKeys(string $userPwd, ?array $SETTINGS = null): array
2182
{
2183
    // Sanitize
2184
    $antiXss = new AntiXSS();
2185
    $userPwd = $antiXss->xss_clean($userPwd);
2186
    // Load classes
2187
    $rsa = new Crypt_RSA();
2188
    $cipher = new Crypt_AES();
2189
    // Create the private and public key
2190
    $res = $rsa->createKey(4096);
2191
    // Encrypt the privatekey
2192
    $cipher->setPassword($userPwd);
2193
    $privatekey = $cipher->encrypt($res['privatekey']);
2194
2195
    $result = [
2196
        'private_key' => base64_encode($privatekey),
2197
        'public_key' => base64_encode($res['publickey']),
2198
        'private_key_clear' => base64_encode($res['privatekey']),
2199
    ];
2200
2201
    // Generate transparent recovery data
2202
    // Generate unique seed for this user
2203
    $userSeed = bin2hex(openssl_random_pseudo_bytes(32));
2204
2205
    // Derive backup encryption key
2206
    $derivedKey = deriveBackupKey($userSeed, $result['public_key'], $SETTINGS);
2207
2208
    // Encrypt private key with derived key (backup)
2209
    $cipherBackup = new Crypt_AES();
2210
    $cipherBackup->setPassword($derivedKey);
2211
    $privatekeyBackup = $cipherBackup->encrypt($res['privatekey']);
2212
2213
    // Generate integrity hash
2214
    $serverSecret = getServerSecret();
2215
    $integrityHash = generateKeyIntegrityHash($userSeed, $result['public_key'], $serverSecret);
2216
2217
    $result['user_seed'] = $userSeed;
2218
    $result['private_key_backup'] = base64_encode($privatekeyBackup);
2219
    $result['key_integrity_hash'] = $integrityHash;
2220
2221
    return $result;
2222
}
2223
2224
/**
2225
 * Permits to decrypt the user's privatekey.
2226
 *
2227
 * @param string $userPwd        User password
2228
 * @param string $userPrivateKey User private key
2229
 *
2230
 * @return string|object
2231
 */
2232
function decryptPrivateKey(string $userPwd, string $userPrivateKey)
2233
{
2234
    // Sanitize
2235
    $antiXss = new AntiXSS();
2236
    $userPwd = $antiXss->xss_clean($userPwd);
2237
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2238
2239
    if (empty($userPwd) === false) {
2240
        // Load classes
2241
        $cipher = new Crypt_AES();
2242
        // Encrypt the privatekey
2243
        $cipher->setPassword($userPwd);
2244
        try {
2245
            return base64_encode((string) $cipher->decrypt(base64_decode($userPrivateKey)));
2246
        } catch (Exception $e) {
2247
            return $e;
2248
        }
2249
    }
2250
    return '';
2251
}
2252
2253
/**
2254
 * Permits to encrypt the user's privatekey.
2255
 *
2256
 * @param string $userPwd        User password
2257
 * @param string $userPrivateKey User private key
2258
 *
2259
 * @return string
2260
 */
2261
function encryptPrivateKey(string $userPwd, string $userPrivateKey): string
2262
{
2263
    // Sanitize
2264
    $antiXss = new AntiXSS();
2265
    $userPwd = $antiXss->xss_clean($userPwd);
2266
    $userPrivateKey = $antiXss->xss_clean($userPrivateKey);
2267
2268
    if (empty($userPwd) === false) {
2269
        // Load classes
2270
        $cipher = new Crypt_AES();
2271
        // Encrypt the privatekey
2272
        $cipher->setPassword($userPwd);        
2273
        try {
2274
            return base64_encode($cipher->encrypt(base64_decode($userPrivateKey)));
2275
        } catch (Exception $e) {
2276
            return $e->getMessage();
2277
        }
2278
    }
2279
    return '';
2280
}
2281
2282
/**
2283
 * Derives a backup encryption key from user seed and public key.
2284
 * Uses PBKDF2 with 100k iterations for strong key derivation.
2285
 *
2286
 * @param string $userSeed User's unique derivation seed (64 hex chars)
2287
 * @param string $publicKey User's public RSA key (base64 encoded)
2288
 * @param array $SETTINGS Teampass settings
2289
 *
2290
 * @return string Derived key (32 bytes, raw binary)
2291
 */
2292
function deriveBackupKey(string $userSeed, string $publicKey, ?array $SETTINGS = null): string
2293
{
2294
    // Sanitize inputs
2295
    $antiXss = new AntiXSS();
2296
    $userSeed = $antiXss->xss_clean($userSeed);
2297
    $publicKey = $antiXss->xss_clean($publicKey);
2298
2299
    // Use public key hash as salt for key derivation
2300
    $salt = hash('sha256', $publicKey, true);
2301
2302
    // Get PBKDF2 iterations from settings (default 100000)
2303
    $iterations = isset($SETTINGS['transparent_key_recovery_pbkdf2_iterations'])
2304
        ? (int) $SETTINGS['transparent_key_recovery_pbkdf2_iterations']
2305
        : 100000;
2306
2307
    // PBKDF2 key derivation with SHA256
2308
    return hash_pbkdf2(
2309
        'sha256',
2310
        hex2bin($userSeed),
2311
        $salt,
2312
        $iterations,
2313
        32, // 256 bits key length
2314
        true // raw binary output
2315
    );
2316
}
2317
2318
/**
2319
 * Generates key integrity hash to detect tampering.
2320
 *
2321
 * @param string $userSeed User derivation seed
2322
 * @param string $publicKey User public key
2323
 * @param string $serverSecret Server-wide secret key
2324
 *
2325
 * @return string HMAC hash (64 hex chars)
2326
 */
2327
function generateKeyIntegrityHash(string $userSeed, string $publicKey, string $serverSecret): string
2328
{
2329
    return hash_hmac('sha256', $userSeed . $publicKey, $serverSecret);
2330
}
2331
2332
/**
2333
 * Verifies key integrity to detect SQL injection or tampering.
2334
 *
2335
 * @param array $userInfo User information from database
2336
 * @param string $serverSecret Server-wide secret key
2337
 *
2338
 * @return bool True if integrity is valid
2339
 */
2340
function verifyKeyIntegrity(array $userInfo, string $serverSecret): bool
2341
{
2342
    // Skip check if no integrity hash stored (legacy users)
2343
    if (empty($userInfo['key_integrity_hash'])) {
2344
        return true;
2345
    }
2346
2347
    if (empty($userInfo['user_derivation_seed']) || empty($userInfo['public_key'])) {
2348
        return false;
2349
    }
2350
2351
    $expectedHash = generateKeyIntegrityHash(
2352
        $userInfo['user_derivation_seed'],
2353
        $userInfo['public_key'],
2354
        $serverSecret
2355
    );
2356
2357
    return hash_equals($expectedHash, $userInfo['key_integrity_hash']);
2358
}
2359
2360
/**
2361
 * Gets server secret for integrity checks.
2362
 * Reads from file or generates if not exists.
2363
 * *
2364
 * @return string Server secret key
2365
 */
2366
function getServerSecret(): string
2367
{
2368
    $ascii_key = file_get_contents(SECUREPATH.'/'.SECUREFILE);
2369
    $key = Key::loadFromAsciiSafeString($ascii_key);
2370
    return $key->saveToAsciiSafeString();
2371
}
2372
2373
/**
2374
 * Attempts transparent recovery when password change is detected.
2375
 *
2376
 * @param array $userInfo User information from database
2377
 * @param string $newPassword New password (clear)
2378
 * @param array $SETTINGS Teampass settings
2379
 *
2380
 * @return array Result with private key or error
2381
 */
2382
function attemptTransparentRecovery(array $userInfo, string $newPassword, array $SETTINGS): array
2383
{
2384
    $session = SessionManager::getSession();
2385
    try {
2386
        // Check if user has recovery data
2387
        if (empty($userInfo['user_derivation_seed']) || empty($userInfo['private_key_backup'])) {
2388
            return [
2389
                'success' => false,
2390
                'error' => 'no_recovery_data',
2391
                'private_key_clear' => '',
2392
            ];
2393
        }
2394
2395
        // Verify key integrity
2396
        $serverSecret = getServerSecret();
2397
        if (!verifyKeyIntegrity($userInfo, $serverSecret)) {
2398
            // Critical security event - integrity check failed
2399
            logEvents(
2400
                $SETTINGS,
2401
                'security_alert',
2402
                'key_integrity_check_failed',
2403
                (string) $userInfo['id'],
2404
                'User: ' . $userInfo['login']
2405
            );
2406
            return [
2407
                'success' => false,
2408
                'error' => 'integrity_check_failed',
2409
                'private_key_clear' => '',
2410
            ];
2411
        }
2412
2413
        // Derive backup key
2414
        $derivedKey = deriveBackupKey(
2415
            $userInfo['user_derivation_seed'],
2416
            $userInfo['public_key'],
2417
            $SETTINGS
2418
        );
2419
2420
        // Decrypt private key using derived key
2421
        $cipher = new Crypt_AES();
2422
        $cipher->setPassword($derivedKey);
2423
        $privateKeyClear = base64_encode($cipher->decrypt(base64_decode($userInfo['private_key_backup'])));
2424
2425
        // Re-encrypt with new password
2426
        $newPrivateKeyEncrypted = encryptPrivateKey($newPassword, $privateKeyClear);
2427
2428
        // Re-encrypt backup with derived key (refresh)
2429
        $cipher->setPassword($derivedKey);
2430
        $newPrivateKeyBackup = base64_encode($cipher->encrypt(base64_decode($privateKeyClear)));
2431
        
2432
        // Update database
2433
        DB::update(
2434
            prefixTable('users'),
2435
            [
2436
                'private_key' => $newPrivateKeyEncrypted,
2437
                'private_key_backup' => $newPrivateKeyBackup,
2438
                'last_pw_change' => time(),
2439
                'special' => 'none',
2440
            ],
2441
            'id = %i',
2442
            $userInfo['id']
2443
        );
2444
2445
        // Log success
2446
        logEvents(
2447
            $SETTINGS,
2448
            'user_connection',
2449
            'auto_reencryption_success',
2450
            (string) $userInfo['id'],
2451
            'User: ' . $userInfo['login']
2452
        );
2453
2454
        // Store in session for immediate use
2455
        $session->set('user-private_key', $privateKeyClear);
2456
        $session->set('user-private_key_recovered', true);
2457
2458
        return [
2459
            'success' => true,
2460
            'error' => '',
2461
        ];
2462
2463
    } catch (Exception $e) {
2464
        // Log failure
2465
        logEvents(
2466
            $SETTINGS,
2467
            'security_alert',
2468
            'auto_reencryption_failed',
2469
            (string) $userInfo['id'],
2470
            'User: ' . $userInfo['login'] . ' - Error: ' . $e->getMessage()
2471
        );
2472
2473
        return [
2474
            'success' => false,
2475
            'error' => 'decryption_failed: ' . $e->getMessage(),
2476
            'private_key_clear' => '',
2477
        ];
2478
    }
2479
}
2480
2481
/**
2482
 * Handles external password change (LDAP/OAuth2) with automatic re-encryption.
2483
 *
2484
 * @param int $userId User ID
2485
 * @param string $newPassword New password (clear)
2486
 * @param array $userInfo User information from database
2487
 * @param array $SETTINGS Teampass settings
2488
 *
2489
 * @return bool True if  handled successfully
2490
 */
2491
function handleExternalPasswordChange(int $userId, string $newPassword, array $userInfo, array $SETTINGS): bool
2492
{
2493
    // Check if password was changed recently (< 30s) to avoid duplicate processing
2494
    if (!empty($userInfo['last_pw_change'])) {
2495
        $timeSinceChange = time() - (int) $userInfo['last_pw_change'];
2496
        if ($timeSinceChange < 30) { // 30 seconds
2497
            return true; // Already processed
2498
        }
2499
    }
2500
2501
    // Try to decrypt with new password first (maybe already updated)
2502
    try {
2503
        $testDecrypt = decryptPrivateKey($newPassword, $userInfo['private_key']);
2504
        if (!empty($testDecrypt)) {
2505
            // Password already works, just update timestamp
2506
            DB::update(
2507
                prefixTable('users'),
2508
                ['last_pw_change' => time()],
2509
                'id = %i',
2510
                $userId
2511
            );
2512
            return true;
2513
        }
2514
    } catch (Exception $e) {
2515
        // Expected - old password doesn't work, continue with recovery
2516
    }
2517
2518
    // Attempt transparent recovery
2519
    $result = attemptTransparentRecovery($userInfo, $newPassword, $SETTINGS);
2520
2521
    if ($result['success']) {
2522
        return true;
2523
    }
2524
2525
    // Recovery failed - disable user and alert admins
2526
    DB::update(
2527
        prefixTable('users'),
2528
        [
2529
            'disabled' => 1,
2530
            'special' => 'recrypt-private-key',
2531
        ],
2532
        'id = %i',
2533
        $userId
2534
    );
2535
2536
    // Log critical event
2537
    logEvents(
2538
        $SETTINGS,
2539
        'security_alert',
2540
        'auto_reencryption_critical_failure',
2541
        (string) $userId,
2542
        'User: ' . $userInfo['login'] . ' - disabled due to key recovery failure'
2543
    );
2544
2545
    return false;
2546
}
2547
2548
/**
2549
 * Encrypts a string using AES.
2550
 *
2551
 * @param string $data String to encrypt
2552
 * @param string $key
2553
 *
2554
 * @return array
2555
 */
2556
function doDataEncryption(string $data, ?string $key = null): array
2557
{
2558
    // Sanitize
2559
    $antiXss = new AntiXSS();
2560
    $data = $antiXss->xss_clean($data);
2561
    
2562
    // Load classes
2563
    $cipher = new Crypt_AES(CRYPT_AES_MODE_CBC);
2564
    // Generate an object key
2565
    $objectKey = is_null($key) === true ? uniqidReal(KEY_LENGTH) : $antiXss->xss_clean($key);
2566
    // Set it as password
2567
    $cipher->setPassword($objectKey);
2568
    return [
2569
        'encrypted' => base64_encode($cipher->encrypt($data)),
2570
        'objectKey' => base64_encode($objectKey),
2571
    ];
2572
}
2573
2574
/**
2575
 * Decrypts a string using AES.
2576
 *
2577
 * @param string $data Encrypted data
2578
 * @param string $key  Key to uncrypt
2579
 *
2580
 * @return string
2581
 */
2582
function doDataDecryption(string $data, string $key): string
2583
{
2584
    // Sanitize
2585
    $antiXss = new AntiXSS();
2586
    $data = $antiXss->xss_clean($data);
2587
    $key = $antiXss->xss_clean($key);
2588
2589
    // Load classes
2590
    $cipher = new Crypt_AES();
2591
    // Set the object key
2592
    $cipher->setPassword(base64_decode($key));
2593
    return base64_encode((string) $cipher->decrypt(base64_decode($data)));
2594
}
2595
2596
/**
2597
 * Encrypts using RSA a string using a public key.
2598
 *
2599
 * @param string $key       Key to be encrypted
2600
 * @param string $publicKey User public key
2601
 *
2602
 * @return string
2603
 */
2604
function encryptUserObjectKey(string $key, string $publicKey): string
2605
{
2606
    // Empty password
2607
    if (empty($key)) return '';
2608
2609
    // Sanitize
2610
    $antiXss = new AntiXSS();
2611
    $publicKey = $antiXss->xss_clean($publicKey);
2612
    // Load classes
2613
    $rsa = new Crypt_RSA();
2614
    // Load the public key
2615
    $decodedPublicKey = base64_decode($publicKey, true);
2616
    if ($decodedPublicKey === false) {
2617
        throw new InvalidArgumentException("Error while decoding key.");
2618
    }
2619
    $rsa->loadKey($decodedPublicKey);
2620
    // Encrypt
2621
    $encrypted = $rsa->encrypt(base64_decode($key));
2622
    if (empty($encrypted)) {  // Check if key is empty or null
2623
        throw new RuntimeException("Error while encrypting key.");
2624
    }
2625
    // Return
2626
    return base64_encode($encrypted);
2627
}
2628
2629
/**
2630
 * Decrypts using RSA an encrypted string using a private key.
2631
 *
2632
 * @param string $key        Encrypted key
2633
 * @param string $privateKey User private key
2634
 *
2635
 * @return string
2636
 */
2637
function decryptUserObjectKey(string $key, string $privateKey): string
2638
{
2639
    // Sanitize
2640
    $antiXss = new AntiXSS();
2641
    $privateKey = $antiXss->xss_clean($privateKey);
2642
2643
    // Load classes
2644
    $rsa = new Crypt_RSA();
2645
    // Load the private key
2646
    $decodedPrivateKey = base64_decode($privateKey, true);
2647
    if ($decodedPrivateKey === false) {
2648
        throw new InvalidArgumentException("Error while decoding private key.");
2649
    }
2650
2651
    $rsa->loadKey($decodedPrivateKey);
2652
2653
    // Decrypt
2654
    try {
2655
        $decodedKey = base64_decode($key, true);
2656
        if ($decodedKey === false) {
2657
            throw new InvalidArgumentException("Error while decoding key.");
2658
        }
2659
2660
        // This check is needed as decrypt() in version 2 can return false in case of error
2661
        $tmpValue = $rsa->decrypt($decodedKey);
2662
        if ($tmpValue !== false) {
0 ignored issues
show
introduced by
The condition $tmpValue !== false is always true.
Loading history...
2663
            return base64_encode($tmpValue);
2664
        } else {
2665
            return '';
2666
        }
2667
    } catch (Exception $e) {
2668
        if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
2669
            error_log('TEAMPASS Error - ldap - '.$e->getMessage());
2670
        }
2671
        return 'Exception: could not decrypt object';
2672
    }
2673
}
2674
2675
/**
2676
 * Encrypts a file.
2677
 *
2678
 * @param string $fileInName File name
2679
 * @param string $fileInPath Path to file
2680
 *
2681
 * @return array
2682
 */
2683
function encryptFile(string $fileInName, string $fileInPath): array
2684
{
2685
    if (defined('FILE_BUFFER_SIZE') === false) {
2686
        define('FILE_BUFFER_SIZE', 128 * 1024);
2687
    }
2688
2689
    // Load classes
2690
    $cipher = new Crypt_AES();
2691
2692
    // Generate an object key
2693
    $objectKey = uniqidReal(32);
2694
    // Set it as password
2695
    $cipher->setPassword($objectKey);
2696
    // Prevent against out of memory
2697
    $cipher->enableContinuousBuffer();
2698
2699
    // Encrypt the file content
2700
    $filePath = filter_var($fileInPath . '/' . $fileInName, FILTER_SANITIZE_URL);
2701
    $fileContent = file_get_contents($filePath);
2702
    $plaintext = $fileContent;
2703
    $ciphertext = $cipher->encrypt($plaintext);
2704
2705
    // Save new file
2706
    // deepcode ignore InsecureHash: is simply used to get a unique name
2707
    $hash = uniqid('', true);
2708
    $fileOut = $fileInPath . '/' . TP_FILE_PREFIX . $hash;
2709
    file_put_contents($fileOut, $ciphertext);
2710
    unlink($fileInPath . '/' . $fileInName);
2711
    return [
2712
        'fileHash' => base64_encode($hash),
2713
        'objectKey' => base64_encode($objectKey),
2714
    ];
2715
}
2716
2717
/**
2718
 * Decrypt a file.
2719
 *
2720
 * @param string $fileName File name
2721
 * @param string $filePath Path to file
2722
 * @param string $key      Key to use
2723
 *
2724
 * @return string|array
2725
 */
2726
function decryptFile(string $fileName, string $filePath, string $key): string|array
2727
{
2728
    if (! defined('FILE_BUFFER_SIZE')) {
2729
        define('FILE_BUFFER_SIZE', 128 * 1024);
2730
    }
2731
    
2732
    // Load classes
2733
    $cipher = new Crypt_AES();
2734
    $antiXSS = new AntiXSS();
2735
    
2736
    // Get file name
2737
    $safeFileName = $antiXSS->xss_clean(base64_decode($fileName));
2738
2739
    // Set the object key
2740
    $cipher->setPassword(base64_decode($key));
2741
    // Prevent against out of memory
2742
    $cipher->enableContinuousBuffer();
2743
    $cipher->disablePadding();
2744
    // Get file content
2745
    $safeFilePath = realpath($filePath . '/' . TP_FILE_PREFIX . $safeFileName);
2746
    if ($safeFilePath !== false && file_exists($safeFilePath)) {
2747
        $ciphertext = file_get_contents(filter_var($safeFilePath, FILTER_SANITIZE_URL));
2748
    } else {
2749
        // Handle the error: file doesn't exist or path is invalid
2750
        return [
2751
            'error' => true,
2752
            'message' => 'This file has not been found.',
2753
        ];
2754
    }
2755
2756
    if (WIP) error_log('DEBUG: File image url -> '.filter_var($safeFilePath, FILTER_SANITIZE_URL));
2757
2758
    // Decrypt file content and return
2759
    return base64_encode($cipher->decrypt($ciphertext));
2760
}
2761
2762
/**
2763
 * Generate a simple password
2764
 *
2765
 * @param int $length Length of string
2766
 * @param bool $symbolsincluded Allow symbols
2767
 *
2768
 * @return string
2769
 */
2770
function generateQuickPassword(int $length = 16, bool $symbolsincluded = true): string
2771
{
2772
    // Generate new user password
2773
    $small_letters = range('a', 'z');
2774
    $big_letters = range('A', 'Z');
2775
    $digits = range(0, 9);
2776
    $symbols = $symbolsincluded === true ?
2777
        ['#', '_', '-', '@', '$', '+', '!'] : [];
2778
    $res = array_merge($small_letters, $big_letters, $digits, $symbols);
2779
    $count = count($res);
2780
    // first variant
2781
2782
    $random_string = '';
2783
    for ($i = 0; $i < $length; ++$i) {
2784
        $random_string .= $res[random_int(0, $count - 1)];
2785
    }
2786
2787
    return $random_string;
2788
}
2789
2790
/**
2791
 * Permit to store the sharekey of an object for users.
2792
 *
2793
 * @param string $object_name             Type for table selection
2794
 * @param int    $post_folder_is_personal Personal
2795
 * @param int    $post_object_id          Object
2796
 * @param string $objectKey               Object key
2797
 * @param array  $SETTINGS                Teampass settings
2798
 * @param int    $user_id                 User ID if needed
2799
 * @param bool   $onlyForUser             If is TRUE, then the sharekey is only for the user
2800
 * @param bool   $deleteAll               If is TRUE, then all existing entries are deleted
2801
 * @param array  $objectKeyArray          Array of objects
2802
 * @param int    $all_users_except_id     All users except this one
2803
 * @param int    $apiUserId               API User ID
2804
 *
2805
 * @return void
2806
 */
2807
function storeUsersShareKey(
2808
    string $object_name,
2809
    int $post_folder_is_personal,
2810
    int $post_object_id,
2811
    string $objectKey,
2812
    bool $onlyForUser = false,
2813
    bool $deleteAll = true,
2814
    array $objectKeyArray = [],
2815
    int $all_users_except_id = -1,
2816
    int $apiUserId = -1
2817
): void {
2818
    
2819
    $session = SessionManager::getSession();
2820
    loadClasses('DB');
2821
2822
    // Delete existing entries for this object
2823
    if ($deleteAll === true) {
2824
        DB::delete(
2825
            $object_name,
2826
            'object_id = %i',
2827
            $post_object_id
2828
        );
2829
    }
2830
2831
    // Get the user ID
2832
    $userId = ($apiUserId === -1) ? (int) $session->get('user-id') : $apiUserId;
2833
    
2834
    // $onlyForUser is only dynamically set by external calls
2835
    if ($onlyForUser === true || (int) $post_folder_is_personal === 1) {
2836
        // For personal items, create sharekeys for the owner user and TP_USER         
2837
        $userIds = [$userId, TP_USER_ID];
2838
2839
        // Get public keys for all target users
2840
        $users = DB::query(
2841
            'SELECT id, public_key
2842
            FROM ' . prefixTable('users') . '
2843
            WHERE id IN %li
2844
            AND public_key != ""',
2845
            $userIds
2846
        );
2847
2848
        if (empty($users) === false) {
2849
            if (empty($objectKey) === false) {
2850
                // Single object key
2851
                foreach ($users as $user) {
2852
                    DB::insert(
2853
                        $object_name,
2854
                        [
2855
                            'object_id' => (int) $post_object_id,
2856
                            'user_id' => (int) $user['id'],
2857
                            'share_key' => encryptUserObjectKey(
2858
                                $objectKey,
2859
                                $user['public_key']
2860
                            ),
2861
                        ]
2862
                    );
2863
                }
2864
            } else if (count($objectKeyArray) > 0) {
2865
                // Multiple object keys
2866
                foreach ($users as $user) {
2867
                    foreach ($objectKeyArray as $object) {
2868
                        DB::insert(
2869
                            $object_name,
2870
                            [
2871
                                'object_id' => (int) $object['objectId'],
2872
                                'user_id' => (int) $user['id'],
2873
                                'share_key' => encryptUserObjectKey(
2874
                                    $object['objectKey'],
2875
                                    $user['public_key']
2876
                                ),
2877
                            ]
2878
                        );
2879
                    }
2880
                }
2881
            }
2882
        }
2883
    } else {
2884
        // Create sharekey for each user
2885
        $user_ids = [OTV_USER_ID, SSH_USER_ID, API_USER_ID];
2886
        if ($all_users_except_id !== -1) {
2887
            array_push($user_ids, (int) $all_users_except_id);
2888
        }
2889
        $users = DB::query(
2890
            'SELECT id, public_key
2891
            FROM ' . prefixTable('users') . '
2892
            WHERE id NOT IN %li
2893
            AND public_key != ""',
2894
            $user_ids
2895
        );
2896
        //DB::debugmode(false);
2897
        foreach ($users as $user) {
2898
            // Insert in DB the new object key for this item by user
2899
            if (count($objectKeyArray) === 0) {
2900
                if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case1 - ' . $object_name . ' - ' . $post_object_id . ' - ' . $user['id'] . ' - ' . $objectKey);
2901
                DB::insert(
2902
                    $object_name,
2903
                    [
2904
                        'object_id' => $post_object_id,
2905
                        'user_id' => (int) $user['id'],
2906
                        'share_key' => encryptUserObjectKey(
2907
                            $objectKey,
2908
                            $user['public_key']
2909
                        ),
2910
                    ]
2911
                );
2912
            } else {
2913
                foreach ($objectKeyArray as $object) {
2914
                    if (WIP === true) error_log('TEAMPASS Debug - storeUsersShareKey case2 - ' . $object_name . ' - ' . $object['objectId'] . ' - ' . $user['id'] . ' - ' . $object['objectKey']);
2915
                    DB::insert(
2916
                        $object_name,
2917
                        [
2918
                            'object_id' => (int) $object['objectId'],
2919
                            'user_id' => (int) $user['id'],
2920
                            'share_key' => encryptUserObjectKey(
2921
                                $object['objectKey'],
2922
                                $user['public_key']
2923
                            ),
2924
                        ]
2925
                    );
2926
                }
2927
            }
2928
        }
2929
    }
2930
}
2931
2932
/**
2933
 * Is this string base64 encoded?
2934
 *
2935
 * @param string $str Encoded string?
2936
 *
2937
 * @return bool
2938
 */
2939
function isBase64(string $str): bool
2940
{
2941
    $str = (string) trim($str);
2942
    if (! isset($str[0])) {
2943
        return false;
2944
    }
2945
2946
    $base64String = (string) base64_decode($str, true);
2947
    if ($base64String && base64_encode($base64String) === $str) {
2948
        return true;
2949
    }
2950
2951
    return false;
2952
}
2953
2954
/**
2955
 * Undocumented function
2956
 *
2957
 * @param string $field Parameter
2958
 *
2959
 * @return array|bool|resource|string
2960
 */
2961
function filterString(string $field)
2962
{
2963
    // Sanitize string
2964
    $field = filter_var(trim($field), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
2965
    if (empty($field) === false) {
2966
        // Load AntiXSS
2967
        $antiXss = new AntiXSS();
2968
        // Return
2969
        return $antiXss->xss_clean($field);
2970
    }
2971
2972
    return false;
2973
}
2974
2975
/**
2976
 * CHeck if provided credentials are allowed on server
2977
 *
2978
 * @param string $login    User Login
2979
 * @param string $password User Pwd
2980
 * @param array  $SETTINGS Teampass settings
2981
 *
2982
 * @return bool
2983
 */
2984
function ldapCheckUserPassword(string $login, string $password, array $SETTINGS): bool
2985
{
2986
    // Build ldap configuration array
2987
    $config = [
2988
        // Mandatory Configuration Options
2989
        'hosts' => [$SETTINGS['ldap_hosts']],
2990
        'base_dn' => $SETTINGS['ldap_bdn'],
2991
        'username' => $SETTINGS['ldap_username'],
2992
        'password' => $SETTINGS['ldap_password'],
2993
2994
        // Optional Configuration Options
2995
        'port' => $SETTINGS['ldap_port'],
2996
        'use_ssl' => (int) $SETTINGS['ldap_ssl'] === 1 ? true : false,
2997
        'use_tls' => (int) $SETTINGS['ldap_tls'] === 1 ? true : false,
2998
        'version' => 3,
2999
        'timeout' => 5,
3000
        'follow_referrals' => false,
3001
3002
        // Custom LDAP Options
3003
        'options' => [
3004
            // See: http://php.net/ldap_set_option
3005
            LDAP_OPT_X_TLS_REQUIRE_CERT => (isset($SETTINGS['ldap_tls_certificate_check']) ? $SETTINGS['ldap_tls_certificate_check'] : LDAP_OPT_X_TLS_HARD),
3006
        ],
3007
    ];
3008
    
3009
    $connection = new Connection($config);
3010
    // Connect to LDAP
3011
    try {
3012
        $connection->connect();
3013
    } catch (\LdapRecord\Auth\BindException $e) {
3014
        $error = $e->getDetailedError();
3015
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
3016
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
3017
        }
3018
        // deepcode ignore ServerLeak: No important data is sent
3019
        echo 'An error occurred.';
3020
        return false;
3021
    }
3022
3023
    // Authenticate user
3024
    try {
3025
        if ($SETTINGS['ldap_type'] === 'ActiveDirectory') {
3026
            $connection->auth()->attempt($login, $password, $stayAuthenticated = true);
3027
        } else {
3028
            $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);
3029
        }
3030
    } catch (\LdapRecord\Auth\BindException $e) {
3031
        $error = $e->getDetailedError();
3032
        if ($error && defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
3033
            error_log('TEAMPASS Error - LDAP - '.$error->getErrorCode()." - ".$error->getErrorMessage(). " - ".$error->getDiagnosticMessage());
3034
        }
3035
        // deepcode ignore ServerLeak: No important data is sent
3036
        echo 'An error occurred.';
3037
        return false;
3038
    }
3039
3040
    return true;
3041
}
3042
3043
/**
3044
 * Removes from DB all sharekeys of this user
3045
 *
3046
 * @param int $userId User's id
3047
 * @param array   $SETTINGS Teampass settings
3048
 *
3049
 * @return bool
3050
 */
3051
function deleteUserObjetsKeys(int $userId, array $SETTINGS = []): bool
3052
{
3053
    // Return if technical accounts
3054
    if ($userId === OTV_USER_ID
3055
        || $userId === SSH_USER_ID
0 ignored issues
show
introduced by
The condition $userId === SSH_USER_ID is always false.
Loading history...
3056
        || $userId === API_USER_ID
0 ignored issues
show
introduced by
The condition $userId === API_USER_ID is always false.
Loading history...
3057
        || $userId === TP_USER_ID
0 ignored issues
show
introduced by
The condition $userId === TP_USER_ID is always false.
Loading history...
3058
    ) {
3059
        return false;
3060
    }
3061
3062
    // Load class DB
3063
    loadClasses('DB');
3064
3065
    // Remove all item sharekeys items
3066
    // expect if personal item
3067
    DB::delete(
3068
        prefixTable('sharekeys_items'),
3069
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
3070
        $userId
3071
    );
3072
    // Remove all item sharekeys files
3073
    DB::delete(
3074
        prefixTable('sharekeys_files'),
3075
        'user_id = %i AND object_id NOT IN (
3076
            SELECT f.id 
3077
            FROM ' . prefixTable('items') . ' AS i 
3078
            INNER JOIN ' . prefixTable('files') . ' AS f ON f.id_item = i.id
3079
            WHERE i.perso = 1
3080
        )',
3081
        $userId
3082
    );
3083
    // Remove all item sharekeys fields
3084
    DB::delete(
3085
        prefixTable('sharekeys_fields'),
3086
        'user_id = %i AND object_id NOT IN (
3087
            SELECT c.id 
3088
            FROM ' . prefixTable('items') . ' AS i 
3089
            INNER JOIN ' . prefixTable('categories_items') . ' AS c ON c.item_id = i.id
3090
            WHERE i.perso = 1
3091
        )',
3092
        $userId
3093
    );
3094
    // Remove all item sharekeys logs
3095
    DB::delete(
3096
        prefixTable('sharekeys_logs'),
3097
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
3098
        $userId
3099
    );
3100
    // Remove all item sharekeys suggestions
3101
    DB::delete(
3102
        prefixTable('sharekeys_suggestions'),
3103
        'user_id = %i AND object_id NOT IN (SELECT i.id FROM ' . prefixTable('items') . ' AS i WHERE i.perso = 1)',
3104
        $userId
3105
    );
3106
    return false;
3107
}
3108
3109
/**
3110
 * Manage list of timezones   $SETTINGS Teampass settings
3111
 *
3112
 * @return array
3113
 */
3114
function timezone_list()
3115
{
3116
    static $timezones = null;
3117
    if ($timezones === null) {
3118
        $timezones = [];
3119
        $offsets = [];
3120
        $now = new DateTime('now', new DateTimeZone('UTC'));
3121
        foreach (DateTimeZone::listIdentifiers() as $timezone) {
3122
            $now->setTimezone(new DateTimeZone($timezone));
3123
            $offsets[] = $offset = $now->getOffset();
3124
            $timezones[$timezone] = '(' . format_GMT_offset($offset) . ') ' . format_timezone_name($timezone);
3125
        }
3126
3127
        array_multisort($offsets, $timezones);
3128
    }
3129
3130
    return $timezones;
3131
}
3132
3133
/**
3134
 * Provide timezone offset
3135
 *
3136
 * @param int $offset Timezone offset
3137
 *
3138
 * @return string
3139
 */
3140
function format_GMT_offset($offset): string
3141
{
3142
    $hours = intval($offset / 3600);
3143
    $minutes = abs(intval($offset % 3600 / 60));
3144
    return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
3145
}
3146
3147
/**
3148
 * Provides timezone name
3149
 *
3150
 * @param string $name Timezone name
3151
 *
3152
 * @return string
3153
 */
3154
function format_timezone_name($name): string
3155
{
3156
    $name = str_replace('/', ', ', $name);
3157
    $name = str_replace('_', ' ', $name);
3158
3159
    return str_replace('St ', 'St. ', $name);
3160
}
3161
3162
/**
3163
 * Provides info if user should use MFA based on roles
3164
 *
3165
 * @param string $userRolesIds  User roles ids
3166
 * @param string $mfaRoles      Roles for which MFA is requested
3167
 *
3168
 * @return bool
3169
 */
3170
function mfa_auth_requested_roles(string $userRolesIds, string $mfaRoles): bool
3171
{
3172
    if (empty($mfaRoles) === true) {
3173
        return true;
3174
    }
3175
3176
    $mfaRoles = array_values(json_decode($mfaRoles, true));
3177
    $userRolesIds = array_filter(explode(';', $userRolesIds));
3178
    if (count($mfaRoles) === 0 || count(array_intersect($mfaRoles, $userRolesIds)) > 0) {
3179
        return true;
3180
    }
3181
3182
    return false;
3183
}
3184
3185
/**
3186
 * Permits to clean a string for export purpose
3187
 *
3188
 * @param string $text
3189
 * @param bool $emptyCheckOnly
3190
 * 
3191
 * @return string
3192
 */
3193
function cleanStringForExport(string $text, bool $emptyCheckOnly = false): string
3194
{
3195
    if (is_null($text) === true || empty($text) === true) {
3196
        return '';
3197
    }
3198
    // only expected to check if $text was empty
3199
    elseif ($emptyCheckOnly === true) {
3200
        return $text;
3201
    }
3202
3203
    return strip_tags(
3204
        cleanString(
3205
            html_entity_decode($text, ENT_QUOTES | ENT_XHTML, 'UTF-8'),
3206
            true)
3207
        );
3208
}
3209
3210
/**
3211
 * Permits to check if user ID is valid
3212
 *
3213
 * @param integer $post_user_id
3214
 * @return bool
3215
 */
3216
function isUserIdValid($userId): bool
3217
{
3218
    if (is_null($userId) === false
3219
        && empty($userId) === false
3220
    ) {
3221
        return true;
3222
    }
3223
    return false;
3224
}
3225
3226
/**
3227
 * Check if a key exists and if its value equal the one expected
3228
 *
3229
 * @param string $key
3230
 * @param integer|string $value
3231
 * @param array $array
3232
 * 
3233
 * @return boolean
3234
 */
3235
function isKeyExistingAndEqual(
3236
    string $key,
3237
    /*PHP8 - integer|string*/$value,
3238
    array $array
3239
): bool
3240
{
3241
    if (isset($array[$key]) === true
3242
        && (is_int($value) === true ?
3243
            (int) $array[$key] === $value :
3244
            (string) $array[$key] === $value)
3245
    ) {
3246
        return true;
3247
    }
3248
    return false;
3249
}
3250
3251
/**
3252
 * Check if a variable is not set or equal to a value
3253
 *
3254
 * @param string|null $var
3255
 * @param integer|string $value
3256
 * 
3257
 * @return boolean
3258
 */
3259
function isKeyNotSetOrEqual(
3260
    /*PHP8 - string|null*/$var,
3261
    /*PHP8 - integer|string*/$value
3262
): bool
3263
{
3264
    if (isset($var) === false
3265
        || (is_int($value) === true ?
3266
            (int) $var === $value :
3267
            (string) $var === $value)
3268
    ) {
3269
        return true;
3270
    }
3271
    return false;
3272
}
3273
3274
/**
3275
 * Check if a key exists and if its value < to the one expected
3276
 *
3277
 * @param string $key
3278
 * @param integer $value
3279
 * @param array $array
3280
 * 
3281
 * @return boolean
3282
 */
3283
function isKeyExistingAndInferior(string $key, int $value, array $array): bool
3284
{
3285
    if (isset($array[$key]) === true && (int) $array[$key] < $value) {
3286
        return true;
3287
    }
3288
    return false;
3289
}
3290
3291
/**
3292
 * Check if a key exists and if its value > to the one expected
3293
 *
3294
 * @param string $key
3295
 * @param integer $value
3296
 * @param array $array
3297
 * 
3298
 * @return boolean
3299
 */
3300
function isKeyExistingAndSuperior(string $key, int $value, array $array): bool
3301
{
3302
    if (isset($array[$key]) === true && (int) $array[$key] > $value) {
3303
        return true;
3304
    }
3305
    return false;
3306
}
3307
3308
/**
3309
 * Check if values in array are set
3310
 * Return true if all set
3311
 * Return false if one of them is not set
3312
 *
3313
 * @param array $arrayOfValues
3314
 * @return boolean
3315
 */
3316
function isSetArrayOfValues(array $arrayOfValues): bool
3317
{
3318
    foreach($arrayOfValues as $value) {
3319
        if (isset($value) === false) {
3320
            return false;
3321
        }
3322
    }
3323
    return true;
3324
}
3325
3326
/**
3327
 * Check if values in array are set
3328
 * Return true if all set
3329
 * Return false if one of them is not set
3330
 *
3331
 * @param array $arrayOfValues
3332
 * @param integer|string $value
3333
 * @return boolean
3334
 */
3335
function isArrayOfVarsEqualToValue(
3336
    array $arrayOfVars,
3337
    /*PHP8 - integer|string*/$value
3338
) : bool
3339
{
3340
    foreach($arrayOfVars as $variable) {
3341
        if ($variable !== $value) {
3342
            return false;
3343
        }
3344
    }
3345
    return true;
3346
}
3347
3348
/**
3349
 * Checks if at least one variable in array is equal to value
3350
 *
3351
 * @param array $arrayOfValues
3352
 * @param integer|string $value
3353
 * @return boolean
3354
 */
3355
function isOneVarOfArrayEqualToValue(
3356
    array $arrayOfVars,
3357
    /*PHP8 - integer|string*/$value
3358
) : bool
3359
{
3360
    foreach($arrayOfVars as $variable) {
3361
        if ($variable === $value) {
3362
            return true;
3363
        }
3364
    }
3365
    return false;
3366
}
3367
3368
/**
3369
 * Checks is value is null, not set OR empty
3370
 *
3371
 * @param string|int|null $value
3372
 * @return boolean
3373
 */
3374
function isValueSetNullEmpty(string|int|null $value) : bool
3375
{
3376
    if (is_null($value) === true || empty($value) === true) {
3377
        return true;
3378
    }
3379
    return false;
3380
}
3381
3382
/**
3383
 * Checks if value is set and if empty is equal to passed boolean
3384
 *
3385
 * @param string|int $value
3386
 * @param boolean $boolean
3387
 * @return boolean
3388
 */
3389
function isValueSetEmpty($value, $boolean = true) : bool
3390
{
3391
    if (empty($value) === $boolean) {
3392
        return true;
3393
    }
3394
    return false;
3395
}
3396
3397
/**
3398
 * Ensure Complexity is translated
3399
 *
3400
 * @return void
3401
 */
3402
function defineComplexity() : void
3403
{
3404
    // Load user's language
3405
    $session = SessionManager::getSession();
3406
    $lang = new Language($session->get('user-language') ?? 'english');
3407
    
3408
    if (defined('TP_PW_COMPLEXITY') === false) {
3409
        define(
3410
            'TP_PW_COMPLEXITY',
3411
            [
3412
                TP_PW_STRENGTH_1 => array(TP_PW_STRENGTH_1, $lang->get('complex_level1'), 'fas fa-thermometer-empty text-danger'),
3413
                TP_PW_STRENGTH_2 => array(TP_PW_STRENGTH_2, $lang->get('complex_level2'), 'fas fa-thermometer-quarter text-warning'),
3414
                TP_PW_STRENGTH_3 => array(TP_PW_STRENGTH_3, $lang->get('complex_level3'), 'fas fa-thermometer-half text-warning'),
3415
                TP_PW_STRENGTH_4 => array(TP_PW_STRENGTH_4, $lang->get('complex_level4'), 'fas fa-thermometer-three-quarters text-success'),
3416
                TP_PW_STRENGTH_5 => array(TP_PW_STRENGTH_5, $lang->get('complex_level5'), 'fas fa-thermometer-full text-success'),
3417
            ]
3418
        );
3419
    }
3420
}
3421
3422
/**
3423
 * Uses Sanitizer to perform data sanitization
3424
 *
3425
 * @param array     $data
3426
 * @param array     $filters
3427
 * @return array|string
3428
 */
3429
function dataSanitizer(array $data, array $filters): array|string
3430
{
3431
    // Load Sanitizer library
3432
    $sanitizer = new Sanitizer($data, $filters);
3433
3434
    // Load AntiXSS
3435
    $antiXss = new AntiXSS();
3436
3437
    // Sanitize post and get variables
3438
    return $antiXss->xss_clean($sanitizer->sanitize());
3439
}
3440
3441
/**
3442
 * Permits to manage the cache tree for a user
3443
 *
3444
 * @param integer $user_id
3445
 * @param string $data
3446
 * @param array $SETTINGS
3447
 * @param string $field_update
3448
 * @return void
3449
 */
3450
function cacheTreeUserHandler(int $user_id, string $data, array $SETTINGS, string $field_update = '')
3451
{
3452
    // Load class DB
3453
    loadClasses('DB');
3454
3455
    // Exists ?
3456
    $userCacheId = DB::queryFirstRow(
3457
        'SELECT increment_id
3458
        FROM ' . prefixTable('cache_tree') . '
3459
        WHERE user_id = %i',
3460
        $user_id
3461
    );
3462
    
3463
    if (is_null($userCacheId) === true || count($userCacheId) === 0) {
3464
        // insert in table
3465
        DB::insert(
3466
            prefixTable('cache_tree'),
3467
            array(
3468
                'data' => $data,
3469
                'timestamp' => time(),
3470
                'user_id' => $user_id,
3471
                'visible_folders' => '',
3472
            )
3473
        );
3474
    } else {
3475
        if (empty($field_update) === true) {
3476
            DB::update(
3477
                prefixTable('cache_tree'),
3478
                [
3479
                    'timestamp' => time(),
3480
                    'data' => $data,
3481
                ],
3482
                'increment_id = %i',
3483
                $userCacheId['increment_id']
3484
            );
3485
        /* USELESS
3486
        } else {
3487
            DB::update(
3488
                prefixTable('cache_tree'),
3489
                [
3490
                    $field_update => $data,
3491
                ],
3492
                'increment_id = %i',
3493
                $userCacheId['increment_id']
3494
            );*/
3495
        }
3496
    }
3497
}
3498
3499
/**
3500
 * Permits to calculate a %
3501
 *
3502
 * @param float $nombre
3503
 * @param float $total
3504
 * @param float $pourcentage
3505
 * @return float
3506
 */
3507
function pourcentage(float $nombre, float $total, float $pourcentage): float
3508
{ 
3509
    $resultat = ($nombre/$total) * $pourcentage;
3510
    return round($resultat);
3511
}
3512
3513
/**
3514
 * Load the folders list from the cache
3515
 *
3516
 * @param string $fieldName
3517
 * @param string $sessionName
3518
 * @param boolean $forceRefresh
3519
 * @return array
3520
 */
3521
function loadFoldersListByCache(
3522
    string $fieldName,
3523
    string $sessionName,
3524
    bool $forceRefresh = false
3525
): array
3526
{
3527
    // Case when refresh is EXPECTED / MANDATORY
3528
    if ($forceRefresh === true) {
3529
        return [
3530
            'state' => false,
3531
            'data' => [],
3532
        ];
3533
    }
3534
    
3535
    $session = SessionManager::getSession();
3536
3537
    // Get last folder update
3538
    $lastFolderChange = DB::queryFirstRow(
3539
        'SELECT valeur FROM ' . prefixTable('misc') . '
3540
        WHERE type = %s AND intitule = %s',
3541
        'timestamp',
3542
        'last_folder_change'
3543
    );
3544
    if (DB::count() === 0) {
3545
        $lastFolderChange['valeur'] = 0;
3546
    }
3547
3548
    // Case when an update in the tree has been done
3549
    // Refresh is then mandatory
3550
    if ((int) $lastFolderChange['valeur'] > (int) (null !== $session->get('user-tree_last_refresh_timestamp') ? $session->get('user-tree_last_refresh_timestamp') : 0)) {
3551
        return [
3552
            'state' => false,
3553
            'data' => [],
3554
        ];
3555
    }
3556
    
3557
    // Does this user has a tree cache
3558
    $userCacheTree = DB::queryFirstRow(
3559
        'SELECT '.$fieldName.'
3560
        FROM ' . prefixTable('cache_tree') . '
3561
        WHERE user_id = %i',
3562
        $session->get('user-id')
3563
    );
3564
    if (empty($userCacheTree[$fieldName]) === false && $userCacheTree[$fieldName] !== '[]') {
3565
        return [
3566
            'state' => true,
3567
            'data' => $userCacheTree[$fieldName],
3568
            'extra' => '',
3569
        ];
3570
    }
3571
3572
    return [
3573
        'state' => false,
3574
        'data' => [],
3575
    ];
3576
}
3577
3578
3579
/**
3580
 * Permits to refresh the categories of folders
3581
 *
3582
 * @param array $folderIds
3583
 * @return void
3584
 */
3585
function handleFoldersCategories(
3586
    array $folderIds
3587
)
3588
{
3589
    // Load class DB
3590
    loadClasses('DB');
3591
3592
    $arr_data = array();
3593
3594
    // force full list of folders
3595
    if (count($folderIds) === 0) {
3596
        $folderIds = DB::queryFirstColumn(
3597
            'SELECT id
3598
            FROM ' . prefixTable('nested_tree') . '
3599
            WHERE personal_folder=%i',
3600
            0
3601
        );
3602
    }
3603
3604
    // Get complexity
3605
    defineComplexity();
3606
3607
    // update
3608
    foreach ($folderIds as $folder) {
3609
        // Do we have Categories
3610
        // get list of associated Categories
3611
        $arrCatList = array();
3612
        $rows_tmp = DB::query(
3613
            'SELECT c.id, c.title, c.level, c.type, c.masked, c.order, c.encrypted_data, c.role_visibility, c.is_mandatory,
3614
            f.id_category AS category_id
3615
            FROM ' . prefixTable('categories_folders') . ' AS f
3616
            INNER JOIN ' . prefixTable('categories') . ' AS c ON (f.id_category = c.parent_id)
3617
            WHERE id_folder=%i',
3618
            $folder
3619
        );
3620
        if (DB::count() > 0) {
3621
            foreach ($rows_tmp as $row) {
3622
                $arrCatList[$row['id']] = array(
3623
                    'id' => $row['id'],
3624
                    'title' => $row['title'],
3625
                    'level' => $row['level'],
3626
                    'type' => $row['type'],
3627
                    'masked' => $row['masked'],
3628
                    'order' => $row['order'],
3629
                    'encrypted_data' => $row['encrypted_data'],
3630
                    'role_visibility' => $row['role_visibility'],
3631
                    'is_mandatory' => $row['is_mandatory'],
3632
                    'category_id' => $row['category_id'],
3633
                );
3634
            }
3635
        }
3636
        $arr_data['categories'] = $arrCatList;
3637
3638
        // Now get complexity
3639
        $valTemp = '';
3640
        $data = DB::queryFirstRow(
3641
            'SELECT valeur
3642
            FROM ' . prefixTable('misc') . '
3643
            WHERE type = %s AND intitule=%i',
3644
            'complex',
3645
            $folder
3646
        );
3647
        if (DB::count() > 0 && empty($data['valeur']) === false) {
3648
            $valTemp = array(
3649
                'value' => $data['valeur'],
3650
                'text' => TP_PW_COMPLEXITY[$data['valeur']][1],
3651
            );
3652
        }
3653
        $arr_data['complexity'] = $valTemp;
3654
3655
        // Now get Roles
3656
        $valTemp = '';
3657
        $rows_tmp = DB::query(
3658
            'SELECT t.title
3659
            FROM ' . prefixTable('roles_values') . ' as v
3660
            INNER JOIN ' . prefixTable('roles_title') . ' as t ON (v.role_id = t.id)
3661
            WHERE v.folder_id = %i
3662
            GROUP BY title',
3663
            $folder
3664
        );
3665
        foreach ($rows_tmp as $record) {
3666
            $valTemp .= (empty($valTemp) === true ? '' : ' - ') . $record['title'];
3667
        }
3668
        $arr_data['visibilityRoles'] = $valTemp;
3669
3670
        // now save in DB
3671
        DB::update(
3672
            prefixTable('nested_tree'),
3673
            array(
3674
                'categories' => json_encode($arr_data),
3675
            ),
3676
            'id = %i',
3677
            $folder
3678
        );
3679
    }
3680
}
3681
3682
/**
3683
 * List all users that have specific roles
3684
 *
3685
 * @param array $roles
3686
 * @return array
3687
 */
3688
function getUsersWithRoles(
3689
    array $roles
3690
): array
3691
{
3692
    $session = SessionManager::getSession();
3693
    $arrUsers = array();
3694
3695
    foreach ($roles as $role) {
3696
        // loop on users and check if user has this role
3697
        $rows = DB::query(
3698
            'SELECT id, fonction_id
3699
            FROM ' . prefixTable('users') . '
3700
            WHERE id != %i AND admin = 0 AND fonction_id IS NOT NULL AND fonction_id != ""',
3701
            $session->get('user-id')
3702
        );
3703
        foreach ($rows as $user) {
3704
            $userRoles = is_null($user['fonction_id']) === false && empty($user['fonction_id']) === false ? explode(';', $user['fonction_id']) : [];
3705
            if (in_array($role, $userRoles, true) === true) {
3706
                array_push($arrUsers, $user['id']);
3707
            }
3708
        }
3709
    }
3710
3711
    return $arrUsers;
3712
}
3713
3714
3715
/**
3716
 * Get all users informations
3717
 *
3718
 * @param integer $userId
3719
 * @return array
3720
 */
3721
function getFullUserInfos(
3722
    int $userId
3723
): array
3724
{
3725
    if (empty($userId) === true) {
3726
        return array();
3727
    }
3728
3729
    $val = DB::queryFirstRow(
3730
        'SELECT *
3731
        FROM ' . prefixTable('users') . '
3732
        WHERE id = %i',
3733
        $userId
3734
    );
3735
3736
    return $val;
3737
}
3738
3739
/**
3740
 * Is required an upgrade
3741
 *
3742
 * @return boolean
3743
 */
3744
function upgradeRequired(): bool
3745
{
3746
    // Get settings.php
3747
    include_once __DIR__. '/../includes/config/settings.php';
3748
3749
    // Get timestamp in DB
3750
    $val = DB::queryFirstRow(
3751
        'SELECT valeur
3752
        FROM ' . prefixTable('misc') . '
3753
        WHERE type = %s AND intitule = %s',
3754
        'admin',
3755
        'upgrade_timestamp'
3756
    );
3757
3758
    // Check if upgrade is required
3759
    return (
3760
        is_null($val) || count($val) === 0 || !defined('UPGRADE_MIN_DATE') || 
3761
        empty($val['valeur']) || (int) $val['valeur'] < (int) UPGRADE_MIN_DATE
3762
    );
3763
}
3764
3765
/**
3766
 * Permits to change the user keys on his demand
3767
 *
3768
 * @param integer $userId
3769
 * @param string $passwordClear
3770
 * @param integer $nbItemsToTreat
3771
 * @param string $encryptionKey
3772
 * @param boolean $deleteExistingKeys
3773
 * @param boolean $sendEmailToUser
3774
 * @param boolean $encryptWithUserPassword
3775
 * @param boolean $generate_user_new_password
3776
 * @param string $emailBody
3777
 * @param boolean $user_self_change
3778
 * @param string $recovery_public_key
3779
 * @param string $recovery_private_key
3780
 * @param bool $userHasToEncryptPersonalItemsAfter
3781
 * @return string
3782
 */
3783
function handleUserKeys(
3784
    int $userId,
3785
    string $passwordClear,
3786
    int $nbItemsToTreat,
3787
    string $encryptionKey = '',
3788
    bool $deleteExistingKeys = false,
3789
    bool $sendEmailToUser = true,
3790
    bool $encryptWithUserPassword = false,
3791
    bool $generate_user_new_password = false,
3792
    string $emailBody = '',
3793
    bool $user_self_change = false,
3794
    string $recovery_public_key = '',
3795
    string $recovery_private_key = '',
3796
    bool $userHasToEncryptPersonalItemsAfter = false
3797
): string
3798
{
3799
    $session = SessionManager::getSession();
3800
    $lang = new Language($session->get('user-language') ?? 'english');
3801
3802
    // prepapre background tasks for item keys generation        
3803
    $userTP = DB::queryFirstRow(
3804
        'SELECT pw, public_key, private_key
3805
        FROM ' . prefixTable('users') . '
3806
        WHERE id = %i',
3807
        TP_USER_ID
3808
    );
3809
    if (DB::count() === 0) {
3810
        return prepareExchangedData(
3811
            array(
3812
                'error' => true,
3813
                'message' => 'User not exists',
3814
            ),
3815
            'encode'
3816
        );
3817
    }
3818
3819
    // Do we need to generate new user password
3820
    if ($generate_user_new_password === true) {
3821
        // Generate a new password
3822
        $passwordClear = GenerateCryptKey(20, false, true, true, false, true);
3823
    }
3824
3825
    // Create password hash
3826
    $passwordManager = new PasswordManager();
3827
    $hashedPassword = $passwordManager->hashPassword($passwordClear);
3828
    if ($passwordManager->verifyPassword($hashedPassword, $passwordClear) === false) {
3829
        return prepareExchangedData(
3830
            array(
3831
                'error' => true,
3832
                'message' => $lang->get('pw_hash_not_correct'),
3833
            ),
3834
            'encode'
3835
        );
3836
    }
3837
3838
    // Check if valid public/private keys
3839
    if ($recovery_public_key !== '' && $recovery_private_key !== '') {
3840
        try {
3841
            // Generate random string
3842
            $random_str = generateQuickPassword(12, false);
3843
            // Encrypt random string with user publick key
3844
            $encrypted = encryptUserObjectKey($random_str, $recovery_public_key);
3845
            // Decrypt $encrypted with private key
3846
            $decrypted = decryptUserObjectKey($encrypted, $recovery_private_key);
3847
            // Check if decryptUserObjectKey returns our random string
3848
            if ($decrypted !== $random_str) {
3849
                throw new Exception('Public/Private keypair invalid.');
3850
            }
3851
        } catch (Exception $e) {
3852
            // Show error message to user and log event
3853
            if (defined('LOG_TO_SERVER') && LOG_TO_SERVER === true) {
3854
                error_log('ERROR: User '.$userId.' - '.$e->getMessage());
3855
            }
3856
            return prepareExchangedData([
3857
                    'error' => true,
3858
                    'message' => $lang->get('pw_encryption_error'),
3859
                ],
3860
                'encode'
3861
            );
3862
        }
3863
    }
3864
3865
    // Generate new keys
3866
    if ($user_self_change === true && empty($recovery_public_key) === false && empty($recovery_private_key) === false){
3867
        $userKeys = [
3868
            'public_key' => $recovery_public_key,
3869
            'private_key_clear' => $recovery_private_key,
3870
            'private_key' => encryptPrivateKey($passwordClear, $recovery_private_key),
3871
        ];
3872
    } else {
3873
        $userKeys = generateUserKeys($passwordClear);
3874
    }
3875
    
3876
    // Handle private key
3877
    insertPrivateKeyWithCurrentFlag(
3878
        $userId,
3879
        $userKeys['private_key'],
3880
    );
3881
3882
    // Save in DB
3883
    // TODO: remove private key field from Users table
3884
    DB::update(
3885
        prefixTable('users'),
3886
        array(
3887
            'pw' => $hashedPassword,
3888
            'public_key' => $userKeys['public_key'],
3889
            'private_key' => $userKeys['private_key'],
3890
            'keys_recovery_time' => NULL,
3891
        ),
3892
        'id=%i',
3893
        $userId
3894
    );
3895
3896
3897
    // update session too
3898
    if ($userId === $session->get('user-id')) {
3899
        $session->set('user-private_key', $userKeys['private_key_clear']);
3900
        $session->set('user-public_key', $userKeys['public_key']);
3901
        // Notify user that he must re download his keys:
3902
        $session->set('user-keys_recovery_time', NULL);
3903
    }
3904
3905
    // Manage empty encryption key
3906
    // Let's take the user's password if asked and if no encryption key provided
3907
    $encryptionKey = $encryptWithUserPassword === true && empty($encryptionKey) === true ? $passwordClear : $encryptionKey;
3908
3909
    // Create process
3910
    DB::insert(
3911
        prefixTable('background_tasks'),
3912
        array(
3913
            'created_at' => time(),
3914
            'process_type' => 'create_user_keys',
3915
            'arguments' => json_encode([
3916
                'new_user_id' => (int) $userId,
3917
                'new_user_pwd' => cryption($passwordClear, '','encrypt')['string'],
3918
                'new_user_code' => cryption(empty($encryptionKey) === true ? uniqidReal(20) : $encryptionKey, '','encrypt')['string'],
3919
                'owner_id' => (int) TP_USER_ID,
3920
                'creator_pwd' => $userTP['pw'],
3921
                'send_email' => $sendEmailToUser === true ? 1 : 0,
3922
                'otp_provided_new_value' => 1,
3923
                'email_body' => empty($emailBody) === true ? '' : $lang->get($emailBody),
3924
                'user_self_change' => $user_self_change === true ? 1 : 0,
3925
                'userHasToEncryptPersonalItemsAfter' => $userHasToEncryptPersonalItemsAfter === true ? 1 : 0,
3926
            ]),
3927
        )
3928
    );
3929
    $processId = DB::insertId();
3930
3931
    // Delete existing keys
3932
    if ($deleteExistingKeys === true) {
3933
        deleteUserObjetsKeys(
3934
            (int) $userId,
3935
        );
3936
    }
3937
3938
    // Create tasks
3939
    createUserTasks($processId, $nbItemsToTreat);
3940
3941
    // update user's new status
3942
    DB::update(
3943
        prefixTable('users'),
3944
        [
3945
            'is_ready_for_usage' => 0,
3946
            'otp_provided' => 1,
3947
            'ongoing_process_id' => $processId,
3948
            'special' => 'generate-keys',
3949
        ],
3950
        'id=%i',
3951
        $userId
3952
    );
3953
3954
    return prepareExchangedData(
3955
        array(
3956
            'error' => false,
3957
            'message' => '',
3958
            'user_password' => $generate_user_new_password === true ? $passwordClear : '',
3959
        ),
3960
        'encode'
3961
    );
3962
}
3963
3964
/**
3965
 * Permits to generate a new password for a user
3966
 *
3967
 * @param integer $processId
3968
 * @param integer $nbItemsToTreat
3969
 * @return void
3970
 
3971
 */
3972
function createUserTasks($processId, $nbItemsToTreat): void
3973
{
3974
    // Create subtask for step 0
3975
    DB::insert(
3976
        prefixTable('background_subtasks'),
3977
        array(
3978
            'task_id' => $processId,
3979
            'created_at' => time(),
3980
            'task' => json_encode([
3981
                'step' => 'step0',
3982
                'index' => 0,
3983
                'nb' => $nbItemsToTreat,
3984
            ]),
3985
        )
3986
    );
3987
3988
    // Prepare the subtask queries
3989
    $queries = [
3990
        'step20' => 'SELECT * FROM ' . prefixTable('items'),
3991
3992
        'step30' => 'SELECT * FROM ' . prefixTable('log_items') . 
3993
                    ' WHERE raison LIKE "at_pw :%" AND encryption_type = "teampass_aes"',
3994
3995
        'step40' => 'SELECT * FROM ' . prefixTable('categories_items') . 
3996
                    ' WHERE encryption_type = "teampass_aes"',
3997
3998
        'step50' => 'SELECT * FROM ' . prefixTable('suggestion'),
3999
4000
        'step60' => 'SELECT * FROM ' . prefixTable('files') . ' AS f
4001
                        INNER JOIN ' . prefixTable('items') . ' AS i ON i.id = f.id_item
4002
                        WHERE f.status = "' . TP_ENCRYPTION_NAME . '"'
4003
    ];
4004
4005
    // Perform loop on $queries to create sub-tasks
4006
    foreach ($queries as $step => $query) {
4007
        DB::query($query);
4008
        createAllSubTasks($step, DB::count(), $nbItemsToTreat, $processId);
4009
    }
4010
4011
    // Create subtask for step 99
4012
    DB::insert(
4013
        prefixTable('background_subtasks'),
4014
        array(
4015
            'task_id' => $processId,
4016
            'created_at' => time(),
4017
            'task' => json_encode([
4018
                'step' => 'step99',
4019
            ]),
4020
        )
4021
    );
4022
}
4023
4024
/**
4025
 * Create all subtasks for a given action
4026
 * @param string $action The action to be performed
4027
 * @param int $totalElements Total number of elements to process
4028
 * @param int $elementsPerIteration Number of elements per iteration
4029
 * @param int $taskId The ID of the task
4030
 */
4031
function createAllSubTasks($action, $totalElements, $elementsPerIteration, $taskId) {
4032
    // Calculate the number of iterations
4033
    $iterations = ceil($totalElements / $elementsPerIteration);
4034
4035
    // Create the subtasks
4036
    for ($i = 0; $i < $iterations; $i++) {
4037
        DB::insert(prefixTable('background_subtasks'), [
4038
            'task_id' => $taskId,
4039
            'created_at' => time(),
4040
            'task' => json_encode([
4041
                "step" => $action,
4042
                "index" => $i * $elementsPerIteration,
4043
                "nb" => $elementsPerIteration,
4044
            ]),
4045
        ]);
4046
    }
4047
}
4048
4049
/**
4050
 * Permeits to check the consistency of date versus columns definition
4051
 *
4052
 * @param string $table
4053
 * @param array $dataFields
4054
 * @return array
4055
 */
4056
function validateDataFields(
4057
    string $table,
4058
    array $dataFields
4059
): array
4060
{
4061
    // Get table structure
4062
    $result = DB::query(
4063
        "SELECT `COLUMN_NAME`, `CHARACTER_MAXIMUM_LENGTH` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '%l' AND TABLE_NAME = '%l';",
4064
        DB_NAME,
4065
        $table
4066
    );
4067
4068
    foreach ($result as $row) {
4069
        $field = $row['COLUMN_NAME'];
4070
        $maxLength = is_null($row['CHARACTER_MAXIMUM_LENGTH']) === false ? (int) $row['CHARACTER_MAXIMUM_LENGTH'] : '';
4071
4072
        if (isset($dataFields[$field]) === true && is_array($dataFields[$field]) === false && empty($maxLength) === false) {
4073
            if (strlen((string) $dataFields[$field]) > $maxLength) {
4074
                return [
4075
                    'state' => false,
4076
                    'field' => $field,
4077
                    'maxLength' => $maxLength,
4078
                    'currentLength' => strlen((string) $dataFields[$field]),
4079
                ];
4080
            }
4081
        }
4082
    }
4083
    
4084
    return [
4085
        'state' => true,
4086
        'message' => '',
4087
    ];
4088
}
4089
4090
/**
4091
 * Adapt special characters sanitized during filter_var with option FILTER_SANITIZE_SPECIAL_CHARS operation
4092
 *
4093
 * @param string $string
4094
 * @return string
4095
 */
4096
function filterVarBack(string $string): string
4097
{
4098
    $arr = [
4099
        '&#060;' => '<',
4100
        '&#062;' => '>',
4101
        '&#034;' => '"',
4102
        '&#039;' => "'",
4103
        '&#038;' => '&',
4104
    ];
4105
4106
    foreach ($arr as $key => $value) {
4107
        $string = str_replace($key, $value, $string);
4108
    }
4109
4110
    return $string;
4111
}
4112
4113
/**
4114
 * 
4115
 */
4116
function storeTask(
4117
    string $taskName,
4118
    int $user_id,
4119
    int $is_personal_folder,
4120
    int $folder_destination_id,
4121
    int $item_id,
4122
    string $object_keys,
4123
    array $fields_keys = [],
4124
    array $files_keys = []
4125
)
4126
{
4127
    if (in_array($taskName, ['item_copy', 'new_item', 'update_item'])) {
4128
        // Create process
4129
        DB::insert(
4130
            prefixTable('background_tasks'),
4131
            array(
4132
                'created_at' => time(),
4133
                'process_type' => $taskName,
4134
                'arguments' => json_encode([
4135
                    'item_id' => $item_id,
4136
                    'object_key' => $object_keys,
4137
                ]),
4138
                'item_id' => $item_id,
4139
            )
4140
        );
4141
        $processId = DB::insertId();
4142
4143
        // Create tasks
4144
        // 1- Create password sharekeys for users of this new ITEM
4145
        DB::insert(
4146
            prefixTable('background_subtasks'),
4147
            array(
4148
                'task_id' => $processId,
4149
                'created_at' => time(),
4150
                'task' => json_encode([
4151
                    'step' => 'create_users_pwd_key',
4152
                    'index' => 0,
4153
                ]),
4154
            )
4155
        );
4156
4157
        // 2- Create fields sharekeys for users of this new ITEM
4158
        DB::insert(
4159
            prefixTable('background_subtasks'),
4160
            array(
4161
                'task_id' => $processId,
4162
                'created_at' => time(),
4163
                'task' => json_encode([
4164
                    'step' => 'create_users_fields_key',
4165
                    'index' => 0,
4166
                    'fields_keys' => $fields_keys,
4167
                ]),
4168
            )
4169
        );
4170
4171
        // 3- Create files sharekeys for users of this new ITEM
4172
        DB::insert(
4173
            prefixTable('background_subtasks'),
4174
            array(
4175
                'task_id' => $processId,
4176
                'created_at' => time(),
4177
                'task' => json_encode([
4178
                    'step' => 'create_users_files_key',
4179
                    'index' => 0,
4180
                    'files_keys' => $files_keys,
4181
                ]),
4182
            )
4183
        );
4184
    }
4185
}
4186
4187
/**
4188
 * 
4189
 */
4190
function createTaskForItem(
4191
    string $processType,
4192
    string|array $taskName,
4193
    int $itemId,
4194
    int $userId,
4195
    string $objectKey,
4196
    int $parentId = -1,
4197
    array $fields_keys = [],
4198
    array $files_keys = []
4199
)
4200
{
4201
    // 1- Create main process
4202
    // ---
4203
    
4204
    // Create process
4205
    DB::insert(
4206
        prefixTable('background_tasks'),
4207
        array(
4208
            'created_at' => time(),
4209
            'process_type' => $processType,
4210
            'arguments' => json_encode([
4211
                'all_users_except_id' => (int) $userId,
4212
                'item_id' => (int) $itemId,
4213
                'object_key' => $objectKey,
4214
                'author' => (int) $userId,
4215
            ]),
4216
            'item_id' => (int) $parentId !== -1 ?  $parentId : null,
4217
        )
4218
    );
4219
    $processId = DB::insertId();
4220
4221
    // 2- Create expected tasks
4222
    // ---
4223
    if (is_array($taskName) === false) {
0 ignored issues
show
introduced by
The condition is_array($taskName) === false is always false.
Loading history...
4224
        $taskName = [$taskName];
4225
    }
4226
    foreach($taskName as $task) {
4227
        if (WIP === true) error_log('createTaskForItem - task: '.$task);
4228
        switch ($task) {
4229
            case 'item_password':
4230
                
4231
                DB::insert(
4232
                    prefixTable('background_subtasks'),
4233
                    array(
4234
                        'task_id' => $processId,
4235
                        'created_at' => time(),
4236
                        'task' => json_encode([
4237
                            'step' => 'create_users_pwd_key',
4238
                            'index' => 0,
4239
                        ]),
4240
                    )
4241
                );
4242
4243
                break;
4244
            case 'item_field':
4245
                
4246
                DB::insert(
4247
                    prefixTable('background_subtasks'),
4248
                    array(
4249
                        'task_id' => $processId,
4250
                        'created_at' => time(),
4251
                        'task' => json_encode([
4252
                            'step' => 'create_users_fields_key',
4253
                            'index' => 0,
4254
                            'fields_keys' => $fields_keys,
4255
                        ]),
4256
                    )
4257
                );
4258
4259
                break;
4260
            case 'item_file':
4261
4262
                DB::insert(
4263
                    prefixTable('background_subtasks'),
4264
                    array(
4265
                        'task_id' => $processId,
4266
                        'created_at' => time(),
4267
                        'task' => json_encode([
4268
                            'step' => 'create_users_files_key',
4269
                            'index' => 0,
4270
                            'fields_keys' => $files_keys,
4271
                        ]),
4272
                    )
4273
                );
4274
                break;
4275
            default:
4276
                # code...
4277
                break;
4278
        }
4279
    }
4280
}
4281
4282
4283
function deleteProcessAndRelatedTasks(int $processId)
4284
{
4285
    // Delete process
4286
    DB::delete(
4287
        prefixTable('background_tasks'),
4288
        'id=%i',
4289
        $processId
4290
    );
4291
4292
    // Delete tasks
4293
    DB::delete(
4294
        prefixTable('background_subtasks'),
4295
        'task_id=%i',
4296
        $processId
4297
    );
4298
4299
}
4300
4301
/**
4302
 * Return PHP binary path
4303
 *
4304
 * @return string
4305
 */
4306
function getPHPBinary(): string
4307
{
4308
    // Get PHP binary path
4309
    $phpBinaryFinder = new PhpExecutableFinder();
4310
    $phpBinaryPath = $phpBinaryFinder->find();
4311
    return $phpBinaryPath === false ? 'false' : $phpBinaryPath;
4312
}
4313
4314
4315
4316
/**
4317
 * Delete unnecessary keys for personal items
4318
 *
4319
 * @param boolean $allUsers
4320
 * @param integer $user_id
4321
 * @return void
4322
 */
4323
function purgeUnnecessaryKeys(bool $allUsers = true, int $user_id=0)
4324
{
4325
    if ($allUsers === true) {
4326
        // Load class DB
4327
        if (class_exists('DB') === false) {
4328
            loadClasses('DB');
4329
        }
4330
4331
        $users = DB::query(
4332
            'SELECT id
4333
            FROM ' . prefixTable('users') . '
4334
            WHERE id NOT IN ('.OTV_USER_ID.', '.TP_USER_ID.', '.SSH_USER_ID.', '.API_USER_ID.')
4335
            ORDER BY login ASC'
4336
        );
4337
        foreach ($users as $user) {
4338
            purgeUnnecessaryKeysForUser((int) $user['id']);
4339
        }
4340
    } else {
4341
        purgeUnnecessaryKeysForUser((int) $user_id);
4342
    }
4343
}
4344
4345
/**
4346
 * Delete unnecessary keys for personal items
4347
 *
4348
 * @param integer $user_id
4349
 * @return void
4350
 */
4351
function purgeUnnecessaryKeysForUser(int $user_id=0)
4352
{
4353
    if ($user_id === 0) {
4354
        return;
4355
    }
4356
4357
    // Load class DB
4358
    loadClasses('DB');
4359
4360
    $personalItems = DB::queryFirstColumn(
4361
        'SELECT id
4362
        FROM ' . prefixTable('items') . ' AS i
4363
        INNER JOIN ' . prefixTable('log_items') . ' AS li ON li.id_item = i.id
4364
        WHERE i.perso = 1 AND li.action = "at_creation" AND li.id_user IN (%i, '.TP_USER_ID.')',
4365
        $user_id
4366
    );
4367
    if (count($personalItems) > 0) {
4368
        // Item keys
4369
        DB::delete(
4370
            prefixTable('sharekeys_items'),
4371
            'object_id IN %li AND user_id NOT IN %ls',
4372
            $personalItems,
4373
            [$user_id, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4374
        );
4375
        // Files keys
4376
        DB::delete(
4377
            prefixTable('sharekeys_files'),
4378
            'object_id IN %li AND user_id NOT IN %ls',
4379
            $personalItems,
4380
            [$user_id, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4381
        );
4382
        // Fields keys
4383
        DB::delete(
4384
            prefixTable('sharekeys_fields'),
4385
            'object_id IN %li AND user_id NOT IN %ls',
4386
            $personalItems,
4387
            [$user_id, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4388
        );
4389
        // Logs keys
4390
        DB::delete(
4391
            prefixTable('sharekeys_logs'),
4392
            'object_id IN %li AND user_id NOT IN %ls',
4393
            $personalItems,
4394
            [$user_id, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4395
        );
4396
    }
4397
}
4398
4399
/**
4400
 * Generate recovery keys file
4401
 *
4402
 * @param integer $userId
4403
 * @param array $SETTINGS
4404
 * @return string
4405
 */
4406
function handleUserRecoveryKeysDownload(int $userId, array $SETTINGS):string
4407
{
4408
    $session = SessionManager::getSession();
4409
    // Check if user exists
4410
    $userInfo = DB::queryFirstRow(
4411
        'SELECT login
4412
        FROM ' . prefixTable('users') . '
4413
        WHERE id = %i',
4414
        $userId
4415
    );
4416
4417
    if (DB::count() > 0) {
4418
        $now = (int) time();
4419
        // Prepare file content
4420
        $export_value = file_get_contents(__DIR__."/../includes/core/teampass_ascii.txt")."\n".
4421
            "Generation date: ".date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now)."\n\n".
4422
            "RECOVERY KEYS - Not to be shared - To be store safely\n\n".
4423
            "Public Key:\n".$session->get('user-public_key')."\n\n".
4424
            "Private Key:\n".$session->get('user-private_key')."\n\n";
4425
4426
        // Update user's keys_recovery_time
4427
        DB::update(
4428
            prefixTable('users'),
4429
            [
4430
                'keys_recovery_time' => $now,
4431
            ],
4432
            'id=%i',
4433
            $userId
4434
        );
4435
        $session->set('user-keys_recovery_time', $now);
4436
4437
        //Log into DB the user's disconnection
4438
        logEvents($SETTINGS, 'user_mngt', 'at_user_keys_download', (string) $userId, $userInfo['login']);
4439
        
4440
        // Return data
4441
        return prepareExchangedData(
4442
            array(
4443
                'error' => false,
4444
                'datetime' => date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], $now),
4445
                'timestamp' => $now,
4446
                'content' => base64_encode($export_value),
4447
                'login' => $userInfo['login'],
4448
            ),
4449
            'encode'
4450
        );
4451
    }
4452
4453
    return prepareExchangedData(
4454
        array(
4455
            'error' => true,
4456
            'datetime' => '',
4457
        ),
4458
        'encode'
4459
    );
4460
}
4461
4462
/**
4463
 * Permits to load expected classes
4464
 *
4465
 * @param string $className
4466
 * @return void
4467
 */
4468
function loadClasses(string $className = ''): void
4469
{
4470
    require_once __DIR__. '/../includes/config/include.php';
4471
    require_once __DIR__. '/../includes/config/settings.php';
4472
    require_once __DIR__.'/../vendor/autoload.php';
4473
4474
    if (defined('DB_PASSWD_CLEAR') === false) {
4475
        define('DB_PASSWD_CLEAR', defuseReturnDecrypted(DB_PASSWD));
4476
    }
4477
4478
    if (empty($className) === false) {
4479
        // Load class DB
4480
        if ((string) $className === 'DB') {
4481
            //Connect to DB
4482
            DB::$host = DB_HOST;
4483
            DB::$user = DB_USER;
4484
            DB::$password = DB_PASSWD_CLEAR;
4485
            DB::$dbName = DB_NAME;
4486
            DB::$port = DB_PORT;
4487
            DB::$encoding = DB_ENCODING;
4488
            DB::$ssl = DB_SSL;
4489
            DB::$connect_options = DB_CONNECT_OPTIONS;
4490
        }
4491
    }
4492
}
4493
4494
/**
4495
 * Returns the page the user is visiting.
4496
 *
4497
 * @return string The page name
4498
 */
4499
function getCurrectPage($SETTINGS)
4500
{
4501
    
4502
    $request = SymfonyRequest::createFromGlobals();
4503
4504
    // Parse the url
4505
    parse_str(
4506
        substr(
4507
            (string) $request->getRequestUri(),
4508
            strpos((string) $request->getRequestUri(), '?') + 1
4509
        ),
4510
        $result
4511
    );
4512
4513
    return $result['page'];
4514
}
4515
4516
/**
4517
 * Permits to return value if set
4518
 *
4519
 * @param string|int $value
4520
 * @param string|int|null $retFalse
4521
 * @param string|int $retTrue
4522
 * @return mixed
4523
 */
4524
function returnIfSet($value, $retFalse = '', $retTrue = null): mixed
4525
{
4526
    if (!empty($value)) {
4527
        return is_null($retTrue) ? $value : $retTrue;
4528
    }
4529
    return $retFalse;
4530
}
4531
4532
4533
/**
4534
 * SEnd email to user
4535
 *
4536
 * @param string $post_receipt
4537
 * @param string $post_body
4538
 * @param string $post_subject
4539
 * @param array $post_replace
4540
 * @param boolean $immediate_email
4541
 * @param string $encryptedUserPassword
4542
 * @return string
4543
 */
4544
function sendMailToUser(
4545
    string $post_receipt,
4546
    string $post_body,
4547
    string $post_subject,
4548
    array $post_replace,
4549
    bool $immediate_email = false,
4550
    $encryptedUserPassword = ''
4551
): ?string {
4552
    global $SETTINGS;
4553
    $emailSettings = new EmailSettings($SETTINGS);
4554
    $emailService = new EmailService();
4555
    $antiXss = new AntiXSS();
4556
4557
    // Sanitize inputs
4558
    $post_receipt = filter_var($post_receipt, FILTER_SANITIZE_EMAIL);
4559
    $post_subject = $antiXss->xss_clean($post_subject);
4560
    $post_body = $antiXss->xss_clean($post_body);
4561
4562
    if (count($post_replace) > 0) {
4563
        $post_body = str_replace(
4564
            array_keys($post_replace),
4565
            array_values($post_replace),
4566
            $post_body
4567
        );
4568
    }
4569
4570
    // Remove newlines to prevent header injection
4571
    $post_body = str_replace(array("\r", "\n"), '', $post_body);    
4572
4573
    if ($immediate_email === true) {
4574
        // Send email
4575
        $ret = $emailService->sendMail(
4576
            $post_subject,
4577
            $post_body,
4578
            $post_receipt,
4579
            $emailSettings,
4580
            '',
4581
            false
4582
        );
4583
    
4584
        $ret = json_decode($ret, true);
4585
    
4586
        return prepareExchangedData(
4587
            array(
4588
                'error' => empty($ret['error']) === true ? false : true,
4589
                'message' => $ret['message'],
4590
            ),
4591
            'encode'
4592
        );
4593
    } else {
4594
        // Send through task handler
4595
        prepareSendingEmail(
4596
            $post_subject,
4597
            $post_body,
4598
            $post_receipt,
4599
            "",
4600
            $encryptedUserPassword,
4601
        );
4602
    }
4603
4604
    return null;
4605
}
4606
4607
/**
4608
 * Converts a password strengh value to zxcvbn level
4609
 * 
4610
 * @param integer $passwordStrength
4611
 * 
4612
 * @return integer
4613
 */
4614
function convertPasswordStrength($passwordStrength): int
4615
{
4616
    if ($passwordStrength === 0) {
4617
        return TP_PW_STRENGTH_1;
4618
    } else if ($passwordStrength === 1) {
4619
        return TP_PW_STRENGTH_2;
4620
    } else if ($passwordStrength === 2) {
4621
        return TP_PW_STRENGTH_3;
4622
    } else if ($passwordStrength === 3) {
4623
        return TP_PW_STRENGTH_4;
4624
    } else {
4625
        return TP_PW_STRENGTH_5;
4626
    }
4627
}
4628
4629
/**
4630
 * Check that a password is strong. The password needs to have at least :
4631
 *   - length >= 10.
4632
 *   - Uppercase and lowercase chars.
4633
 *   - Number or special char.
4634
 *   - Not contain username, name or mail part.
4635
 *   - Different from previous password.
4636
 * 
4637
 * @param string $password - Password to ckeck.
4638
 * @return bool - true if the password is strong, false otherwise.
4639
 */
4640
function isPasswordStrong($password) {
4641
    $session = SessionManager::getSession();
4642
4643
    // Password can't contain login, name or lastname
4644
    $forbiddenWords = [
4645
        $session->get('user-login'),
4646
        $session->get('user-name'),
4647
        $session->get('user-lastname'),
4648
    ];
4649
4650
    // Cut out the email
4651
    if ($email = $session->get('user-email')) {
4652
        $emailParts = explode('@', $email);
4653
4654
        if (count($emailParts) === 2) {
4655
            // Mail username (removed @domain.tld)
4656
            $forbiddenWords[] = $emailParts[0];
4657
4658
            // Organisation name (removed username@ and .tld)
4659
            $domain = explode('.', $emailParts[1]);
4660
            if (count($domain) > 1)
4661
                $forbiddenWords[] = $domain[0];
4662
        }
4663
    }
4664
4665
    // Search forbidden words in password
4666
    foreach ($forbiddenWords as $word) {
4667
        if (empty($word))
4668
            continue;
4669
4670
        // Stop if forbidden word found in password
4671
        if (stripos($password, $word) !== false)
4672
            return false;
4673
    }
4674
4675
    // Get password complexity
4676
    $length = strlen($password);
4677
    $hasUppercase = preg_match('/[A-Z]/', $password);
4678
    $hasLowercase = preg_match('/[a-z]/', $password);
4679
    $hasNumber = preg_match('/[0-9]/', $password);
4680
    $hasSpecialChar = preg_match('/[\W_]/', $password);
4681
4682
    // Get current user hash
4683
    $userHash = DB::queryFirstRow(
4684
        "SELECT pw FROM " . prefixtable('users') . " WHERE id = %d;",
4685
        $session->get('user-id')
4686
    )['pw'];
4687
4688
    $passwordManager = new PasswordManager();
4689
    
4690
    return $length >= 8
4691
           && $hasUppercase
4692
           && $hasLowercase
4693
           && ($hasNumber || $hasSpecialChar)
4694
           && !$passwordManager->verifyPassword($userHash, $password);
4695
}
4696
4697
4698
/**
4699
 * Converts a value to a string, handling various types and cases.
4700
 *
4701
 * @param mixed $value La valeur à convertir
4702
 * @param string $default Valeur par défaut si la conversion n'est pas possible
4703
 * @return string
4704
 */
4705
function safeString($value, string $default = ''): string
4706
{
4707
    // Simple cases
4708
    if (is_string($value)) {
4709
        return $value;
4710
    }
4711
    
4712
    if (is_scalar($value)) {
4713
        return (string) $value;
4714
    }
4715
    
4716
    // Special cases
4717
    if (is_null($value)) {
4718
        return $default;
4719
    }
4720
    
4721
    if (is_array($value)) {
4722
        return empty($value) ? $default : json_encode($value, JSON_UNESCAPED_UNICODE);
4723
    }
4724
    
4725
    if (is_object($value)) {
4726
        // Vérifie si l'objet implémente __toString()
4727
        if (method_exists($value, '__toString')) {
4728
            return (string) $value;
4729
        }
4730
        
4731
        // Alternative: serialize ou json selon le contexte
4732
        return get_class($value) . (method_exists($value, 'getId') ? '#' . $value->getId() : '');
4733
    }
4734
    
4735
    if (is_resource($value)) {
4736
        return 'Resource#' . get_resource_id($value) . ' of type ' . get_resource_type($value);
4737
    }
4738
    
4739
    // Cas par défaut
4740
    return $default;
4741
}
4742
4743
/**
4744
 * Check if a user has access to a file
4745
 *
4746
 * @param integer $userId
4747
 * @param integer $fileId
4748
 * @return boolean
4749
 */
4750
function userHasAccessToFile(int $userId, int $fileId): bool
4751
{
4752
    // Check if user is admin
4753
    // Refuse access if user does not exist and/or is admin
4754
    $user = DB::queryFirstRow(
4755
        'SELECT admin
4756
        FROM ' . prefixTable('users') . '
4757
        WHERE id = %i',
4758
        $userId
4759
    );
4760
    if (DB::count() === 0 || (int) $user['admin'] === 1) {
4761
        return false;
4762
    }
4763
4764
    // Get file info
4765
    $file = DB::queryFirstRow(
4766
        'SELECT f.id_item, i.id_tree
4767
        FROM ' . prefixTable('files') . ' as f
4768
        INNER JOIN ' . prefixTable('items') . ' AS i ON i.id = f.id_item
4769
        WHERE f.id = %i',
4770
        $fileId
4771
    );
4772
    if (DB::count() === 0) {
4773
        return false;
4774
    }
4775
4776
    // Check if user has access to the item
4777
    include_once __DIR__. '/items.queries.php';
4778
    $itemAccess = getCurrentAccessRights(
4779
        (int) filter_var($userId, FILTER_SANITIZE_NUMBER_INT),
4780
        (int) filter_var($file['id_item'], FILTER_SANITIZE_NUMBER_INT),
4781
        (int) filter_var($file['id_tree'], FILTER_SANITIZE_NUMBER_INT),
4782
        (string) filter_var('show', FILTER_SANITIZE_SPECIAL_CHARS),
4783
    );
4784
4785
    return $itemAccess['access'] === true;
4786
}
4787
4788
/**
4789
 * Check if a user has access to a backup file
4790
 * 
4791
 * @param integer $userId
4792
 * @param string $file
4793
 * @param string $key
4794
 * @param string $keyTmp
4795
 * @return boolean
4796
 */
4797
function userHasAccessToBackupFile(int $userId, string $file, string $key, string $keyTmp): bool
4798
{
4799
    $session = SessionManager::getSession();
4800
4801
    // Ensure session keys are ok
4802
    if ($session->get('key') !== $key || $session->get('user-key_tmp') !== $keyTmp) {
4803
        return false;
4804
    }
4805
    
4806
    // Check if user is admin
4807
    // Refuse access if user does not exist and/or is not admin
4808
    $user = DB::queryFirstRow(
4809
        'SELECT admin
4810
        FROM ' . prefixTable('users') . '
4811
        WHERE id = %i',
4812
        $userId
4813
    );
4814
    if (DB::count() === 0 || (int) $user['admin'] === 0) {
4815
        return false;
4816
    }
4817
    
4818
    // Ensure that user has performed the backup
4819
    DB::queryFirstRow(
4820
        'SELECT f.id
4821
        FROM ' . prefixTable('log_system') . ' as f
4822
        WHERE f.type = %s AND f.label = %s AND f.qui = %i AND f.field_1 = %s',
4823
        'admin_action',
4824
        'dataBase backup',
4825
        $userId,
4826
        $file
4827
    );
4828
    if (DB::count() === 0) {
4829
        return false;
4830
    }
4831
4832
    return true;
4833
}
4834
4835
/**
4836
 * Ensure that personal items have only keys for their owner
4837
 *
4838
 * @param integer $userId
4839
 * @param integer $itemId
4840
 * @return boolean
4841
 */
4842
function EnsurePersonalItemHasOnlyKeysForOwner(int $userId, int $itemId): bool
4843
{
4844
    // Check if user is admin
4845
    // Refuse access if user does not exist and/or is admin
4846
    $user = DB::queryFirstRow(
4847
        'SELECT admin
4848
        FROM ' . prefixTable('users') . '
4849
        WHERE id = %i',
4850
        $userId
4851
    );
4852
    if (DB::count() === 0 || (int) $user['admin'] === 1) {
4853
        return false;
4854
    }
4855
4856
    // Get item info
4857
    $item = DB::queryFirstRow(
4858
        'SELECT i.perso, i.id_tree
4859
        FROM ' . prefixTable('items') . ' as i
4860
        WHERE i.id = %i',
4861
        $itemId
4862
    );
4863
    if (DB::count() === 0 || (int) $item['perso'] === 0) {
4864
        return false;
4865
    }
4866
4867
    // Get item owner
4868
    $itemOwner = DB::queryFirstRow(
4869
        'SELECT li.id_user
4870
        FROM ' . prefixTable('log_items') . ' as li
4871
        WHERE li.id_item = %i AND li.action = %s',
4872
        $itemId,
4873
        'at_creation'
4874
    );
4875
    if (DB::count() === 0 || (int) $itemOwner['id_user'] !== $userId) {
4876
        return false;
4877
    }
4878
4879
    // Delete all keys for this item except for the owner and TeamPass system user
4880
    DB::delete(
4881
        prefixTable('sharekeys_items'),
4882
        'object_id = %i AND user_id NOT IN %ls',
4883
        $itemId,
4884
        [$userId, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4885
    );
4886
    DB::delete(
4887
        prefixTable('sharekeys_files'),
4888
        'object_id IN (SELECT id FROM '.prefixTable('files').' WHERE id_item = %i) AND user_id NOT IN %ls',
4889
        $itemId,
4890
        [$userId, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4891
    );
4892
    DB::delete(
4893
        prefixTable('sharekeys_fields'),
4894
        'object_id IN (SELECT id FROM '.prefixTable('fields').' WHERE id_item = %i) AND user_id NOT IN %ls',
4895
        $itemId,
4896
        [$userId, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4897
    );
4898
    DB::delete(
4899
        prefixTable('sharekeys_logs'),
4900
        'object_id IN (SELECT id FROM '.prefixTable('log_items').' WHERE id_item = %i) AND user_id NOT IN %ls',
4901
        $itemId,
4902
        [$userId, TP_USER_ID, API_USER_ID, OTV_USER_ID,SSH_USER_ID]
4903
    );
4904
4905
    return true;
4906
}
4907
4908
/**
4909
 * Insert a new record in a table with an "is_current" flag.
4910
 * This function ensures that only one record per user has the "is_current" flag set to true.
4911
 * 
4912
 * @param int $userId The ID of the user.
4913
 * @param string $privateKey The private key to be inserted.
4914
 * @return void
4915
 */
4916
function insertPrivateKeyWithCurrentFlag(int $userId, string $privateKey) {    
4917
    try {
4918
        DB::startTransaction();
4919
        
4920
        // Disable is_current for existing records of the user
4921
        DB::update(
4922
            prefixTable('user_private_keys'),
4923
            array('is_current' => false),
4924
            "user_id = %i AND is_current = %i",
4925
            $userId,
4926
            true
4927
        );
4928
        
4929
        // Insert the new record
4930
        DB::insert(
4931
            prefixTable('user_private_keys'),
4932
            array(
4933
                'user_id' => $userId,
4934
                'private_key' => $privateKey,
4935
                'is_current' => true,
4936
            )
4937
        );
4938
        
4939
        DB::commit();
4940
        
4941
    } catch (Exception $e) {
4942
        DB::rollback();
4943
        throw $e;
4944
    }
4945
}
4946
4947
/**
4948
 * Check and migrate personal items at user login
4949
 * After successful authentication and private key decryption
4950
 * 
4951
 * @param int $userId User ID
4952
 * @param string $privateKeyDecrypted Decrypted private key from login
4953
 * @param string $passwordClear Clear user password
4954
 * @return void
4955
 */
4956
function checkAndMigratePersonalItems($userId, $privateKeyDecrypted, $passwordClear) {
4957
    $session = SessionManager::getSession();
4958
    $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
4959
4960
    // 1. Check migration flag in users table
4961
    $user = DB::queryFirstRow(
4962
        "SELECT personal_items_migrated, login 
4963
         FROM ".prefixTable('users')." 
4964
         WHERE id = %i",
4965
        $userId
4966
    );
4967
    
4968
    if ((int) $user['personal_items_migrated'] === 1) {
4969
        return; // Already migrated, nothing to do
4970
    }
4971
    
4972
    // 2. Check if user actually has personal items to migrate
4973
    $personalFolderId = DB::queryFirstField(
4974
        "SELECT id FROM ".prefixTable('nested_tree') ."
4975
         WHERE personal_folder = 1 
4976
         AND title = %s",
4977
        $userId
4978
    );
4979
    
4980
    if (!$personalFolderId) {
4981
        // User has no personal folder, mark as migrated
4982
        DB::update(prefixTable('users'), [
4983
            'personal_items_migrated' => 1
4984
        ], ['id' => $userId]);
4985
        return;
4986
    }
4987
    
4988
    // 3. Count items to migrate
4989
    // Get list of all personal subfolders
4990
    $personalFoldersIds = $tree->getDescendants($personalFolderId, true, false, true);
4991
    $itemsToMigrate = DB::query(
4992
        "SELECT i.id
4993
         FROM ".prefixTable('items')." i
4994
         WHERE i.perso = 1 
4995
         AND i.id_tree IN %li",
4996
        $personalFoldersIds
4997
    );
4998
    
4999
    $totalItems = count($itemsToMigrate);
5000
    
5001
    if ($totalItems == 0) {
5002
        // No items to migrate, mark user as migrated
5003
        DB::update(prefixTable('users'), [
5004
            'personal_items_migrated' => 1
5005
        ], ['id' => $userId]);
5006
        return;
5007
    }
5008
    
5009
    // 4. Check if migration task already exists and is pending
5010
    $existingTask = DB::queryFirstRow(
5011
        "SELECT increment_id, status FROM ".prefixTable('background_tasks')."
5012
         WHERE process_type = 'migrate_user_personal_items'
5013
         AND item_id = %i
5014
         AND status IN ('pending', 'in_progress')
5015
         ORDER BY created_at DESC LIMIT 1",
5016
        $userId
5017
    );
5018
    
5019
    if ($existingTask) {
5020
        // Migration already in progress
5021
        $session->set('migration_personal_items_in_progress', true);
5022
        return;
5023
    }
5024
    
5025
    // 5. Create migration task
5026
    createUserMigrationTask($userId, $privateKeyDecrypted, $passwordClear, json_encode($personalFoldersIds));
5027
    
5028
    // 6. Notify user
5029
    $session->set('migration_personal_items_started', true);
5030
    $session->set('migration_total_items', $totalItems);
5031
}
5032
5033
/**
5034
 * Create migration task for a specific user
5035
 * 
5036
 * @param int $userId User ID
5037
 * @param string $privateKeyDecrypted Decrypted private key
5038
 * @param string $passwordClear Clear user password
5039
 * @param string $personalFolderIds
5040
 * @return void
5041
 */
5042
function createUserMigrationTask($userId, $privateKeyDecrypted, $passwordClear, $personalFolderIds): void
5043
{
5044
    // Decrypt all personal items with this key
5045
    // Launch the re-encryption process for personal items
5046
    // Create process
5047
    DB::insert(
5048
        prefixTable('background_tasks'),
5049
        array(
5050
            'created_at' => time(),
5051
            'process_type' => 'migrate_user_personal_items',
5052
            'arguments' => json_encode([
5053
                'user_id' => (int) $userId,
5054
                'user_pwd' => cryption($passwordClear, '','encrypt')['string'],
5055
                'user_private_key' => cryption($privateKeyDecrypted, '','encrypt')['string'],
5056
                'personal_folders_ids' => $personalFolderIds,
5057
            ]),
5058
            'is_in_progress' => 0,
5059
            'status' => 'pending',
5060
            'item_id' => $userId // Use item_id to store user_id for easy filtering
5061
        )
5062
    );
5063
    $processId = DB::insertId();
5064
5065
    // Create tasks
5066
    createUserMigrationSubTasks($processId, NUMBER_ITEMS_IN_BATCH);
5067
5068
    // update user's new status
5069
    DB::update(
5070
        prefixTable('users'),
5071
        [
5072
            'is_ready_for_usage' => 0,
5073
            'ongoing_process_id' => $processId,
5074
        ],
5075
        'id=%i',
5076
        $userId
5077
    );
5078
}
5079
5080
function createUserMigrationSubTasks($processId, $nbItemsToTreat): void
5081
{
5082
    // Prepare the subtask queries
5083
    $queries = [
5084
        'user-personal-items-migration-step10' => 'SELECT * FROM ' . prefixTable('items'),
5085
5086
        'user-personal-items-migration-step20' => 'SELECT * FROM ' . prefixTable('log_items') . 
5087
                    ' WHERE raison LIKE "at_pw :%" AND encryption_type = "teampass_aes"',
5088
5089
        'user-personal-items-migration-step30' => 'SELECT * FROM ' . prefixTable('categories_items') . 
5090
                    ' WHERE encryption_type = "teampass_aes"',
5091
5092
        'user-personal-items-migration-step40' => 'SELECT * FROM ' . prefixTable('suggestion'),
5093
5094
        'user-personal-items-migration-step50' => 'SELECT * FROM ' . prefixTable('files') . ' AS f
5095
                        INNER JOIN ' . prefixTable('items') . ' AS i ON i.id = f.id_item
5096
                        WHERE f.status = "' . TP_ENCRYPTION_NAME . '"'
5097
    ];
5098
5099
    // Perform loop on $queries to create sub-tasks
5100
    foreach ($queries as $step => $query) {
5101
        DB::query($query);
5102
        createAllSubTasks($step, DB::count(), $nbItemsToTreat, $processId);
5103
    }
5104
5105
    // Create subtask for step final
5106
    DB::insert(
5107
        prefixTable('background_subtasks'),
5108
        array(
5109
            'task_id' => $processId,
5110
            'created_at' => time(),
5111
            'task' => json_encode([
5112
                'step' => 'user-personal-items-migration-step-final',
5113
            ]),
5114
        )
5115
    );
5116
}