Skip to content
Snippets Groups Projects
ResController.php 60.7 KiB
Newer Older
  • Learn to ignore specific revisions
  •     private static function controlFileData(array $args)
    
            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 tags : 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['diffusionList'])) {
                if (!Validator::arrayType()->notEmpty()->validate($body['diffusionList'])) {
    
                    return ['errors' => 'Body diffusionList is not an array'];
    
                foreach ($body['diffusionList'] as $key => $diffusion) {
    
                    if ($diffusion['mode'] == 'dest') {
    
                            return ['errors' => "Body diffusionList has multiple dest"];
    
                    if ($diffusion['type'] == 'user' || $diffusion['mode'] == 'dest') {
    
                        $user = UserModel::getByLogin(['login' => $diffusion['id'], 'select' => [1]]);
    
                            return ['errors' => "Body diffusionList[{$key}] id does not exist"];
    
                        $entity = EntityModel::getByEntityId(['entityId' => $diffusion['id'], 'select' => [1]]);
    
                            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'];
    
        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['mandatory'] && empty($body[$indexingModelField['identifier']])) {
                    return ['errors' => "Body {$indexingModelField['identifier']} is empty"];
    
        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"];
                }
            }
    
    
        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"];
    
    
        public function getList(Request $request, Response $response)
        {
            $data = $request->getParams();
    
            if (!Validator::stringType()->notEmpty()->validate($data['select'])) {
                return $response->withStatus(400)->withJson(['errors' => 'Bad Request: select is not valid']);
            }
            if (!Validator::stringType()->notEmpty()->validate($data['clause'])) {
                return $response->withStatus(400)->withJson(['errors' => 'Bad Request: clause is not valid']);
            }
            if (!empty($data['withFile'])) {
                if (!Validator::boolType()->validate($data['withFile'])) {
                    return $response->withStatus(400)->withJson(['errors' => 'Bad Request: withFile parameter is not a boolean']);
                }
            }
    
            if (!empty($data['orderBy'])) {
                if (!Validator::arrayType()->notEmpty()->validate($data['orderBy'])) {
                    return $response->withStatus(400)->withJson(['errors' => 'Bad Request: orderBy parameter not valid']);
                }
            }
    
            if (!empty($data['limit'])) {
                if (!Validator::intType()->validate($data['limit'])) {
                    return $response->withStatus(400)->withJson(['errors' => 'Bad Request: limit parameter not valid']);
                }
            }
            $select = explode(',', $data['select']);
    
            $sve_start_date = false;
            $keySve = array_search('sve_start_date', array_map('trim', $select));
            if ($keySve !== false) {
                unset($select[$keySve]);
                $sve_start_date = true;
            }
    
            if ($sve_start_date && empty($select)) {
                $select[] = 'res_id';
            }
    
            if (!PreparedClauseController::isRequestValid(['select' => $select, 'clause' => $data['clause'], 'orderBy' => $data['orderBy'], 'limit' => $data['limit'], 'userId' => $GLOBALS['userId']])) {
                return $response->withStatus(400)->withJson(['errors' => _INVALID_REQUEST]);
            }
    
            $where = [$data['clause']];
            if ($GLOBALS['userId'] != 'superadmin') {
                $groupsClause = GroupController::getGroupsClause(['userId' => $GLOBALS['userId']]);
                if (empty($groupsClause)) {
                    return $response->withStatus(400)->withJson(['errors' => 'User has no groups']);
                }
                $where[] = "({$groupsClause})";
            }
    
            if ($data['withFile'] === true) {
                $select[] = 'res_id';
            }
    
            $resources = ResModel::getOnView(['select' => $select, 'where' => $where, 'orderBy' => $data['orderBy'], 'limit' => $data['limit']]);
            if (!empty($resources) && $data['withFile'] === true) {
                foreach ($resources as $key => $res) {
                    $document = ResModel::getById(['resId' => $res['res_id'], 'select' => ['path', 'filename', 'docserver_id']]);
                    $docserver = DocserverModel::getByDocserverId(['docserverId' => $document['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
                    if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) {
                        continue;
                    }
                    $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $document['path']) . $document['filename'];
                    if (!file_exists($pathToDocument)) {
                        continue;
                    }
                    $file = file_get_contents($pathToDocument);
                    $base64Content = base64_encode($file);
                    $resources[$key]['fileBase64Content'] = $base64Content;
                }
            }
            if (!empty($resources) && $sve_start_date) {
                $aResId = [];
                foreach ($resources as $res) {
                    $aResId[] = $res['res_id'];
                }
                $aSveStartDate = AcknowledgementReceiptModel::getByResIds([
                    'select'  => ['res_id', 'min(send_date) as send_date'],
                    'resIds'  => $aResId,
                    'where'   => ['send_date IS NOT NULL', 'send_date != \'\''],
                    'groupBy' => ['res_id']
                ]);
                foreach ($resources as $key => $res) {
                    $resources[$key]['sve_start_date'] = null;
                    foreach ($aSveStartDate as $valueSveStartDate) {
                        if ($res['res_id'] == $valueSveStartDate['res_id']) {
                            $resources[$key]['sve_start_date'] = $valueSveStartDate['send_date'];
                            break;
                        }
                    }
                }
            }
    
            return $response->withJson(['resources' => $resources, 'count' => count($resources)]);
        }