Passed
Pull Request — master (#4596)
by
unknown
06:17
created

FolderManager   F

Complexity

Total Complexity 61

Size/Duplication

Total Lines 429
Duplicated Lines 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 184
c 8
b 0
f 0
dl 0
loc 429
rs 3.52
wmc 61

20 Methods

Rating   Name   Duplication   Size   Complexity  
A checkDuplicateFolderAllowed() 0 19 4
A isParentFolderAllowed() 0 8 3
A isTitleNumeric() 0 3 1
A checkComplexityLevel() 0 24 6
A getParentFolderData() 0 23 3
A manageFolderPermissions() 0 18 6
A updateUserFolderCache() 0 40 4
A copyCustomFieldsCategories() 0 7 2
A loadSettings() 0 5 1
A __construct() 0 4 1
A canCreateFolder() 0 7 6
A createFolder() 0 18 2
A refreshCacheForUsersWithSimilarRoles() 0 34 3
A insertFolder() 0 15 3
A rebuildFolderTree() 0 11 3
A addComplexity() 0 7 1
A setFolderCategories() 0 3 1
A errorResponse() 0 6 1
B createNewFolder() 0 26 9
A updateTimestamp() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like FolderManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FolderManager, and based on these observations, apply Extract Interface, too.

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      folders.class.php
26
 * @author    Nils Laumaillé ([email protected])
27
 * @copyright 2009-2024 Teampass.net
28
 * @license   GPL-3.0
29
 * @see       https://www.teampass.net
30
 */
31
32
use TeampassClasses\NestedTree\NestedTree;
33
use TeampassClasses\SessionManager\SessionManager;
34
use TeampassClasses\ConfigManager\ConfigManager;
35
36
class FolderManager
37
{
38
    private $lang;
39
    private $settings;
40
41
    /**
42
     * Constructor
43
     */
44
    public function __construct($lang)
45
    {
46
        $this->lang = $lang;
47
        $this->loadSettings();
48
    }
49
50
    /**
51
     * Load settings
52
     */
53
    private function loadSettings()
54
    {
55
        // Load config if $SETTINGS not defined
56
        $configManager = new ConfigManager();
57
        $this->settings = $configManager->getAllSettings();
58
    }
59
60
    /**
61
     * Create a new folder
62
     *
63
     * @param array $params
64
     * @return array
65
     */
66
    public function createNewFolder(array $params): array
67
    {
68
        // Décomposer les paramètres pour une meilleure lisibilité
69
        extract($params);
70
71
        if ($this->isTitleNumeric($title)) {
72
            return $this->errorResponse($this->lang->get('error_only_numbers_in_folder_name'));
73
        }
74
75
        if (!$this->isParentFolderAllowed($parent_id, $user_accessible_folders, $user_is_admin)) {
76
           if ($parent_id != 0 && $user_can_create_root_folder == false )
77
               return $this->errorResponse($this->lang->get('error_folder_not_allowed_for_this_user'));
78
        }
79
80
        if (!$this->checkDuplicateFolderAllowed($title) && $personal_folder == 0) {
81
            return $this->errorResponse($this->lang->get('error_group_exist'));
82
        }
83
84
        $parentFolderData = $this->getParentFolderData($parent_id);
85
86
        $parentComplexity = $this->checkComplexityLevel($parentFolderData, $complexity, $parent_id);
87
        if (isset($parentComplexity ['error']) && $parentComplexity['error'] === true) {
88
            return $this->errorResponse($this->lang->get('error_folder_complexity_lower_than_top_folder') . " [<b>{$this->settings['TP_PW_COMPLEXITY'][$parentComplexity['valeur']][1]}</b>]");
89
        }
90
91
        return $this->createFolder($params, array_merge($parentFolderData, $parentComplexity));
92
    }
93
94
    /**
95
     * Check if title is numeric
96
     *
97
     * @param string $title
98
     * @return boolean
99
     */
100
    private function isTitleNumeric($title)
101
    {
102
        return is_numeric($title);
103
    }
104
105
    /**
106
     * Check if parent folder is allowed
107
     *
108
     * @param integer $parent_id
109
     * @param array $user_accessible_folders
110
     * @param boolean $user_is_admin
111
     * @return boolean
112
     */
113
    private function isParentFolderAllowed($parent_id, $user_accessible_folders, $user_is_admin)
114
    {
115
        if (in_array($parent_id, $user_accessible_folders) === false
116
            && (int) $user_is_admin !== 1
117
        ) {
118
            return false;
119
        }
120
        return true;
121
    }
122
123
    /**
124
     * Check if duplicate folder is allowed
125
     *
126
     * @param string $title
127
     * @return boolean
128
     */
129
    private function checkDuplicateFolderAllowed($title)
130
    {
131
        if (
132
            isset($this->settings['duplicate_folder']) === true
133
            && (int) $this->settings['duplicate_folder'] === 0
134
        ) {
135
            DB::query(
136
                'SELECT *
137
                FROM ' . prefixTable('nested_tree') . '
138
                WHERE title = %s AND personal_folder = 0',
139
                $title
140
            );
141
            $counter = DB::count();
142
            if ($counter !== 0) {
143
                return false;
144
            }
145
            return true;
146
        }
147
        return true;
148
    }
149
150
    /**
151
     * Get parent folder data
152
     *
153
     * @param integer $parent_id
154
     * @return array
155
     */
156
    private function getParentFolderData($parent_id)
157
    {
158
        //check if parent folder is personal
159
        $data = DB::queryfirstrow(
160
            'SELECT personal_folder, bloquer_creation, bloquer_modification
161
            FROM ' . prefixTable('nested_tree') . '
162
            WHERE id = %i',
163
            $parent_id
164
        );
165
166
        // inherit from parent the specific settings it has
167
        if (DB::count() > 0) {
168
            $parentBloquerCreation = $data['bloquer_creation'];
169
            $parentBloquerModification = $data['bloquer_modification'];
170
        } else {
171
            $parentBloquerCreation = 0;
172
            $parentBloquerModification = 0;
173
        }
174
175
        return [
176
            'isPersonal' => null !== $data['personal_folder'] ? $data['personal_folder'] : 0,
177
            'parentBloquerCreation' => $parentBloquerCreation,
178
            'parentBloquerModification' => $parentBloquerModification,
179
        ];
180
    }
181
182
    /**
183
     * Check complexity level
184
     *
185
     * @param array $data
186
     * @param integer $complexity
187
     * @param integer $parent_id
188
     * @return array|boolean
189
     */
190
    private function checkComplexityLevel(
191
        $data,
192
        $complexity,
193
        $parent_id
194
    )
195
    {
196
        if (isset($data) === false || (int) $data['isPersonal'] === 0) {    
197
            // get complexity level for this folder
198
            $data = DB::queryfirstrow(
199
                'SELECT valeur
200
                FROM ' . prefixTable('misc') . '
201
                WHERE intitule = %i AND type = %s',
202
                $parent_id,
203
                'complex'
204
            );
205
            if (isset($data['valeur']) === true && intval($complexity) < intval($data['valeur'])) {
206
                return [
207
                    'error' => true,
208
                ];
209
            }
210
        }
211
212
        return [
213
            'parent_complexity' => isset($data['valeur']) === true ? $data['valeur'] : 0,
214
        ];
215
    }
216
217
    /**
218
     * Creates a new folder in the system, applying necessary settings, permissions, 
219
     * cache updates, and user role management.
220
     *
221
     * @param array $params - Parameters for folder creation (e.g., title, icon, etc.)
222
     * @param array $parentFolderData - Parent folder data (e.g., ID, permissions)
223
     * @return array - Returns an array indicating success or failure
224
     */
225
    private function createFolder($params, $parentFolderData)
226
    {
227
        extract($params);
228
        extract($parentFolderData);
229
230
        if ($this->canCreateFolder($isPersonal, $user_is_admin, $user_is_manager, $user_can_manage_all_users, $user_can_create_root_folder)) {
231
            $newId = $this->insertFolder($params, $parentFolderData);
232
            $this->addComplexity($newId, $complexity);
233
            $this->setFolderCategories($newId);
234
            $this->updateTimestamp();
235
            $this->rebuildFolderTree($user_is_admin, $title, $parent_id, $isPersonal, $user_id, $newId);
236
            $this->manageFolderPermissions($parent_id, $newId, $user_roles, $access_rights, $user_is_admin);
237
            $this->copyCustomFieldsCategories($parent_id, $newId);
238
            $this->refreshCacheForUsersWithSimilarRoles($user_roles);
239
240
            return ['error' => false, 'newId' => $newId];
241
        } else {
242
            return ['error' => true, 'newId' => null];
243
        }
244
    }
245
246
    /**
247
     * Checks if the user has the permissions to create a folder.
248
     */
249
    private function canCreateFolder($isPersonal, $user_is_admin, $user_is_manager, $user_can_manage_all_users, $user_can_create_root_folder)
250
    {
251
        return (int)$isPersonal === 1 ||
252
            (int)$user_is_admin === 1 ||
253
            ((int)$user_is_manager === 1 || (int)$user_can_manage_all_users === 1) ||
254
            ($this->settings['enable_user_can_create_folders'] ?? false) ||
255
            ((int)$user_can_create_root_folder === 1);
256
    }
257
258
    /**
259
     * Inserts a new folder into the database and returns the new folder ID.
260
     */
261
    private function insertFolder($params, $parentFolderData)
262
    {
263
        DB::insert(prefixTable('nested_tree'), [
264
            'parent_id' => $params['parent_id'],
265
            'title' => $params['title'],
266
            'personal_folder' => $params['personal_folder'] ?? 0,
267
            'renewal_period' => $params['duration'] ?? 0,
268
            'bloquer_creation' => $params['create_auth_without'] ?? $parentFolderData['parentBloquerCreation'],
269
            'bloquer_modification' => $params['edit_auth_without'] ?? $parentFolderData['parentBloquerModification'],
270
            'fa_icon' => empty($params['icon']) ? TP_DEFAULT_ICON : $params['icon'],
271
            'fa_icon_selected' => empty($params['icon_selected']) ? TP_DEFAULT_ICON_SELECTED : $params['icon_selected'],
272
            'categories' => '',
273
        ]);
274
275
        return DB::insertId();
276
    }
277
278
    /**
279
     * Adds complexity settings for the newly created folder.
280
     */
281
    private function addComplexity($folderId, $complexity)
282
    {
283
        DB::insert(prefixTable('misc'), [
284
            'type' => 'complex',
285
            'intitule' => $folderId,
286
            'valeur' => $complexity,
287
            'created_at' => time(),
288
        ]);
289
    }
290
291
    /**
292
     * Ensures that folder categories are set.
293
     */
294
    private function setFolderCategories($folderId)
295
    {
296
        handleFoldersCategories([$folderId]);
297
    }
298
299
    /**
300
     * Updates the last folder change timestamp.
301
     */
302
    private function updateTimestamp()
303
    {
304
        DB::update(prefixTable('misc'), [
305
            'valeur' => time(),
306
            'updated_at' => time(),
307
        ], 'type = %s AND intitule = %s', 'timestamp', 'last_folder_change');
308
    }
309
310
    /**
311
     * Rebuilds the folder tree and updates the cache for non-admin users.
312
     */
313
    private function rebuildFolderTree($user_is_admin, $title, $parent_id, $isPersonal, $user_id, $newId)
314
    {
315
        $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
316
        $tree->rebuild();
317
        
318
        // Update session visible flolders
319
        $sess_key = $isPersonal ? 'user-personal_folders' : 'user-accessible_folders';
320
        SessionManager::addRemoveFromSessionArray($sess_key, [$newId], 'add');
321
322
        if ($user_is_admin === 0) {
323
            $this->updateUserFolderCache($tree, $title, $parent_id, $isPersonal, $user_id, $newId);
324
        }
325
    }
326
327
    /**
328
     * Updates the user folder cache for non-admin users.
329
     */
330
    private function updateUserFolderCache($tree, $title, $parent_id, $isPersonal, $user_id, $newId)
331
    {
332
        $path = '';
333
        $tree_path = $tree->getPath(0, false);
334
        foreach ($tree_path as $fld) {
335
            $path .= empty($path) ? $fld->title : '/' . $fld->title;
336
        }
337
338
        $new_json = [
339
            "path" => $path,
340
            "id" => $newId,
341
            "level" => count($tree_path),
342
            "title" => $title,
343
            "disabled" => 0,
344
            "parent_id" => $parent_id,
345
            "perso" => $isPersonal,
346
            "is_visible_active" => 0,
347
        ];
348
349
        $cache_tree = DB::queryFirstRow('SELECT increment_id, folders, visible_folders FROM ' . prefixTable('cache_tree') . ' WHERE user_id = %i', (int)$user_id);
350
351
        if (empty($cache_tree)) {
352
            DB::insert(prefixTable('cache_tree'), [
353
                'user_id' => $user_id,
354
                'folders' => json_encode([$newId]),
355
                'visible_folders' => json_encode($new_json),
356
                'timestamp' => time(),
357
                'data' => '[{}]',
358
            ]);
359
        } else {
360
            $folders = json_decode($cache_tree['folders'] ?? '[]', true);
361
            $visible_folders = json_decode($cache_tree['visible_folders'] ?? '[]', true);
362
            $folders[] = $newId;
363
            $visible_folders[] = $new_json;
364
365
            DB::update(prefixTable('cache_tree'), [
366
                'folders' => json_encode($folders),
367
                'visible_folders' => json_encode($visible_folders),
368
                'timestamp' => time(),
369
            ], 'increment_id = %i', (int)$cache_tree['increment_id']);
370
        }
371
    }
372
373
    /**
374
     * Manages folder permissions based on user roles or parent folder settings.
375
     */
376
    private function manageFolderPermissions($parent_id, $newId, $user_roles, $access_rights, $user_is_admin)
377
    {
378
        if ($this->settings['subfolder_rights_as_parent'] ?? false) {
379
            $rows = DB::query('SELECT role_id, type FROM ' . prefixTable('roles_values') . ' WHERE folder_id = %i', $parent_id);
380
            foreach ($rows as $record) {
381
                DB::insert(prefixTable('roles_values'), [
382
                    'role_id' => $record['role_id'],
383
                    'folder_id' => $newId,
384
                    'type' => $record['type'],
385
                ]);
386
            }
387
        } elseif ((int)$user_is_admin !== 1) {
388
            foreach (array_unique(explode(';', $user_roles)) as $role) {
389
                if (!empty($role)) {
390
                    DB::insert(prefixTable('roles_values'), [
391
                        'role_id' => $role,
392
                        'folder_id' => $newId,
393
                        'type' => $access_rights,
394
                    ]);
395
                }
396
            }
397
        }
398
    }
399
400
    /**
401
     * Copies custom field categories from the parent folder to the newly created folder.
402
     */
403
    private function copyCustomFieldsCategories($parent_id, $newId)
404
    {
405
        $rows = DB::query('SELECT id_category FROM ' . prefixTable('categories_folders') . ' WHERE id_folder = %i', $parent_id);
406
        foreach ($rows as $record) {
407
            DB::insert(prefixTable('categories_folders'), [
408
                'id_category' => $record['id_category'],
409
                'id_folder' => $newId,
410
            ]);
411
        }
412
    }
413
414
    /**
415
     * Refresh the cache for users with similar roles to the current user.
416
     */
417
    private function refreshCacheForUsersWithSimilarRoles($user_roles)
418
    {
419
        $usersWithSimilarRoles = getUsersWithRoles(explode(";", $user_roles));
420
        foreach ($usersWithSimilarRoles as $user) {
421
422
            // Arguments field
423
            $arguments = json_encode([
424
                'user_id' => (int) $user,
425
            ], JSON_HEX_QUOT | JSON_HEX_TAG);
426
427
            // Search for existing job
428
            $count = DB::queryFirstRow(
429
                'SELECT COUNT(*) AS count
430
                FROM ' . prefixTable('background_tasks') . '
431
                WHERE is_in_progress = %i AND process_type = %s AND arguments = %s',
432
                0,
433
                'user_build_cache_tree',
434
                $arguments
435
            )['count'];
436
437
            // Don't insert duplicates
438
            if ($count > 0)
439
                continue;
440
441
            // Insert new background task
442
            DB::insert(
443
                prefixTable('background_tasks'),
444
                array(
445
                    'created_at' => time(),
446
                    'process_type' => 'user_build_cache_tree',
447
                    'arguments' => $arguments,
448
                    'updated_at' => '',
449
                    'finished_at' => '',
450
                    'output' => '',
451
                )
452
            );
453
        }
454
    }
455
456
    /**
457
     * Returns an error response.
458
     */
459
    private function errorResponse($message, $newIdSuffix = "")
460
    {
461
        return [
462
            'error' => true,
463
            'message' => $message,
464
            'newId' => '' . $newIdSuffix,
465
        ];
466
    }
467
}
468