diff --git a/.vscode/settings.json b/.vscode/settings.json index fe76d727..73c4e5f3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -23,4 +23,6 @@ "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, + "javascript.preferences.importModuleSpecifier": "relative", + "javascript.preferences.importModuleSpecifierEnding": "js", } diff --git a/appinfo/routes.php b/appinfo/routes.php index 490b7f5d..051a7621 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -22,10 +22,15 @@ ['name' => 'search#indexInternal', 'url' => '/api/search/internal', 'verb' => 'GET'], ['name' => 'search#show', 'url' => '/api/search/{id}', 'verb' => 'GET'], ['name' => 'search#showInternal', 'url' => '/api/search/internal/{id}', 'verb' => 'GET'], + ['name' => 'search#preflighted_cors', 'url' => '/api/{path}', 'verb' => 'OPTIONS', 'requirements' => ['path' => '.+']], + ['name' => 'themes#index', 'url' => '/search/themes', 'verb' => 'GET'], + ['name' => 'themes#index', 'url' => '/api/search/themes', 'verb' => 'GET'], + ['name' => 'themes#indexInternal', 'url' => '/api/themes', 'verb' => 'GET'], + ['name' => 'themes#show', 'url' => '/api/search/themes/{id}', 'verb' => 'GET'], + ['name' => 'themes#showInternal', 'url' => '/api/themes/{id}', 'verb' => 'GET'], ['name' => 'directory#page', 'url' => '/directory', 'verb' => 'GET'], ['name' => 'directory#synchronise', 'url' => '/api/directory/{id}/sync', 'verb' => 'GET'], ['name' => 'configuration#index', 'url' => '/configuration', 'verb' => 'GET'], - ['name' => 'configuration#create', 'url' => '/configuration', 'verb' => 'POST'], - ['name' => 'search#preflighted_cors', 'url' => '/api/{path}', 'verb' => 'OPTIONS', 'requirements' => ['path' => '.+']] + ['name' => 'configuration#create', 'url' => '/configuration', 'verb' => 'POST'] ], ]; diff --git a/lib/Controller/AttachmentsController.php b/lib/Controller/AttachmentsController.php index c32773da..74327310 100644 --- a/lib/Controller/AttachmentsController.php +++ b/lib/Controller/AttachmentsController.php @@ -35,9 +35,9 @@ public function __construct private function insertNestedObjects(array $object, ObjectService $objectService, array $config): array { - foreach($object as $key => $value) { + foreach ($object as $key => $value) { try { - if( + if ( is_string(value: $value) && $key !== 'id' && Uuid::isValid(uuid: $value) === true @@ -109,8 +109,8 @@ public function index(ObjectService $objectService): JSONResponse $filters = $this->request->getParams(); unset($filters['_route']); - foreach($filters as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($filters as $key => $value) { + if (str_starts_with($key, '_')) { unset($filters[$key]); } } @@ -306,8 +306,8 @@ public function create(ObjectService $objectService, ElasticSearchService $elast // Remove fields we should never post. unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with(haystack: $key, needle: '_')) { + foreach ($data as $key => $value) { + if (str_starts_with(haystack: $key, needle: '_')) { unset($data[$key]); } } @@ -343,8 +343,8 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear // Remove fields we should never post. unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with(haystack: $key, needle: '_')) { + foreach ($data as $key => $value) { + if (str_starts_with(haystack: $key, needle: '_')) { unset($data[$key]); } } diff --git a/lib/Controller/CatalogiController.php b/lib/Controller/CatalogiController.php index 1d2dd062..73753297 100644 --- a/lib/Controller/CatalogiController.php +++ b/lib/Controller/CatalogiController.php @@ -44,7 +44,7 @@ public function index(ObjectService $objectService, SearchService $searchService unset($filters['_route']); $fieldsToSearch = ['title', 'description', 'summary']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -80,7 +80,7 @@ public function index(ObjectService $objectService, SearchService $searchService */ public function show(string|int $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { @@ -124,11 +124,11 @@ public function create(ObjectService $objectService, DirectoryService $directory } // @todo dit is alleen omdat er een onredenlijke verplichting aan de database is toegeveoegd - if(array_key_exists('metadata',$data) === false){ + if (array_key_exists('metadata',$data) === false){ $data['metadata'] = []; } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $result = $this->catalogMapper->createFromArray(object: $data); @@ -177,7 +177,7 @@ public function update(string|int $id, ObjectService $objectService, DirectorySe unset($data['id']); } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $result = $this->catalogMapper->updateFromArray(id: (int) $id, object: $data); @@ -218,7 +218,7 @@ public function destroy(string|int $id, ObjectService $objectService, DirectoryS $directoryService->listCatalog(['id' => $id, 'listed' => false]); - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->catalogMapper->delete($this->catalogMapper->find((int) $id)); diff --git a/lib/Controller/DirectoryController.php b/lib/Controller/DirectoryController.php index 45f29771..234d3d4e 100644 --- a/lib/Controller/DirectoryController.php +++ b/lib/Controller/DirectoryController.php @@ -54,7 +54,7 @@ public function index(ObjectService $objectService, SearchService $searchService unset($filters['_route']); $fieldsToSearch = ['summary']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -85,7 +85,7 @@ public function index(ObjectService $objectService, SearchService $searchService */ public function show(string|int $id, ObjectService $objectService, DirectoryService $directoryService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { @@ -129,14 +129,14 @@ public function update(string|int $id, ObjectService $objectService): JSONRespon // Remove fields we should never post unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($data as $key => $value) { + if (str_starts_with($key, '_')) { unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->listingMapper->updateFromArray(id: (int) $id, object: $data)); @@ -164,7 +164,7 @@ public function update(string|int $id, ObjectService $objectService): JSONRespon */ public function destroy(string|int $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->listingMapper->delete($this->listingMapper->find((int) $id)); @@ -192,7 +192,7 @@ public function destroy(string|int $id, ObjectService $objectService): JSONRespo */ public function synchronise(string|int $id, DirectoryService $directoryService, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { diff --git a/lib/Controller/MetaDataController.php b/lib/Controller/MetaDataController.php index d72812e8..00f262ea 100644 --- a/lib/Controller/MetaDataController.php +++ b/lib/Controller/MetaDataController.php @@ -54,7 +54,7 @@ public function index(ObjectService $objectService, SearchService $searchService unset($filters['_route']); $fieldsToSearch = ['title', 'description']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -86,7 +86,7 @@ public function index(ObjectService $objectService, SearchService $searchService */ public function show(string|int $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { @@ -120,20 +120,20 @@ public function create(ObjectService $objectService, IURLGenerator $urlGenerator unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($data as $key => $value) { + if (str_starts_with($key, '_')) { unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $object = $this->metaDataMapper->createFromArray(object: $data); $id = $object->getId(); - if($object->getSource() === null) { + if ($object->getSource() === null) { $source = $urlGenerator->getAbsoluteURL($urlGenerator->linkToRoute(routeName:"opencatalogi.metadata.show", arguments: ['id' => $id])); $object->setSource($source); $this->metaDataMapper->update($object); @@ -153,10 +153,10 @@ public function create(ObjectService $objectService, IURLGenerator $urlGenerator config: $dbConfig ); - if(isset($data['source']) === false || $data['source'] === null) { + if (isset($data['source']) === false || $data['source'] === null) { $returnData['source'] = $urlGenerator->getAbsoluteURL($urlGenerator->linkToRoute(routeName:"opencatalogi.metadata.show", arguments: ['id' => $returnData['id']])); $returnData = $objectService->saveObject( - data: $data, + data: $returnData, config: $dbConfig ); } @@ -175,13 +175,13 @@ public function update(string|int $id, ObjectService $objectService): JSONRespon // Remove fields we should never post unset($data['id'],$data['source']); - foreach($data as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($data as $key => $value) { + if (str_starts_with($key, '_')) { unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->metaDataMapper->updateFromArray(id: (int) $id, object: $data)); @@ -209,7 +209,7 @@ public function update(string|int $id, ObjectService $objectService): JSONRespon */ public function destroy(string|int $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->metaDataMapper->delete($this->metaDataMapper->find(id: (int) $id)); diff --git a/lib/Controller/OrganisationsController.php b/lib/Controller/OrganisationsController.php index 2fe4bf06..c1fb1722 100644 --- a/lib/Controller/OrganisationsController.php +++ b/lib/Controller/OrganisationsController.php @@ -52,7 +52,7 @@ public function index(ObjectService $objectService, SearchService $searchService unset($filters['_route']); $fieldsToSearch = ['title', 'description', 'summary']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -92,7 +92,7 @@ public function index(ObjectService $objectService, SearchService $searchService */ public function show(string $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { @@ -137,7 +137,7 @@ public function create(ObjectService $objectService): JSONResponse unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->organisationMapper->createFromArray(object: $data)); @@ -150,11 +150,14 @@ public function create(ObjectService $objectService): JSONResponse 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') ]; - $filters['_schema'] = 'organisation'; + $data['_schema'] = 'organisation'; - $result = $objectService->findObjects(filters: $filters, config: $dbConfig); + $returnData = $objectService->saveObject( + data: $data, + config: $dbConfig + ); - return new JSONResponse(["results" => $result['documents']]); + return new JSONResponse($returnData); } catch (\Exception $e) { return new JSONResponse(['error' => $e->getMessage()], 500); } @@ -181,7 +184,7 @@ public function update(string $id, ObjectService $objectService): JSONResponse unset($data['id']); } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->organisationMapper->updateFromArray(id: (int) $id, object: $data)); @@ -213,7 +216,7 @@ public function update(string $id, ObjectService $objectService): JSONResponse */ public function destroy(string $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->organisationMapper->delete($this->organisationMapper->find((int) $id)); diff --git a/lib/Controller/PublicationsController.php b/lib/Controller/PublicationsController.php index 97904af5..3264ef8d 100644 --- a/lib/Controller/PublicationsController.php +++ b/lib/Controller/PublicationsController.php @@ -46,9 +46,9 @@ public function __construct private function insertNestedObjects(array $object, ObjectService $objectService, array $config): array { //@TODO keep in mind that unpublished objects should not be inserted, and that objects should be updated if a subobject is updated. - foreach($object as $key => $value) { + foreach ($object as $key => $value) { try { - if( + if ( is_string(value: $value) && $key !== 'id' && Uuid::isValid(uuid: $value) === true @@ -57,7 +57,7 @@ private function insertNestedObjects(array $object, ObjectService $objectService $object[$key] = $subObject; } - if( + if ( is_array(value: $value) === true && array_is_list(array: $value) === true ) { @@ -118,7 +118,7 @@ public function index(ObjectService $objectService, SearchService $searchService unset($filters['_route']); $fieldsToSearch = ['p.title', 'p.description', 'p.summary']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -469,8 +469,8 @@ public function create(ObjectService $objectService, ElasticSearchService $elast // Remove fields we should never post unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($data as $key => $value) { + if (str_starts_with($key, '_')) { unset($data[$key]); } } @@ -481,7 +481,7 @@ public function create(ObjectService $objectService, ElasticSearchService $elast return new JSONResponse(data: ['message' => $exception->getMessage()], statusCode: 400); } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $returnData = $this->publicationMapper->createFromArray($data); @@ -498,7 +498,7 @@ public function create(ObjectService $objectService, ElasticSearchService $elast config: $dbConfig ); } - if( + if ( $this->config->hasKey(app: $this->appName, key: 'elasticLocation') === true && $this->config->getValueString(app: $this->appName, key: 'elasticLocation') !== '' && $this->config->hasKey(app: $this->appName, key: 'elasticKey') === true @@ -532,13 +532,13 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear // Remove fields we should never post unset($data['id']); - foreach($data as $key => $value) { - if(str_starts_with($key, '_')) { + foreach ($data as $key => $value) { + if (str_starts_with($key, '_')) { unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $returnData = $this->publicationMapper->updateFromArray(id: (int) $id, object: $data); @@ -558,7 +558,7 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear ); } - if( + if ( $this->config->hasKey(app: $this->appName, key: 'elasticLocation') === true && $this->config->getValueString(app: $this->appName, key: 'elasticLocation') !== '' && $this->config->hasKey(app: $this->appName, key: 'elasticKey') === true @@ -587,7 +587,7 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear */ public function destroy(string|int $id, ObjectService $objectService, ElasticSearchService $elasticSearchService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->publicationMapper->delete($this->publicationMapper->find(id: (int) $id)); @@ -605,7 +605,7 @@ public function destroy(string|int $id, ObjectService $objectService, ElasticSea ); } - if( + if ( $this->config->hasKey(app: $this->appName, key: 'elasticLocation') === true && $this->config->getValueString(app: $this->appName, key: 'elasticLocation') !== '' && $this->config->hasKey(app: $this->appName, key: 'elasticKey') === true diff --git a/lib/Controller/SearchController.php b/lib/Controller/SearchController.php index 9da7418a..6341bfce 100644 --- a/lib/Controller/SearchController.php +++ b/lib/Controller/SearchController.php @@ -2,6 +2,7 @@ namespace OCA\OpenCatalogi\Controller; +use GuzzleHttp\Exception\GuzzleException; use OCA\OpenCatalogi\Service\ElasticSearchService; use OCA\OpenCatalogi\Db\PublicationMapper; use OCA\OpenCatalogi\Service\SearchService; @@ -79,13 +80,15 @@ public function page(?string $getParameter) ); } - /** - * @CORS - * @PublicPage - * @NoCSRFRequired - */ - public function index(SearchService $searchService): JSONResponse - { + /** + * The Index function. + * + * @param SearchService $searchService The Search Service. + * + * @return JSONResponse The Response. + */ + private function searchIndex(SearchService $searchService): JSONResponse + { $elasticConfig['location'] = $this->config->getValueString(app: $this->appName, key: 'elasticLocation'); $elasticConfig['key'] = $this->config->getValueString(app: $this->appName, key: 'elasticKey'); $elasticConfig['index'] = $this->config->getValueString(app: $this->appName, key: 'elasticIndex'); @@ -97,12 +100,12 @@ public function index(SearchService $searchService): JSONResponse $filters = $this->request->getParams(); unset($filters['_route']); - // Status must be always published when searching for publications - $filters['status'] = 'published'; + // Status must be always published when searching for publications + $filters['status'] = 'published'; - $fieldsToSearch = ['p.title', 'p.description', 'p.summary']; + $fieldsToSearch = ['p.title', 'p.description', 'p.summary']; - if($this->config->hasKey($this->appName, 'elasticLocation') === false + if ($this->config->hasKey($this->appName, 'elasticLocation') === false || $this->config->getValueString($this->appName, 'elasticLocation') === '' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -112,12 +115,12 @@ public function index(SearchService $searchService): JSONResponse $offset = 0; $page = 0; - if(isset($filters['_limit']) === true) { - $limit = $filters['_limit']; + if (isset($filters['_limit']) === true) { + $limit = (int) $filters['_limit']; } if (isset($filters['_page']) === true) { - $page = $filters['_page']; + $page = (int) $filters['_page']; $offset = ($limit * ($filters['_page'] - 1)); } @@ -150,90 +153,6 @@ public function index(SearchService $searchService): JSONResponse $filters = array_combine(keys: $keys, values: $values); - $requiredElasticConfig = ['location', 'key', 'index']; - $missingFields = null; - foreach ($requiredElasticConfig as $key) { - if (isset($elasticConfig[$key]) === false || empty($elasticConfig[$key])) { - $missingFields .= "$key, "; - } - } - - if ($missingFields !== null) { - $errorMessage = "Missing the following elastic configuration: {$missingFields}please update your elastic connection in application settings."; - $response = new JSONResponse(data: ['code' => 403, 'message' => $errorMessage], statusCode: 403); - - return $response; - } - - $data = $searchService->search(parameters: $filters, elasticConfig: $elasticConfig, dbConfig: $dbConfig); - - return new JSONResponse($data); - } - - /** - * @PublicPage - * @NoCSRFRequired - */ - public function indexInternal(SearchService $searchService): JSONResponse - { - $elasticConfig['location'] = $this->config->getValueString(app: $this->appName, key: 'elasticLocation'); - $elasticConfig['key'] = $this->config->getValueString(app: $this->appName, key: 'elasticKey'); - $elasticConfig['index'] = $this->config->getValueString(app: $this->appName, key: 'elasticIndex'); - - $dbConfig['base_uri'] = $this->config->getValueString(app: $this->appName, key: 'mongodbLocation'); - $dbConfig['headers']['api-key'] = $this->config->getValueString(app: $this->appName, key: 'mongodbKey'); - $dbConfig['mongodbCluster'] = $this->config->getValueString(app: $this->appName, key: 'mongodbCluster'); - - $filters = $this->request->getParams(); - unset($filters['_route']); - - // Status must be always published when searching for publications - $filters['status'] = 'published'; - - $fieldsToSearch = ['p.title', 'p.description', 'p.summary']; - - if($this->config->hasKey($this->appName, 'elasticLocation') === false - || $this->config->getValueString($this->appName, 'elasticLocation') === '' - ) { - $searchParams = $searchService->createMySQLSearchParams(filters: $filters); - $searchConditions = $searchService->createMySQLSearchConditions(filters: $filters, fieldsToSearch: $fieldsToSearch, searchParams: $searchParams); - - $limit = 30; - $offset = 0; - - if(isset($filters['_limit']) === true) { - $limit = $filters['_limit']; - } - - if(isset($filters['_page']) === true) { - $offset = ($limit * ($filters['_page'] - 1)); - } - - $filters = $searchService->unsetSpecialQueryParams(filters: $filters); - - $total = $this->publicationMapper->count($filters); - $results = $this->publicationMapper->findAll(limit: $limit, offset: $offset, filters: $filters, searchConditions: $searchConditions, searchParams: $searchParams); - $pages = (int) ceil($total / $limit); - - return new JSONResponse([ - 'results' => $results, - 'facets' => [], - 'count' => count($results), - 'limit' => $limit, - 'page' => isset($filters['_page']) === true ? $filters['_page'] : 1, - 'pages' => $pages === 0 ? 1 : $pages, - 'total' => $total - ]); - } - - //@TODO: find a better way to get query params. This fixes it for now. - $keys = array_keys(array: $filters); - $values = array_values(array: $filters); - - $keys = str_replace('_', '.', $keys); - - $filters = array_combine(keys: $keys, values: $values); - $requiredElasticConfig = ['location', 'key', 'index']; $missingFields = null; foreach ($requiredElasticConfig as $key) { @@ -255,19 +174,43 @@ public function indexInternal(SearchService $searchService): JSONResponse } + /** + * @CORS + * @PublicPage + * @NoCSRFRequired + */ + public function index(SearchService $searchService): JSONResponse + { + return $this->searchIndex(searchService: $searchService); + } /** - * @CORS * @PublicPage * @NoCSRFRequired */ - public function show(string|int $id, SearchService $searchService, ObjectService $objectService): JSONResponse + public function indexInternal(SearchService $searchService): JSONResponse + { + return $this->searchIndex(searchService: $searchService); + } + + + /** + * The Show function. + * + * @param string|int $id The id. + * @param SearchService $searchService The Search Service. + * @param ObjectService $objectService The Object Service. + * + * @return JSONResponse The response. + * @throws GuzzleException + */ + private function searchShow(string|int $id, SearchService $searchService, ObjectService $objectService): JSONResponse { $elasticConfig['location'] = $this->config->getValueString(app: $this->appName, key: 'elasticLocation'); $elasticConfig['key'] = $this->config->getValueString(app: $this->appName, key: 'elasticKey'); $elasticConfig['index'] = $this->config->getValueString(app: $this->appName, key: 'elasticIndex'); - if($this->config->hasKey($this->appName, 'elasticLocation') === false + if ($this->config->hasKey($this->appName, 'elasticLocation') === false || $this->config->getValueString($this->appName, 'elasticLocation') === '' ) { if ($this->config->hasKey($this->appName, 'mongoStorage') === false @@ -276,7 +219,7 @@ public function show(string|int $id, SearchService $searchService, ObjectService try { $object = $this->publicationMapper->find(id: (int) $id); - if($object->getStatus() === 'published') { + if ($object->getStatus() === 'published') { return new JSONResponse($object->jsonSerialize()); } throw new DoesNotExistException('object not published'); @@ -317,14 +260,22 @@ public function show(string|int $id, SearchService $searchService, ObjectService $data = $searchService->search(parameters: $filters, elasticConfig: $elasticConfig, dbConfig: $dbConfig); - if(count($data['results']) > 0) { + if (count($data['results']) > 0) { return new JSONResponse($data['results'][0]); } return new JSONResponse(data: ['error' => ['code' => 404, 'message' => 'the requested resource could not be found']], statusCode: 404); } - + /** + * @CORS + * @PublicPage + * @NoCSRFRequired + */ + public function show(string|int $id, SearchService $searchService, ObjectService $objectService): JSONResponse + { + return $this->searchShow(id: $id, searchService: $searchService, objectService: $objectService); + } /** * @PublicPage @@ -332,65 +283,7 @@ public function show(string|int $id, SearchService $searchService, ObjectService */ public function showInternal(string|int $id, SearchService $searchService, ObjectService $objectService): JSONResponse { - $elasticConfig['location'] = $this->config->getValueString(app: $this->appName, key: 'elasticLocation'); - $elasticConfig['key'] = $this->config->getValueString(app: $this->appName, key: 'elasticKey'); - $elasticConfig['index'] = $this->config->getValueString(app: $this->appName, key: 'elasticIndex'); - - if($this->config->hasKey($this->appName, 'elasticLocation') === false - || $this->config->getValueString($this->appName, 'elasticLocation') === '' - ) { - if ($this->config->hasKey($this->appName, 'mongoStorage') === false - || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' - ) { - try { - $object = $this->publicationMapper->find(id: (int) $id); - - if($object->getStatus() === 'published') { - return new JSONResponse($object->jsonSerialize()); - } - throw new DoesNotExistException('object not published'); - } catch (DoesNotExistException $exception) { - return new JSONResponse(data: ['error' => 'Not Found'], statusCode: 404); - } - } - - $dbConfig['base_uri'] = $this->config->getValueString(app: $this->appName, key: 'mongodbLocation'); - $dbConfig['headers']['api-key'] = $this->config->getValueString(app: $this->appName, key: 'mongodbKey'); - $dbConfig['mongodbCluster'] = $this->config->getValueString(app: $this->appName, key: 'mongodbCluster'); - - $filters['_id'] = (string) $id; - - $result = $objectService->findObject(filters: $filters, config: $dbConfig); - - return new JSONResponse($result); - } - - $dbConfig['base_uri'] = $this->config->getValueString(app: $this->appName, key: 'mongodbLocation'); - $dbConfig['headers']['api-key'] = $this->config->getValueString(app: $this->appName, key: 'mongodbKey'); - $dbConfig['mongodbCluster'] = $this->config->getValueString(app: $this->appName, key: 'mongodbCluster'); - - $filters = ['_id' => (string) $id]; - - $requiredElasticConfig = ['location', 'key', 'index']; - $missingFields = null; - foreach ($requiredElasticConfig as $key) { - if (isset($elasticConfig[$key]) === false) { - $missingFields .= "$key "; - } - } - - if ($missingFields !== null) { - $errorMessage = "Missing the following elastic configuration: {$missingFields}please update your elastic connection in application settings."; - return new JSONResponse(['message' => $errorMessage], 403); - } - - $data = $searchService->search(parameters: $filters, elasticConfig: $elasticConfig, dbConfig: $dbConfig); - - if(count($data['results']) > 0) { - return new JSONResponse($data['results'][0]); - } - - return new JSONResponse(data: ['error' => ['code' => 404, 'message' => 'the requested resource could not be found']], statusCode: 404); + return $this->searchShow(id: $id, searchService: $searchService, objectService: $objectService); } } diff --git a/lib/Controller/ThemesController.php b/lib/Controller/ThemesController.php index 9d98d37a..160b64ef 100644 --- a/lib/Controller/ThemesController.php +++ b/lib/Controller/ThemesController.php @@ -2,6 +2,7 @@ namespace OCA\OpenCatalogi\Controller; +use GuzzleHttp\Exception\GuzzleException; use OCA\OpenCatalogi\Db\ThemeMapper; use OCA\OpenCatalogi\Service\ObjectService; use OCA\OpenCatalogi\Service\SearchService; @@ -40,20 +41,21 @@ public function page(): TemplateResponse } /** - * Return (and serach) all objects + * The Index function. * - * @NoAdminRequired - * @NoCSRFRequired + * @param ObjectService $objectService The Object service. + * @param SearchService $searchService The Search service. * - * @return JSONResponse + * @return JSONResponse The Response. + * @throws GuzzleException */ - public function index(ObjectService $objectService, SearchService $searchService): JSONResponse + private function themesIndex(ObjectService $objectService, SearchService $searchService): JSONResponse { - $filters = $this->request->getParams(); + $filters = $this->request->getParams(); unset($filters['_route']); - $fieldsToSearch = ['title', 'description', 'summary']; + $fieldsToSearch = ['title', 'description', 'summary']; - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $searchParams = $searchService->createMySQLSearchParams(filters: $filters); @@ -66,34 +68,72 @@ public function index(ObjectService $objectService, SearchService $searchService $filters = $searchService->createMongoDBSearchFilter(filters: $filters, fieldsToSearch: $fieldsToSearch); $filters = $searchService->unsetSpecialQueryParams(filters: $filters); - try { - $dbConfig = [ - 'base_uri' => $this->config->getValueString($this->appName, 'mongodbLocation'), - 'headers' => ['api-key' => $this->config->getValueString($this->appName, 'mongodbKey')], - 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') - ]; + try { + $dbConfig = [ + 'base_uri' => $this->config->getValueString($this->appName, 'mongodbLocation'), + 'headers' => ['api-key' => $this->config->getValueString($this->appName, 'mongodbKey')], + 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') + ]; - $filters['_schema'] = 'theme'; + $filters['_schema'] = 'theme'; - $result = $objectService->findObjects(filters: $filters, config: $dbConfig); + $result = $objectService->findObjects(filters: $filters, config: $dbConfig); - return new JSONResponse(["results" => $result['documents']]); - } catch (\Exception $e) { - return new JSONResponse(['error' => $e->getMessage()], 500); - } + return new JSONResponse(["results" => $result['documents']]); + } catch (\Exception $e) { + return new JSONResponse(['error' => $e->getMessage()], 500); + } } /** - * Read a single object + * Return (and serach) all objects * + * @CORS + * @PublicPage * @NoAdminRequired * @NoCSRFRequired * - * @return JSONResponse + * @param ObjectService $objectService The Object service. + * @param SearchService $searchService The Search service. + * + * @return JSONResponse The Response. + * @throws GuzzleException */ - public function show(string $id, ObjectService $objectService): JSONResponse + public function index(ObjectService $objectService, SearchService $searchService): JSONResponse + { + return $this->themesIndex($objectService, $searchService); + } + + /** + * Return (and serach) all objects + * + * @PublicPage + * @NoAdminRequired + * @NoCSRFRequired + * + * @param ObjectService $objectService The Object service. + * @param SearchService $searchService The Search service. + * + * @return JSONResponse The Response. + * @throws GuzzleException + */ + public function indexInternal(ObjectService $objectService, SearchService $searchService): JSONResponse + { + return $this->themesIndex($objectService, $searchService); + } + + /** + * The Show function. + * + * @param string $id The id. + * @param ObjectService $objectService The Object Service. + * + * @return JSONResponse The response. + * @throws GuzzleException + */ + private function themesShow(string $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { try { @@ -103,26 +143,63 @@ public function show(string $id, ObjectService $objectService): JSONResponse } } - try { - $dbConfig = [ - 'base_uri' => $this->config->getValueString($this->appName, 'mongodbLocation'), - 'headers' => ['api-key' => $this->config->getValueString($this->appName, 'mongodbKey')], - 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') - ]; + try { + $dbConfig = [ + 'base_uri' => $this->config->getValueString($this->appName, 'mongodbLocation'), + 'headers' => ['api-key' => $this->config->getValueString($this->appName, 'mongodbKey')], + 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') + ]; - $filters['_id'] = (string) $id; + $filters['_id'] = (string) $id; - $result = $objectService->findObject($filters, $dbConfig); + $result = $objectService->findObject($filters, $dbConfig); - return new JSONResponse($result); - } catch (\Exception $e) { - return new JSONResponse(['error' => $e->getMessage()], 500); - } + return new JSONResponse($result); + } catch (\Exception $e) { + return new JSONResponse(['error' => $e->getMessage()], 500); + } + } + + /** + * Read a single object + * + * @CORS + * @PublicPage + * @NoAdminRequired + * @NoCSRFRequired + * + * @param string $id The id. + * @param ObjectService $objectService The Object Service. + * + * @return JSONResponse The response. + * @throws GuzzleException + */ + public function show(string $id, ObjectService $objectService): JSONResponse + { + return $this->themesShow($id, $objectService); + } + + /** + * Read a single object + * + * @PublicPage + * @NoAdminRequired + * @NoCSRFRequired + * + * @param string $id The id. + * @param ObjectService $objectService The Object Service. + * + * @return JSONResponse The response. + * @throws GuzzleException + */ + public function showInternal(string $id, ObjectService $objectService): JSONResponse + { + return $this->themesShow($id, $objectService); } /** - * Creatue an object + * Create an object * * @NoAdminRequired * @NoCSRFRequired @@ -139,7 +216,7 @@ public function create(ObjectService $objectService): JSONResponse unset($data[$key]); } } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->themeMapper->createFromArray(object: $data)); @@ -152,11 +229,14 @@ public function create(ObjectService $objectService): JSONResponse 'mongodbCluster' => $this->config->getValueString($this->appName, 'mongodbCluster') ]; - $filters['_schema'] = 'organisation'; + $data['_schema'] = 'theme'; - $result = $objectService->findObjects(filters: $filters, config: $dbConfig); + $returnData = $objectService->saveObject( + data: $data, + config: $dbConfig + ); - return new JSONResponse(["results" => $result['documents']]); + return new JSONResponse($returnData); } catch (\Exception $e) { return new JSONResponse(['error' => $e->getMessage()], 500); } @@ -183,7 +263,7 @@ public function update(string $id, ObjectService $objectService): JSONResponse unset($data['id']); } - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { return new JSONResponse($this->themeMapper->updateFromArray(id: (int) $id, object: $data)); @@ -215,7 +295,7 @@ public function update(string $id, ObjectService $objectService): JSONResponse */ public function destroy(string $id, ObjectService $objectService): JSONResponse { - if($this->config->hasKey($this->appName, 'mongoStorage') === false + if ($this->config->hasKey($this->appName, 'mongoStorage') === false || $this->config->getValueString($this->appName, 'mongoStorage') !== '1' ) { $this->themeMapper->delete($this->themeMapper->find((int) $id)); diff --git a/lib/Cron/DirectorySync.php b/lib/Cron/DirectorySync.php index 3a2d0946..cb85f20f 100644 --- a/lib/Cron/DirectorySync.php +++ b/lib/Cron/DirectorySync.php @@ -7,7 +7,7 @@ use OCP\AppFramework\Utility\ITimeFactory; /** - * + * * Docs: https://docs.nextcloud.com/server/latest/developer_manual/basics/backgroundjobs.html */ class DirectorySync extends TimedJob { @@ -28,6 +28,6 @@ public function __construct(ITimeFactory $time, DirectoryService $directoryServi protected function run($arguments) { $this->directoryService->doCronSync(); } - -} \ No newline at end of file + +} diff --git a/lib/Db/Attachment.php b/lib/Db/Attachment.php index c23e40fe..09a1041c 100644 --- a/lib/Db/Attachment.php +++ b/lib/Db/Attachment.php @@ -61,7 +61,7 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } diff --git a/lib/Db/Catalog.php b/lib/Db/Catalog.php index 938e5122..5697f25f 100644 --- a/lib/Db/Catalog.php +++ b/lib/Db/Catalog.php @@ -44,7 +44,7 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = []; } diff --git a/lib/Db/CatalogMapper.php b/lib/Db/CatalogMapper.php index 71284aee..b4a3e2fc 100644 --- a/lib/Db/CatalogMapper.php +++ b/lib/Db/CatalogMapper.php @@ -37,7 +37,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters ->setMaxResults($limit) ->setFirstResult($offset); - foreach($filters as $filter => $value) { + foreach ($filters as $filter => $value) { if ($value === 'IS NOT NULL') { $qb->andWhere($qb->expr()->isNotNull($filter)); } elseif ($value === 'IS NULL') { diff --git a/lib/Db/Listing.php b/lib/Db/Listing.php index 3bc89066..5417c21a 100644 --- a/lib/Db/Listing.php +++ b/lib/Db/Listing.php @@ -52,11 +52,11 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - if(isset($object['metadata']) === false) { + if (isset($object['metadata']) === false) { $object['metadata'] = []; } - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } diff --git a/lib/Db/MetaData.php b/lib/Db/MetaData.php index d1e0c508..8135bb23 100644 --- a/lib/Db/MetaData.php +++ b/lib/Db/MetaData.php @@ -42,7 +42,7 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } @@ -69,7 +69,7 @@ public function jsonSerialize(): array } switch ($property['format']) { case 'string': - // For now array as string + // For now array as string case 'array': $properties[$key]['default'] = (string) $property; break; diff --git a/lib/Db/MetaDataMapper.php b/lib/Db/MetaDataMapper.php index 3bce0ac4..50ee05a0 100644 --- a/lib/Db/MetaDataMapper.php +++ b/lib/Db/MetaDataMapper.php @@ -37,7 +37,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters ->setMaxResults($limit) ->setFirstResult($offset); - foreach($filters as $filter => $value) { + foreach ($filters as $filter => $value) { if ($value === 'IS NOT NULL') { $qb->andWhere($qb->expr()->isNotNull($filter)); } elseif ($value === 'IS NULL') { diff --git a/lib/Db/Organisation.php b/lib/Db/Organisation.php index fd168a89..67e8f3c1 100644 --- a/lib/Db/Organisation.php +++ b/lib/Db/Organisation.php @@ -43,7 +43,7 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } diff --git a/lib/Db/OrganisationMapper.php b/lib/Db/OrganisationMapper.php index 0701e61c..33ec35b0 100644 --- a/lib/Db/OrganisationMapper.php +++ b/lib/Db/OrganisationMapper.php @@ -37,7 +37,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters ->setMaxResults($limit) ->setFirstResult($offset); - foreach($filters as $filter => $value) { + foreach ($filters as $filter => $value) { if ($value === 'IS NOT NULL') { $qb->andWhere($qb->expr()->isNotNull($filter)); } elseif ($value === 'IS NULL') { diff --git a/lib/Db/Publication.php b/lib/Db/Publication.php index 8813884b..631d9414 100644 --- a/lib/Db/Publication.php +++ b/lib/Db/Publication.php @@ -87,7 +87,7 @@ public function hydrate(array $object): self $object['schema'] = $object['metaData'] ?? $this->getMetaData(); } - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } @@ -102,7 +102,7 @@ public function hydrate(array $object): self } $this->setAttachmentCount('0'); - if($this->attachments !== null) { + if ($this->attachments !== null) { $this->setAttachmentCount(count($this->getAttachments())); } diff --git a/lib/Db/PublicationMapper.php b/lib/Db/PublicationMapper.php index d2ff7624..79cc0831 100644 --- a/lib/Db/PublicationMapper.php +++ b/lib/Db/PublicationMapper.php @@ -116,7 +116,7 @@ protected function findEntitiesCustom(IQueryBuilder $query): array { private function parseComplexFilter(IQueryBuilder $queryBuilder, array $filter, string $name): IQueryBuilder { - foreach($filter as $key => $value) { + foreach ($filter as $key => $value) { switch($key) { case '>=': case 'after': @@ -144,8 +144,8 @@ private function parseComplexFilter(IQueryBuilder $queryBuilder, array $filter, private function addFilters(IQueryBuilder $queryBuilder, array $filters): IQueryBuilder { - foreach($filters as $key => $filter) { - if(is_array($filter) === false) { + foreach ($filters as $key => $filter) { + if (is_array($filter) === false) { $queryBuilder->andWhere($queryBuilder->expr()->eq($key, $queryBuilder->createNamedParameter($filter))); $queryBuilder->setParameter($key, $filter); continue; @@ -212,7 +212,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters foreach ($searchConditions as $condition) { $qb->andWhere($condition); } - + // Bind all parameters at once using setParameters() $paramBindings = []; foreach ($searchParams as $param => $value) { @@ -224,7 +224,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters $paramBindings[$param] = $value; } } - + // Use setParameters to bind all at once foreach ($paramBindings as $param => $binding) { if (is_array($binding) === true) { diff --git a/lib/Db/Theme.php b/lib/Db/Theme.php index a8365809..14942b34 100644 --- a/lib/Db/Theme.php +++ b/lib/Db/Theme.php @@ -35,7 +35,7 @@ public function hydrate(array $object): self { $jsonFields = $this->getJsonFields(); - foreach($object as $key => $value) { + foreach ($object as $key => $value) { if (in_array($key, $jsonFields) === true && $value === []) { $value = null; } diff --git a/lib/Db/ThemeMapper.php b/lib/Db/ThemeMapper.php index 561b30d4..e65d4fa0 100644 --- a/lib/Db/ThemeMapper.php +++ b/lib/Db/ThemeMapper.php @@ -37,7 +37,7 @@ public function findAll(?int $limit = null, ?int $offset = null, ?array $filters ->setMaxResults($limit) ->setFirstResult($offset); - foreach($filters as $filter => $value) { + foreach ($filters as $filter => $value) { if ($value === 'IS NOT NULL') { $qb->andWhere($qb->expr()->isNotNull($filter)); } elseif ($value === 'IS NULL') { diff --git a/lib/Flow/Operations/AutomatedPublishing.php b/lib/Flow/Operations/AutomatedPublishing.php index 0cc3d10c..3e186027 100644 --- a/lib/Flow/Operations/AutomatedPublishing.php +++ b/lib/Flow/Operations/AutomatedPublishing.php @@ -24,15 +24,15 @@ public function validateOperation(): bool { /** * Determens for what kind of users the opertation is available - * + * * var $scope is presented from the IManager as a constant with 0 for ADMIN and 1 for USER */ public function isAvailableForScope(int $scope): bool { - if(scope === 0){ + if (scope === 0){ return false; } return false; } -} \ No newline at end of file +} diff --git a/lib/Migration/Version6Date20240723125106.php b/lib/Migration/Version6Date20240723125106.php index b04a1818..4b39b1c2 100644 --- a/lib/Migration/Version6Date20240723125106.php +++ b/lib/Migration/Version6Date20240723125106.php @@ -40,7 +40,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === false) { + if ($schema->hasTable(tableName: 'publications') === false) { $table = $schema->createTable(tableName: 'publications'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, diff --git a/lib/Migration/Version6Date20240724084920.php b/lib/Migration/Version6Date20240724084920.php index 193a230c..7cca7301 100644 --- a/lib/Migration/Version6Date20240724084920.php +++ b/lib/Migration/Version6Date20240724084920.php @@ -40,7 +40,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'catalogi') === false) { + if ($schema->hasTable(tableName: 'catalogi') === false) { $table = $schema->createTable(tableName: 'catalogi'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, diff --git a/lib/Migration/Version6Date20240725114845.php b/lib/Migration/Version6Date20240725114845.php index b4fcc63b..e451bb70 100644 --- a/lib/Migration/Version6Date20240725114845.php +++ b/lib/Migration/Version6Date20240725114845.php @@ -40,7 +40,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'metadata') === false) { + if ($schema->hasTable(tableName: 'metadata') === false) { $table = $schema->createTable(tableName: 'metadata'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, @@ -70,7 +70,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt } - if($schema->hasTable(tableName: 'listings') === false) { + if ($schema->hasTable(tableName: 'listings') === false) { $table = $schema->createTable(tableName: 'listings'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, @@ -120,7 +120,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt } - if($schema->hasTable(tableName: 'organizations') === false) { + if ($schema->hasTable(tableName: 'organizations') === false) { $table = $schema->createTable(tableName: 'organizations'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, @@ -159,7 +159,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt } - if($schema->hasTable(tableName: 'attachments') === false) { + if ($schema->hasTable(tableName: 'attachments') === false) { $table = $schema->createTable(tableName: 'attachments'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ 'autoincrement' => true, diff --git a/lib/Migration/Version6Date20240726122212.php b/lib/Migration/Version6Date20240726122212.php index 604b4962..a047ecf0 100644 --- a/lib/Migration/Version6Date20240726122212.php +++ b/lib/Migration/Version6Date20240726122212.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'catalogi') === true) { + if ($schema->hasTable(tableName: 'catalogi') === true) { $table = $schema->getTable(tableName: 'catalogi'); - if($table->hasColumn(name: 'reference')) { + if ($table->hasColumn(name: 'reference')) { $table->dropColumn(name: 'reference'); } diff --git a/lib/Migration/Version6Date20240726132348.php b/lib/Migration/Version6Date20240726132348.php index 13dc10ca..0d0230f3 100644 --- a/lib/Migration/Version6Date20240726132348.php +++ b/lib/Migration/Version6Date20240726132348.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === true) { + if ($schema->hasTable(tableName: 'publications') === true) { $table = $schema->getTable(tableName: 'publications'); - if($table->hasColumn(name: 'published') === false) { + if ($table->hasColumn(name: 'published') === false) { $table->addColumn(name: 'published', typeName: Types::DATETIME); } diff --git a/lib/Migration/Version6Date20240726140008.php b/lib/Migration/Version6Date20240726140008.php index 829e84fe..89f37a7a 100644 --- a/lib/Migration/Version6Date20240726140008.php +++ b/lib/Migration/Version6Date20240726140008.php @@ -39,10 +39,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === true) { + if ($schema->hasTable(tableName: 'publications') === true) { $table = $schema->getTable(tableName: 'publications'); - if($table->hasColumn(name: 'publicationDate')) { + if ($table->hasColumn(name: 'publicationDate')) { $table->dropColumn(name: 'publicationDate'); } diff --git a/lib/Migration/Version6Date20240726140328.php b/lib/Migration/Version6Date20240726140328.php index b2ed8e9f..3b0ea79f 100644 --- a/lib/Migration/Version6Date20240726140328.php +++ b/lib/Migration/Version6Date20240726140328.php @@ -39,10 +39,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === true) { + if ($schema->hasTable(tableName: 'publications') === true) { $table = $schema->getTable(tableName: 'publications'); - if($table->hasColumn(name: 'publication_date')) { + if ($table->hasColumn(name: 'publication_date')) { $table->dropColumn(name: 'publication_date'); } diff --git a/lib/Migration/Version6Date20240731141731.php b/lib/Migration/Version6Date20240731141731.php index b89799e8..3a02db4d 100644 --- a/lib/Migration/Version6Date20240731141731.php +++ b/lib/Migration/Version6Date20240731141731.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'listings') === true) { + if ($schema->hasTable(tableName: 'listings') === true) { $table = $schema->getTable(tableName: 'listings'); - if($table->hasColumn(name: 'catalog_id') === false) { + if ($table->hasColumn(name: 'catalog_id') === false) { $table->addColumn(name: 'catalog_id', typeName: Types::STRING); } } diff --git a/lib/Migration/Version6Date20240806073229.php b/lib/Migration/Version6Date20240806073229.php index 93cf243e..66cad10a 100644 --- a/lib/Migration/Version6Date20240806073229.php +++ b/lib/Migration/Version6Date20240806073229.php @@ -43,7 +43,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt /** * Let build the themas tabsle */ - if($schema->hasTable(tableName: 'themas') === false) { + if ($schema->hasTable(tableName: 'themas') === false) { $table = $schema->createTable(tableName: 'themas'); $table->addColumn(name: 'id', typeName: Types::BIGINT, options: [ @@ -67,7 +67,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt 'notnull' => false, ]); - + $table->setPrimaryKey(columnNames: ['id']); } diff --git a/lib/Migration/Version6Date20240806114939.php b/lib/Migration/Version6Date20240806114939.php index 98a279f3..cba457dd 100644 --- a/lib/Migration/Version6Date20240806114939.php +++ b/lib/Migration/Version6Date20240806114939.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'catalogi') === true) { + if ($schema->hasTable(tableName: 'catalogi') === true) { $table = $schema->getTable(tableName: 'catalogi'); - if($table->hasColumn(name: 'listed') === false) { + if ($table->hasColumn(name: 'listed') === false) { $table->addColumn(name: 'listed', typeName: Types::BOOLEAN, options: ['notNull' => false, 'default' => false]); } diff --git a/lib/Migration/Version6Date20240808085441.php b/lib/Migration/Version6Date20240808085441.php index c1a2bea2..382dd55d 100644 --- a/lib/Migration/Version6Date20240808085441.php +++ b/lib/Migration/Version6Date20240808085441.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'catalogi') === true) { + if ($schema->hasTable(tableName: 'catalogi') === true) { $table = $schema->getTable(tableName: 'catalogi'); - if($table->hasColumn(name: 'organization') === false) { + if ($table->hasColumn(name: 'organization') === false) { $table->addColumn( name: 'organization', typeName: Types::STRING, @@ -52,7 +52,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt 'default' => null ]); } - if($table->hasColumn(name: 'metadata') === false) { + if ($table->hasColumn(name: 'metadata') === false) { $metadata = $table->addColumn( name: 'metadata', typeName: Types::JSON, diff --git a/lib/Migration/Version6Date20240808092738.php b/lib/Migration/Version6Date20240808092738.php index e5babbe7..197cbf5f 100644 --- a/lib/Migration/Version6Date20240808092738.php +++ b/lib/Migration/Version6Date20240808092738.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === true) { + if ($schema->hasTable(tableName: 'publications') === true) { $table = $schema->getTable(tableName: 'publications'); - if($table->hasColumn(name: 'published') === true) { + if ($table->hasColumn(name: 'published') === true) { $column = $table->getColumn(name: 'published'); $column->setDefault(default: null); } diff --git a/lib/Migration/Version6Date20240808093230.php b/lib/Migration/Version6Date20240808093230.php index 81e9d2bc..4aeaf8df 100644 --- a/lib/Migration/Version6Date20240808093230.php +++ b/lib/Migration/Version6Date20240808093230.php @@ -39,10 +39,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'publications') === true) { + if ($schema->hasTable(tableName: 'publications') === true) { $table = $schema->getTable(tableName: 'publications'); - if($table->hasColumn(name: 'published') === true) { + if ($table->hasColumn(name: 'published') === true) { $column = $table->getColumn(name: 'published'); $column->setNotnull(notnull: false); } diff --git a/lib/Migration/Version6Date20240808115347.php b/lib/Migration/Version6Date20240808115347.php index 4e60dccb..8b6f9a1d 100644 --- a/lib/Migration/Version6Date20240808115347.php +++ b/lib/Migration/Version6Date20240808115347.php @@ -40,13 +40,13 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'catalogi') === true) { + if ($schema->hasTable(tableName: 'catalogi') === true) { $table = $schema->getTable(tableName: 'catalogi'); - if($table->hasColumn(name: 'organization') === true) { + if ($table->hasColumn(name: 'organization') === true) { $column = $table->dropColumn('organization'); } - if($table->hasColumn(name: 'organisation') === false) { + if ($table->hasColumn(name: 'organisation') === false) { $table->addColumn( name: 'organisation', typeName: Types::STRING, diff --git a/lib/Migration/Version6Date20240809120147.php b/lib/Migration/Version6Date20240809120147.php index eb923ff0..b48e11a7 100644 --- a/lib/Migration/Version6Date20240809120147.php +++ b/lib/Migration/Version6Date20240809120147.php @@ -40,13 +40,13 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'listings') === true) { + if ($schema->hasTable(tableName: 'listings') === true) { $table = $schema->getTable(tableName: 'listings'); - if($table->hasColumn(name: 'organization') === true) { + if ($table->hasColumn(name: 'organization') === true) { $column = $table->dropColumn('organization'); } - if($table->hasColumn(name: 'organisation') === false) { + if ($table->hasColumn(name: 'organisation') === false) { $table->addColumn( name: 'organisation', typeName: Types::STRING, @@ -54,7 +54,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt 'notNull' => false, 'default' => null ]); - $output->info('organisation should be added to listing'); + $output->info('organisation should be added to listing'); } } diff --git a/lib/Migration/Version6Date20240809141351.php b/lib/Migration/Version6Date20240809141351.php index 8f8563ee..8d6ea875 100644 --- a/lib/Migration/Version6Date20240809141351.php +++ b/lib/Migration/Version6Date20240809141351.php @@ -40,10 +40,10 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'metadata') === true) { + if ($schema->hasTable(tableName: 'metadata') === true) { $table = $schema->getTable(tableName: 'metadata'); - if($table->hasColumn(name: 'source') === false) { + if ($table->hasColumn(name: 'source') === false) { $table->addColumn( name: 'source', typeName: Types::STRING, diff --git a/lib/Migration/Version6Date20240816084024.php b/lib/Migration/Version6Date20240816084024.php index 52476108..da41a43a 100644 --- a/lib/Migration/Version6Date20240816084024.php +++ b/lib/Migration/Version6Date20240816084024.php @@ -40,18 +40,18 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'listings') === true) { + if ($schema->hasTable(tableName: 'listings') === true) { $table = $schema->getTable(tableName: 'listings'); - if($table->hasColumn(name: 'reference') === true) { + if ($table->hasColumn(name: 'reference') === true) { $table->dropColumn(name: 'reference'); } } - if($schema->hasTable(tableName: 'metadata') === true) { + if ($schema->hasTable(tableName: 'metadata') === true) { $table = $schema->getTable(tableName: 'metadata'); - if($table->hasColumn(name: 'summary') === false) { + if ($table->hasColumn(name: 'summary') === false) { $column = $table->addColumn(name: 'summary', typeName: Types::STRING); $column->setNotnull(notnull: false)->setDefault(default: null); } diff --git a/lib/Migration/Version6Date20240816111746.php b/lib/Migration/Version6Date20240816111746.php index 5acf0d18..06f2b304 100644 --- a/lib/Migration/Version6Date20240816111746.php +++ b/lib/Migration/Version6Date20240816111746.php @@ -40,18 +40,18 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'listings') === true) { + if ($schema->hasTable(tableName: 'listings') === true) { $table = $schema->getTable(tableName: 'listings'); - if($table->hasColumn(name: 'status_code') === false) { + if ($table->hasColumn(name: 'status_code') === false) { $table->addColumn(name: 'status_code', typeName: Types::INTEGER)->setNotnull(notnull: false); } } - if($schema->hasTable(tableName: 'metadata') === true) { + if ($schema->hasTable(tableName: 'metadata') === true) { $table = $schema->getTable(tableName: 'metadata'); - if($table->hasColumn(name: 'archive') === false) { + if ($table->hasColumn(name: 'archive') === false) { $column = $table->addColumn(name: 'archive', typeName: Types::JSON); $column->setNotnull(notnull: false)->setDefault(default: null); } diff --git a/lib/Migration/Version6Date20240816115114.php b/lib/Migration/Version6Date20240816115114.php index 3c198963..b29dcd88 100644 --- a/lib/Migration/Version6Date20240816115114.php +++ b/lib/Migration/Version6Date20240816115114.php @@ -39,15 +39,15 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt */ $schema = $schemaClosure(); - if($schema->hasTable(tableName: 'listings') === true) { + if ($schema->hasTable(tableName: 'listings') === true) { $table = $schema->getTable(tableName: 'listings'); - if($table->hasColumn(name: 'status_code') === true) { + if ($table->hasColumn(name: 'status_code') === true) { $table->getColumn(name: 'status_code')->setNotnull(notnull: false)->setDefault(default: null); $output->info("Updated 'status_code' column to listings table as nullable with default null"); } } - + return $schema; } diff --git a/lib/Migration/Version6Date20240923093806.php b/lib/Migration/Version6Date20240923093806.php new file mode 100644 index 00000000..6ec7d277 --- /dev/null +++ b/lib/Migration/Version6Date20240923093806.php @@ -0,0 +1,108 @@ +hasTable(tableName: 'publications') === true) { + $table = $schema->getTable(tableName: 'publications'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'attachments') === true) { + $table = $schema->getTable(tableName: 'attachments'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'catalogi') === true) { + $table = $schema->getTable(tableName: 'catalogi'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'listings') === true) { + $table = $schema->getTable(tableName: 'listings'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'metadata') === true) { + $table = $schema->getTable(tableName: 'metadata'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'organisations') === true) { + $table = $schema->getTable(tableName: 'organisations'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + if($schema->hasTable(tableName: 'themes') === true) { + $table = $schema->getTable(tableName: 'themes'); + if($table->hasColumn(name: 'description') === true) { + $column = $table->getColumn(name: 'description'); + $column->setLength(length: 20000); + } + } + + return $schema; + } + + /** + * @param IOutput $output + * @param Closure(): ISchemaWrapper $schemaClosure + * @param array $options + */ + public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { + } +} diff --git a/lib/Service/DirectoryService.php b/lib/Service/DirectoryService.php index a4f3c842..2acd58cb 100644 --- a/lib/Service/DirectoryService.php +++ b/lib/Service/DirectoryService.php @@ -47,12 +47,12 @@ private function getDirectoryEntry(string $catalogId): array public function registerToExternalDirectory (array $newDirectory = [], ?string $url = null, array &$externalDirectories = []): int { - if($newDirectory !== [] && $url === null) { + if ($newDirectory !== [] && $url === null) { $url = $newDirectory['directory']; } - if($this->config->getValueString(app: $this->appName, key: 'mongoStorage') !== '1') { + if ($this->config->getValueString(app: $this->appName, key: 'mongoStorage') !== '1') { $catalogi = $this->listingMapper->findAll(); } else { $dbConfig['base_uri'] = $this->config->getValueString('opencatalogi', 'mongodbLocation'); @@ -62,13 +62,13 @@ public function registerToExternalDirectory (array $newDirectory = [], ?string $ $catalogi = $this->objectService->findObjects(filters: ['_schema' => 'directory'], config: $dbConfig)['documents']; } - foreach($catalogi as $catalog) { - if($catalog instanceof Listing) { + foreach ($catalogi as $catalog) { + if ($catalog instanceof Listing) { $catalog = $catalog->jsonSerialize(); } unset($catalog['_id'], $catalog['id'], $catalog['_schema']); - if($catalog['directory'] !== $this->urlGenerator->getAbsoluteURL(url: $this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index"))) { + if ($catalog['directory'] !== $this->urlGenerator->getAbsoluteURL(url: $this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index"))) { continue; } @@ -77,7 +77,7 @@ public function registerToExternalDirectory (array $newDirectory = [], ?string $ $externalDirectories = $this->fetchFromExternalDirectory(url: $url, update: true); - if($result !== null) { + if ($result !== null) { return $result->getStatusCode(); } return 200; @@ -90,7 +90,7 @@ private function createDirectoryFromResult(array $result, bool $update = false): $myDirectory = $this->getDirectoryEntry(catalogId: ''); - if( + if ( isset($result['directory']) === false || $result['directory'] === $myDirectory['directory'] || ( @@ -102,21 +102,21 @@ private function createDirectoryFromResult(array $result, bool $update = false): } else if (count($this->listDirectory(filters: ['catalogId' => $result['catalogId'], 'directory' => $result['directory']])) > 0 && $update === true) { $listing = $this->listDirectory(filters: ['catalogId' => $result['catalogId'], 'directory' => $result['directory']])[0]; - if($listing instanceof Listing) { + if ($listing instanceof Listing) { $listing = $listing->jsonSerialize(); } $id = $listing['id']; } - if($this->config->getValueString($this->appName, 'mongoStorage') === '1') { + if ($this->config->getValueString($this->appName, 'mongoStorage') === '1') { $dbConfig['base_uri'] = $this->config->getValueString(app: 'opencatalogi', key: 'mongodbLocation'); $dbConfig['headers']['api-key'] = $this->config->getValueString(app: 'opencatalogi', key: 'mongodbKey'); $dbConfig['mongodbCluster'] = $this->config->getValueString(app: 'opencatalogi', key: 'mongodbCluster'); $result['_schema'] = 'directory'; - if(isset($id) === true) { + if (isset($id) === true) { $this->objectService->updateObject( filters: ['id' => $id], update: $result, @@ -129,21 +129,49 @@ private function createDirectoryFromResult(array $result, bool $update = false): config: $dbConfig ); } else { - if(isset($id) === true) { + if (isset($id) === true) { return $this->listingMapper->updateFromArray(id: $id, object: $result)->jsonSerialize(); } return $this->listingMapper->createFromArray(object: $result)->jsonSerialize(); } } + /** + * array_map function for fetching a directory for a listing. + * + * @param Listing $listing + * @return string + */ + private function getDirectory(Listing $listing): string + { + return $listing->getDirectory(); + } + + /** + * Get all directories to scan. + * + * @return array + */ + private function getDirectories(): array + { + $listings = $this->listingMapper->findAll(); + + $directories = array_map(callback: [$this, 'getDirectory'], array: $listings); + + return array_unique(array: $directories); + } + + /** + * Run a synchronisation based on cron + * + * @return array + */ public function doCronSync(): array { $results = []; - $directories = []; - //@todo get unique direcotries form the database - $directories[] = 'https://directory.opencatalogi.nl/apps/opencatalogi/api/directory'; - foreach($directories as $key -> $directory){ - $result = $this->fetchFromExternalDirectory([], $directory, true); + $directories = $this->getDirectories(); + foreach ($directories as $key=>$directory){ + $result = $this->fetchFromExternalDirectory(url: $directory, update: true); $results = array_merge_recursive($results, $result); } @@ -153,21 +181,34 @@ public function doCronSync(): array { // Get or update the data for an specifi exernal directory public function fetchFromExternalDirectory(array $directory = [], ?string $url = null, bool $update = false): array { - if($directory !== [] && $url === null) { + if ($directory !== [] && $url === null) { $url = $directory['directory']; } $result = $this->client->get(uri: $url); - if(str_contains(haystack: $result->getHeader('Content-Type')[0], needle: 'application/json') === false) { - $result = $this->client->get(uri: rtrim(string: $url, characters: '/').'/apps/opencatalogi/api/directory'); + if (str_contains(haystack: $result->getHeader('Content-Type')[0], needle: 'application/json') === false) { + $url = rtrim(string: $url, characters: '/').'/apps/opencatalogi/api/directory'; + $result = $this->client->get(uri: $url); } $results = json_decode(json: $result->getBody()->getContents(), associative: true); $addedDirectories = []; + $catalogs = []; - foreach($results['results'] as $record) { + foreach ($results['results'] as $record) { + $catalogs[] = $record['catalogId']; $addedDirectories[] = $this->createDirectoryFromResult(result: $record, update: $update); + + } + + + $localListings = $this->listingMapper->findAll(filters: ['directory' => $url]); + + foreach ($localListings as $localListing) { + if (in_array(needle: $localListing->getCatalogId(), haystack: $catalogs) === false) { + $this->listingMapper->delete($localListing); + } } return $addedDirectories; @@ -199,12 +240,12 @@ public function listDirectory(array $filters = [], int $limit = 30, int $offset public function deleteListing(string $catalogId, string $directoryUrl): void { - if($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false + if ($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false || $this->config->getValueString(app: $this->appName, key: 'mongoStorage') !== '1' ) { $results = $this->listingMapper->findAll(filters: ['directory' => $directoryUrl, 'catalog_id' => $catalogId]); - foreach($results as $result) { + foreach ($results as $result) { $this->listingMapper->delete(entity: $result); } @@ -218,7 +259,7 @@ public function deleteListing(string $catalogId, string $directoryUrl): void $results = $this->objectService->findObjects(filters: ['directory' => $directoryUrl, 'catalogId' => $catalogId, '_schema' => 'directory'], config: $dbConfig); - foreach($results['documents'] as $result) { + foreach ($results['documents'] as $result) { $this->objectService->deleteObject(filters: ['_id' => $result['_id']], config: $dbConfig); } @@ -229,14 +270,14 @@ public function directoryExists(string $catalogId, ?array &$listing = null): boo { $directoryUrl = $this->urlGenerator->getAbsoluteURL(url: $this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index")); - if($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false + if ($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false || $this->config->getValueString(app: $this->appName, key: 'mongoStorage') !== '1' ) { $results = $this->listingMapper->findAll(filters: ['directory' => $directoryUrl, 'catalog_id' => $catalogId]); $result = count($results) > 0; - if($result === true) { + if ($result === true) { $listing = $results[0]->jsonSerialize(); } return $result; @@ -252,7 +293,7 @@ public function directoryExists(string $catalogId, ?array &$listing = null): boo $result = count(value: $results['documents']) > 0; - if($result === true) { + if ($result === true) { $listing = $results['documents'][0]; } @@ -264,7 +305,7 @@ public function listCatalog (array $catalog): array $existingListing = null; $catalogId = $catalog['id']; - if($catalog['listed'] === false) { + if ($catalog['listed'] === false) { $this->deleteListing(catalogId: $catalogId, directoryUrl: $this->urlGenerator->getAbsoluteURL(url: $this->urlGenerator->linkToRoute(routeName:"opencatalogi.directory.index")),); return $catalog; } @@ -278,10 +319,10 @@ public function listCatalog (array $catalog): array $listing['organisation'] = $catalog['organisation']; $listing['metadata'] = $catalog['metadata']; - if($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false + if ($this->config->hasKey(app: $this->appName, key: 'mongoStorage') === false || $this->config->getValueString(app: $this->appName, key: 'mongoStorage') !== '1' ) { - if($this->directoryExists(catalogId: $catalogId, listing: $existingListing) === true) { + if ($this->directoryExists(catalogId: $catalogId, listing: $existingListing) === true) { $listing = $this->listingMapper->updateFromArray(id: $existingListing['id'], object: $listing); } else { $listing = $this->listingMapper->createFromArray(object: $listing); @@ -299,7 +340,7 @@ public function listCatalog (array $catalog): array $listing['_schema'] = 'directory'; - if($this->directoryExists(catalogId: $catalogId, listing: $existingListing) === true) { + if ($this->directoryExists(catalogId: $catalogId, listing: $existingListing) === true) { $returnData = $this->objectService->updateObject(filters: ['id' => $existingListing['id']], update: $listing, config: $dbConfig); } else { $returnData = $this->objectService->saveObject(data: $listing, config: $dbConfig); diff --git a/lib/Service/ElasticSearchService.php b/lib/Service/ElasticSearchService.php index 3f0be4a7..cb4e67cc 100644 --- a/lib/Service/ElasticSearchService.php +++ b/lib/Service/ElasticSearchService.php @@ -35,7 +35,7 @@ public function addObject(array $object, array $config): array { $client = $this->getClient(config: $config); - if(isset($object['_id']) === true) { + if (isset($object['_id']) === true) { unset($object['_id']); } @@ -75,7 +75,7 @@ public function updateObject(string $id, array $object, array $config): array { $client = $this->getClient(config: $config); - if(isset($object['_id']) === true) { + if (isset($object['_id']) === true) { unset($object['_id']); } @@ -94,15 +94,15 @@ public function updateObject(string $id, array $object, array $config): array public function parseFilter(string $name, array|string $filter): array { - if(is_array($filter) === false) { + if (is_array($filter) === false) { return ['match' => [$name => $filter]]; } - foreach($filter as $key => $value) { + foreach ($filter as $key => $value) { switch($key) { case 'regexp': case 'like': - if(preg_match("/^\/.+\/[a-z]*$/i", $value) !== false) { + if (preg_match("/^\/.+\/[a-z]*$/i", $value) !== false) { return ['regexp' => [$name => strtolower($value)]]; } else { return ['match' => [$name => $value]]; @@ -137,18 +137,18 @@ public function parseFilters (array $filters): array ] ]; - if(isset($filters['.search']) === true) { + if (isset($filters['.search']) === true) { $body['query']['bool']['must'][] = ['query_string' => ['query' => '*'.$filters['.search'].'*']]; } - if(isset($filters['.queries']) === true) { - foreach($filters['.queries'] as $query) { + if (isset($filters['.queries']) === true) { + foreach ($filters['.queries'] as $query) { $body['runtime_mappings'][$query] = ['type' => 'keyword']; $body['aggs'][$query] = ['terms' => ['field' => $query]]; } } - if(isset($filters['.catalogi']) === true) { + if (isset($filters['.catalogi']) === true) { $body['query']['bool']['must'][] = [ 'match' => [ 'catalogi._id' => [ @@ -159,13 +159,13 @@ public function parseFilters (array $filters): array ]; } - if(isset($filters['.limit']) === true) { + if (isset($filters['.limit']) === true) { $body['size'] = (int) $filters['.limit']; unset($filters['.limit']); } - if(isset($filters['.page']) === true) { - if(isset($body['size']) === true) { + if (isset($filters['.page']) === true) { + if (isset($body['size']) === true) { $body['from'] = $body['size'] * ($filters['.page'] - 1); } unset($filters['.page']); @@ -238,7 +238,7 @@ public function searchObject(array $filters, array $config, int &$totalResults = $totalResults = $result['hits']['total']['value']; $return = ['results' => array_map(callback: [$this, 'formatResults'], array: $result['hits']['hits'])]; - if(isset($result['aggregations']) === true) { + if (isset($result['aggregations']) === true) { $return['facets'] = array_map([$this, 'mapAggregationResults'], $result['aggregations']); } else { $return['facets'] = []; diff --git a/lib/Service/SearchService.php b/lib/Service/SearchService.php index 8a1d4a37..42d2b834 100644 --- a/lib/Service/SearchService.php +++ b/lib/Service/SearchService.php @@ -30,13 +30,13 @@ public function mergeFacets(array $existingAggregation, array $newAggregation): $existingAggregationMapped = []; $newAggregationMapped = []; - foreach($existingAggregation as $value) { + foreach ($existingAggregation as $value) { $existingAggregationMapped[$value['_id']] = $value['count']; } - foreach($newAggregation as $value) { - if(isset ($existingAggregationMapped[$value['_id']]) === true) { + foreach ($newAggregation as $value) { + if (isset ($existingAggregationMapped[$value['_id']]) === true) { $newAggregationMapped[$value['_id']] = $existingAggregationMapped[$value['_id']] + $value['count']; } else { $newAggregationMapped[$value['_id']] = $value['count']; @@ -54,13 +54,13 @@ public function mergeFacets(array $existingAggregation, array $newAggregation): private function mergeAggregations(?array $existingAggregations, ?array $newAggregations): array { - if($newAggregations === null) { + if ($newAggregations === null) { return []; } - foreach($newAggregations as $key => $aggregation) { - if(isset($existingAggregations[$key]) === false) { + foreach ($newAggregations as $key => $aggregation) { + if (isset($existingAggregations[$key]) === false) { $existingAggregations[$key] = $aggregation; } else { $existingAggregations[$key] = $this->mergeFacets($existingAggregations[$key], $aggregation); @@ -88,7 +88,7 @@ public function search(array $parameters, array $elasticConfig, array $dbConfig, $limit = isset($parameters['.limit']) === true ? $parameters['.limit'] : 30; $page = isset($parameters['.page']) === true ? $parameters['.page'] : 1; - if($elasticConfig['location'] !== '') { + if ($elasticConfig['location'] !== '') { $localResults = $this->elasticService->searchObject(filters: $parameters, config: $elasticConfig, totalResults: $totalResults,); } @@ -96,7 +96,7 @@ public function search(array $parameters, array $elasticConfig, array $dbConfig, // $directory = $this->objectService->findObjects(filters: ['_schema' => 'directory'], config: $dbConfig); - if(count($directory) === 0) { + if (count($directory) === 0) { $pages = (int) ceil($totalResults / $limit); return [ 'results' => $localResults['results'], @@ -116,8 +116,8 @@ public function search(array $parameters, array $elasticConfig, array $dbConfig, $promises = []; - foreach($directory as $instance) { - if( + foreach ($directory as $instance) { + if ( $instance['default'] === false || isset($parameters['.catalogi']) === true && in_array($instance['catalogId'], $parameters['.catalogi']) === false @@ -130,7 +130,7 @@ public function search(array $parameters, array $elasticConfig, array $dbConfig, unset($parameters['.catalogi']); - foreach($searchEndpoints as $searchEndpoint => $catalogi) { + foreach ($searchEndpoints as $searchEndpoint => $catalogi) { $parameters['_catalogi'] = $catalogi; @@ -139,8 +139,8 @@ public function search(array $parameters, array $elasticConfig, array $dbConfig, $responses = Utils::settle($promises)->wait(); - foreach($responses as $response) { - if($response['state'] === 'fulfilled') { + foreach ($responses as $response) { + if ($response['state'] === 'fulfilled') { $responseData = json_decode( json: $response['value']->getBody()->getContents(), associative: true @@ -323,7 +323,7 @@ public function unsetSpecialQueryParams(array $filters): array if (str_starts_with($key, '_')) { unset($filters[$key]); } - if($key === 'search') { + if ($key === 'search') { unset($filters[$key]); } } @@ -404,12 +404,12 @@ public function parseQueryString (string $queryString = ''): array { $pairs = explode(separator: '&', string: $queryString); - foreach($pairs as $pair) { + foreach ($pairs as $pair) { $kvpair = explode(separator: '=', string: $pair); $key = urldecode(string: $kvpair[0]); $value = ''; - if(count(value: $kvpair) === 2) { + if (count(value: $kvpair) === 2) { $value = urldecode(string: $kvpair[1]); } diff --git a/lib/Service/ValidationService.php b/lib/Service/ValidationService.php index 80a2035b..ff60ccaf 100644 --- a/lib/Service/ValidationService.php +++ b/lib/Service/ValidationService.php @@ -58,7 +58,7 @@ public function getMongodbConfig(): array public function getCatalog (string $id): array { if ($this->config->hasKey(app: $this->appName, key: 'mongoStorage') !== false - || $this->config->getValueString(app: $this->appName, key: 'mongoStorage') === '1' + && $this->config->getValueString(app: $this->appName, key: 'mongoStorage') === '1' ) { $filter = ['id' => $id, '_schema' => 'catalog']; @@ -99,7 +99,7 @@ public function validatePublication(array $publication): array } // var_dump($catalog['metadata'], $metadata, in_array(needle: $metadata, haystack: $catalog['metadata'])); - if(in_array(needle: $metadata, haystack: $catalog['metadata']) === false) { + if (in_array(needle: $metadata, haystack: $catalog['metadata']) === false) { throw new OCSBadRequestException(message: 'Given metadata object not present in catalog'); } diff --git a/package-lock.json b/package-lock.json index c1435f86..13151b64 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,6 +46,7 @@ "@nextcloud/webpack-vue-config": "^6.0.1", "@pinia/testing": "^0.1.5", "@types/jest": "^29.5.12", + "@types/lodash": "^4.17.7", "@types/node": "^22.5.0", "@vue/test-utils": "^2.4.6", "@vue/vue2-jest": "^29.2.6", @@ -4704,6 +4705,12 @@ "license": "MIT", "peer": true }, + "node_modules/@types/lodash": { + "version": "4.17.7", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.7.tgz", + "integrity": "sha512-8wTvZawATi/lsmNu10/j2hk1KEP0IvjubqPE3cu1Xz7xfXXt5oCq3SNUz4fMIP4XGF9Ky+Ue2tBA3hcS7LSBlA==", + "dev": true + }, "node_modules/@types/mdast": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", @@ -15222,8 +15229,7 @@ "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "license": "MIT" + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, "node_modules/lodash.debounce": { "version": "4.0.8", diff --git a/package.json b/package.json index 9569ada9..fdccad01 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "@nextcloud/webpack-vue-config": "^6.0.1", "@pinia/testing": "^0.1.5", "@types/jest": "^29.5.12", + "@types/lodash": "^4.17.7", "@types/node": "^22.5.0", "@vue/test-utils": "^2.4.6", "@vue/vue2-jest": "^29.2.6", diff --git a/src/dialogs/attachment/CopyAttachmentDialog.vue b/src/dialogs/attachment/CopyAttachmentDialog.vue index 7e23f451..76a2fd1f 100644 --- a/src/dialogs/attachment/CopyAttachmentDialog.vue +++ b/src/dialogs/attachment/CopyAttachmentDialog.vue @@ -47,6 +47,8 @@ import { NcButton, NcDialog, NcNoteCard, NcLoadingIcon } from '@nextcloud/vue' import Cancel from 'vue-material-design-icons/Cancel.vue' import ContentCopy from 'vue-material-design-icons/ContentCopy.vue' +import { Attachment } from '../../entities/index.js' + export default { name: 'CopyAttachmentDialog', components: { @@ -69,62 +71,19 @@ export default { methods: { CopyAttachment() { this.loading = true - publicationStore.attachmentItem.title = 'KOPIE: ' + publicationStore.attachmentItem.title - publicationStore.attachmentItem.status = 'concept' - publicationStore.attachmentItem.published = 'null' - delete publicationStore.attachmentItem.id - delete publicationStore.attachmentItem._id - fetch( - '/index.php/apps/opencatalogi/api/attachments', - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(publicationStore.attachmentItem), - }, - ) - .then((response) => { - this.loading = false - this.succes = true - response.json().then((data) => { - if (publicationStore.publicationItem) { - publicationStore.getPublicationAttachments(publicationStore.publicationItem?.id) + const attachmentClone = { ...publicationStore.attachmentItem } - fetch( - `/index.php/apps/opencatalogi/api/publications/${publicationStore.publicationItem.id}`, - { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - ...publicationStore.publicationItem, - attachments: [...publicationStore.publicationItem.attachments, data.id], - catalogi: publicationStore.publicationItem.catalogi.id, - metaData: publicationStore.publicationItem.metaData, - }), - }, - ) - .then((response) => { - this.loading = false + attachmentClone.title = 'KOPIE: ' + attachmentClone.title - // Lets refresh the publicationList - publicationStore.refreshPublicationList() - response.json().then((data) => { - publicationStore.setPublicationItem(data) - }) + const newAttachmentItem = new Attachment({ + ...attachmentClone, + }) - }) - .catch((err) => { - this.error = err - this.loading = false - }) - // store.refreshCatalogiList() - } - }) - publicationStore.setAttachmentItem(response) + publicationStore.addAttachment(newAttachmentItem, publicationStore.publicationItem) + .then(({ response }) => { + this.loading = false + this.succes = response.ok // Wait for the user to read the feedback then close the model const self = this diff --git a/src/dialogs/attachment/DeleteAttachmentDialog.vue b/src/dialogs/attachment/DeleteAttachmentDialog.vue index ce93cb8b..e8959ab7 100644 --- a/src/dialogs/attachment/DeleteAttachmentDialog.vue +++ b/src/dialogs/attachment/DeleteAttachmentDialog.vue @@ -8,7 +8,7 @@ import { publicationStore, navigationStore } from '../../store/store.js' name="Bijlage verwijderen" :can-close="false">

- Wil je {{ publicationStore.attachmentItem.name ?? publicationStore.attachmentItem.title }} definitief verwijderen? Deze actie kan niet ongedaan worden gemaakt. + Wil je {{ publicationStore.attachmentItem?.title }} definitief verwijderen? Deze actie kan niet ongedaan worden gemaakt.

Bijlage succesvol verwijderd

@@ -61,7 +61,6 @@ export default { }, data() { return { - filterdAttachments: [], loading: false, succes: false, error: false, @@ -70,58 +69,16 @@ export default { methods: { DeleteAttachment() { this.loading = true - fetch( - `/index.php/apps/opencatalogi/api/attachments/${publicationStore.attachmentItem.id}`, - { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - }, - }, - ) - .then((response) => { - this.loading = false - this.succes = true - // Lets refresh the attachment list - if (publicationStore.publicationItem) { - publicationStore.getPublicationAttachments(publicationStore.publicationItem?.id) - this.filterdAttachments = publicationStore.publicationItem.attachments.filter((attachment) => { return parseInt(attachment) !== parseInt(publicationStore.attachmentItem.id) }) - - fetch( - `/index.php/apps/opencatalogi/api/publications/${publicationStore.publicationItem.id}`, - { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - ...publicationStore.publicationItem, - attachments: [...this.filterdAttachments], - catalogi: publicationStore.publicationItem.catalogi.id, - metaData: publicationStore.publicationItem.metaData, - }), - }, - ) - .then((response) => { - this.loading = false - // Lets refresh the publicationList - publicationStore.refreshPublicationList() - response.json().then((data) => { - publicationStore.setPublicationItem(data) - }) - }) - .catch((err) => { - this.error = err - this.loading = false - }) - } + publicationStore.deleteAttachment(publicationStore.attachmentItem?.id, publicationStore.publicationItem) + .then(({ response }) => { + this.loading = false + this.succes = response.ok // Wait for the user to read the feedback then close the model const self = this setTimeout(function() { self.succes = false - publicationStore.setAttachmentItem(false) navigationStore.setDialog(false) }, 2000) }) diff --git a/src/dialogs/attachment/DepublishAttachmentDialog.vue b/src/dialogs/attachment/DepublishAttachmentDialog.vue index 91980a76..739a2cd7 100644 --- a/src/dialogs/attachment/DepublishAttachmentDialog.vue +++ b/src/dialogs/attachment/DepublishAttachmentDialog.vue @@ -47,6 +47,8 @@ import { NcButton, NcDialog, NcNoteCard, NcLoadingIcon } from '@nextcloud/vue' import Cancel from 'vue-material-design-icons/Cancel.vue' import PublishOff from 'vue-material-design-icons/PublishOff.vue' +import { Attachment } from '../../entities/index.js' + export default { name: 'DepublishAttachmentDialog', components: { @@ -60,7 +62,6 @@ export default { }, data() { return { - loading: false, succes: false, error: false, @@ -69,32 +70,29 @@ export default { methods: { depublishAttachment() { this.loading = true - publicationStore.attachmentItem.published = null - fetch( - `/index.php/apps/opencatalogi/api/attachments/${publicationStore.attachmentItem.id}`, - { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(publicationStore.attachmentItem), - }, - ).then(() => { - this.loading = false - this.succes = true - if (publicationStore.publicationItem) { - publicationStore.getPublicationAttachments(publicationStore.publicationItem?.id) - } + const attachmentClone = { ...publicationStore.attachmentItem } + + attachmentClone.published = null + + const attachmentItem = new Attachment(attachmentClone) - // Wait for the user to read the feedback then close the model - const self = this - setTimeout(function() { - self.succes = false - publicationStore.setAttachmentItem(false) - navigationStore.setDialog(false) - }, 2000) - }) + publicationStore.editAttachment(attachmentItem) + .then(({ response }) => { + this.loading = false + this.succes = response.ok + + if (publicationStore.publicationItem) { + publicationStore.getPublicationAttachments(publicationStore.publicationItem?.id) + } + + // Wait for the user to read the feedback then close the model + const self = this + setTimeout(function() { + self.succes = false + navigationStore.setDialog(false) + }, 2000) + }) .catch((err) => { this.error = err this.loading = false diff --git a/src/dialogs/attachment/PublishAttachmentDialog.vue b/src/dialogs/attachment/PublishAttachmentDialog.vue index 27f37b25..2d3a1bee 100644 --- a/src/dialogs/attachment/PublishAttachmentDialog.vue +++ b/src/dialogs/attachment/PublishAttachmentDialog.vue @@ -5,7 +5,7 @@ import { publicationStore, navigationStore } from '../../store/store.js'