From f6231a16b913021935a336261a48d8546559ba77 Mon Sep 17 00:00:00 2001
From: Claudiu Cristea <clau.cristea@gmail.com>
Date: Tue, 10 Sep 2024 11:33:26 +0300
Subject: [PATCH] ISAICP-9062: Rely on collection state.

---
 .opts.yml                                     |   2 -
 .../oss_catalogue_visibility.feature          |   2 +
 .../dashboard/src/Form/DashboardForm.php      |   4 +-
 .../joinup_oss_catalogue.install              |   3 +
 .../joinup_oss_catalogue.module               | 100 ++++++++++--------
 .../src/Access/KillSwitchCheck.php            |   3 +-
 .../Commands/JoinupOssCatalogueCommands.php   |   4 +-
 .../JoinupDataSanitizationCommands.php        |  17 ---
 .../src/Plugin/Block/ExploreBlock.php         |   2 +-
 9 files changed, 67 insertions(+), 70 deletions(-)

diff --git a/.opts.yml b/.opts.yml
index 08b2313c75..1ae028cf44 100644
--- a/.opts.yml
+++ b/.opts.yml
@@ -14,8 +14,6 @@ upgrade_commands:
     - rm disable-config-readonly
     - vendor/bin/drush joinup:unpublish-alert --category
     - scripts/check_status_report.php
-    # TODO: Remove this command in ISAICP-9053.
-    - vendor/bin/drush state:set joinup.oss_catalogue_is_disabled 1 --input-format=boolean
   append:
     acceptance:
       - touch disable-config-readonly
diff --git a/tests/features/communities/oss_catalogue/oss_catalogue_visibility.feature b/tests/features/communities/oss_catalogue/oss_catalogue_visibility.feature
index 36fc5ecd6b..d1970cbae4 100644
--- a/tests/features/communities/oss_catalogue/oss_catalogue_visibility.feature
+++ b/tests/features/communities/oss_catalogue/oss_catalogue_visibility.feature
@@ -62,6 +62,8 @@ Feature: Test EU OSS Catalogue killswitch
     Then the response status code should be 200
     And I go to the content page of the type "oss_solution" with the title "The Opensource Panacea"
     Then the response status code should be 200
+    When I am on the homepage
+    Then I should see "EU Open Source Solutions Catalogue"
 
     Given I am an anonymous user
     When I go to "/eu-oss-catalogue"
diff --git a/web/modules/custom/dashboard/src/Form/DashboardForm.php b/web/modules/custom/dashboard/src/Form/DashboardForm.php
index c06b5662e5..0f02afb930 100644
--- a/web/modules/custom/dashboard/src/Form/DashboardForm.php
+++ b/web/modules/custom/dashboard/src/Form/DashboardForm.php
@@ -114,14 +114,14 @@ public function buildForm(array $form, FormStateInterface $form_state): array {
       '#type' => 'submit',
       '#value' => $this->t('Enable EU OSS Catalogue'),
       '#submit' => ['::enableEuOssCatalogueSubmitForm'],
-      '#access' => $hasEnableDisablePermission && !joinup_oss_catalogue_is_enabled(),
+      '#access' => $hasEnableDisablePermission && !joinup_oss_catalogue_feature()->isAllowed(),
     ];
     // @todo Remove this button in ISAICP-9053.
     $form['actions']['disable'] = [
       '#type' => 'submit',
       '#value' => $this->t('Disable EU OSS Catalogue'),
       '#submit' => ['::disableEuOssCatalogueSubmitForm'],
-      '#access' => $hasEnableDisablePermission && joinup_oss_catalogue_is_enabled(),
+      '#access' => $hasEnableDisablePermission && joinup_oss_catalogue_feature()->isAllowed(),
     ];
 
     return $form;
diff --git a/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.install b/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.install
index ce8d1aa03f..a91e60a0c8 100644
--- a/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.install
+++ b/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.install
@@ -34,4 +34,7 @@ function joinup_oss_catalogue_update_200002(): void {
     ->loadEntityByUuid('node', OssCatalogueCollectionInterface::LANDING_PAGE)
     ->set('field_topic', 11195)
     ->save();
+
+  // We're not using anymore this switch.
+  \Drupal::state()->delete('joinup.oss_catalogue_is_disabled');
 }
diff --git a/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.module b/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.module
index 0adfdf2379..9eedf4aabb 100644
--- a/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.module
+++ b/web/modules/custom/joinup_communities/joinup_oss_catalogue/joinup_oss_catalogue.module
@@ -191,13 +191,25 @@ function joinup_oss_catalogue_preprocess_views_view__eu_oss_catalogue_admin_caro
 /**
  * Checks whether the EU OSS Catalogue functionality is enabled.
  *
- * @return bool
- *   Whether the EU OSS Catalogue functionality is enabled.
+ * @return \Drupal\Core\Access\AccessResultInterface
+ *   Access result.
  *
  * @todo Remove this function in ISAICP-9053.
  */
-function joinup_oss_catalogue_is_enabled(): bool {
-  return !\Drupal::state()->get('joinup.oss_catalogue_is_disabled', FALSE);
+function joinup_oss_catalogue_feature(): AccessResultInterface {
+  static $cache;
+  if (!isset($cache)) {
+    $collection = \Drupal::entityTypeManager()->getStorage('rdf_entity')
+      ->load(OssCatalogueCollectionInterface::COLLECTION_ENTITY_ID);
+    if (!$collection instanceof CollectionInterface) {
+      $cache = AccessResult::allowed();
+    }
+    else {
+      $state = $collection->get('field_ar_state')->first()->getValue()['value'] ?? NULL;
+      $cache = AccessResult::allowedIf($state === 'published')->addCacheableDependency($collection);
+    }
+  }
+  return $cache;
 }
 
 /**
@@ -215,7 +227,7 @@ function joinup_oss_catalogue_entity_access(EntityInterface $entity): AccessResu
     ($entity instanceof OssSolutionInterface)
   ) {
     return AccessResult::forbiddenIf(
-      !joinup_oss_catalogue_is_enabled(),
+      !joinup_oss_catalogue_feature()->isAllowed(),
       'EU OSS Catalogue is disabled',
     )->addCacheableDependency($entity);
   }
@@ -242,7 +254,7 @@ function joinup_oss_catalogue_module_implements_alter(array &$implementations, s
  * @todo Remove this function in ISAICP-9053.
  */
 function joinup_oss_catalogue_cron(): void {
-  if (joinup_oss_catalogue_is_enabled()) {
+  if (joinup_oss_catalogue_feature()->isAllowed()) {
     // Only run if EU OSS Catalogue functionality is enabled.
     eu_oss_catalogue_cron();
     eu_oss_vitality_index_cron();
@@ -259,48 +271,48 @@ function joinup_oss_catalogue_cron(): void {
  */
 function joinup_oss_catalogue_toggle(string $toggle): void {
   assert(in_array($toggle, ['enable', 'disable'], TRUE));
-  $entityTypeManager = \Drupal::entityTypeManager();
-  $state = \Drupal::state();
 
-  if ($toggle === 'enable') {
-    $state->delete('joinup.oss_catalogue_is_disabled');
-    $collection = $entityTypeManager->getStorage('rdf_entity')
-      ->load(OssCatalogueCollectionInterface::COLLECTION_ENTITY_ID);
-    $collection->skip_notification = TRUE;
-    $collection->set('field_ar_state', 'published')->save();
+  $entityTypeManager = \Drupal::entityTypeManager();
+  $uri = OssCatalogueCollectionInterface::COLLECTION_ENTITY_ID;
+  if (!$collection = $entityTypeManager->getStorage('rdf_entity')->load($uri)) {
+    // If the EU OSS Catalogue collection is missing exit there's nothing to do.
     return;
   }
 
-  $state->set('joinup.oss_catalogue_is_disabled', TRUE);
-
-  $uri = OssCatalogueCollectionInterface::COLLECTION_ENTITY_ID;
-  $collection = \Drupal::entityTypeManager()->getStorage('rdf_entity')->load($uri);
   $collection->skip_notification = TRUE;
-  $collection->set('field_ar_state', 'draft')->save();
+  $state = $toggle === 'enable' ? 'published' : 'draft';
+  $collection->set('field_ar_state', $state)->save();
+
+  if ($toggle === 'disable') {
+    // Unfortunately, we don't have an API to  unpublish a collection because
+    // when setting the state field to 'draft', we're creating a forward
+    // revision and the published version still exist and is shown on UIs. In
+    // order to unpublish, we perform the following operations:
+    // - Remove the published triples.
+    // - Remove the document from Solr and from search_api_item table.
+    $sparql = <<<SPARQL
+      WITH <http://joinup.eu/collection/published>
+      DELETE { <$uri> ?p ?o }
+      WHERE  { <$uri> ?p ?o }
+      SPARQL;
+    \Drupal::getContainer()->get('rdf_sync.connection')->update($sparql);
+    $sapiId = 'entity:rdf_entity/' . $uri;
+    $solrHelper = new Helper();
+    /** @var \Drupal\search_api_solr\SolrConnectorInterface $connector */
+    $connector = $entityTypeManager->getStorage('search_api_server')->load('joinup')
+      ->getBackend()
+      ->getSolrConnector();
+    $deleteQuery = $connector
+      ->getUpdateQuery()
+      ->addDeleteQuery('ss_search_api_id:' . $solrHelper->escapePhrase($sapiId))
+      ->addCommit();
+    $connector->update($deleteQuery);
+    \Drupal::database()->delete('search_api_item')
+      ->condition('index_id', ['published', 'unpublished'], 'IN')
+      ->condition('item_id', $sapiId)
+      ->execute();
+  }
 
-  // Unfortunately, we cannot unpublish a collection. When setting the state
-  // to 'draft', we're creating a forward revision. In order to unpublish, we:
-  // - Remove the published triples.
-  // - Remove the document from Solr and from search_api_item table.
-  $sparql = <<<SPARQL
-    WITH <http://joinup.eu/collection/published>
-    DELETE { <$uri> ?p ?o }
-    WHERE  { <$uri> ?p ?o }
-    SPARQL;
-  \Drupal::getContainer()->get('rdf_sync.connection')->update($sparql);
-  $sapiId = 'entity:rdf_entity/' . $uri;
-  $solrHelper = new Helper();
-  /** @var \Drupal\search_api_solr\SolrConnectorInterface $connector */
-  $connector = $entityTypeManager->getStorage('search_api_server')->load('joinup')
-    ->getBackend()
-    ->getSolrConnector();
-  $deleteQuery = $connector
-    ->getUpdateQuery()
-    ->addDeleteQuery('ss_search_api_id:' . $solrHelper->escapePhrase($sapiId))
-    ->addCommit();
-  $connector->update($deleteQuery);
-  \Drupal::database()->delete('search_api_item')
-    ->condition('index_id', ['published', 'unpublished'], 'IN')
-    ->condition('item_id', $sapiId)
-    ->execute();
+  // The 'Explore' block caches is time-based (6h). Explicitly clear the cache.
+  \Drupal::getContainer()->get('cache_tags.invalidator')->invalidateTags(['homepage_explore_block']);
 }
diff --git a/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Access/KillSwitchCheck.php b/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Access/KillSwitchCheck.php
index 5c68df86ad..b7f3a37723 100644
--- a/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Access/KillSwitchCheck.php
+++ b/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Access/KillSwitchCheck.php
@@ -4,7 +4,6 @@
 
 namespace Drupal\joinup_oss_catalogue\Access;
 
-use Drupal\Core\Access\AccessResult;
 use Drupal\Core\Access\AccessResultInterface;
 use Drupal\Core\Routing\Access\AccessInterface;
 use Drupal\Core\Routing\RouteMatchInterface;
@@ -33,7 +32,7 @@ public function access(Route $route, RouteMatchInterface $routeMatch): AccessRes
     if ($requirement !== 'TRUE') {
       throw new \Exception("The _eu_oss_catalogue_check_enabled route requirement when present can only have 'TRUE' as value but '$requirement' was given.");
     }
-    return joinup_oss_catalogue_is_enabled() ? AccessResult::allowed() : AccessResult::forbidden('EU OSS Catalogue functionality is disabled');
+    return joinup_oss_catalogue_feature();
   }
 
 }
diff --git a/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Drush/Commands/JoinupOssCatalogueCommands.php b/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Drush/Commands/JoinupOssCatalogueCommands.php
index 78e167c5de..6c5ca72201 100644
--- a/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Drush/Commands/JoinupOssCatalogueCommands.php
+++ b/web/modules/custom/joinup_communities/joinup_oss_catalogue/src/Drush/Commands/JoinupOssCatalogueCommands.php
@@ -40,7 +40,7 @@ public function __construct(
    */
   #[CLI\Hook(type: HookManager::REPLACE_COMMAND_HOOK, target: 'eu-oss:fetch')]
   public function fetch(string $provider): string {
-    if (joinup_oss_catalogue_is_enabled()) {
+    if (joinup_oss_catalogue_feature()->isAllowed()) {
       $commands = new EuOssCatalogueCommands($this->euOssCatalogueService, $this->providerPluginManager);
       return $commands->fetch($provider);
     }
@@ -52,7 +52,7 @@ public function fetch(string $provider): string {
    */
   #[CLI\Hook(type: HookManager::REPLACE_COMMAND_HOOK, target: 'eu-oss:generate-vitality-index')]
   public function generate(string $nid): string {
-    if (joinup_oss_catalogue_is_enabled()) {
+    if (joinup_oss_catalogue_feature()->isAllowed()) {
       $commands = new EuOssVitalityIndexCommands($this->vitalityIndexGenerator, $this->entityTypeManager);
       return $commands->generate($nid);
     }
diff --git a/web/modules/custom/joinup_core/src/Commands/JoinupDataSanitizationCommands.php b/web/modules/custom/joinup_core/src/Commands/JoinupDataSanitizationCommands.php
index 8734c8dff3..fc64beb5af 100644
--- a/web/modules/custom/joinup_core/src/Commands/JoinupDataSanitizationCommands.php
+++ b/web/modules/custom/joinup_core/src/Commands/JoinupDataSanitizationCommands.php
@@ -47,8 +47,6 @@ public function sanitize($result, CommandData $commandData): void {
     $this->sanitizeLogAlertsSettings();
     $this->sanitizeEmailConfirmerData();
     $this->sanitizeDownloadEventData();
-    // @todo Remove this call in ISAICP-9053.
-    $this->sanitizeEuOssCatalogueSwitcher();
   }
 
   /**
@@ -62,8 +60,6 @@ public function messages(&$messages, InputInterface $input): void {
     $messages[] = dt('Sanitize log alerts settings.');
     $messages[] = dt('Sanitize email confirmer data.');
     $messages[] = dt('Sanitize download event data.');
-    // @todo Remove this message in ISAICP-9053.
-    $messages[] = dt('Sanitize EU OSS Catalogue switcher.');
   }
 
   /**
@@ -183,17 +179,4 @@ protected function sanitizeEntityFieldsData(string $entityType, array $fieldName
     }
   }
 
-  /**
-   * Sanitizes the EU OSS Catalogue switcher.
-   *
-   * @todo Remove this method in ISAICP-9053.
-   */
-  protected function sanitizeEuOssCatalogueSwitcher(): void {
-    $this->db->delete('key_value')
-      ->condition('collection', 'state')
-      ->condition('name', 'joinup.oss_catalogue_is_disabled')
-      ->execute();
-    $this->logger()->success(dt('joinup.oss_catalogue_is_disabled state var sanitized.'));
-  }
-
 }
diff --git a/web/modules/custom/joinup_front_page/src/Plugin/Block/ExploreBlock.php b/web/modules/custom/joinup_front_page/src/Plugin/Block/ExploreBlock.php
index 2a23ee1dca..bd560af3ac 100644
--- a/web/modules/custom/joinup_front_page/src/Plugin/Block/ExploreBlock.php
+++ b/web/modules/custom/joinup_front_page/src/Plugin/Block/ExploreBlock.php
@@ -138,7 +138,7 @@ public function getCacheTags(): array {
     // whenever any of the content types shown in it change. The front page is
     // heavily trafficked and too frequent cache invalidations might affect
     // performance.
-    return [];
+    return ['homepage_explore_block'];
   }
 
   /**
-- 
GitLab