FolderController.php 28.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php

/**
 * Copyright Maarch since 2008 under licence GPLv3.
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 */

/**
 * @brief Folder Controller
 *
 * @author dev@maarch.org
 */

namespace Folder\controllers;

17
use Attachment\models\AttachmentModel;
18 19
use Basket\models\BasketModel;
use Basket\models\GroupBasketModel;
20
use Entity\models\EntityModel;
21
use Folder\models\EntityFolderModel;
22
use Folder\models\FolderModel;
23
use Folder\models\ResourceFolderModel;
24
use Group\models\GroupModel;
25
use Group\models\ServiceModel;
26
use History\controllers\HistoryController;
27
use Resource\controllers\ResController;
28
use Resource\controllers\ResourceListController;
29
use Resource\models\ResModel;
30
use Resource\models\ResourceListModel;
31 32 33
use Respect\Validation\Validator;
use Slim\Http\Request;
use Slim\Http\Response;
34
use SrcCore\controllers\PreparedClauseController;
35
use SrcCore\models\DatabaseModel;
36
use SrcCore\models\ValidatorModel;
37
use User\models\UserModel;
38 39 40 41 42

class FolderController
{
    public function get(Request $request, Response $response)
    {
43
        $folders = FolderController::getScopeFolders(['login' => $GLOBALS['userId']]);
44

45
        $userEntities = EntityModel::getWithUserEntities(['select'  => ['entities.id'], 'where' => ['user_id = ?'], 'data' => [$GLOBALS['userId']]]);
46 47 48 49 50 51 52

        $userEntities = array_column($userEntities, 'id');
        if (empty($userEntities)) {
            $userEntities = 0;
        }

        $foldersWithResources = FolderModel::getWithEntitiesAndResources([
53
            'select'   => ['COUNT(DISTINCT resources_folders.res_id)', 'resources_folders.folder_id'],
54 55 56 57 58
            'where'    => ['(entities_folders.entity_id in (?) OR folders.user_id = ?)'],
            'data'     => [$userEntities, $GLOBALS['id']],
            'groupBy'  => ['resources_folders.folder_id']
        ]);

59 60
        $tree = [];
        foreach ($folders as $folder) {
61 62 63 64 65
            $key = array_keys(array_column($foldersWithResources, 'folder_id'), $folder['id']);
            $count = 0;
            if (isset($key[0])) {
                $count = $foldersWithResources[$key[0]]['count'];
            }
66 67 68 69 70 71 72 73
            $insert = [
                'name'       => $folder['label'],
                'id'         => $folder['id'],
                'label'      => $folder['label'],
                'public'     => $folder['public'],
                'user_id'    => $folder['user_id'],
                'parent_id'  => $folder['parent_id'],
                'level'      => $folder['level'],
74
                'countResources' => $count
75 76 77
            ];
            if ($folder['level'] == 0) {
                $tree[] = $insert;
78
            } else {
79
                $found = false;
80 81 82
                foreach ($tree as $key => $branch) {
                    if ($branch['id'] == $folder['parent_id']) {
                        array_splice($tree, $key + 1, 0, [$insert]);
83
                        $found = true;
84 85 86
                        break;
                    }
                }
87
                if (!$found) {
88 89
                    $insert['level'] = 0;
                    $insert['parent_id'] = null;
90 91
                    $tree[] = $insert;
                }
92 93 94
            }
        }

95
        return $response->withJson(['folders' => $tree]);
96 97
    }

98
    public function getById(Request $request, Response $response, array $args)
99
    {
100 101
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
102 103
        }

104
        $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $args['id']]);
105 106
        if (empty($folder[0])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder not found or out of your perimeter']);
107 108
        }

109
        $folder = $folder[0];
110 111
        $ownerInfo = UserModel::getById(['select' => ['firstname', 'lastname'], 'id' => $folder['user_id']]);
        $folder['ownerDisplayName'] = $ownerInfo['firstname'] . ' ' . $ownerInfo['lastname'];
112 113 114

        $folder['sharing']['entities'] = [];
        if ($folder['public']) {
115
            $entitiesFolder = EntityFolderModel::getByFolderId(['folder_id' => $args['id'], 'select' => ['entities_folders.entity_id', 'entities_folders.edition', 'entities.entity_label']]);
116
            foreach ($entitiesFolder as $value) {
117
                $folder['sharing']['entities'][] = ['entity_id' => $value['entity_id'], 'edition' => $value['edition'], 'label' => $value['entity_label']];
118 119 120
            }
        }

121
        return $response->withJson(['folder' => $folder]);
122 123 124 125
    }

    public function create(Request $request, Response $response)
    {
126
        $data = $request->getParsedBody();
127 128 129 130 131 132 133 134

        if (!Validator::stringType()->notEmpty()->validate($data['label'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body label is empty or not a string']);
        }
        if (!empty($data['parent_id']) && !Validator::intval()->validate($data['parent_id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body parent_id is not a numeric']);
        }

135
        if (empty($data['parent_id'])) {
136
            $data['parent_id'] = null;
137 138
            $owner  = $GLOBALS['id'];
            $public = false;
139
            $level  = 0;
140
        } else {
141 142 143 144 145 146 147
            $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $data['parent_id'], 'edition' => true]);
            if (empty($folder[0])) {
                return $response->withStatus(400)->withJson(['errors' => 'Parent Folder not found or out of your perimeter']);
            }
            $owner  = $folder[0]['user_id'];
            $public = $folder[0]['public'];
            $level  = $folder[0]['level'] + 1;
148 149
        }

150
        $id = FolderModel::create([
151 152 153 154 155
            'label'     => $data['label'],
            'public'    => $public,
            'user_id'   => $owner,
            'parent_id' => $data['parent_id'],
            'level'     => $level
156
        ]);
157

158
        if ($public && !empty($data['parent_id'])) {
159
            $entitiesSharing = EntityFolderModel::getByFolderId(['folder_id' => $data['parent_id']]);
160
            foreach ($entitiesSharing as $entity) {
161 162 163 164 165 166 167 168
                EntityFolderModel::create([
                    'folder_id' => $id,
                    'entity_id' => $entity['entity_id'],
                    'edition'   => $entity['edition'],
                ]);
            }
        }

169 170 171 172
        HistoryController::add([
            'tableName' => 'folders',
            'recordId'  => $id,
            'eventType' => 'ADD',
173
            'info'      => _FOLDER_CREATION . " : {$data['label']}",
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
            'moduleId'  => 'folder',
            'eventId'   => 'folderCreation',
        ]);

        return $response->withJson(['folder' => $id]);
    }

    public function update(Request $request, Response $response, array $aArgs)
    {
        $data = $request->getParams();

        if (!Validator::numeric()->notEmpty()->validate($aArgs['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query id is empty or not an integer']);
        }
        if (!Validator::stringType()->notEmpty()->validate($data['label'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body label is empty or not a string']);
        }
191
        if (!empty($data['parent_id']) && !Validator::intval()->validate($data['parent_id'])) {
192
            return $response->withStatus(400)->withJson(['errors' => 'Body parent_id is not a numeric']);
193 194 195
        }
        if ($data['parent_id'] == $aArgs['id']) {
            return $response->withStatus(400)->withJson(['errors' => 'Parent_id and id can not be the same']);
196
        }
197
        if (!empty($data['parent_id']) && FolderController::isParentFolder(['parent_id' => $data['parent_id'], 'id' => $aArgs['id']])) {
198
            return $response->withStatus(400)->withJson(['errors' => 'parent_id does not exist or Id is a parent of parent_id']);
199
        }
200

201 202 203 204
        $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $aArgs['id'], 'edition' => true]);
        if (empty($folder[0])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder not found or out of your perimeter']);
        }
205

206
        if (empty($data['parent_id'])) {
207
            $data['parent_id'] = null;
208
            $level = 0;
209
        } else {
210 211
            $folderParent = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $data['parent_id']]);
            if (empty($folderParent[0])) {
212 213
                return $response->withStatus(400)->withJson(['errors' => 'Parent Folder not found or out of your perimeter']);
            }
214
            $level = $folderParent[0]['level'] + 1;
215 216
        }

217 218
        $this->updateChildren($aArgs['id'], $level);

219 220 221
        FolderModel::update([
            'set' => [
                'label'      => $data['label'],
222 223
                'parent_id'  => $data['parent_id'],
                'level'      => $level
224 225 226 227
            ],
            'where' => ['id = ?'],
            'data' => [$aArgs['id']]
        ]);
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        HistoryController::add([
            'tableName' => 'folders',
            'recordId'  => $aArgs['id'],
            'eventType' => 'UP',
            'info'      => _FOLDER_MODIFICATION . " : {$data['label']}",
            'moduleId'  => 'folder',
            'eventId'   => 'folderModification',
        ]);

        return $response->withStatus(200);
    }

    public function sharing(Request $request, Response $response, array $aArgs)
    {
        $data = $request->getParams();

        if (!Validator::numeric()->notEmpty()->validate($aArgs['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query id is empty or not an integer']);
        }
248
        if (!Validator::boolType()->validate($data['public'])) {
249 250
            return $response->withStatus(400)->withJson(['errors' => 'Body public is empty or not a boolean']);
        }
251 252 253
        if ($data['public'] && !isset($data['sharing']['entities'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body sharing/entities does not exists']);
        }
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        DatabaseModel::beginTransaction();
        $sharing = FolderController::folderSharing(['folderId' => $aArgs['id'], 'public' => $data['public'], 'sharing' => $data['sharing']]);
        if (!$sharing) {
            DatabaseModel::rollbackTransaction();
            return $response->withStatus(400)->withJson(['errors' => 'Can not share/unshare folder because almost one folder is out of your perimeter']);
        }
        DatabaseModel::commitTransaction();

        HistoryController::add([
            'tableName' => 'folders',
            'recordId'  => $aArgs['id'],
            'eventType' => 'UP',
            'info'      => _FOLDER_SHARING_MODIFICATION . " : {$data['label']}",
            'moduleId'  => 'folder',
            'eventId'   => 'folderModification',
        ]);

Damien's avatar
Damien committed
272
        return $response->withStatus(204);
273 274 275 276 277
    }

    public function folderSharing($aArgs = [])
    {
        $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $aArgs['folderId'], 'edition' => true]);
278
        if (empty($folder[0])) {
279
            return false;
280
        }
281 282 283

        FolderModel::update([
            'set' => [
284
                'public' => empty($aArgs['public']) ? 'false' : 'true',
285 286
            ],
            'where' => ['id = ?'],
287
            'data' => [$aArgs['folderId']]
288 289
        ]);

290
        EntityFolderModel::deleteByFolderId(['folder_id' => $aArgs['folderId']]);
291

292 293
        if ($aArgs['public'] && !empty($aArgs['sharing']['entities'])) {
            foreach ($aArgs['sharing']['entities'] as $entity) {
294
                EntityFolderModel::create([
295
                    'folder_id' => $aArgs['folderId'],
296 297 298
                    'entity_id' => $entity['entity_id'],
                    'edition'   => $entity['edition'],
                ]);
299 300 301
            }
        }

302 303 304 305 306 307 308 309 310
        $folderChild = FolderModel::getChild(['id' => $aArgs['folderId'], 'select' => ['id']]);
        if (!empty($folderChild)) {
            foreach ($folderChild as $child) {
                $sharing = FolderController::folderSharing(['folderId' => $child['id'], 'public' => $aArgs['public'], 'sharing' => $aArgs['sharing']]);
                if (!$sharing) {
                    return false;
                }
            }
        }
311

312
        return true;
313 314 315 316 317 318 319 320
    }

    public function delete(Request $request, Response $response, array $aArgs)
    {
        if (!Validator::numeric()->notEmpty()->validate($aArgs['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Query id is empty or not an integer']);
        }

321
        $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $aArgs['id'], 'edition' => true]);
322
        
323 324 325 326 327 328 329
        DatabaseModel::beginTransaction();
        $deletion = FolderController::folderDeletion(['folderId' => $aArgs['id']]);
        if (!$deletion) {
            DatabaseModel::rollbackTransaction();
            return $response->withStatus(400)->withJson(['errors' => 'Can not delete because almost one folder is out of your perimeter']);
        }
        DatabaseModel::commitTransaction();
330

331 332 333 334
        HistoryController::add([
            'tableName' => 'folder',
            'recordId'  => $aArgs['id'],
            'eventType' => 'DEL',
335
            'info'      => _FOLDER_SUPPRESSION . " : {$folder[0]['label']}",
336 337 338 339
            'moduleId'  => 'folder',
            'eventId'   => 'folderSuppression',
        ]);

Damien's avatar
Damien committed
340
        return $response->withStatus(204);
341
    }
342

343
    public static function folderDeletion(array $aArgs = [])
344 345 346 347 348 349 350 351
    {
        $folder = FolderController::getScopeFolders(['login' => $GLOBALS['userId'], 'folderId' => $aArgs['folderId'], 'edition' => true]);
        if (empty($folder[0])) {
            return false;
        }

        FolderModel::delete(['where' => ['id = ?'], 'data' => [$aArgs['folderId']]]);
        EntityFolderModel::deleteByFolderId(['folder_id' => $aArgs['folderId']]);
352
        ResourceFolderModel::delete(['where' => ['folder_id = ?'], 'data' => [$aArgs['folderId']]]);
353 354 355 356 357 358 359 360 361 362 363 364 365

        $folderChild = FolderModel::getChild(['id' => $aArgs['folderId'], 'select' => ['id']]);
        if (!empty($folderChild)) {
            foreach ($folderChild as $child) {
                $deletion = FolderController::folderDeletion(['folderId' => $child['id']]);
                if (!$deletion) {
                    return false;
                }
            }
        }
        return true;
    }

366 367 368 369 370 371 372 373 374 375 376 377 378 379
    public function getResourcesById(Request $request, Response $response, array $args)
    {
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        if (!FolderController::hasFolder(['id' => $args['id'], 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder out of perimeter']);
        }

        $foldersResources = ResourceFolderModel::get(['select' => ['res_id'], 'where' => ['folder_id = ?'], 'data' => [$args['id']]]);
        $foldersResources = array_column($foldersResources, 'res_id');

        $formattedResources = [];
380
        $allResources = [];
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        $count = 0;
        if (!empty($foldersResources)) {
            $queryParams = $request->getQueryParams();
            $queryParams['offset'] = (empty($queryParams['offset']) || !is_numeric($queryParams['offset']) ? 0 : (int)$queryParams['offset']);
            $queryParams['limit'] = (empty($queryParams['limit']) || !is_numeric($queryParams['limit']) ? 10 : (int)$queryParams['limit']);

            $allQueryData = ResourceListController::getResourcesListQueryData(['data' => $queryParams]);
            if (!empty($allQueryData['order'])) {
                $data['order'] = $allQueryData['order'];
            }

            $rawResources = ResourceListModel::getOnView([
                'select'    => ['res_id'],
                'table'     => $allQueryData['table'],
                'leftJoin'  => $allQueryData['leftJoin'],
                'where'     => array_merge(['res_id in (?)'], $allQueryData['where']),
                'data'      => array_merge([$foldersResources], $allQueryData['queryData']),
                'orderBy'   => empty($data['order']) ? ['creation_date'] : [$data['order']]
            ]);

            $resIds = ResourceListController::getIdsWithOffsetAndLimit(['resources' => $rawResources, 'offset' => $queryParams['offset'], 'limit' => $queryParams['limit']]);

403 404 405 406
            foreach ($rawResources as $resource) {
                $allResources[] = $resource['res_id'];
            }

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
            $formattedResources = [];
            if (!empty($resIds)) {
                $excludeAttachmentTypes = ['converted_pdf', 'print_folder'];
                if (!ServiceModel::hasService(['id' => 'view_documents_with_notes', 'userId' => $GLOBALS['userId'], 'location' => 'attachments', 'type' => 'use'])) {
                    $excludeAttachmentTypes[] = 'document_with_notes';
                }

                $attachments = AttachmentModel::getOnView([
                    'select'    => ['COUNT(res_id)', 'res_id_master'],
                    'where'     => ['res_id_master in (?)', 'status not in (?)', 'attachment_type not in (?)', '((status = ? AND typist = ?) OR status != ?)'],
                    'data'      => [$resIds, ['DEL', 'OBS'], $excludeAttachmentTypes, 'TMP', $GLOBALS['userId'], 'TMP'],
                    'groupBy'   => ['res_id_master']
                ]);

                $select = [
                    'res_letterbox.res_id', 'res_letterbox.subject', 'res_letterbox.barcode', 'mlb_coll_ext.alt_identifier',
                    'status.label_status AS "status.label_status"', 'status.img_filename AS "status.img_filename"', 'priorities.color AS "priorities.color"'
                ];
                $tableFunction = ['status', 'mlb_coll_ext', 'priorities'];
                $leftJoinFunction = ['res_letterbox.status = status.id', 'res_letterbox.res_id = mlb_coll_ext.res_id', 'res_letterbox.priority = priorities.id'];

                $order = 'CASE res_letterbox.res_id ';
                foreach ($resIds as $key => $resId) {
                    $order .= "WHEN {$resId} THEN {$key} ";
                }
                $order .= 'END';

                $resources = ResourceListModel::getOnResource([
                    'select'    => $select,
                    'table'     => $tableFunction,
                    'leftJoin'  => $leftJoinFunction,
                    'where'     => ['res_letterbox.res_id in (?)'],
                    'data'      => [$resIds],
                    'orderBy'   => [$order]
                ]);

                $formattedResources = ResourceListController::getFormattedResources([
                    'resources'     => $resources,
                    'userId'        => $GLOBALS['id'],
                    'attachments'   => $attachments,
                    'checkLocked'   => false
                ]);
            }

            $count = count($rawResources);
        }

454
        return $response->withJson(['resources' => $formattedResources, 'countResources' => $count, 'allResources' => $allResources]);
455 456 457 458 459 460 461 462
    }

    public function addResourcesById(Request $request, Response $response, array $args)
    {
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

Damien's avatar
Damien committed
463 464 465 466 467
        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body resources is empty or not an array']);
        }

468 469 470 471 472 473 474 475
        if (!FolderController::hasFolder(['id' => $args['id'], 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder out of perimeter']);
        }

        $foldersResources = ResourceFolderModel::get(['select' => ['res_id'], 'where' => ['folder_id = ?'], 'data' => [$args['id']]]);
        $foldersResources = array_column($foldersResources, 'res_id');

        $resourcesToClassify = array_diff($body['resources'], $foldersResources);
476 477 478 479
        if (empty($resourcesToClassify)) {
            return $response->withJson(['countResources' => count($foldersResources)]);
        }

480 481 482 483 484 485 486 487 488
        if (!ResController::hasRightByResId(['resId' => $resourcesToClassify, 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Resources out of perimeter']);
        }

        foreach ($resourcesToClassify as $value) {
            ResourceFolderModel::create(['folder_id' => $args['id'], 'res_id' => $value]);
        }

        return $response->withJson(['countResources' => count($foldersResources) + count($resourcesToClassify)]);
489 490
    }

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    public function removeResourcesById(Request $request, Response $response, array $args)
    {
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        if (!FolderController::hasFolder(['id' => $args['id'], 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder out of perimeter']);
        }

        $foldersResources = ResourceFolderModel::get(['select' => ['res_id'], 'where' => ['folder_id = ?'], 'data' => [$args['id']]]);
        $foldersResources = array_column($foldersResources, 'res_id');

        $body = $request->getParsedBody();
        if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Body resources is empty or not an array']);
        }

        $resourcesToUnclassify = array_intersect($foldersResources, $body['resources']);
        if (empty($resourcesToUnclassify)) {
            return $response->withJson(['countResources' => count($foldersResources)]);
        }

        if (!ResController::hasRightByResId(['resId' => $resourcesToUnclassify, 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Resources out of perimeter']);
        }

        foreach ($resourcesToUnclassify as $value) {
            ResourceFolderModel::delete(['where' => ['folder_id = ?', 'res_id = ?'], 'data' => [$args['id'], $value]]);
        }

        return $response->withJson(['countResources' => count($foldersResources) - count($resourcesToUnclassify)]);
    }

525
    public function getBasketsFromFolder(Request $request, Response $response, array $args)
526 527 528 529 530 531
    {
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        if (!FolderController::hasFolder(['id' => $args['id'], 'userId' => $GLOBALS['id']])) {
Damien's avatar
Damien committed
532
            return $response->withStatus(403)->withJson(['errors' => 'Folder out of perimeter']);
533 534 535 536
        }

        $foldersResource = ResourceFolderModel::get(['select' => [1], 'where' => ['folder_id = ?', 'res_id = ?'], 'data' => [$args['id'], $args['resId']]]);
        if (empty($foldersResource)) {
Damien's avatar
Damien committed
537
            return $response->withStatus(403)->withJson(['errors' => 'Resource out of perimeter']);
538 539 540
        }

        $baskets = BasketModel::getWithPreferences([
541
            'select'    => ['baskets.id', 'baskets.basket_name', 'baskets.basket_clause', 'users_baskets_preferences.group_serial_id', 'usergroups.group_desc'],
542 543 544
            'where'     => ['users_baskets_preferences.user_serial_id = ?'],
            'data'      => [$GLOBALS['id']]
        ]);
545
        $groupsBaskets = [];
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        $inCheckedBaskets = [];
        $outCheckedBaskets = [];
        foreach ($baskets as $basket) {
            if (in_array($basket['id'], $outCheckedBaskets)) {
                continue;
            } else {
                if (!in_array($basket['id'], $inCheckedBaskets)) {
                    $preparedClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $GLOBALS['userId']]);
                    $resource = ResModel::getOnView(['select' => [1], 'where' => ['res_id = ?', "({$preparedClause})"], 'data' => [$args['resId']]]);
                    if (empty($resource)) {
                        $outCheckedBaskets[] = $basket['id'];
                        continue;
                    }
                }
                $inCheckedBaskets[] = $basket['id'];
561
                $groupsBaskets[] = ['groupId' => $basket['group_serial_id'], 'groupName' => $basket['group_desc'], 'basketId' => $basket['id'], 'basketName' => $basket['basket_name']];
562 563 564
            }
        }

565
        return $response->withJson(['groupsBaskets' => $groupsBaskets]);
566 567
    }

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    public function getFilters(Request $request, Response $response, array $args)
    {
        if (!Validator::numeric()->notEmpty()->validate($args['id'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Route id is not an integer']);
        }

        if (!FolderController::hasFolder(['id' => $args['id'], 'userId' => $GLOBALS['id']])) {
            return $response->withStatus(400)->withJson(['errors' => 'Folder out of perimeter']);
        }

        $foldersResources = ResourceFolderModel::get(['select' => ['res_id'], 'where' => ['folder_id = ?'], 'data' => [$args['id']]]);
        $foldersResources = array_column($foldersResources, 'res_id');

        if (empty($foldersResources)) {
            return $response->withJson(['entities' => [], 'priorities' => [], 'categories' => [], 'statuses' => [], 'entitiesChildren' => []]);
        }

        $where = ['(res_id in (?))'];
        $queryData = [$foldersResources];
        $queryParams = $request->getQueryParams();

        $filters = ResourceListController::getFormattedFilters(['where' => $where, 'queryData' => $queryData, 'queryParams' => $queryParams]);

        return $response->withJson($filters);
    }

594 595 596
    // login (string) : Login of user connected
    // folderId (integer) : Check specific folder
    // edition (boolean) : whether user can edit or not
597
    public static function getScopeFolders(array $aArgs)
598 599
    {
        $login = $aArgs['login'];
600
        $userEntities = EntityModel::getWithUserEntities(['select'  => ['entities.id'], 'where' => ['user_id = ?'], 'data' => [$login]]);
601 602 603 604 605 606 607 608

        $userEntities = array_column($userEntities, 'id');
        if (empty($userEntities)) {
            $userEntities = 0;
        }

        $user = UserModel::getByLogin(['login' => $login, 'select' => ['id']]);

609
        if ($aArgs['edition']) {
610
            $edition = [1];
611
        } else {
612
            $edition = [0, 1, null];
613 614 615 616
        }

        $where = ['(user_id = ? OR (entity_id in (?) AND entities_folders.edition in (?)))'];
        $data = [$user['id'], $userEntities, $edition];
617 618 619

        if (!empty($aArgs['folderId'])) {
            $where[] = 'folders.id = ?';
620
            $data[]  = $aArgs['folderId'];
621 622
        }

623 624 625 626
        $folders = FolderModel::getWithEntities([
            'select'    => ['distinct (folders.id)', 'folders.*'],
            'where'     => $where,
            'data'      => $data,
627
            'orderBy'   => ['level', 'label']
628 629 630 631
        ]);

        return $folders;
    }
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

    private static function hasFolder(array $args)
    {
        ValidatorModel::notEmpty($args, ['id', 'userId']);
        ValidatorModel::intVal($args, ['id', 'userId']);


        $user = UserModel::getById(['id' => $args['userId'], 'select' => ['user_id']]);

        $entities = UserModel::getEntitiesById(['userId' => $user['user_id']]);
        $entities = array_column($entities, 'id');

        if (empty($entities)) {
            $entities = [0];
        }

        $folders = FolderModel::getWithEntities([
            'select'   => [1],
            'where'    => ['folders.id = ?', '(user_id = ? OR entity_id in (?))'],
            'data'     => [$args['id'], $args['userId'], $entities]
        ]);

        if (empty($folders)) {
            return false;
        }

        return true;
    }
660 661 662 663 664 665 666 667 668 669 670

    private static function isParentFolder(array $args)
    {
        $parentInfo = FolderModel::getById(['id' => $args['parent_id'], 'select' => ['folders.id', 'parent_id']]);
        if (empty($parentInfo) || $parentInfo['id'] == $args['id']) {
            return true;
        } elseif (!empty($parentInfo['parent_id'])) {
            return FolderController::isParentFolder(['parent_id' => $parentInfo['parent_id'], 'id' => $args['id']]);
        }
        return false;
    }
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693

    private function updateChildren($parentId, $levelParent)
    {
        $folderChild = FolderModel::getChild(['id' => $parentId]);
        if (!empty($folderChild)) {

            $level = -1;
            foreach ($folderChild as $child) {
                $level = $levelParent + 1;
                $this->updateChildren($child['id'], $level);
            }

            $idsChildren = array_column($folderChild, 'id');

            FolderModel::update([
                'set' => [
                    'level' => $level
                ],
                'where' => ['id in (?)'],
                'data' => [$idsChildren]
            ]);
        }
    }
694
}