Skip to content
Snippets Groups Projects
ResourceControlController.php 21.3 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    <?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 Resource Control Controller
    * @author dev@maarch.org
    */
    
    namespace Resource\controllers;
    
    use Contact\models\ContactModel;
    use Convert\models\AdrModel;
    use CustomField\models\CustomFieldModel;
    use Doctype\models\DoctypeModel;
    use Entity\models\EntityModel;
    use Folder\controllers\FolderController;
    use IndexingModel\models\IndexingModelFieldModel;
    use IndexingModel\models\IndexingModelModel;
    use Priority\models\PriorityModel;
    use Resource\models\ResModel;
    use Respect\Validation\Validator;
    use SrcCore\controllers\PreparedClauseController;
    use Status\models\StatusModel;
    use Tag\models\TagModel;
    use User\models\UserGroupModel;
    use User\models\UserModel;
    
    class ResourceControlController
    {
        protected static function controlResource(array $args)
        {
            $currentUser = UserModel::getById(['id' => $GLOBALS['id'], 'select' => ['loginmode']]);
            $isWebServiceUser = $currentUser['loginmode'] == 'restMode';
    
            $body = $args['body'];
    
            if (empty($body)) {
                return ['errors' => 'Body is not set or empty'];
            } elseif (!Validator::intVal()->notEmpty()->validate($body['doctype'])) {
                return ['errors' => 'Body doctype is empty or not an integer'];
            } elseif (!Validator::intVal()->notEmpty()->validate($body['modelId'])) {
                return ['errors' => 'Body modelId is empty or not an integer'];
            } elseif ($isWebServiceUser && !Validator::stringType()->notEmpty()->validate($body['status'])) {
                return ['errors' => 'Body status is empty or not a string'];
            }
    
            $doctype = DoctypeModel::getById(['id' => $body['doctype'], 'select' => [1]]);
            if (empty($doctype)) {
                return ['errors' => 'Body doctype does not exist'];
            }
    
            $indexingModel = IndexingModelModel::getById(['id' => $body['modelId'], 'select' => ['master', 'enabled']]);
            if (empty($indexingModel)) {
                return ['errors' => 'Body modelId does not exist'];
            } elseif (!$indexingModel['enabled']) {
                return ['errors' => 'Body modelId is disabled'];
            } elseif (!empty($indexingModel['master'])) {
                return ['errors' => 'Body modelId is not public'];
            }
    
            $control = ResourceControlController::controlFileData(['body' => $body]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            $control = ResourceControlController::controlAdjacentData(['body' => $body, 'isWebServiceUser' => $isWebServiceUser]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            if (!$isWebServiceUser) {
                $control = ResourceControlController::controlIndexingModelFields(['body' => $body]);
                if (!empty($control['errors'])) {
                    return ['errors' => $control['errors']];
                }
    
                if (!empty($body['initiator'])) {
                    $userEntities = UserModel::getEntitiesByLogin(['login' => $GLOBALS['userId']]);
                    $userEntities = array_column($userEntities, 'id');
                    if (!in_array($body['initiator'], $userEntities)) {
                        return ['errors' => "Body initiator does not belong to your entities"];
                    }
                }
            }
    
            $control = ResourceControlController::controlDestination(['body' => $body]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
            $control = ResourceControlController::controlDates(['body' => $body]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            if (!empty($body['status'])) {
                $status = StatusModel::getById(['id' => $body['status'], 'select' => [1]]);
                if (empty($status)) {
                    return ['errors' => 'Body status does not exist'];
                }
            }
    
            if (!empty($body['linkedResources'])) {
                if (!ResController::hasRightByResId(['resId' => [$body['linkedResources']], 'userId' => $GLOBALS['id']])) {
                    return ['errors' => 'Body linkedResources out of perimeter'];
                }
            }
    
            return true;
        }
    
        protected static function controlUpdateResource(array $args)
        {
            $body = $args['body'];
    
            $resource = ResModel::getById(['resId' => $args['resId'], 'select' => ['status', 'model_id', 'external_signatory_book_id']]);
            if (empty($resource['status'])) {
                return ['errors' => 'Resource status is empty. It can not be modified'];
            }
            $status = StatusModel::getById(['id' => $resource['status'], 'select' => ['can_be_modified']]);
            if ($status['can_be_modified'] != 'Y') {
                return ['errors' => 'Resource can not be modified because of status'];
            }
    
            if (empty($body)) {
                return ['errors' => 'Body is not set or empty'];
            } elseif (!Validator::intVal()->notEmpty()->validate($body['doctype'])) {
                return ['errors' => 'Body doctype is empty or not an integer'];
            } elseif (!empty($body['encodedFile']) && !empty($resource['external_signatory_book_id'])) {
                return ['errors' => 'Resource is in external signature book, file can not be modified'];
            } elseif (!empty($body['encodedFile']) && ResourceControlController::isSigned(['resId' => $args['resId']])) {
                return ['errors' => 'Resource is signed, file can not be modified'];
            }
    
            $doctype = DoctypeModel::getById(['id' => $body['doctype'], 'select' => [1]]);
            if (empty($doctype)) {
                return ['errors' => 'Body doctype does not exist'];
            }
    
            $control = ResourceControlController::controlFileData(['body' => $body]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            $control = ResourceControlController::controlAdjacentData(['body' => $body, 'isWebServiceUser' => false]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            $body['modelId'] = $resource['model_id'];
            $control = ResourceControlController::controlIndexingModelFields(['body' => $body, 'isProcessing' => $args['isProcessing']]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            if (!empty($body['initiator'])) {
                $userEntities = UserModel::getEntitiesByLogin(['login' => $GLOBALS['userId']]);
                $userEntities = array_column($userEntities, 'id');
                if (!in_array($body['initiator'], $userEntities)) {
                    return ['errors' => "Body initiator does not belong to your entities"];
                }
            }
    
            $control = ResourceControlController::controlDestination(['body' => $body]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
            $control = ResourceControlController::controlDates(['body' => $body, 'resId' => $args['resId']]);
            if (!empty($control['errors'])) {
                return ['errors' => $control['errors']];
            }
    
            return true;
        }
    
        private static function isSigned(array $args)
        {
            $signedDocument = AdrModel::getDocuments([
                'select'    => [1],
                'where'     => ['res_id = ?', 'type = ?'],
                'data'      => [$args['resId'], 'SIGN']
            ]);
    
            if (empty($signedDocument)) {
                return false;
            }
    
            return true;
        }
    
        private static function controlFileData(array $args)
        {
            $body = $args['body'];
    
            if (!empty($body['encodedFile'])) {
                if (!Validator::stringType()->notEmpty()->validate($body['format'])) {
                    return ['errors' => 'Body format is empty or not a string'];
                }
    
                $file     = base64_decode($body['encodedFile']);
                $finfo    = new \finfo(FILEINFO_MIME_TYPE);
                $mimeType = $finfo->buffer($file);
                if (!StoreController::isFileAllowed(['extension' => $body['format'], 'type' => $mimeType])) {
                    return ['errors' => "Format with this mimeType is not allowed : {$body['format']} {$mimeType}"];
                }
            }
    
            return true;
        }
    
        private static function controlAdjacentData(array $args)
        {
            $body = $args['body'];
    
            if (!empty($body['customFields'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['customFields'])) {
                    return ['errors' => 'Body customFields is not an array'];
                }
                $customFields = CustomFieldModel::get(['select' => ['count(1)'], 'where' => ['id in (?)'], 'data' => [array_keys($body['customFields'])]]);
                if (count($body['customFields']) != $customFields[0]['count']) {
                    return ['errors' => 'Body customFields : One or more custom fields do not exist'];
                }
            }
            if (!empty($body['folders'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['folders'])) {
                    return ['errors' => 'Body folders is not an array'];
                }
                if (!FolderController::hasFolders(['folders' => $body['folders'], 'userId' => $GLOBALS['id']])) {
                    return ['errors' => 'Body folders : One or more folders do not exist or are out of perimeter'];
                }
            }
            if (!empty($body['tags'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['tags'])) {
                    return ['errors' => 'Body tags is not an array'];
                }
                $tags = TagModel::get(['select' => ['count(1)'], 'where' => ['id in (?)'], 'data' => [$body['tags']]]);
                if (count($body['tags']) != $tags[0]['count']) {
                    return ['errors' => 'Body tags : One or more tags do not exist'];
                }
            }
            if (!empty($body['senders'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['senders'])) {
                    return ['errors' => 'Body senders is not an array'];
                }
                foreach ($body['senders'] as $key => $sender) {
                    if (!Validator::arrayType()->notEmpty()->validate($sender)) {
                        return ['errors' => "Body senders[{$key}] is not an array"];
                    }
                    if ($sender['type'] == 'contact') {
                        $senderItem = ContactModel::getById(['id' => $sender['id'], 'select' => [1]]);
                    } elseif ($sender['type'] == 'user') {
                        $senderItem = UserModel::getById(['id' => $sender['id'], 'select' => [1]]);
                    } elseif ($sender['type'] == 'entity') {
                        $senderItem = EntityModel::getById(['id' => $sender['id'], 'select' => [1]]);
                    } else {
                        return ['errors' => "Body senders[{$key}] type is not valid"];
                    }
                    if (empty($senderItem)) {
                        return ['errors' => "Body senders[{$key}] id does not exist"];
                    }
                }
            }
            if (!empty($body['recipients'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['recipients'])) {
                    return ['errors' => 'Body recipients is not an array'];
                }
                foreach ($body['recipients'] as $key => $recipient) {
                    if (!Validator::arrayType()->notEmpty()->validate($recipient)) {
                        return ['errors' => "Body recipients[{$key}] is not an array"];
                    }
                    if ($recipient['type'] == 'contact') {
                        $recipientItem = ContactModel::getById(['id' => $recipient['id'], 'select' => [1]]);
                    } elseif ($recipient['type'] == 'user') {
                        $recipientItem = UserModel::getById(['id' => $recipient['id'], 'select' => [1]]);
                    } elseif ($recipient['type'] == 'entity') {
                        $recipientItem = EntityModel::getById(['id' => $recipient['id'], 'select' => [1]]);
                    } else {
                        return ['errors' => "Body recipients[{$key}] type is not valid"];
                    }
                    if (empty($recipientItem)) {
                        return ['errors' => "Body recipients[{$key}] id does not exist"];
                    }
                }
            }
            if (!empty($body['diffusionList'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['diffusionList'])) {
                    return ['errors' => 'Body diffusionList is not an array'];
                }
                $destFound = false;
                foreach ($body['diffusionList'] as $key => $diffusion) {
                    if ($diffusion['mode'] == 'dest') {
                        if ($destFound) {
                            return ['errors' => "Body diffusionList has multiple dest"];
                        }
                        $destFound = true;
                    }
                    if ($diffusion['type'] == 'user' || $diffusion['mode'] == 'dest') {
                        $item = UserModel::getById(['id' => $diffusion['id'], 'select' => [1]]);
                    } else {
                        $item = EntityModel::getById(['id' => $diffusion['id'], 'select' => [1]]);
                    }
                    if (empty($item)) {
                        return ['errors' => "Body diffusionList[{$key}] id does not exist"];
                    }
                }
                if (!$destFound) {
                    return ['errors' => 'Body diffusion has no dest'];
                }
            }
            if (!$args['isWebServiceUser'] && !empty($body['destination']) && empty($destFound)) {
                return ['errors' => 'Body diffusion has no dest'];
            }
    
            return true;
        }
    
        private static function controlIndexingModelFields(array $args)
        {
            $body = $args['body'];
    
            $indexingModelFields = IndexingModelFieldModel::get(['select' => ['identifier', 'mandatory'], 'where' => ['model_id = ?'], 'data' => [$body['modelId']]]);
            foreach ($indexingModelFields as $indexingModelField) {
                if (strpos($indexingModelField['identifier'], 'indexingCustomField_') !== false) {
                    $customFieldId = explode('_', $indexingModelField['identifier'])[1];
                    if ($indexingModelField['mandatory'] && empty($body['customFields'][$customFieldId])) {
                        return ['errors' => "Body customFields[{$customFieldId}] is empty"];
                    }
                    if (!empty($body['customFields'][$customFieldId])) {
                        $customField = CustomFieldModel::getById(['id' => $customFieldId, 'select' => ['type', 'values']]);
                        $possibleValues = empty($customField['values']) ? [] : json_decode($customField['values']);
                        if (($customField['type'] == 'select' || $customField['type'] == 'radio') && !in_array($body['customFields'][$customFieldId], $possibleValues)) {
                            return ['errors' => "Body customFields[{$customFieldId}] has wrong value"];
                        } elseif ($customField['type'] == 'checkbox') {
                            if (!is_array($body['customFields'][$customFieldId])) {
                                return ['errors' => "Body customFields[{$customFieldId}] is not an array"];
                            }
                            foreach ($body['customFields'][$customFieldId] as $value) {
                                if (!in_array($value, $possibleValues)) {
                                    return ['errors' => "Body customFields[{$customFieldId}] has wrong value"];
                                }
                            }
                        } elseif ($customField['type'] == 'string' && !Validator::stringType()->notEmpty()->validate($body['customFields'][$customFieldId])) {
                            return ['errors' => "Body customFields[{$customFieldId}] is not a string"];
                        } elseif ($customField['type'] == 'integer' && !Validator::intVal()->notEmpty()->validate($body['customFields'][$customFieldId])) {
                            return ['errors' => "Body customFields[{$customFieldId}] is not an integer"];
                        } elseif ($customField['type'] == 'date' && !Validator::date()->notEmpty()->validate($body['customFields'][$customFieldId])) {
                            return ['errors' => "Body customFields[{$customFieldId}] is not a date"];
                        }
                    }
                } elseif ($indexingModelField['identifier'] == 'destination' && !empty($args['isProcessing'])) {
                    continue;
                } elseif ($indexingModelField['mandatory'] && !isset($body[$indexingModelField['identifier']])) {
                    return ['errors' => "Body {$indexingModelField['identifier']} is not set"];
                }
            }
    
            return true;
        }
    
        private static function controlDates(array $args)
        {
            $body = $args['body'];
    
            if (!empty($body['documentDate'])) {
                if (!Validator::date()->notEmpty()->validate($body['documentDate'])) {
                    return ['errors' => "Body documentDate is not a date"];
                }
    
                $documentDate = new \DateTime($body['documentDate']);
                $tmr = new \DateTime('tomorrow');
                if ($documentDate > $tmr) {
                    return ['errors' => "Body documentDate is not a valid date"];
                }
            }
            if (!empty($body['arrivalDate'])) {
                if (!Validator::date()->notEmpty()->validate($body['arrivalDate'])) {
                    return ['errors' => "Body arrivalDate is not a date"];
                }
    
                $arrivalDate = new \DateTime($body['arrivalDate']);
                $tmr = new \DateTime('tomorrow');
                if ($arrivalDate > $tmr) {
                    return ['errors' => "Body arrivalDate is not a valid date"];
                }
            }
            if (!empty($body['departureDate'])) {
                if (!Validator::date()->notEmpty()->validate($body['departureDate'])) {
                    return ['errors' => "Body departureDate is not a date"];
                }
                $departureDate = new \DateTime($body['departureDate']);
                if (!empty($documentDate) && $departureDate < $documentDate) {
                    return ['errors' => "Body departureDate is not a valid date"];
                }
            }
            if (!empty($body['processLimitDate'])) {
                if (!Validator::date()->notEmpty()->validate($body['processLimitDate'])) {
                    return ['errors' => "Body processLimitDate is not a date"];
                }
    
                if (!empty($args['resId'])) {
                    $resource = ResModel::getById(['resId' => $args['resId'], 'select' => ['process_limit_date']]);
                    if (!empty($resource['process_limit_date'])) {
                        $originProcessLimitDate = new \DateTime($resource['process_limit_date']);
                    }
                }
                $processLimitDate = new \DateTime($body['processLimitDate']);
                if (empty($originProcessLimitDate) || $originProcessLimitDate != $processLimitDate) {
                    $today = new \DateTime();
                    $today->setTime(00, 00, 00);
                    if ($processLimitDate < $today) {
                        return ['errors' => "Body processLimitDate is not a valid date"];
                    }
                }
            } elseif (!empty($body['priority'])) {
                $priority = PriorityModel::getById(['id' => $body['priority'], 'select' => [1]]);
                if (empty($priority)) {
                    return ['errors' => "Body priority does not exist"];
                }
            }
    
            return true;
        }
    
        private static function controlDestination(array $args)
        {
            $body = $args['body'];
    
            if (!empty($body['destination'])) {
                $groups = UserGroupModel::getWithGroups([
                    'select'    => ['usergroups.indexation_parameters'],
                    'where'     => ['usergroup_content.user_id = ?', 'usergroups.can_index = ?'],
                    'data'      => [$GLOBALS['id'], true]
                ]);
    
                $clauseToProcess = '';
                $allowedEntities = [];
                foreach ($groups as $group) {
                    $group['indexation_parameters'] = json_decode($group['indexation_parameters'], true);
                    foreach ($group['indexation_parameters']['keywords'] as $keywordValue) {
                        if (strpos($clauseToProcess, IndexingController::KEYWORDS[$keywordValue]) === false) {
                            if (!empty($clauseToProcess)) {
                                $clauseToProcess .= ', ';
                            }
                            $clauseToProcess .= IndexingController::KEYWORDS[$keywordValue];
                        }
                    }
                    $allowedEntities = array_merge($allowedEntities, $group['indexation_parameters']['entities']);
                    $allowedEntities = array_unique($allowedEntities);
                }
    
                if (!empty($clauseToProcess)) {
                    $preparedClause = PreparedClauseController::getPreparedClause(['clause' => $clauseToProcess, 'login' => $GLOBALS['userId']]);
                    $preparedEntities = EntityModel::get(['select' => ['id'], 'where' => ['enabled = ?', "entity_id in {$preparedClause}"], 'data' => ['Y']]);
                    $preparedEntities = array_column($preparedEntities, 'id');
                    $allowedEntities = array_merge($allowedEntities, $preparedEntities);
                    $allowedEntities = array_unique($allowedEntities);
                }
    
                if (!in_array($body['destination'], $allowedEntities)) {
                    return ['errors' => "Body destination is out of your indexing parameters"];
                }
            }
    
            return true;
        }
    }