From 629095a2b47b339103275fc1f1587ae352d1fc85 Mon Sep 17 00:00:00 2001
From: qadan
Date: Thu, 9 Jul 2020 13:42:51 -0300
Subject: [PATCH 01/12] first pass at coding standards overhaul
---
.../embargoes_embargo_entity.schema.yml | 8 +-
.../embargoes_ip_range_entity.schema.yml | 11 +-
embargoes.install | 14 +-
embargoes.libraries.yml | 7 -
embargoes.module | 173 +++-----------
embargoes.services.yml | 29 ++-
js/embargoes-file-embargoes.js | 8 -
src/Access/EmbargoedAccessInterface.php | 48 ++++
src/Access/EmbargoedAccessResult.php | 219 ++++++++++++++++++
src/Access/EmbargoedFileAccess.php | 51 ++++
src/Access/EmbargoedMediaAccess.php | 51 ++++
src/Access/EmbargoedNodeAccess.php | 49 ++++
.../EmbargoesIpAccessDeniedController.php | 60 ++++-
src/Controller/EmbargoesLogController.php | 48 +++-
.../EmbargoesNodeEmbargoesController.php | 64 ++++-
src/EmbargoesEmbargoEntityListBuilder.php | 8 +-
src/EmbargoesEmbargoesService.php | 201 ++++++++++++----
src/EmbargoesEmbargoesServiceInterface.php | 144 +++++++++++-
src/EmbargoesIpRangeEntityListBuilder.php | 2 +-
src/EmbargoesIpRangesService.php | 45 +++-
src/EmbargoesIpRangesServiceInterface.php | 40 +++-
src/EmbargoesLogService.php | 22 +-
src/EmbargoesLogServiceInterface.php | 8 +-
src/Entity/EmbargoesEmbargoEntity.php | 131 ++++++++++-
.../EmbargoesEmbargoEntityInterface.php | 151 +++++++++++-
src/Entity/EmbargoesIpRangeEntity.php | 34 ++-
.../EmbargoesIpRangeEntityInterface.php | 52 ++++-
src/Form/EmbargoesEmbargoEntityForm.php | 103 +++++---
src/Form/EmbargoesIpRangeEntityForm.php | 31 ++-
src/Form/EmbargoesNodeEmbargoesForm.php | 140 +++++++----
src/Form/EmbargoesNotificationsForm.php | 147 ++++++------
src/Form/EmbargoesSettingsForm.php | 7 +-
.../Block/EmbargoesEmbargoPoliciesBlock.php | 84 ++++++-
.../Condition/EmbargoesEmbargoedCondition.php | 24 +-
34 files changed, 1742 insertions(+), 472 deletions(-)
delete mode 100644 embargoes.libraries.yml
delete mode 100644 js/embargoes-file-embargoes.js
create mode 100644 src/Access/EmbargoedAccessInterface.php
create mode 100644 src/Access/EmbargoedAccessResult.php
create mode 100644 src/Access/EmbargoedFileAccess.php
create mode 100644 src/Access/EmbargoedMediaAccess.php
create mode 100644 src/Access/EmbargoedNodeAccess.php
diff --git a/config/schema/embargoes_embargo_entity.schema.yml b/config/schema/embargoes_embargo_entity.schema.yml
index bca5cbd..6d2659c 100644
--- a/config/schema/embargoes_embargo_entity.schema.yml
+++ b/config/schema/embargoes_embargo_entity.schema.yml
@@ -17,6 +17,7 @@ embargoes.embargoes_embargo_entity.*:
exempt_ips:
type: string
label: 'Exempt IP Ranges'
+ nullable: true
exempt_users:
type: sequence
label: 'Exempt Users'
@@ -26,8 +27,13 @@ embargoes.embargoes_embargo_entity.*:
target_id:
type: integer
additional_emails:
- type: string
+ type: sequence
label: 'Additional Emails'
+ sequence:
+ type: mapping
+ mapping:
+ additional_email:
+ type: string
embargoed_node:
type: integer
label: 'Embargoed Node'
diff --git a/config/schema/embargoes_ip_range_entity.schema.yml b/config/schema/embargoes_ip_range_entity.schema.yml
index ce296c8..0d9894c 100644
--- a/config/schema/embargoes_ip_range_entity.schema.yml
+++ b/config/schema/embargoes_ip_range_entity.schema.yml
@@ -8,9 +8,14 @@ embargoes.embargoes_ip_range_entity.*:
label:
type: label
label: 'Label'
- range:
- type: string
- label: 'Range'
+ ranges:
+ type: sequence
+ label: 'Ranges'
+ sequence:
+ type: mapping
+ mapping:
+ range:
+ type: string
proxy_url:
type: string
label: 'Proxy URL'
diff --git a/embargoes.install b/embargoes.install
index fc77727..38c2651 100644
--- a/embargoes.install
+++ b/embargoes.install
@@ -1,15 +1,15 @@
'Embargo log table.',
diff --git a/embargoes.libraries.yml b/embargoes.libraries.yml
deleted file mode 100644
index 2316543..0000000
--- a/embargoes.libraries.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-embargoes-file-embargoes:
- version: 1.x
- js:
- js/embargoes-file-embargoes.js: {}
- dependencies:
- - core/jquery
- - core/jquery.once
diff --git a/embargoes.module b/embargoes.module
index 2ba2e54..cfc0be4 100644
--- a/embargoes.module
+++ b/embargoes.module
@@ -1,167 +1,64 @@
id());
- $ip = \Drupal::request()->getClientIp();
- $embargoes = \Drupal::service('embargoes.embargoes')->getActiveNodeEmbargoesByNids($nids, $ip, $account);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($embargoes);
- if (!empty($embargoes) && empty($ip_allowed_embargoes)) {
- $access = \Drupal\Core\Access\AccessResult::forbidden();
- }
- else {
- $access = \Drupal\Core\Access\AccessResult::neutral();
- }
- return $access;
+function embargoes_node_access(NodeInterface $node, $operation, AccountInterface $account) {
+ return \Drupal::service('embargoes.node_access')->isActivelyEmbargoed($node, $account);
}
/**
* Implements hook_ENTITY_TYPE_access().
*/
-function embargoes_media_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account){
- $nids = \Drupal::service('embargoes.embargoes')->getMediaParentNids($entity->id());
- $ip = \Drupal::request()->getClientIp();
- $active_embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids($nids, $ip, $account);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($active_embargoes);
- if (!empty($active_embargoes) && empty($ip_allowed_embargoes)) {
- $access = \Drupal\Core\Access\AccessResult::forbidden();
- }
- else {
- $access = \Drupal\Core\Access\AccessResult::neutral();
- }
- return $access;
+function embargoes_media_access(EntityInterface $media, $operation, AccountInterface $account) {
+ return \Drupal::service('embargoes.media_access')->isActivelyEmbargoed($media, $account);
}
/**
* Implements hook_ENTITY_TYPE_access().
*/
-function embargoes_file_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account){
- $nids = \Drupal::service('embargoes.embargoes')->getParentNidsOfFileEntity($entity);
- $ip = \Drupal::request()->getClientIp();
- $active_embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids($nids, $ip, $account);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($active_embargoes);
- if (!empty($active_embargoes) && empty($ip_allowed_embargoes)) {
- $access = \Drupal\Core\Access\AccessResult::forbidden();
- }
- else {
- $access = \Drupal\Core\Access\AccessResult::neutral();
- }
- return $access;
+function embargoes_file_access(EntityInterface $file, $operation, AccountInterface $account) {
+ return \Drupal::service('embargoes.file_access')->isActivelyEmbargoed($file, $account);
}
/**
* Implements hook_node_view().
*/
-function embargoes_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
- $ip = \Drupal::request()->getClientIp();
- $user = \Drupal::currentUser();
- $path = \Drupal::request()->getRequestUri();
- $active_embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids(array($entity->id()), $ip, $user);
- $active_node_embargoes = \Drupal::service('embargoes.embargoes')->getActiveNodeEmbargoesByNids(array($entity->id()), $ip, $user);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($active_node_embargoes);
- if (!empty($active_node_embargoes)) {
- $build['#attached']['library'][] = 'embargoes/embargoes-file-embargoes';
- }
- if (!empty($active_node_embargoes) && !empty($ip_allowed_embargoes)) {
- $imploded_ranges = implode('.', array_unique($ip_allowed_embargoes));
- $response = new RedirectResponse("/embargoes/ip-access-denied?path={$path}&ranges={$imploded_ranges}");
+function embargoes_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
+ $node_embargo = \Drupal::service('embargoes.node_access');
+ $ip_url = $node_embargo->getIpEmbargoedRedirectUrl($entity);
+ if ($ip_url) {
+ $response = new RedirectResponse($ip_url);
$response->send();
}
- else if ((\Drupal::config('embargoes.settings')->get('show_embargo_message') == FALSE || is_null(\Drupal::config('embargoes.settings')->get('show_embargo_message'))) && $view_mode != 'teaser') {;
- $embargoes = \Drupal::service('embargoes.embargoes')->getCurrentEmbargoesByNids(array($entity->id()));
- if (!empty($embargoes)) {
- $build['#cache']['max-age'] = 0;
- $embargo_count = count($embargoes);
- $embargo_word = ($embargo_count > 1 ? "embargoes" : "embargo" );
- drupal_set_message("This resource is under {$embargo_count} {$embargo_word}:", 'warning');
- foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
- $embargo_message = "- Access to ";
- if ($embargo->getEmbargoTypeAsInt() == 0) {
- $embargo_message .= " all associated files of this resource";
- }
- else {
- $embargo_message .= " this resource and all associated files";
- }
- $embargo_message .= " is restricted";
- if ($embargo->getExemptIps() != 'none') {
- $ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
- $embargo_message .= " to the {$ip_range->label()} network";
- }
- else {
- }
- if ($embargo->getExpirationTypeAsInt() == 0) {
- $embargo_message .= " indefinitely.";
- }
- else {
- $embargo_message .= " until {$embargo->getExpirationDate()}.";
- }
- drupal_set_message($embargo_message, 'warning');
- }
- }
+ else {
+ $node_embargo->setEmbargoMessage($entity);
}
}
/**
* Implements hook_ENTITY_TYPE_view().
*/
-function embargoes_media_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
- $ip = \Drupal::request()->getClientIp();
- $user = \Drupal::currentUser();
- $path = \Drupal::request()->getRequestUri();
- $nids = \Drupal::service('embargoes.embargoes')->getMediaParentNids($entity->id());
- $active_embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids($nids, $ip, $user);
- $active_node_embargoes = \Drupal::service('embargoes.embargoes')->getActiveNodeEmbargoesByNids(array($entity->id()), $ip, $user);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($active_embargoes);
- if (!empty($active_embargoes)) {
- $build['#attached']['library'][] = 'embargoes/embargoes-file-embargoes';
- }
- if (!empty($active_node_embargoes) && !empty($ip_allowed_embargoes)) {
- $imploded_ranges = implode('.', array_unique($ip_allowed_embargoes));
- $response = new RedirectResponse("/embargoes/ip-access-denied?path={$path}&ranges={$imploded_ranges}");
+function embargoes_media_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
+ $media_embargo = \Drupal::service('embargoes.media_access');
+ $ip_url = $media_embargo->getIpEmbargoedRedirectUrl($entity);
+ if ($ip_url) {
+ $response = new RedirectResponse($ip_url);
$response->send();
}
- else if ((\Drupal::config('embargoes.settings')->get('show_embargo_message') == FALSE) || is_null(\Drupal::config('embargoes.settings')->get('show_embargo_message')) && $view_mode != 'teaser') {;
- $embargoes = \Drupal::service('embargoes.embargoes')->getCurrentEmbargoesByNids(array($entity->id()));
- if (!empty($embargoes)) {
- $build['#cache']['max-age'] = 0;
- $embargo_count = count($embargoes);
- $embargo_word = ($embargo_count > 1 ? "embargoes" : "embargo" );
- drupal_set_message("This resource is under {$embargo_count} {$embargo_word}:", 'warning');
- foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
- $embargo_message = "- Access to ";
- if ($embargo->getEmbargoTypeAsInt() == 0) {
- $embargo_message .= " all associated files of this resource";
- }
- else {
- $embargo_message .= " this resource and all associated files";
- }
- $embargo_message .= " is restricted";
- if ($embargo->getExemptIps() != 'none') {
- $ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
- $embargo_message .= " to the {$ip_range->label()} network";
- }
- else {
- }
- if ($embargo->getExpirationTypeAsInt() == 0) {
- $embargo_message .= " indefinitely.";
- }
- else {
- $embargo_message .= " until {$embargo->getExpirationDate()}.";
- }
- drupal_set_message($embargo_message, 'warning');
- }
- }
+ else {
+ $media_embargo->setEmbargoMessage($entity);
}
}
@@ -172,17 +69,11 @@ function embargoes_file_download($uri) {
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties(['uri' => $uri]);
- $file = array_values($files)[0];
- $nids = \Drupal::service('embargoes.embargoes')->getParentNidsOfFileEntity($file);
- $ip = \Drupal::request()->getClientIp();
- $user = \Drupal::currentUser();
- $path = \Drupal::request()->getRequestUri();
- $embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids($nids, $ip, $user);
- $ip_allowed_embargoes = \Drupal::service('embargoes.embargoes')->getIpAllowedEmbargoes($embargoes);
- if (!empty($embargoes) && !empty($ip_allowed_embargoes)) {
- $imploded_ranges = implode('.', array_unique($ip_allowed_embargoes));
- $response = new RedirectResponse("/embargoes/ip-access-denied?path={$path}&ranges={$imploded_ranges}");
+ $file = reset($files);
+ $file_embargo = \Drupal::service('embargoes.file_access');
+ $ip_url = $file_embargo->getIpEmbargoedRedirectUrl($file);
+ if ($ip_url) {
+ $response = new RedirectResponse($ip_url);
$response->send();
}
- return NULL;
}
diff --git a/embargoes.services.yml b/embargoes.services.yml
index 486675f..28a9b31 100644
--- a/embargoes.services.yml
+++ b/embargoes.services.yml
@@ -7,7 +7,32 @@ services:
arguments: ['@database']
embargoes.embargoes:
class: Drupal\embargoes\EmbargoesEmbargoesService
- arguments: []
+ arguments: ['@entity_type.manager', '@entity_field.manager', '@embargoes.ips']
embargoes.ips:
class: Drupal\embargoes\EmbargoesIpRangesService
- arguments: []
+ arguments: ['@entity_type.manager']
+ embargoes.node_access:
+ class: Drupal\embargoes\Access\EmbargoedNodeAccess
+ arguments: ['@embargoes.embargoes', '@request_stack', '@entity_type.manager', '@config.factory', '@messenger', '@string_translation', '@url_generator', '@current_user']
+ embargoes.media_access:
+ class: Drupal\embargoes\Access\EmbargoedMediaAccess
+ arguments:
+ - '@embargoes.embargoes'
+ - '@request_stack'
+ - '@entity_type.manager'
+ - '@config.factory'
+ - '@messenger'
+ - '@string_translation'
+ - '@url_generator'
+ - '@current_user'
+ embargoes.file_access:
+ class: Drupal\embargoes\Access\EmbargoedFileAccess
+ arguments:
+ - '@embargoes.embargoes'
+ - '@request_stack'
+ - '@entity_type.manager'
+ - '@config.factory'
+ - '@messenger'
+ - '@string_translation'
+ - '@url_generator'
+ - '@current_user'
diff --git a/js/embargoes-file-embargoes.js b/js/embargoes-file-embargoes.js
deleted file mode 100644
index c506dbb..0000000
--- a/js/embargoes-file-embargoes.js
+++ /dev/null
@@ -1,8 +0,0 @@
-(function ($, Drupal) {
- Drupal.behaviors.embargoes = {
- attach: function (context, settings) {
- $('div.field--type-file a').css('color', 'lightgray');
- $('div.field--type-file a').attr('title', 'Access to this file is restricted.');
- }
- };
-})(jQuery, Drupal);
diff --git a/src/Access/EmbargoedAccessInterface.php b/src/Access/EmbargoedAccessInterface.php
new file mode 100644
index 0000000..17a3e9c
--- /dev/null
+++ b/src/Access/EmbargoedAccessInterface.php
@@ -0,0 +1,48 @@
+embargoes = $embargoes;
+ $this->request = $request_stack->getCurrentRequest();
+ $this->entityTypeManager = $entity_type_manager;
+ $this->config = $config;
+ $this->messenger = $messenger;
+ $this->translator = $translator;
+ $this->urlGenerator = $url_generator;
+ $this->currentUser = $current_user;
+ }
+
+ /**
+ * Return the type of entity this should apply to.
+ *
+ * @return string
+ * The entity type this access control should apply to.
+ */
+ public static function entityType() {
+ return '';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isActivelyEmbargoed(EntityInterface $entity) {
+ $group_type = $entity->getEntityType()->getGroupType();
+ $expected = static::entityType();
+ if ($group_type !== $expected) {
+ throw new InvalidArgumentException($this->translator->translate('Attempting to check embargoed access status for an entity of type %type (expected: %expected)', [
+ '%type' => $group_type,
+ '%expected' => $expected,
+ ]));
+ }
+ return AccessResult::neutral();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setEmbargoMessage(EntityInterface $entity) {
+ $embargoes = $this->embargoes->getCurrentEmbargoesByNids([$entity->id()]);
+ if ($this->shouldSetEmbargoMessage() && !empty($embargoes)) {
+ // Warnings to pop.
+ $messages = [
+ $this->translator->formatPlural(count($embargoes), 'This resource is under 1 embargo', 'This resource is under @count embargoes'),
+ ];
+ // Pop additional warnings per embargo.
+ foreach ($embargoes as $embargo_id) {
+ $embargo = $this->entityTypeManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
+ if ($embargo) {
+ // Custom built message from three conditions: are nodes or files
+ // embargoed, are networks exempt, and does it expire?
+ $type = $embargo->getEmbargoType();
+ $ip_range = $embargo->getExemptIps() ?
+ $this->entityTypeManager->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps()) :
+ NULL;
+ $expiration = $embargo->getExpirationType();
+ $expiration_date = $expiration ? $embargo->getExpirationDate() : '';
+ $args = [
+ '%date' => $expiration_date,
+ '%ip_range' => $ip_range,
+ ];
+ // Determine a message to set.
+ if (!$type && is_null($ip_range) && !$expiration) {
+ $messages[] = $this->translator->translate('- Access to all associated files of this resource is restricted indefinitely.');
+ }
+ elseif (!$type && is_null($ip_range) && $expiration) {
+ $messages[] = $this->translator->translate('- Access to all associated files of this resource is restricted until %date.', $args);
+ }
+ elseif (!$type && !is_null($ip_range) && !$expiration) {
+ $messages[] = $this->translator->translate('- Access to all associated files of this resource is restricted to the %ip_range network indefinitely.', $args);
+ }
+ elseif (!$type && !is_null($ip_range) && $expiration) {
+ $messages[] = $this->translator->translate('- Access to all associated files of this resource is restricted to the %ip_range network until %date.', $args);
+ }
+ elseif ($type && is_null($ip_range) && !$expiration) {
+ $messages[] = $this->translator->translate('- Access to this resource and all associated resources is restricted indefinitely.');
+ }
+ elseif ($type && is_null($ip_range) && $expiration) {
+ $messages[] = $this->translator->translate('- Access to this resource and all associated resources is restricted until %date.', $args);
+ }
+ elseif ($type && !is_null($ip_range) && !$expiration) {
+ $messages[] = $this->translator->translate('- Access to this resource and all associated resources is restricted to the %ip_range network indefinitely.', $args);
+ }
+ else {
+ $messages[] = $this->translator->translate('- Access to this resource and all associated resources is restricted to the %ip_range network until %date.', $args);
+ }
+ }
+ }
+ foreach ($messages as $message) {
+ $this->messenger->addWarning($message);
+ }
+ }
+ }
+
+ /**
+ * Helper to determine if the embargo message should be set.
+ *
+ * @return bool
+ * TRUE or FALSE depending on whether an embargo message should be set.
+ */
+ protected function shouldSetEmbargoMessage() {
+ $show_embargo_message = $this->config
+ ->get('embargoes.settings')
+ ->get('show_embargo_message');
+ return (bool) $show_embargo_message;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpEmbargoRedirectUrl(EntityInterface $entity) {
+ return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [
+ 'query' => [
+ 'path' => $this->request->getRequestUri(),
+ 'ranges' => [],
+ ],
+ ]);
+ }
+
+}
diff --git a/src/Access/EmbargoedFileAccess.php b/src/Access/EmbargoedFileAccess.php
new file mode 100644
index 0000000..8fba2d9
--- /dev/null
+++ b/src/Access/EmbargoedFileAccess.php
@@ -0,0 +1,51 @@
+currentUser);
+ $parent_nodes = $this->embargoes->getParentNidsOfFileEntity($file);
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $this->currentUser);
+ if (!empty($embargoes) && empty($this->embargoes->getIpAllowedEmbargoes($embargoes))) {
+ $state = AccessResult::forbidden();
+ }
+ return $state;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpEmbargoedRedirectUrl(EntityInterface $file) {
+ $parent_nodes = $this->embargoes->getParentNidsOfFileEntity($file);
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $this->currentUser);
+ $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes);
+ if (!empty($embargoes) && !empty($ip_allowed_embargoes)) {
+ return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [
+ 'query' => [
+ 'path' => $this->request->getRequestUri(),
+ 'ranges' => $ip_allowed_embargoes,
+ ],
+ ]);
+ }
+ return NULL;
+ }
+
+}
diff --git a/src/Access/EmbargoedMediaAccess.php b/src/Access/EmbargoedMediaAccess.php
new file mode 100644
index 0000000..ac95c29
--- /dev/null
+++ b/src/Access/EmbargoedMediaAccess.php
@@ -0,0 +1,51 @@
+currentUser);
+ $parent_nodes = $this->embargoes->getMediaParentNids($media->id());
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $this->currentUser);
+ if (!empty($embargoes) && empty($this->embargoes->getIpAllowedEmbargoes($embargoes))) {
+ $state = AccessResult::forbidden();
+ }
+ return $state;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpEmbargoedRedirectUrl(EntityInterface $media) {
+ $parent_nodes = $this->embargoes->getMediaParentNids($media->id());
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $this->currentUser);
+ $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes);
+ if (!empty($embargoes) && !empty($ip_allowed_embargoes)) {
+ return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [
+ 'query' => [
+ 'path' => $this->request->getRequestUri(),
+ 'ranges' => $ip_allowed_embargoes,
+ ],
+ ]);
+ }
+ return NULL;
+ }
+
+}
diff --git a/src/Access/EmbargoedNodeAccess.php b/src/Access/EmbargoedNodeAccess.php
new file mode 100644
index 0000000..db12788
--- /dev/null
+++ b/src/Access/EmbargoedNodeAccess.php
@@ -0,0 +1,49 @@
+currentUser);
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids([$node->id()], $this->request->getClientIp(), $this->currentUser);
+ if (!empty($embargoes) && empty($this->embargoes->getIpAllowedEmbargoes($embargoes))) {
+ $state = AccessResult::forbidden();
+ }
+ return $state;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpEmbargoedRedirectUrl(EntityInterface $node) {
+ $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids([$node->id()], $this->request->getClientIp(), $this->currentUser);
+ $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes);
+ if (!empty($embargoes) && !empty($ip_allowed_embargoes)) {
+ return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [
+ 'query' => [
+ 'path' => $this->request->getRequestUri(),
+ 'ranges' => $ip_allowed_embargoes,
+ ],
+ ]);
+ }
+ return NULL;
+ }
+
+}
diff --git a/src/Controller/EmbargoesIpAccessDeniedController.php b/src/Controller/EmbargoesIpAccessDeniedController.php
index ed411bb..8b2af19 100644
--- a/src/Controller/EmbargoesIpAccessDeniedController.php
+++ b/src/Controller/EmbargoesIpAccessDeniedController.php
@@ -3,25 +3,69 @@
namespace Drupal\embargoes\Controller;
use Drupal\Core\Controller\ControllerBase;
-use Drupal\Core\Render\Markup;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\Request;
/**
* Class EmbargoesLogController.
*/
class EmbargoesIpAccessDeniedController extends ControllerBase {
+ /**
+ * The HTTP request.
+ *
+ * @var Symfony\Component\HttpFoundation\Request
+ */
+ protected $request;
+
+ /**
+ * Constructs an IP access denied controller.
+ *
+ * @param Symfony\Component\HttpFoundation\Request $request
+ * The current request.
+ */
+ public function __construct(Request $request = NULL) {
+ $this->request = $request;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('request_stack')->getCurrentRequest());
+ }
+
+ /**
+ * Helper function to attempt to get the current request.
+ *
+ * @return string|null
+ * The requested resource, or NULL if there is no current request.
+ */
+ protected function getRequestedResource() {
+ if (!is_null($this->request)) {
+ $path = $this->request->query->get('path');
+ $host = $this->request->getSchemeAndHttpHost();
+ return "{$host}{$path}";
+ }
+ }
+
+ /**
+ * Formats a response for an IP access denied page.
+ *
+ * @return array
+ * Renderable array of markup for IP access denied.
+ */
public function response() {
- $allowed_ranges = explode('.', $_GET['ranges']);
- $host = \Drupal::request()->getSchemeAndHttpHost();
- $path = $_GET['path'];
- $requested_resource = $host . $path;
- $contact_email = \Drupal::config('embargoes.settings')->get('embargo_contact_email');
+ $allowed_ranges = explode('.', $this->request->query->get('ranges'));
+ $requested_resource = $this->getRequestedResource();
+ $contact_email = $this->config('embargoes.settings')->get('embargo_contact_email');
$message = "Your request for the following resource could not be resolved:
{$requested_resource}
";
$message .= "Access to this resource is restricted to the following networks:
";
foreach ($allowed_ranges as $allowed_range) {
- $allowed_range_entity = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($allowed_range);
+ $allowed_range_entity = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($allowed_range);
if ($allowed_range_entity->getProxyUrl() != '') {
$message .= "- {$allowed_range_entity->label()}
";
}
@@ -38,7 +82,7 @@ public function response() {
return [
'#type' => 'markup',
'#markup' => render($message),
- '#cache' => array("max-age" => 0),
+ '#cache' => ["max-age" => 0],
];
}
diff --git a/src/Controller/EmbargoesLogController.php b/src/Controller/EmbargoesLogController.php
index 0e7b90d..202d743 100644
--- a/src/Controller/EmbargoesLogController.php
+++ b/src/Controller/EmbargoesLogController.php
@@ -3,16 +3,44 @@
namespace Drupal\embargoes\Controller;
use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Database\Connection;
use Drupal\Core\Render\Markup;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class EmbargoesLogController.
*/
class EmbargoesLogController extends ControllerBase {
+ /**
+ * Database connection.
+ *
+ * @var Drupal\Core\Database\Connection
+ */
+ protected $connection;
+
+ /**
+ * Constructs an embargo log controller.
+ */
+ public function __construct(Connection $database) {
+ $this->connection = $database;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static($container->get('database'));
+ }
+
+ /**
+ * Creates markup for a log entry.
+ *
+ * @return array
+ * A renderable array of markup representing a log.
+ */
public function showRenderedLog() {
- $database = \Drupal::database();
- $result = $database->getConnection()
+ $result = $this->connection
->select('embargoes_log', 'el')
->fields('el')
->orderBy('el.time', 'DESC')
@@ -21,8 +49,9 @@ public function showRenderedLog() {
$formatted_log = [];
foreach ($result as $record) {
$formatted_time = date('c', $record->time);
- $node_title = \Drupal::entityTypeManager()->getStorage('node')->load($record->node)->get('title')->value;
- $username = \Drupal\user\Entity\User::load($record->uid)->getUsername();
+ $node_title = $this->entityTypeManager()->getStorage('node')->load($record->node)->get('title')->value;
+ $user = $this->entityTypeManager()->getStorage('user')->load($record->uid);
+ $username = $user ? $user->getUsername() : 'Missing User';
if ($record->action == "deleted") {
$embargo_formatted = Markup::create("{$record->embargo}");
}
@@ -36,14 +65,21 @@ public function showRenderedLog() {
'time' => $formatted_time,
'action' => ucfirst($record->action),
'node' => Markup::create("$node_title"),
- 'user' => Markup::create("$username"),
+ 'user' => Markup::create("$username"),
];
array_push($formatted_log, $row);
}
$pre_rendered_log = [
'#type' => 'table',
- '#header' => ['Event ID', 'Embargo ID', 'Time', 'Action', 'Embargoed Node', 'User Responsible'],
+ '#header' => [
+ 'Event ID',
+ 'Embargo ID',
+ 'Time',
+ 'Action',
+ 'Embargoed Node',
+ 'User Responsible',
+ ],
'#rows' => $formatted_log,
];
diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php
index 317de49..1088351 100644
--- a/src/Controller/EmbargoesNodeEmbargoesController.php
+++ b/src/Controller/EmbargoesNodeEmbargoesController.php
@@ -2,18 +2,50 @@
namespace Drupal\embargoes\Controller;
+use Drupal\embargoes\EmbargoesEmbargoesServiceInterface;
+use Drupal\node\NodeInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;
-use Drupal\node\NodeInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class EmbargoesLogController.
*/
class EmbargoesNodeEmbargoesController extends ControllerBase {
+ /**
+ * Embargoes service.
+ *
+ * @var \Drupal\embargoes\EmbargoesEmbargoesServiceInterface
+ */
+ protected $embargoes;
+
+ /**
+ * Constructs an embargoes node controller.
+ *
+ * @param \Drupal\embargoes\EmbargoesEmbargoesServiceInterface $embargoes
+ * Embargoes service.
+ */
+ public function __construct(EmbargoesEmbargoesServiceInterface $embargoes) {
+ $this->embargoes = $embargoes;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static($container->get('embargoes.embargoes'));
+ }
+
+ /**
+ * Gets markup for displaying embargoes on a node.
+ *
+ * @return array
+ * Renderable array to show the embargoes on a node.
+ */
public function showEmbargoes(NodeInterface $node = NULL) {
- $embargo_ids = \Drupal::service('embargoes.embargoes')->getAllEmbargoesByNids(array($node->id()));
+ $embargo_ids = $this->embargoes->getAllEmbargoesByNids([$node->id()]);
if (empty($embargo_ids)) {
$markup['embargoes'] = [
'#type' => 'markup',
@@ -23,11 +55,12 @@ public function showEmbargoes(NodeInterface $node = NULL) {
else {
$rows = [];
foreach ($embargo_ids as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
- if ($embargo->getExpirationType() == 0 ) {
+ if ($embargo->getExpirationType() == 0) {
$expiry = 'Indefinite';
- } else {
+ }
+ else {
$expiry = $embargo->getExpirationDate();
}
@@ -37,17 +70,17 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$formatted_users[] = "None";
}
else {
- foreach ($embargo->getExemptUsers() as $user){
+ foreach ($embargo->getExemptUsers() as $user) {
$uid = $user['target_id'];
- $user_entity = \Drupal\user\Entity\User::load($uid);
- $user_name = $user_entity->getUserName();
+ $user_entity = $this->entityTypeManager()->getStorage('user')->load($uid);
+ $user_name = $user_entity ? $user_entity->getUserName() : 'Missing User';
$formatted_users[] = "{$user_name}";
}
}
$formatted_exempt_users_row = Markup::create(implode("
", $formatted_users));
- if ($embargo->getExemptIps() != 'none') {
- $ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
+ if (!is_null($embargo->getExemptIps())) {
+ $ip_range = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
$ip_range_label = $ip_range->label();
$ip_range_formatted = Markup::create("{$ip_range_label}");
}
@@ -55,7 +88,7 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$ip_range_formatted = "None";
}
- $formatted_emails = Markup::create(str_replace(',', '
', str_replace(' ', '', $embargo->getAdditionalEmails())));
+ $formatted_emails = Markup::create(implode('
', $embargo->getAdditionalEmails()));
$row = [
'type' => ($embargo->getEmbargoType() == 1 ? 'Node' : 'Files'),
@@ -70,7 +103,14 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$markup['embargoes'] = [
'#type' => 'table',
- '#header' => ['Type', 'Expiration Date', 'Exempt IP Range', 'Exempt Users', 'Additional Emails', 'Edit'],
+ '#header' => [
+ 'Type',
+ 'Expiration Date',
+ 'Exempt IP Range',
+ 'Exempt Users',
+ 'Additional Emails',
+ 'Edit',
+ ],
'#rows' => $rows,
];
}
diff --git a/src/EmbargoesEmbargoEntityListBuilder.php b/src/EmbargoesEmbargoEntityListBuilder.php
index 8216b3d..271335b 100644
--- a/src/EmbargoesEmbargoEntityListBuilder.php
+++ b/src/EmbargoesEmbargoEntityListBuilder.php
@@ -2,6 +2,7 @@
namespace Drupal\embargoes;
+use Drupal\user\Entity\User;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\Markup;
@@ -33,9 +34,9 @@ public function buildHeader() {
public function buildRow(EntityInterface $entity) {
$formatted_users = [];
- foreach ($entity->getExemptUsers() as $user){
+ foreach ($entity->getExemptUsers() as $user) {
$uid = $user['target_id'];
- $user_entity = \Drupal\user\Entity\User::load($uid);
+ $user_entity = User::load($uid);
$user_name = $user_entity->getUserName();
$formatted_users[] = "{$user_name}";
@@ -47,7 +48,6 @@ public function buildRow(EntityInterface $entity) {
$node_title = $node->title->value;
$formatted_node_row = Markup::create("{$node_title}");
-
$ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($entity->getExemptIps());
if (!is_null($ip_range)) {
$ip_range_label = $ip_range->label();
@@ -57,7 +57,7 @@ public function buildRow(EntityInterface $entity) {
$ip_range_formatted = "None";
}
- $formatted_emails = Markup::create(str_replace(',', '
', str_replace(' ', '', $entity->getAdditionalEmails())));
+ $formatted_emails = Markup::create(implode('
', $entity->getAdditionalEmails()));
$row['id'] = $entity->id();
$row['embargo_type'] = ($entity->getEmbargoType() == 1 ? 'Node' : 'Files');
diff --git a/src/EmbargoesEmbargoesService.php b/src/EmbargoesEmbargoesService.php
index 4081071..5dd32c9 100644
--- a/src/EmbargoesEmbargoesService.php
+++ b/src/EmbargoesEmbargoesService.php
@@ -2,32 +2,80 @@
namespace Drupal\embargoes;
+use Drupal\file\FileInterface;
+use Drupal\field\Entity\FieldStorageConfig;
+use Drupal\Core\Entity\EntityFieldManagerInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Session\AccountInterface;
+
/**
* Class EmbargoesEmbargoesService.
- */ class EmbargoesEmbargoesService implements EmbargoesEmbargoesServiceInterface {
+ */
+class EmbargoesEmbargoesService implements EmbargoesEmbargoesServiceInterface {
+
+ /**
+ * An entity type manager interface.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityManager;
+
+ /**
+ * An entity field manager.
+ *
+ * @var \Drupal\Core\Entity\EntityFieldManagerInterface
+ */
+ protected $fieldManager;
+
+ /**
+ * An embargo IP ranges service.
+ *
+ * @var \Drupal\embargoes\EmbargoesIpRangesServiceInterface
+ */
+ protected $ipRanges;
/**
* Constructs a new EmbargoesEmbargoesService object.
+ *
+ * @param \Drupal\Core\Entity\EntityTypeManagerInterface $manager
+ * An entity type manager.
+ * @param \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager
+ * An entity field manager.
+ * @param \Drupal\embargoes\EmbargoesIpRangesServiceInterface $ip_ranges
+ * An embargoes IP range service.
*/
- public function __construct() {
+ public function __construct(EntityTypeManagerInterface $manager, EntityFieldManagerInterface $field_manager, EmbargoesIpRangesServiceInterface $ip_ranges) {
+ $this->entityManager = $manager;
+ $this->fieldManager = $field_manager;
+ $this->ipRanges = $ip_ranges;
}
- public function getAllEmbargoesByNids($nids) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getAllEmbargoesByNids(array $nids) {
$all_embargoes = [];
foreach ($nids as $nid) {
- $query = \Drupal::entityQuery('embargoes_embargo_entity')
- ->condition('embargoed_node', $nid);
- $node_embargoes = $query->execute();
+ $node_embargoes = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->getQuery()
+ ->condition('embargoed_node', $nid)
+ ->execute();
$all_embargoes = array_merge($all_embargoes, $node_embargoes);
}
return $all_embargoes;
}
- public function getCurrentEmbargoesByNids($nids) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getCurrentEmbargoesByNids(array $nids) {
$current_embargoes = [];
- $embargoes = \Drupal::service('embargoes.embargoes')->getAllEmbargoesByNids($nids);
+ $embargoes = $this->getAllEmbargoesByNids($nids);
foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
if ($embargo->getExpirationTypeAsInt() == 0) {
$current_embargoes[$embargo_id] = $embargo_id;
}
@@ -42,28 +90,47 @@ public function getCurrentEmbargoesByNids($nids) {
return $current_embargoes;
}
- public function getIpAllowedCurrentEmbargoesByNids($nids) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpAllowedCurrentEmbargoesByNids(array $nids) {
$ip_allowed_current_embargoes = [];
- $embargoes = \Drupal::service('embargoes.embargoes')->getCurrentEmbargoesByNids($nids);
+ $embargoes = $this->getCurrentEmbargoesByNids($nids);
foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
- if ($embargo->getExemptIps() != 'none') {
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
+ if (!is_null($embargo->getExemptIps())) {
$ip_allowed_current_embargoes[$embargo_id] = $embargo_id;
}
}
return $ip_allowed_current_embargoes;
}
-
-
-
- public function getActiveEmbargoesByNids($nids, $ip, $user) {
- $current_user_id = $user->id();
+ /**
+ * Gets embargoes for the given node IDs that apply to the given user.
+ *
+ * @param int[] $nids
+ * The list of node IDs to query against.
+ * @param string $ip
+ * An IP address to test against for these embargoes.
+ * @param \Drupal\Core\Session\AccountInterface $user
+ * The user entity to test embargoes against.
+ *
+ * @return int[]
+ * An associative array mapping any embargoes from the given node IDs that
+ * apply to the user to that same ID. An embargo does not apply to the user
+ * if any of the following conditions are true:
+ * - The embargo is exempted by the given $ip
+ * - The user is in the list of exempt users for the embargo
+ * - The user has the 'bypass embargoes restrictions' permission
+ */
+ public function getActiveEmbargoesByNids(array $nids, $ip, AccountInterface $user) {
$active_embargoes = [];
- $embargoes = \Drupal::service('embargoes.embargoes')->getCurrentEmbargoesByNids($nids);
+ $embargoes = $this->getCurrentEmbargoesByNids($nids);
foreach ($embargoes as $embargo_id) {
- $ip_is_exempt = \Drupal::service('embargoes.embargoes')->isIpInExemptRange($ip, $embargo_id);
- $user_is_exempt = \Drupal::service('embargoes.embargoes')->isUserInExemptUsers($user, $embargo_id);
+ $ip_is_exempt = $this->isIpInExemptRange($ip, $embargo_id);
+ $user_is_exempt = $this->isUserInExemptUsers($user, $embargo_id);
$role_is_exempt = $user->hasPermission('bypass embargoes restrictions');
if (!$ip_is_exempt && !$user_is_exempt && !$role_is_exempt) {
$active_embargoes[$embargo_id] = $embargo_id;
@@ -72,11 +139,16 @@ public function getActiveEmbargoesByNids($nids, $ip, $user) {
return $active_embargoes;
}
- public function getActiveNodeEmbargoesByNids($nids, $ip, $user) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getActiveNodeEmbargoesByNids(array $nids, $ip, AccountInterface $user) {
$active_node_embargoes = [];
- $embargoes = \Drupal::service('embargoes.embargoes')->getActiveEmbargoesByNids($nids, $ip, $user);
+ $embargoes = $this->getActiveEmbargoesByNids($nids, $ip, $user);
foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
if ($embargo->getEmbargoTypeAsInt() == 1) {
$active_node_embargoes[$embargo_id] = $embargo_id;
}
@@ -84,21 +156,29 @@ public function getActiveNodeEmbargoesByNids($nids, $ip, $user) {
return $active_node_embargoes;
}
- public function getIpAllowedEmbargoes($embargoes) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getIpAllowedEmbargoes(array $embargoes) {
$ip_allowed_embargoes = [];
foreach ($embargoes as $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
- if ($embargo->getExemptIps() != 'none') {
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
+ if (!is_null($embargo->getExemptIps())) {
$ip_allowed_embargoes[$embargo_id] = $embargo->getExemptIps();
}
}
return $ip_allowed_embargoes;
}
-
-
- public function isUserInExemptUsers($user, $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ /**
+ * {@inheritdoc}
+ */
+ public function isUserInExemptUsers(AccountInterface $user, $embargo_id) {
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
$exempt_users = $embargo->getExemptUsers();
if (is_null($exempt_users)) {
$user_is_exempt = FALSE;
@@ -118,25 +198,32 @@ public function isUserInExemptUsers($user, $embargo_id) {
return $user_is_exempt;
}
+ /**
+ * {@inheritdoc}
+ */
public function isIpInExemptRange($ip, $embargo_id) {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityManager
+ ->getStorage('embargoes_embargo_entity')
+ ->load($embargo_id);
$range_id = $embargo->getExemptIps();
- if ($range_id == 'none') {
+ if (is_null($range_id)) {
$ip_is_exempt = FALSE;
}
else {
- $ip_is_exempt = \Drupal::service('embargoes.ips')->isIpInRange($ip, $embargo->getExemptIps());
+ $ip_is_exempt = $this->ipRanges->isIpInRange($ip, $range_id);
}
return $ip_is_exempt;
}
+ /**
+ * {@inheritdoc}
+ */
public function getNodeMediaReferenceFields() {
- $efm = \Drupal::service('entity_field.manager');
- $entity_fields = array_keys($efm->getFieldMapByFieldType('entity_reference')['node']);
+ $entity_fields = array_keys($this->fieldManager->getFieldMapByFieldType('entity_reference')['node']);
$media_fields = [];
foreach ($entity_fields as $field) {
if (strpos($field, 'field_') === 0) {
- $field_data = \Drupal\field\Entity\FieldStorageConfig::loadByName('node', $field);
+ $field_data = FieldStorageConfig::loadByName('node', $field);
if ($field_data->getSetting('target_type') == 'media') {
$media_fields[] = $field;
}
@@ -145,15 +232,33 @@ public function getNodeMediaReferenceFields() {
return $media_fields;
}
+ /**
+ * Gets a list of nodes that are the parent of the given media ID.
+ *
+ * @param int $mid
+ * The ID of the media entity to get parents for.
+ *
+ * @return int[]
+ * A list of node IDs that are parents of the given media. A node is a
+ * parent of the given media if either:
+ * - The media implements and has one or more valid values for
+ * field_media_of, or
+ * - Any node implements an entity_reference field that targets media, and
+ * contains a value targeting the given $mid
+ */
public function getMediaParentNids($mid) {
- $media_entity = \Drupal::entityTypeManager()->getStorage('media')->load($mid);
- if ($media_entity->hasField('field_media_of')) {
+ $media_entity = $this->entityManager
+ ->getStorage('media')
+ ->load($mid);
+ if ($media_entity && $media_entity->hasField('field_media_of')) {
$nid = $media_entity->get('field_media_of')->getString();
- $nids = array($nid);
- }
+ $nids = [$nid];
+ }
else {
- $media_fields = \Drupal::service('embargoes.embargoes')->getNodeMediaReferenceFields();
- $query = \Drupal::entityQuery('node');
+ $media_fields = $this->getNodeMediaReferenceFields();
+ $query = $this->entityManager
+ ->getStorage('node')
+ ->getQuery();
$group = $query->orConditionGroup();
foreach ($media_fields as $field) {
$group->condition($field, $mid);
@@ -164,7 +269,10 @@ public function getMediaParentNids($mid) {
return $nids;
}
- public function getParentNidsOfFileEntity($file) {
+ /**
+ * {@inheritdoc}
+ */
+ public function getParentNidsOfFileEntity(FileInterface $file) {
$relationships = file_get_file_references($file);
if (!$relationships) {
$nids = [];
@@ -178,11 +286,12 @@ public function getParentNidsOfFileEntity($file) {
foreach ($relationship as $key => $value) {
switch ($key) {
case 'node':
- $nids = array(array_keys($value)[0]);
+ $nids = [array_keys($value)[0]];
break;
+
case 'media':
$mid = array_keys($value)[0];
- $nids = \Drupal::service('embargoes.embargoes')->getMediaParentNids($mid);
+ $nids = $this->getMediaParentNids($mid);
break;
}
}
diff --git a/src/EmbargoesEmbargoesServiceInterface.php b/src/EmbargoesEmbargoesServiceInterface.php
index 066ae52..6d76a03 100644
--- a/src/EmbargoesEmbargoesServiceInterface.php
+++ b/src/EmbargoesEmbargoesServiceInterface.php
@@ -2,21 +2,149 @@
namespace Drupal\embargoes;
+use Drupal\file\FileInterface;
+use Drupal\Core\Session\AccountInterface;
+
/**
* Interface EmbargoesEmbargoesServiceInterface.
*/
interface EmbargoesEmbargoesServiceInterface {
- public function getAllEmbargoesByNids($nids);
- public function getCurrentEmbargoesByNids($nids);
- public function getIpAllowedCurrentEmbargoesByNids($nids);
- public function getActiveEmbargoesByNids($nids, $ip, $user);
- public function getActiveNodeEmbargoesByNids($nids, $ip, $user);
- public function getIpAllowedEmbargoes($embargoes);
- public function isUserInExemptUsers($user, $embargo_id);
+ /**
+ * Gets a list of all embargoes that apply to the given node IDs.
+ *
+ * @param int[] $nids
+ * The list of node IDs to get embargoes for.
+ *
+ * @return int[]
+ * An array of embargo entity IDs for the given nodes.
+ */
+ public function getAllEmbargoesByNids(array $nids);
+
+ /**
+ * Gets a list of unexpired embargoes that apply to the given node IDs.
+ *
+ * @param int[] $nids
+ * The list of node IDs to get active embargoes for.
+ *
+ * @return int[]
+ * An array of active embargo entity IDs for the given nodes.
+ */
+ public function getCurrentEmbargoesByNids(array $nids);
+
+ /**
+ * Gets embargoes for the given node IDs that have attached IP ranges.
+ *
+ * @param int[] $nids
+ * The list of node IDs to get IP-allowed embargoes for.
+ *
+ * @return int[]
+ * An array of embargoes applied to the given node IDs that have attached
+ * IP ranges.
+ */
+ public function getIpAllowedCurrentEmbargoesByNids(array $nids);
+
+ /**
+ * Gets embargoes for the given node IDs that apply to the given user.
+ *
+ * @param int[] $nids
+ * The list of node IDs to query against.
+ * @param string $ip
+ * An IP address to test against for these embargoes.
+ * @param \Drupal\Core\Session\AccountInterface $user
+ * The user entity to test embargoes against.
+ *
+ * @return int[]
+ * An associative array mapping any embargoes from the given node IDs that
+ * apply to the user to that same node ID.
+ */
+ public function getActiveEmbargoesByNids(array $nids, $ip, AccountInterface $user);
+
+ /**
+ * Gets node-level embargoes for the given node IDs that apply to the user.
+ *
+ * @param int[] $nids
+ * The list of node IDs to query against.
+ * @param string $ip
+ * An IP address to test against for these embargoes.
+ * @param \Drupal\Core\Session\AccountInterface $user
+ * The user entity to test embargoes against.
+ *
+ * @return int[]
+ * An associative array mapping any embargoes from the given node IDs that
+ * apply to the user to that same node ID, filtered to only include
+ * embargoes that apply to the node itself.
+ */
+ public function getActiveNodeEmbargoesByNids(array $nids, $ip, AccountInterface $user);
+
+ /**
+ * Filters and returns exempt IP ranges for the given embargo IDs.
+ *
+ * @param int[] $embargoes
+ * A list of embargo entity IDs to check IP ranges for.
+ *
+ * @return string[]
+ * An associative array containing any $embargoes that have a configured
+ * exempt IP range, paired with the ID for that exempt IP range.
+ */
+ public function getIpAllowedEmbargoes(array $embargoes);
+
+ /**
+ * Determines whether a given $user is in the exemption list for an embargo.
+ *
+ * @param \Drupal\Core\Session\AccountInterface $user
+ * The user entity to test against.
+ * @param int $embargo_id
+ * The embargo to check the list of exempt users for.
+ *
+ * @return bool
+ * TRUE or FALSE, depending on whether or not the given user is in the list
+ * of exempt users for the given embargo.
+ */
+ public function isUserInExemptUsers(AccountInterface $user, $embargo_id);
+
+ /**
+ * Determines whether an IP address is in the exemption range for an embargo.
+ *
+ * @param string $ip
+ * An IP address to check against.
+ * @param int $embargo_id
+ * The embargo to check IP exemptions for.
+ *
+ * @return bool
+ * TRUE or FALSE, depending on whether or not the given IP address falls
+ * within the exemption range for the given embargo.
+ */
public function isIpInExemptRange($ip, $embargo_id);
+
+ /**
+ * Gets a list of entity_reference fields that target media.
+ *
+ * @return \Drupal\Core\Entity\EntityInterface
+ * A list of entity_reference fields that target media entities.
+ */
public function getNodeMediaReferenceFields();
+
+ /**
+ * Gets a list of nodes that are the parent of the given media ID.
+ *
+ * @param int $mid
+ * The ID of the media entity to get parents for.
+ *
+ * @return int[]
+ * A list of node IDs that are parents of the given media.
+ */
public function getMediaParentNids($mid);
- public function getParentNidsOfFileEntity($file);
+
+ /**
+ * Gets a list of parent node IDs for the given file entity.
+ *
+ * @param \Drupal\file\FileInterface $file
+ * The file entity to get parent node IDs for.
+ *
+ * @return int[]
+ * An array of node IDs that are parents of the given file.
+ */
+ public function getParentNidsOfFileEntity(FileInterface $file);
}
diff --git a/src/EmbargoesIpRangeEntityListBuilder.php b/src/EmbargoesIpRangeEntityListBuilder.php
index 6f7a218..af712f5 100644
--- a/src/EmbargoesIpRangeEntityListBuilder.php
+++ b/src/EmbargoesIpRangeEntityListBuilder.php
@@ -28,7 +28,7 @@ public function buildHeader() {
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['id'] = $entity->id();
- $row['range'] = Markup::create(str_replace('|', '
', $entity->getRange()));
+ $row['range'] = Markup::create(implode('
', $entity->getRanges()));
$row['proxy_url'] = $entity->getProxyUrl();
return $row + parent::buildRow($entity);
}
diff --git a/src/EmbargoesIpRangesService.php b/src/EmbargoesIpRangesService.php
index 9144734..0a1d5bb 100644
--- a/src/EmbargoesIpRangesService.php
+++ b/src/EmbargoesIpRangesService.php
@@ -2,20 +2,35 @@
namespace Drupal\embargoes;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+
/**
* Class EmbargoesIpRangesService.
*/
class EmbargoesIpRangesService implements EmbargoesIpRangesServiceInterface {
/**
- * Constructs a new EmbargoesIpRangesService object.
+ * IP range entity storage instance.
+ *
+ * @var \Drupal\Core\Entity\EntityStorageInterface
*/
- public function __construct() {
+ protected $rangeStorage;
+ /**
+ * Constructs a new EmbargoesIpRangesService object.
+ *
+ * @param \Drupal\Core\Entity\EntityTypeManagerInterface $manager
+ * EntityTypeManager interface.
+ */
+ public function __construct(EntityTypeManagerInterface $manager) {
+ $this->rangeStorage = $manager->getStorage('embargoes_ip_range_entity');
}
+ /**
+ * {@inheritdoc}
+ */
public function getIpRanges() {
- $ip_range_entities = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->loadMultiple();
+ $ip_range_entities = $this->rangeStorage->loadMultiple();
$ips = [];
foreach ($ip_range_entities as $ip) {
$ips[$ip->id()] = $ip->label();
@@ -23,19 +38,24 @@ public function getIpRanges() {
return $ips;
}
+ /**
+ * {@inheritdoc}
+ */
public function getIpRangesAsSelectOptions() {
- $ip_range_entities = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->loadMultiple();
+ $ip_range_entities = $this->rangeStorage->loadMultiple();
$ips = [];
- $ips['none'] = 'None';
+ $ips[NULL] = 'None';
foreach ($ip_range_entities as $ip) {
$ips[$ip->id()] = $ip->label();
}
return $ips;
}
- public function detectIpRangeStringErrors($string) {
+ /**
+ * {@inheritdoc}
+ */
+ public function detectIpRangeStringErrors(array $ranges) {
$errors = [];
- $ranges = explode('|', trim($string));
foreach ($ranges as $range) {
$range_array = explode("/", trim($range));
if (count($range_array) != 2) {
@@ -44,7 +64,7 @@ public function detectIpRangeStringErrors($string) {
else {
$nets = explode('.', $range_array[0]);
foreach ($nets as $net) {
- if ((intval($net) == 0 && $net != '0' ) || intval($net) > 255) {
+ if ((intval($net) == 0 && $net != '0') || intval($net) > 255) {
$errors[] = "Invalid net '{$net}' in {$range}";
}
}
@@ -57,12 +77,14 @@ public function detectIpRangeStringErrors($string) {
return $errors;
}
+ /**
+ * {@inheritdoc}
+ */
public function isIpInRange($ip, $range_name) {
if ($range_name != 'none') {
- $range_string = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($range_name)->getRange();
+ $ranges = $this->rangeStorage->load($range_name)->getRanges();
$response = FALSE;
- if (!\Drupal::service('embargoes.ips')->detectIpRangeStringErrors($range_string)) {
- $ranges = explode('|', trim($range_string));
+ if (!$this->detectIpRangeStringErrors($ranges)) {
foreach ($ranges as $range) {
list($net, $mask) = explode("/", trim($range));
$ip_net = ip2long($net);
@@ -77,4 +99,5 @@ public function isIpInRange($ip, $range_name) {
}
return $response;
}
+
}
diff --git a/src/EmbargoesIpRangesServiceInterface.php b/src/EmbargoesIpRangesServiceInterface.php
index dff29a2..7eb59ff 100644
--- a/src/EmbargoesIpRangesServiceInterface.php
+++ b/src/EmbargoesIpRangesServiceInterface.php
@@ -7,9 +7,47 @@
*/
interface EmbargoesIpRangesServiceInterface {
+ /**
+ * Gets the list of IP range entities.
+ *
+ * @return string[]
+ * An associative array of IP ranges, pairing IDs with labels.
+ */
public function getIpRanges();
+
+ /**
+ * Gets the list of IP range entities as form options.
+ *
+ * @return string[]
+ * An associative array of IP ranges, pairing IDs with labels, including a
+ * NULL option associated with the string 'None'.
+ */
public function getIpRangesAsSelectOptions();
- public function detectIpRangeStringErrors($string);
+
+ /**
+ * Helper to detect errors in IP range strings.
+ *
+ * @param string[] $ranges
+ * A list of IP range strings to check.
+ *
+ * @return string[]
+ * A list of errors detected. If the return array is empty, no errors were
+ * detected.
+ */
+ public function detectIpRangeStringErrors(array $ranges);
+
+ /**
+ * Helper to detect if an IP address is in range of a particular IP range.
+ *
+ * @param string $ip
+ * The IP address to check.
+ * @param string $range_name
+ * The name of the IP range to check the address against.
+ *
+ * @return bool
+ * TRUE/FALSE depending on whether or not the given IP address falls in the
+ * given range.
+ */
public function isIpInRange($ip, $range_name);
}
diff --git a/src/EmbargoesLogService.php b/src/EmbargoesLogService.php
index cef6286..c471476 100644
--- a/src/EmbargoesLogService.php
+++ b/src/EmbargoesLogService.php
@@ -10,20 +10,36 @@
class EmbargoesLogService implements EmbargoesLogServiceInterface {
/**
- * @var \Drupal\Core\Database\Connection $database
- *
* Database connection.
+ *
+ * @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructs a new EmbargoesLogService object.
+ *
+ * @param \Drupal\Core\Database\Connection $connection
+ * A database connection object.
*/
public function __construct(Connection $connection) {
$this->database = $connection;
}
- public function logEmbargoEvent($values) {
+ /**
+ * Logs an embargo event in the embargoes_log table.
+ *
+ * @param array $values
+ * An associative array pairing columns in the new log with the values that
+ * should be placed in that new log. The 'time' parameter will be generated
+ * and is overwritten if provided. Other than that the following must be
+ * provided:
+ * - 'action': Either 'created' or 'updated'.
+ * - 'node': The node ID this embargo event applied to.
+ * - 'embargo': The ID of the embargo associated with this event.
+ * - 'uid': The ID of the user that instantiated this event.
+ */
+ public function logEmbargoEvent(array $values) {
$values['time'] = time();
return $this->database->insert('embargoes_log')
->fields($values)
diff --git a/src/EmbargoesLogServiceInterface.php b/src/EmbargoesLogServiceInterface.php
index 1176878..614709f 100644
--- a/src/EmbargoesLogServiceInterface.php
+++ b/src/EmbargoesLogServiceInterface.php
@@ -7,6 +7,12 @@
*/
interface EmbargoesLogServiceInterface {
- public function logEmbargoEvent($values);
+ /**
+ * Logs an embargo event.
+ *
+ * @param array $values
+ * Associative array of keys and values that should be applied to the log.
+ */
+ public function logEmbargoEvent(array $values);
}
diff --git a/src/Entity/EmbargoesEmbargoEntity.php b/src/Entity/EmbargoesEmbargoEntity.php
index 175b816..78079e6 100644
--- a/src/Entity/EmbargoesEmbargoEntity.php
+++ b/src/Entity/EmbargoesEmbargoEntity.php
@@ -2,6 +2,7 @@
namespace Drupal\embargoes\Entity;
+use Drupal\user\Entity\User;
use Drupal\Core\Config\Entity\ConfigEntityBase;
/**
@@ -46,22 +47,72 @@ class EmbargoesEmbargoEntity extends ConfigEntityBase implements EmbargoesEmbarg
*/
protected $id;
+ /**
+ * The type of embargo.
+ *
+ * @var bool
+ */
protected $embargo_type;
+ /**
+ * The type of expiration.
+ *
+ * @var bool
+ */
protected $expiration_type;
+ /**
+ * The date of expiration for a scheduled embargo.
+ *
+ * @var string
+ */
protected $expiration_date;
- protected $exempt_ips = [];
+ /**
+ * The ID of a configured IP exemption range, or NULL.
+ *
+ * @var string|null
+ */
+ protected $exempt_ips;
+ /**
+ * An array of user UIDs exempt from the embargo.
+ *
+ * @var int[]
+ */
protected $exempt_users = [];
+ /**
+ * An array of email addresses to be notified in regards to the embargo.
+ *
+ * @var string[]
+ */
protected $additional_emails = [];
+ /**
+ * The ID of the node this embargo applies to.
+ *
+ * @var int
+ */
protected $embargoed_node;
+ /**
+ * The current notification status of the embargo.
+ *
+ * Either 'created', 'updated', 'warned', or 'expired'.
+ *
+ * @var string
+ */
protected $notification_status;
+ /**
+ * Constructor function.
+ *
+ * @param array $values
+ * Associative array of parameters to apply to this entity.
+ * @param string $entity_type
+ * The type of entity.
+ */
public function __construct(array $values, $entity_type) {
$uuid = \Drupal::service('uuid')->generate();
$checksummed_uuid = sha1($uuid);
@@ -70,75 +121,117 @@ public function __construct(array $values, $entity_type) {
parent::__construct($values, $entity_type);
}
+ /**
+ * {@inheritdoc}
+ */
public function save() {
parent::save();
drupal_flush_all_caches();
}
+ /**
+ * {@inheritdoc}
+ */
public function delete() {
parent::delete();
drupal_flush_all_caches();
}
+ /**
+ * {@inheritdoc}
+ */
public function getEmbargoType() {
return $this->get('embargo_type');
}
+ /**
+ * {@inheritdoc}
+ */
public function getEmbargoTypeAsInt() {
return intval($this->get('embargo_type'));
}
- public function setEmbargoType($type){
+ /**
+ * {@inheritdoc}
+ */
+ public function setEmbargoType($type) {
$this->set('embargo_type', $type);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getExpirationType() {
return $this->get('expiration_type');
}
+ /**
+ * {@inheritdoc}
+ */
public function getExpirationTypeAsInt() {
return intval($this->get('expiration_type'));
}
- public function setExpirationType($type){
+ /**
+ * {@inheritdoc}
+ */
+ public function setExpirationType($type) {
$this->set('expiration_type', $type);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getExpirationDate() {
return $this->get('expiration_date');
}
- public function setExpirationDate($date){
+ /**
+ * {@inheritdoc}
+ */
+ public function setExpirationDate($date) {
$this->set('expiration_date', $date);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getExemptIps() {
return $this->get('exempt_ips');
}
+ /**
+ * {@inheritdoc}
+ */
public function setExemptIps($range) {
- if (!$range) {
- $range = [];
- }
$this->set('exempt_ips', $range);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getExemptUsers() {
return $this->get('exempt_users');
}
+ /**
+ * {@inheritdoc}
+ */
public function getExemptUsersEntities() {
$exempt_user_entities = [];
foreach ($this->getExemptUsers() as $user) {
- $exempt_user_entities[] = \Drupal\user\Entity\User::load($user['target_id']);
+ $exempt_user_entities[] = User::load($user['target_id']);
}
return $exempt_user_entities;
}
+ /**
+ * {@inheritdoc}
+ */
public function setExemptUsers($users) {
if (!$users) {
$users = [];
@@ -147,31 +240,47 @@ public function setExemptUsers($users) {
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getAdditionalEmails() {
return $this->get('additional_emails');
}
+ /**
+ * {@inheritdoc}
+ */
public function setAdditionalEmails($emails) {
- if (!$emails) {
- $emails = [];
- }
+ $emails = array_map('trim', explode(',', trim($emails)));
$this->set('additional_emails', $emails);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getEmbargoedNode() {
return $this->get('embargoed_node');
}
+ /**
+ * {@inheritdoc}
+ */
public function setEmbargoedNode($node) {
$this->set('embargoed_node', $node);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getNotificationStatus() {
return $this->get('notification_status');
}
+ /**
+ * {@inheritdoc}
+ */
public function setNotificationStatus($status) {
$this->set('notification_status', $status);
return $this;
diff --git a/src/Entity/EmbargoesEmbargoEntityInterface.php b/src/Entity/EmbargoesEmbargoEntityInterface.php
index 559ae9a..0a5054b 100644
--- a/src/Entity/EmbargoesEmbargoEntityInterface.php
+++ b/src/Entity/EmbargoesEmbargoEntityInterface.php
@@ -9,31 +9,180 @@
*/
interface EmbargoesEmbargoEntityInterface extends ConfigEntityInterface {
+ /**
+ * Returns the type of embargo.
+ *
+ * @return bool
+ * Either FALSE for a file-level embargo or TRUE for a node-level embargo.
+ */
public function getEmbargoType();
+
+ /**
+ * Casts the type of embargo to an integer.
+ *
+ * @return int
+ * Either 0 for a file-level embargo or 1 for a node-level embargo.
+ */
public function getEmbargoTypeAsInt();
+
+ /**
+ * Sets the embargo type.
+ *
+ * @param bool $type
+ * Either FALSE for an indefinite embargo or TRUE for a node-level embargo.
+ *
+ * @return bool
+ * The newly-set embargo type.
+ */
public function setEmbargoType($type);
+ /**
+ * Gets the type of expiration.
+ *
+ * @return bool
+ * Either FALSE for an indefinite embargo or TRUE for a scheduled embargo.
+ */
public function getExpirationType();
+
+ /**
+ * Gets the type of expiration as an integer.
+ *
+ * @return int
+ * Either 0 for an indefinite embargo or 1 for a scheduled embargo.
+ */
public function getExpirationTypeAsInt();
+
+ /**
+ * Sets the expiration type.
+ *
+ * @param bool $type
+ * Either FALSE for an indefinite embargo or TRUE for a scheduled embargo.
+ *
+ * @return bool
+ * The newly-set expiration type.
+ */
public function setExpirationType($type);
+ /**
+ * Gets the date of expiration for a scheduled embargo.
+ *
+ * @return string
+ * An ISO-8601 timestamp.
+ */
public function getExpirationDate();
+
+ /**
+ * Sets the date of expiration for a scheduled embargo.
+ *
+ * @param string $date
+ * An ISO-8601 timestamp.
+ *
+ * @return string
+ * The newly-set timestamp.
+ */
public function setExpirationDate($date);
+ /**
+ * Gets the machine name for the exempt IP range.
+ *
+ * @return string|null
+ * The ID for a configured exempt IP range, or NULL.
+ */
public function getExemptIps();
+
+ /**
+ * Sets the exempt IP range machine name.
+ *
+ * @param string|null $range
+ * The machine name for a configured exempt IP range, or NULL.
+ */
public function setExemptIps($range);
+ /**
+ * Gets the list of exempt users.
+ *
+ * @return int[]
+ * A list of user IDs exempt from the embargo.
+ */
public function getExemptUsers();
+
+ /**
+ * Gets the list of exempt users as user entities.
+ *
+ * @return \Drupal\user\Entity\User[]
+ * A list of user entities exempt from the embargo.
+ */
public function getExemptUsersEntities();
- public function setExemptUsers($user);
+ /**
+ * Sets the list of users exempt from this embargo.
+ *
+ * @param array|bool $users
+ * A list of user IDs exempt from this embargo, or FALSE to set an empty
+ * list.
+ *
+ * @return array
+ * The newly-set users array.
+ */
+ public function setExemptUsers($users);
+
+ /**
+ * Get the ID of the embargoed node this embargo applies to.
+ *
+ * @return int
+ * The ID of the embargoed node this embargo applies to.
+ */
public function getEmbargoedNode();
+
+ /**
+ * Sets the ID of the node this embargo applies to.
+ *
+ * @param int $node
+ * The ID of the node this embargo applies to.
+ *
+ * @return int
+ * The ID of the node this embargo was set to apply to.
+ */
public function setEmbargoedNode($node);
+ /**
+ * An array of email addresses to be notified in regards to the embargo.
+ *
+ * @return string[]
+ * An array of email addresses.
+ */
public function getAdditionalEmails();
+
+ /**
+ * Sets the list of email addresses to be notified in regards to the embargo.
+ *
+ * @param string $emails
+ * A list of email addresses to be notified in regards to the embargo.
+ *
+ * @return string[]
+ * The list of email addresses, parsed into an array.
+ */
public function setAdditionalEmails($emails);
+ /**
+ * Gets the current notification status of the embargo.
+ *
+ * @return string
+ * The current notification status of the embargo - one of either 'created',
+ * 'updated', 'warned', or 'expired'.
+ */
public function getNotificationStatus();
+
+ /**
+ * Sets the current notification status of the embargo.
+ *
+ * @param string $status
+ * The current notification status of the embargo - one of either 'created',
+ * 'updated', 'warned', or 'expired'.
+ *
+ * @return string
+ * The new notification status.
+ */
public function setNotificationStatus($status);
}
diff --git a/src/Entity/EmbargoesIpRangeEntity.php b/src/Entity/EmbargoesIpRangeEntity.php
index 95954e3..1bb9c89 100644
--- a/src/Entity/EmbargoesIpRangeEntity.php
+++ b/src/Entity/EmbargoesIpRangeEntity.php
@@ -55,11 +55,11 @@ class EmbargoesIpRangeEntity extends ConfigEntityBase implements EmbargoesIpRang
protected $label;
/**
- * The IP Range range.
+ * The IP Range ranges.
*
- * @var string
+ * @var string[]
*/
- protected $range;
+ protected $ranges;
/**
* The IP Range proxy URL.
@@ -68,31 +68,49 @@ class EmbargoesIpRangeEntity extends ConfigEntityBase implements EmbargoesIpRang
*/
protected $proxy_url;
+ /**
+ * {@inheritdoc}
+ */
public function id() {
return $this->get('id');
}
+ /**
+ * {@inheritdoc}
+ */
public function label() {
return $this->get('label');
}
- public function getRange() {
- return $this->get('range');
+ /**
+ * {@inheritdoc}
+ */
+ public function getRanges() {
+ return $this->get('ranges');
}
- public function setRange($range) {
- $this->set('range', $range);
+ /**
+ * {@inheritdoc}
+ */
+ public function setRanges($ranges) {
+ $ranges = array_map('trim', explode('|', trim($ranges)));
+ $this->set('ranges', $ranges);
return $this;
}
+ /**
+ * {@inheritdoc}
+ */
public function getProxyUrl() {
return $this->get('proxy_url');
}
+ /**
+ * {@inheritdoc}
+ */
public function setProxyUrl($proxy_url) {
$this->set('proxy_url', $proxy_url);
return $this;
}
-
}
diff --git a/src/Entity/EmbargoesIpRangeEntityInterface.php b/src/Entity/EmbargoesIpRangeEntityInterface.php
index 23c13a6..21f4e90 100644
--- a/src/Entity/EmbargoesIpRangeEntityInterface.php
+++ b/src/Entity/EmbargoesIpRangeEntityInterface.php
@@ -9,12 +9,60 @@
*/
interface EmbargoesIpRangeEntityInterface extends ConfigEntityInterface {
+ /**
+ * Gets the ID of this IP range.
+ *
+ * @return string
+ * The unique identifier of this IP range.
+ */
public function id();
+
+ /**
+ * Gets the label used for this IP range.
+ *
+ * @return string
+ * The label to be used for this IP range.
+ */
public function label();
- public function getRange();
- public function setRange($range);
+ /**
+ * Gets the list of IP ranges inclusive in this range.
+ *
+ * @return string[]
+ * An array of CIDR IP ranges.
+ */
+ public function getRanges();
+
+ /**
+ * Sets the list of IP ranges inclusive in this range.
+ *
+ * @param string $ranges
+ * String representing the list of ranges to apply.
+ *
+ * @return array
+ * The list of ranges, parsed into an array.
+ */
+ public function setRanges($ranges);
+ /**
+ * Gets the proxy URL for this IP range.
+ *
+ * @return string
+ * A URL to use as a proxy for this range, to refer users to a location
+ * representative of the network blocked by this range.
+ */
public function getProxyUrl();
+
+ /**
+ * Sets the proxy URL for this IP range.
+ *
+ * @param string $proxy_url
+ * A URL to use as a proxy for this range, to refer users to a location
+ * representative of the network blocked by this range.
+ *
+ * @return string
+ * The newly-set proxy URL.
+ */
public function setProxyUrl($proxy_url);
+
}
diff --git a/src/Form/EmbargoesEmbargoEntityForm.php b/src/Form/EmbargoesEmbargoEntityForm.php
index ff73101..c42b05b 100644
--- a/src/Form/EmbargoesEmbargoEntityForm.php
+++ b/src/Form/EmbargoesEmbargoEntityForm.php
@@ -2,14 +2,53 @@
namespace Drupal\embargoes\Form;
+use Drupal\embargoes\EmbargoesIpRangesServiceInterface;
+use Drupal\embargoes\EmbargoesLogServiceInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class EmbargoesEmbargoEntityForm.
*/
class EmbargoesEmbargoEntityForm extends EntityForm {
+ /**
+ * An embargoes IP ranges manager.
+ *
+ * @var \Drupal\embargoes\EmbargoesIpRangesServiceInterface
+ */
+ protected $ipRanges;
+
+ /**
+ * An embargoes logging service.
+ *
+ * @var \Drupal\embargoes\EmbargoesLogServiceInterface
+ */
+ protected $embargoesLog;
+
+ /**
+ * Constructor for the node embargo form.
+ *
+ * @param \Drupal\embargoes\EmbargoesIpRangesServiceInterface $ip_ranges
+ * An embargoes IP ranges manager.
+ * @param \Drupal\embargoes\EmbargoesLogServiceInterface $embargoes_log
+ * An embargoes logging service.
+ */
+ public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log) {
+ $this->ipRanges = $ip_ranges;
+ $this->embargoesLog = $embargoes_log;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('embargoes.ips'),
+ $container->get('embargoes.log'));
+ }
+
/**
* {@inheritdoc}
*/
@@ -17,30 +56,30 @@ public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$embargo = $this->entity;
- $form['embargo_type'] = array(
+ $form['embargo_type'] = [
'#type' => 'radios',
'#title' => $this->t('Embargo type'),
'#default_value' => $embargo->getEmbargoTypeAsInt(),
'#options' => [
- '0' => t('Files'),
- '1' => t('Node'),
+ '0' => $this->t('Files'),
+ '1' => $this->t('Node'),
],
- );
+ ];
- $form['expiration_type'] = array(
+ $form['expiration_type'] = [
'#type' => 'radios',
'#title' => $this->t('Expiration type'),
'#default_value' => $embargo->getExpirationTypeAsInt(),
'#options' => [
- '0' => t('Indefinite'),
- '1' => t('Scheduled'),
+ '0' => $this->t('Indefinite'),
+ '1' => $this->t('Scheduled'),
],
'#attributes' => [
'name' => 'expiry_type',
],
- );
+ ];
- $form['expiration_date'] = array(
+ $form['expiration_date'] = [
'#type' => 'date',
'#title' => $this->t('Expiration date'),
'#default_value' => $embargo->getExpirationDate(),
@@ -52,16 +91,16 @@ public function form(array $form, FormStateInterface $form_state) {
':input[name="expiry_type"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['exempt_ips'] = array(
+ $form['exempt_ips'] = [
'#type' => 'select',
'#title' => $this->t('Exempt IP ranges'),
- '#options' => \Drupal::service('embargoes.ips')->getIpRangesAsSelectOptions(),
- '#default_value' => ( !is_null($embargo->getExemptIps()) ? $embargo->getExemptIps() : 'none' ),
- );
+ '#options' => $this->ipRanges->getIpRangesAsSelectOptions(),
+ '#default_value' => (!is_null($embargo->getExemptIps()) ? $embargo->getExemptIps() : NULL),
+ ];
- $form['exempt_users'] = array(
+ $form['exempt_users'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#title' => $this->t('Exempt users'),
@@ -70,36 +109,36 @@ public function form(array $form, FormStateInterface $form_state) {
'#selection_settings' => [
'include_anonymous' => FALSE,
],
- );
+ ];
- $form['additional_emails'] = array(
+ $form['additional_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Additional Emails'),
- '#default_value' => $embargo->getAdditionalEmails(),
- );
+ '#default_value' => implode(',', $embargo->getAdditionalEmails()),
+ ];
$embargoed_node = $embargo->getEmbargoedNode();
- $form['embargoed_node'] = array(
+ $form['embargoed_node'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#title' => $this->t('Embargoed node'),
'#maxlength' => 255,
'#default_value' => $embargoed_node ? $embargoed_node : '',
'#required' => TRUE,
- );
+ ];
- $form['notification_status'] = array(
+ $form['notification_status'] = [
'#type' => 'select',
'#title' => $this->t('Notification status'),
'#default_value' => $embargo->getNotificationStatus(),
'#options' => [
- 'created' => 'Created',
- 'updated' => 'Updated',
- 'warned' => 'Warned',
- 'expired' => 'Expired',
+ 'created' => $this->t('Created'),
+ 'updated' => $this->t('Updated'),
+ 'warned' => $this->t('Warned'),
+ 'expired' => $this->t('Expired'),
],
'#required' => TRUE,
- );
+ ];
return $form;
}
@@ -120,18 +159,18 @@ public function save(array $form, FormStateInterface $form_state) {
$status = $embargo->save();
$log_values['node'] = $embargo->getEmbargoedNode();
- $log_values['uid'] = \Drupal::currentUser()->id();
+ $log_values['uid'] = $this->currentUser()->id();
$log_values['embargo'] = $embargo->id();
if ($status == SAVED_NEW) {
- $log_values['action'] = 'created';
+ $log_values['action'] = 'created';
}
else {
- $log_values['action'] = 'updated';
+ $log_values['action'] = 'updated';
}
- \Drupal::messenger()->addMessage("Your embargo has been {$log_values['action']}.");
- \Drupal::service('embargoes.log')->logEmbargoEvent($log_values);
+ $this->messenger()->addMessage("Your embargo has been {$log_values['action']}.");
+ $this->embargoesLog->logEmbargoEvent($log_values);
$form_state->setRedirectUrl($embargo->toUrl('collection'));
}
diff --git a/src/Form/EmbargoesIpRangeEntityForm.php b/src/Form/EmbargoesIpRangeEntityForm.php
index 97e97a4..7b442b6 100644
--- a/src/Form/EmbargoesIpRangeEntityForm.php
+++ b/src/Form/EmbargoesIpRangeEntityForm.php
@@ -2,14 +2,40 @@
namespace Drupal\embargoes\Form;
+use Drupal\embargoes\EmbargoesIpRangesServiceInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class EmbargoesIpRangeEntityForm.
*/
class EmbargoesIpRangeEntityForm extends EntityForm {
+ /**
+ * An embargoes IP ranges manager.
+ *
+ * @var \Drupal\embargoes\EmbargoesIpRangesServiceInterface
+ */
+ protected $ipRanges;
+
+ /**
+ * Constructor for the IP range entity form.
+ *
+ * @param \Drupal\embargoes\EmbargoesIpRangesServiceInterface $ip_ranges
+ * An embargoes IP ranges manager.
+ */
+ public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges) {
+ $this->ipRanges = $ip_ranges;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static($container->get('embargoes.ips'));
+ }
+
/**
* {@inheritdoc}
*/
@@ -40,7 +66,7 @@ public function form(array $form, FormStateInterface $form_state) {
'#type' => 'textfield',
'#title' => $this->t('Range'),
'#maxlength' => 255,
- '#default_value' => $range->getRange(),
+ '#default_value' => implode('|', $range->getRanges()),
'#description' => $this->t("IP range to be used. Please list in CIDR format, and separate multiple ranges with a '|'."),
'#required' => TRUE,
];
@@ -65,12 +91,13 @@ public function save(array $form, FormStateInterface $form_state) {
$range->setProxyUrl($form_state->getValue('proxy_url'));
$status = $range->save();
- $errors = \Drupal::service('embargoes.ips')->detectIpRangeStringErrors($form_state->getValue('range'));
+ $errors = $this->ipRanges->detectIpRangeStringErrors($form_state->getValue('range'));
if (!$errors) {
switch ($status) {
case SAVED_NEW:
$this->messenger()->addMessage($this->t('Created the %label IP Range.', ['%label' => $range->label()]));
break;
+
default:
$this->messenger()->addMessage($this->t('Saved the %label IP Range.', ['%label' => $range->label()]));
}
diff --git a/src/Form/EmbargoesNodeEmbargoesForm.php b/src/Form/EmbargoesNodeEmbargoesForm.php
index 3b6e817..2fcaff6 100644
--- a/src/Form/EmbargoesNodeEmbargoesForm.php
+++ b/src/Form/EmbargoesNodeEmbargoesForm.php
@@ -2,15 +2,66 @@
namespace Drupal\embargoes\Form;
+use Drupal\embargoes\EmbargoesIpRangesServiceInterface;
+use Drupal\embargoes\EmbargoesLogServiceInterface;
+use Drupal\node\NodeInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\node\NodeInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class EmbargoesNodeEmbargoesForm.
*/
class EmbargoesNodeEmbargoesForm extends FormBase {
+ /**
+ * An entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityManager;
+
+ /**
+ * An embargoes IP ranges manager.
+ *
+ * @var \Drupal\embargoes\EmbargoesIpRangesServiceInterface
+ */
+ protected $ipRanges;
+
+ /**
+ * An embargoes logging service.
+ *
+ * @var \Drupal\embargoes\EmbargoesLogServiceInterface
+ */
+ protected $embargoesLog;
+
+ /**
+ * Constructor for the node embargo form.
+ *
+ * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
+ * An entity type manager.
+ * @param \Drupal\embargoes\EmbargoesIpRangesServiceInterface $ip_ranges
+ * An embargoes IP ranges manager.
+ * @param \Drupal\embargoes\EmbargoesLogServiceInterface $embargoes_log
+ * An embargoes logging service.
+ */
+ public function __construct(EntityTypeManagerInterface $entity_manager, EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log) {
+ $this->entityManager = $entity_manager;
+ $this->ipRanges = $ip_ranges;
+ $this->embargoesLog = $embargoes_log;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('entity_type.manager'),
+ $container->get('embargoes.ips'),
+ $container->get('embargoes.log'));
+ }
+
/**
* {@inheritdoc}
*/
@@ -23,60 +74,59 @@ public function getFormId() {
*/
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL, $embargo_id = NULL) {
-
if ($embargo_id != "add") {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->load($embargo_id);
}
- $form['embargo_id'] = array(
+ $form['embargo_id'] = [
'#type' => 'hidden',
'#value' => $embargo_id,
- );
+ ];
- $form['embargoed_node'] = array(
+ $form['embargoed_node'] = [
'#type' => 'hidden',
'#value' => $node->id(),
- );
+ ];
- $form['embargo_type'] = array(
+ $form['embargo_type'] = [
'#type' => 'radios',
'#title' => $this->t('Embargo type'),
'#description' => $this->t('Select the type of embargo to be applied. "Files" will leave the node itself visible (including searches and indexing), only restricting access to the attached files. "Node" will suppress access of the node completely from users, searches and indexing.'),
- '#default_value' => ( $embargo_id != 'add' ? $embargo->getEmbargoTypeAsInt() : FALSE ),
+ '#default_value' => ($embargo_id != 'add' ? $embargo->getEmbargoTypeAsInt() : FALSE),
'#required' => TRUE,
'#options' => [
- '0' => t('Files'),
- '1' => t('Node'),
+ '0' => $this->t('Files'),
+ '1' => $this->t('Node'),
],
'#attributes' => [
'name' => 'embargo_type',
],
- );
+ ];
- $form['expiry'] = array(
+ $form['expiry'] = [
'#type' => 'fieldset',
'#title' => $this->t('Expiration'),
- );
+ ];
- $form['expiry']['expiry_type'] = array(
+ $form['expiry']['expiry_type'] = [
'#type' => 'radios',
'#title' => $this->t('Expiration type'),
- '#default_value' => ( $embargo_id != 'add' ? $embargo->getExpirationTypeAsInt() : FALSE ),
+ '#default_value' => ($embargo_id != 'add' ? $embargo->getExpirationTypeAsInt() : FALSE),
'#required' => TRUE,
'#options' => [
- '0' => t('Indefinite'),
- '1' => t('Scheduled'),
+ '0' => $this->t('Indefinite'),
+ '1' => $this->t('Scheduled'),
],
'#attributes' => [
'name' => 'expiry_type',
],
- );
+ ];
- $form['expiry']['expiry_date'] = array(
+ $form['expiry']['expiry_date'] = [
'#type' => 'date',
'#title' => $this->t('Expiration date'),
'#description' => $this->t('Schedule the date on which the embargo will expire'),
- '#default_value' => ( $embargo_id != 'add' ? $embargo->getExpirationDate() : FALSE ),
+ '#default_value' => ($embargo_id != 'add' ? $embargo->getExpirationDate() : FALSE),
'#states' => [
'visible' => [
':input[name="expiry_type"]' => ['value' => '1'],
@@ -85,39 +135,36 @@ public function buildForm(array $form, FormStateInterface $form_state, NodeInter
':input[name="expiry_type"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['exemptions'] = array(
+ $form['exemptions'] = [
'#type' => 'fieldset',
'#title' => $this->t('Exemptions'),
- );
+ ];
- $form['exemptions']['exempt_ips'] = array(
+ $form['exemptions']['exempt_ips'] = [
'#type' => 'select',
'#title' => $this->t('Exempt IP ranges'),
'#description' => $this->t('Select the name of a pre-configured IP range that is exempt from this specific embargo. IP ranges must be set up by an administrator.'),
- '#options' => \Drupal::service('embargoes.ips')->getIpRangesAsSelectOptions(),
- '#default_value' => ($embargo_id != 'add' ? $embargo->getExemptIps() : FALSE),
- );
-
+ '#options' => $this->ipRanges->getIpRangesAsSelectOptions(),
+ '#default_value' => ($embargo_id != 'add' ? (is_null($embargo->getExemptIps()) ? 'none' : $embargo->getExemptIps()) : NULL),
+ ];
- $form['exemptions']['exempt_users'] = array(
+ $form['exemptions']['exempt_users'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#tags' => TRUE,
'#title' => $this->t('Exempt users'),
'#description' => $this->t('Enter the username of users that are exempt from this specific embargo. Use a comma to separate multiple exempt users.'),
- '#default_value' => ($embargo_id != 'add' ? $embargo->getExemptUsersEntities() : FALSE ),
- );
+ '#default_value' => ($embargo_id != 'add' ? $embargo->getExemptUsersEntities() : FALSE),
+ ];
- $form['additional_emails'] = array(
+ $form['additional_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Additional Emails'),
- '#description' => $this->t('Enter additional emails addresses that should recieve notifications regarding this embargo.'),
- '#default_value' => ($embargo_id != 'add' ? $embargo->getAdditionalEmails() : ''),
- );
-
-
+ '#description' => $this->t('A comma-separated list of emails addresses that should recieve notifications regarding this embargo.'),
+ '#default_value' => ($embargo_id != 'add' ? implode(',', $embargo->getAdditionalEmails()) : ''),
+ ];
$form['submit'] = [
'#type' => 'submit',
@@ -127,23 +174,16 @@ public function buildForm(array $form, FormStateInterface $form_state, NodeInter
return $form;
}
- /**
- * {@inheritdoc}
- */
- public function validateForm(array &$form, FormStateInterface $form_state) {
- parent::validateForm($form, $form_state);
- }
-
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$embargo_id = $form_state->getValue('embargo_id');
if ($embargo_id == 'add') {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->create();
+ $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->create();
}
else {
- $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
+ $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->load($embargo_id);
}
$embargo->setEmbargoType($form_state->getValue('embargo_type'));
@@ -156,7 +196,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
$embargo->save();
$log_values['node'] = $embargo->getEmbargoedNode();
- $log_values['uid'] = \Drupal::currentUser()->id();
+ $log_values['uid'] = $this->currentUser()->id();
$log_values['embargo'] = $embargo->id();
if ($embargo_id == 'add') {
@@ -166,8 +206,8 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
$log_values['action'] = 'updated';
}
- \Drupal::messenger()->addMessage("Your embargo has been {$log_values['action']}.");
- \Drupal::service('embargoes.log')->logEmbargoEvent($log_values);
+ $this->messenger()->addMessage("Your embargo has been {$log_values['action']}.");
+ $this->embargoesLog->logEmbargoEvent($log_values);
$form_state->setRedirect('embargoes.node.embargoes', ['node' => $form_state->getValue('embargoed_node')]);
}
diff --git a/src/Form/EmbargoesNotificationsForm.php b/src/Form/EmbargoesNotificationsForm.php
index 6776419..7abde3a 100644
--- a/src/Form/EmbargoesNotificationsForm.php
+++ b/src/Form/EmbargoesNotificationsForm.php
@@ -31,23 +31,23 @@ public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('embargoes.notifications');
$form = parent::buildForm($form, $form_state);
- $form['creations'] = array(
+ $form['creations'] = [
'#type' => 'fieldset',
'#title' => $this->t('Embargo Creation Notifications'),
- );
- $form['creations']['creations_active'] = array(
+ ];
+ $form['creations']['creations_active'] = [
'#type' => 'radios',
'#title' => $this->t('Enable embargo creation notification emails'),
- '#default_value' => ( !is_null($config->get('creations_active')) ? $config->get('creations_active') : 0 ),
+ '#default_value' => (!is_null($config->get('creations_active')) ? $config->get('creations_active') : 0),
'#options' => [
- '0' => t('Disabled'),
- '1' => t('Enabled'),
+ '0' => $this->t('Disabled'),
+ '1' => $this->t('Enabled'),
],
'#attributes' => [
'name' => 'creations_active',
],
- );
- $form['creations']['creations_from_address'] = array(
+ ];
+ $form['creations']['creations_from_address'] = [
'#type' => 'textfield',
'#title' => $this->t('From Address'),
'#description' => $this->t('Enter email address that embargo creation notification emails should be sent from'),
@@ -57,8 +57,8 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="creations_active"]' => ['value' => '1'],
],
],
- );
- $form['creations']['creations_emails'] = array(
+ ];
+ $form['creations']['creations_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Default email recipients'),
'#description' => $this->t('Enter email addresses that should recieve all embargo creation notification emails by default'),
@@ -68,7 +68,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="creations_active"]' => ['value' => '1'],
],
],
- );
+ ];
$creations_template_default = << 'textarea',
'#title' => $this->t('Creation notification email template'),
'#description' => $this->t('Modify the email template sent for embargo creation notifications, using [recipient_email_address], [contact_email_address], [node_title], [node_link], and [expiration_date] as tokens.'),
- '#default_value' => ( !is_null($config->get('creations_template')) ? $config->get('creations_template') : $creations_template_default ),
+ '#default_value' => (!is_null($config->get('creations_template')) ? $config->get('creations_template') : $creations_template_default),
'#states' => [
'visible' => [
':input[name="creations_active"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['updates'] = array(
+ $form['updates'] = [
'#type' => 'fieldset',
'#title' => $this->t('Embargo Update Notifications'),
- );
- $form['updates']['updates_active'] = array(
+ ];
+ $form['updates']['updates_active'] = [
'#type' => 'radios',
'#title' => $this->t('Enable embargo update notification emails'),
- '#default_value' => ( !is_null($config->get('updates_active')) ? $config->get('updates_active') : 0 ),
+ '#default_value' => (!is_null($config->get('updates_active')) ? $config->get('updates_active') : 0),
'#options' => [
- '0' => t('Disabled'),
- '1' => t('Enabled'),
+ '0' => $this->t('Disabled'),
+ '1' => $this->t('Enabled'),
],
'#attributes' => [
'name' => 'updates_active',
],
- );
- $form['updates']['updates_from_address'] = array(
+ ];
+ $form['updates']['updates_from_address'] = [
'#type' => 'textfield',
'#title' => $this->t('From Address'),
'#description' => $this->t('Enter email address that embargo update notification emails should be sent from'),
@@ -117,8 +117,8 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="updates_active"]' => ['value' => '1'],
],
],
- );
- $form['updates']['updates_emails'] = array(
+ ];
+ $form['updates']['updates_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Default email recipients'),
'#description' => $this->t('Enter email addresses that should recieve all embargo update notification emails by default'),
@@ -128,7 +128,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="updates_active"]' => ['value' => '1'],
],
],
- );
+ ];
$updates_template_default = << 'textarea',
'#title' => $this->t('Update notification email template'),
'#description' => $this->t('Modify the email template sent for embargo update notifications, using [recipient_email_address], [contact_email_address], [node_title], [node_link], and [expiration_date] as tokens.'),
- '#default_value' => ( !is_null($config->get('updates_template')) ? $config->get('updates_template') : $updates_template_default ),
+ '#default_value' => (!is_null($config->get('updates_template')) ? $config->get('updates_template') : $updates_template_default),
'#states' => [
'visible' => [
':input[name="updates_active"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['deletions'] = array(
+ $form['deletions'] = [
'#type' => 'fieldset',
'#title' => $this->t('Embargo Deletion Notifications'),
- );
- $form['deletions']['deletions_active'] = array(
+ ];
+ $form['deletions']['deletions_active'] = [
'#type' => 'radios',
'#title' => $this->t('Enable embargo deletion notification emails'),
- '#default_value' => ( !is_null($config->get('deletions_active')) ? $config->get('deletions_active') : 0 ),
+ '#default_value' => (!is_null($config->get('deletions_active')) ? $config->get('deletions_active') : 0),
'#options' => [
- '0' => t('Disabled'),
- '1' => t('Enabled'),
+ '0' => $this->t('Disabled'),
+ '1' => $this->t('Enabled'),
],
'#attributes' => [
'name' => 'deletions_active',
],
- );
- $form['deletions']['deletions_from_address'] = array(
+ ];
+ $form['deletions']['deletions_from_address'] = [
'#type' => 'textfield',
'#title' => $this->t('From Address'),
'#description' => $this->t('Enter email address that embargo deletion notification emails should be sent from'),
@@ -177,8 +177,8 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="deletions_active"]' => ['value' => '1'],
],
],
- );
- $form['deletions']['deletions_emails'] = array(
+ ];
+ $form['deletions']['deletions_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Default email recipients'),
'#description' => $this->t('Enter email addresses that should recieve all embargo deletion notification emails by default'),
@@ -188,7 +188,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="deletions_active"]' => ['value' => '1'],
],
],
- );
+ ];
$deletions_template_default = << 'textarea',
'#title' => $this->t('Deletion notification email template'),
'#description' => $this->t('Modify the email template sent for embargo deletion notifications, using [recipient_email_address], [contact_email_address], [node_title], and [node_link] as tokens.'),
- '#default_value' => ( !is_null($config->get('deletions_template')) ? $config->get('deletions_template') : $deletions_template_default ),
+ '#default_value' => (!is_null($config->get('deletions_template')) ? $config->get('deletions_template') : $deletions_template_default),
'#states' => [
'visible' => [
':input[name="deletions_active"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['warnings'] = array(
+ $form['warnings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Embargo Expiration Warning Notifications'),
- );
- $form['warnings']['warnings_active'] = array(
+ ];
+ $form['warnings']['warnings_active'] = [
'#type' => 'radios',
'#title' => $this->t('Enable embargo expiration warning notification emails'),
- '#default_value' => ( !is_null($config->get('warnings_active')) ? $config->get('warnings_active') : 0 ),
+ '#default_value' => (!is_null($config->get('warnings_active')) ? $config->get('warnings_active') : 0),
'#options' => [
- '0' => t('Disabled'),
- '1' => t('Enabled'),
+ '0' => $this->t('Disabled'),
+ '1' => $this->t('Enabled'),
],
'#attributes' => [
'name' => 'warnings_active',
],
- );
- $form['warnings']['warnings_period'] = array(
+ ];
+ $form['warnings']['warnings_period'] = [
'#type' => 'number',
'#title' => $this->t('Days until expiry'),
'#description' => $this->t('Enter the number of days before an embargo expires that an embargo expiration warning notification should be sent'),
@@ -237,8 +237,8 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="warnings_active"]' => ['value' => '1'],
],
],
- );
- $form['warnings']['warnings_from_address'] = array(
+ ];
+ $form['warnings']['warnings_from_address'] = [
'#type' => 'textfield',
'#title' => $this->t('From Address'),
'#description' => $this->t('Enter email address that embargo warning notification emails should be sent from'),
@@ -248,17 +248,18 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="warnings_active"]' => ['value' => '1'],
],
],
- );
- $form['warnings']['warnings_emails'] = array(
+ ];
+ $form['warnings']['warnings_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Default email recipients'),
'#description' => $this->t('Enter email addresses that should recieve all embargo expiration warning notification emails by default'),
- '#default_value' => $config->get('warnings_emails'), '#states' => [
+ '#default_value' => $config->get('warnings_emails'),
+ '#states' => [
'visible' => [
':input[name="warnings_active"]' => ['value' => '1'],
],
],
- );
+ ];
$warnings_template_default = << 'textarea',
'#title' => $this->t('Warning notification email template'),
'#description' => $this->t('Modify the email template sent for embargo expiration warning notifications, using [recipient_email_address], [contact_email_address], [node_title], [node_link], expiration_date] and [expiration_warning_period] as tokens.'),
- '#default_value' => ( !is_null($config->get('warnings_template')) ? $config->get('warnings_template') : $warnings_template_default ),
+ '#default_value' => (!is_null($config->get('warnings_template')) ? $config->get('warnings_template') : $warnings_template_default),
'#states' => [
'visible' => [
':input[name="warnings_active"]' => ['value' => '1'],
],
],
- );
+ ];
- $form['expirations'] = array(
+ $form['expirations'] = [
'#type' => 'fieldset',
'#title' => $this->t('Embargo Expiration Notifications'),
- );
- $form['expirations']['expirations_active'] = array(
+ ];
+ $form['expirations']['expirations_active'] = [
'#type' => 'radios',
'#title' => $this->t('Enable embargo expiration notification emails'),
- '#default_value' => ( !is_null($config->get('expirations_active')) ? $config->get('expirations_active') : 0 ),
+ '#default_value' => (!is_null($config->get('expirations_active')) ? $config->get('expirations_active') : 0),
'#options' => [
- '0' => t('Disabled'),
- '1' => t('Enabled'),
+ '0' => $this->t('Disabled'),
+ '1' => $this->t('Enabled'),
],
'#attributes' => [
'name' => 'expirations_active',
],
- );
- $form['expirations']['expirations_from_address'] = array(
+ ];
+ $form['expirations']['expirations_from_address'] = [
'#type' => 'textfield',
'#title' => $this->t('From Address'),
'#description' => $this->t('Enter email address that embargo expiration notification emails should be sent from'),
@@ -307,8 +308,8 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="expirations_active"]' => ['value' => '1'],
],
],
- );
- $form['expirations']['expirations_emails'] = array(
+ ];
+ $form['expirations']['expirations_emails'] = [
'#type' => 'textfield',
'#title' => $this->t('Default email recipients'),
'#description' => $this->t('Enter email addresses that should recieve all embargo expiration notification emails by default'),
@@ -318,7 +319,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
':input[name="expirations_active"]' => ['value' => '1'],
],
],
- );
+ ];
$expirations_template_default = << 'textarea',
'#title' => $this->t('Expiration notification email template'),
'#description' => $this->t('Modify the email template sent for embargo expiration notifications, using [recipient_email_address], [contact_email_address], [node_title], [node_link], and [expiration_date] as tokens.'),
- '#default_value' => ( !is_null($config->get('expirations_template')) ? $config->get('expirations_template') : $expirations_template_default ),
+ '#default_value' => (!is_null($config->get('expirations_template')) ? $config->get('expirations_template') : $expirations_template_default),
'#states' => [
'visible' => [
':input[name="expirations_active"]' => ['value' => '1'],
],
],
- );
+ ];
return $form;
}
diff --git a/src/Form/EmbargoesSettingsForm.php b/src/Form/EmbargoesSettingsForm.php
index 6c7d9bc..94a0e26 100644
--- a/src/Form/EmbargoesSettingsForm.php
+++ b/src/Form/EmbargoesSettingsForm.php
@@ -1,6 +1,7 @@
'email',
'#title' => $this->t('Contact Email'),
'#description' => $this->t('Email address for who should be contacted in case users have questions about access.'),
- '#default_value' => ( !empty($config->get('embargo_contact_email')) ? $config->get('embargo_contact_email') : \Drupal::config('system.site')->get('mail') ),
+ '#default_value' => (!empty($config->get('embargo_contact_email')) ? $config->get('embargo_contact_email') : $this->config('system.site')->get('mail')),
];
$form['add_contact_to_notifications'] = [
'#type' => 'checkbox',
'#title' => $this->t('Add contact to notifications'),
'#description' => $this->t('Add contact email to all embargo notifications by default.'),
- '#default_value' => ( !is_null($config->get('add_contact_to_notifications')) ? $config->get('add_contact_to_notifications') : TRUE ),
+ '#default_value' => (!is_null($config->get('add_contact_to_notifications')) ? $config->get('add_contact_to_notifications') : TRUE),
];
$form['show_embargo_message'] = [
'#type' => 'checkbox',
'#title' => $this->t('Show embargo message'),
'#description' => $this->t('Show a Drupal warning message on nodes under active embargoes.'),
- '#default_value' => ( !is_null($config->get('show_embargo_message')) ? $config->get('show_embargo_message') : TRUE ),
+ '#default_value' => (!is_null($config->get('show_embargo_message')) ? $config->get('show_embargo_message') : TRUE),
];
return $form;
diff --git a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
index de94b7d..7628bd1 100644
--- a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
+++ b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
@@ -2,8 +2,14 @@
namespace Drupal\embargoes\Plugin\Block;
+use Drupal\node\NodeInterface;
+use Drupal\embargoes\EmbargoesEmbargoesServiceInterface;
use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\Markup;
+use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
+use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a "Embargo Policies" block.
@@ -14,26 +20,83 @@
* category = @Translation("Embargoes")
* )
*/
-class EmbargoesEmbargoPoliciesBlock extends BlockBase {
+class EmbargoesEmbargoPoliciesBlock extends BlockBase implements ContainerFactoryPluginInterface {
+
+ /**
+ * A route matching interface.
+ *
+ * @var \Drupal\Core\Routing\ResettableStackedRouteMatchInterface
+ */
+ protected $routeMatch;
+
+ /**
+ * An embargoes service.
+ *
+ * @var \Drupal\embargoes\EmbargoesEmbargoesServiceInterface
+ */
+ protected $embargoes;
+
+ /**
+ * An entity type manager.
+ *
+ * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+ */
+ protected $entityManager;
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+ return new static(
+ $configuration,
+ $plugin_id,
+ $plugin_definition,
+ $container->get('current_route_match'),
+ $container->get('embargoes.embargoes'),
+ $container->get('entity_type.manager'));
+ }
+
+ /**
+ * Constructs an embargoes policies block.
+ *
+ * @param array $configuration
+ * Block configuration.
+ * @param string $plugin_id
+ * The plugin ID.
+ * @param mixed $plugin_definition
+ * The plugin definition.
+ * @param \Drupal\Core\Routing\ResettableStackedRouteMatchInterface $route_match
+ * A route matching interface.
+ * @param \Drupal\embargoes\EmbargoesEmbargoesServiceInterface $embargoes
+ * An embargoes management service.
+ * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
+ * An entity type manager.
+ */
+ public function __construct(array $configuration, $plugin_id, $plugin_definition, ResettableStackedRouteMatchInterface $route_match, EmbargoesEmbargoesServiceInterface $embargoes, EntityTypeManagerInterface $entity_manager) {
+ parent::construct($configuration, $plugin_id, $plugin_definition);
+ $this->routeMatch = $route_match;
+ $this->embargoes = $embargoes;
+ $this->entityManager = $entity_manager;
+ }
/**
* {@inheritdoc}
*/
public function build() {
- $node = \Drupal::routeMatch()->getParameter('node');
- if ($node instanceof \Drupal\node\NodeInterface) {
- $embargoes = \Drupal::service('embargoes.embargoes')->getCurrentEmbargoesByNids(array($node->id()));
+ $node = $this->routeMatch->getParameter('node');
+ if ($node instanceof NodeInterface) {
+ $embargoes = $this->embargoes->getCurrentEmbargoesByNids([$node->id()]);
$embargo_count = count($embargoes);
if (count($embargoes) > 0) {
$embargo_plurality = ($embargo_count == 1 ? "embargo" : "embargoes");
$body = "This resource has {$embargo_count} {$embargo_plurality}:";
foreach ($embargoes as $embargo_id) {
$body .= "
";
- $message .= "If any of the listed networks above appear as links, you may be able to reach the resource by authenticating through a proxy.
";
- if ($contact_email != '') {
- $message .= "If you have any questions about access to this resource, contact {$contact_email} for more information.
";
- }
return [
- '#type' => 'markup',
- '#markup' => render($message),
- '#cache' => ["max-age" => 0],
+ '#theme' => 'embargoes_ip_access_denied',
+ '#variables' => [
+ 'requested_resource' => $requested_resource,
+ 'ranges' => $ranges,
+ 'contact_email' => $contact_email,
+ ],
];
}
diff --git a/src/EmbargoesIpRangeEntityListBuilder.php b/src/Controller/EmbargoesIpRangeEntityListBuilder.php
similarity index 85%
rename from src/EmbargoesIpRangeEntityListBuilder.php
rename to src/Controller/EmbargoesIpRangeEntityListBuilder.php
index af712f5..075abd9 100644
--- a/src/EmbargoesIpRangeEntityListBuilder.php
+++ b/src/Controller/EmbargoesIpRangeEntityListBuilder.php
@@ -1,10 +1,9 @@
label();
$row['id'] = $entity->id();
- $row['range'] = Markup::create(implode('
', $entity->getRanges()));
+ $row['range'] = ['#markup' => implode('
', $entity->getRanges())];
$row['proxy_url'] = $entity->getProxyUrl();
return $row + parent::buildRow($entity);
}
diff --git a/src/Controller/EmbargoesLogController.php b/src/Controller/EmbargoesLogController.php
index 202d743..f4486f3 100644
--- a/src/Controller/EmbargoesLogController.php
+++ b/src/Controller/EmbargoesLogController.php
@@ -4,7 +4,6 @@
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
-use Drupal\Core\Render\Markup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -21,6 +20,9 @@ class EmbargoesLogController extends ControllerBase {
/**
* Constructs an embargo log controller.
+ *
+ * @var \Drupal\Core\Database\Connection $database
+ * Database connection.
*/
public function __construct(Connection $database) {
$this->connection = $database;
@@ -51,12 +53,18 @@ public function showRenderedLog() {
$formatted_time = date('c', $record->time);
$node_title = $this->entityTypeManager()->getStorage('node')->load($record->node)->get('title')->value;
$user = $this->entityTypeManager()->getStorage('user')->load($record->uid);
- $username = $user ? $user->getUsername() : 'Missing User';
+ $username = $user ? $user->getUsername() : $this->t('Missing User');
if ($record->action == "deleted") {
- $embargo_formatted = Markup::create("{$record->embargo}");
+ $embargo_formatted = ['#markup' => "{$record->embargo}"];
}
else {
- $embargo_formatted = Markup::create("{$record->embargo}");
+ $embargo_formatted = [
+ '#type' => 'link',
+ '#title' => $record->embargo,
+ '#link' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.edit_form', [
+ 'id' => $record->embargo,
+ ]),
+ ];
}
$row = [
@@ -64,8 +72,20 @@ public function showRenderedLog() {
'embargo' => $embargo_formatted,
'time' => $formatted_time,
'action' => ucfirst($record->action),
- 'node' => Markup::create("$node_title"),
- 'user' => Markup::create("$username"),
+ 'node' => [
+ '#type' => 'link',
+ '#title' => $node_title,
+ '#link' => $this->urlGenerator->generateFromRoute('entity.node.canonical', [
+ 'node' => $record->node,
+ ]),
+ ],
+ 'user' => [
+ '#type' => 'link',
+ '#title' => $username,
+ '#link' => $this->urlGenerator->generateFromRoute('entity.user.canonical', [
+ 'user' => $record->uid,
+ ]),
+ ],
];
array_push($formatted_log, $row);
}
@@ -73,19 +93,19 @@ public function showRenderedLog() {
$pre_rendered_log = [
'#type' => 'table',
'#header' => [
- 'Event ID',
- 'Embargo ID',
- 'Time',
- 'Action',
- 'Embargoed Node',
- 'User Responsible',
+ $this->t('Event ID'),
+ $this->t('Embargo ID'),
+ $this->t('Time'),
+ $this->t('Action'),
+ $this->t('Embargoed Node'),
+ $this->t('User Responsible'),
],
'#rows' => $formatted_log,
];
return [
'#type' => 'markup',
- '#markup' => render($pre_rendered_log),
+ '#markup' => $pre_rendered_log,
];
}
diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php
index ba09277..3c0282d 100644
--- a/src/Controller/EmbargoesNodeEmbargoesController.php
+++ b/src/Controller/EmbargoesNodeEmbargoesController.php
@@ -5,7 +5,6 @@
use Drupal\embargoes\EmbargoesEmbargoesServiceInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\Controller\ControllerBase;
-use Drupal\Core\Render\Markup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -48,8 +47,7 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$embargo_ids = $this->embargoes->getAllEmbargoesByNids([$node->id()]);
if (empty($embargo_ids)) {
$markup['embargoes'] = [
- '#type' => 'markup',
- '#markup' => Markup::create('There are no embargoes on this node.
'),
+ '#markup' => $this->t('There are no embargoes on this node.'),
];
}
else {
@@ -58,7 +56,7 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$embargo = $this->entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id);
if ($embargo->getExpirationType() == 0) {
- $expiry = 'Indefinite';
+ $expiry = $this->t('Indefinite');
}
else {
$expiry = $embargo->getExpirationDate();
@@ -73,35 +71,61 @@ public function showEmbargoes(NodeInterface $node = NULL) {
foreach ($embargo->getExemptUsers() as $user) {
$uid = $user['target_id'];
$user_entity = $this->entityTypeManager()->getStorage('user')->load($uid);
- $user_name = $user_entity ? $user_entity->getUserName() : 'Missing User';
- $formatted_users[] = "{$user_name}";
+ $user_name = $user_entity ? $user_entity->getUserName() : $this->t('Missing User');
+ $formatted_users[] = [
+ '#type' => 'link',
+ '#title' => $user_name,
+ '#url' => $this->urlGenerator->generateFromRoute('entity.user.canonical', [
+ 'user' => $uid,
+ ]),
+ ];
}
}
- $formatted_exempt_users_row = Markup::create(implode("
", $formatted_users));
+ $formatted_exempt_users_row = ['data' => $formatted_users];
if (!is_null($embargo->getExemptIps())) {
$ip_range = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
if (!is_null($ip_range)) {
- $ip_range_label = $ip_range->label();
- $ip_range_formatted = Markup::create("{$ip_range_label}");
+ $ip_range_formatted = [
+ '#type' => 'link',
+ '#title' => $ip_range->label(),
+ '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_ip_range.edit_form', [
+ 'id' => $embargo->getExemptIps(),
+ ]),
+ ];
}
else {
- $ip_range_formatted = 'None';
+ $ip_range_formatted = $this->t('None');
}
}
else {
- $ip_range_formatted = "None";
+ $ip_range_formatted = $this->t('None');
}
- $formatted_emails = Markup::create(implode('
', $embargo->getAdditionalEmails()));
+ $formatted_emails = [
+ '#markup' => implode('
', $embargo->getAdditionalEmails()),
+ ];
$row = [
- 'type' => ($embargo->getEmbargoType() == 1 ? 'Node' : 'Files'),
+ 'type' => ($embargo->getEmbargoType() == 1 ? $this->t('Node') : $this->t('Files')),
'expiry' => $expiry,
'exempt_ips' => $ip_range_formatted,
'exempt_users' => $formatted_exempt_users_row,
'additional_emails' => $formatted_emails,
- 'edit' => Markup::create("Edit
Delete"),
+ 'edit' => [
+ '#type' => 'link',
+ '#title' => $this->t('Edit'),
+ '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.edit_form', [
+ 'id' => $embargo_id,
+ ]),
+ ],
+ 'delete' => [
+ '#type' => 'link',
+ '#title' => $this->t('Delete'),
+ '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.delete_form', [
+ 'id' => $embargo_id,
+ ]),
+ ],
];
array_push($rows, $row);
}
@@ -109,26 +133,25 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$markup['embargoes'] = [
'#type' => 'table',
'#header' => [
- 'Type',
- 'Expiration Date',
- 'Exempt IP Range',
- 'Exempt Users',
- 'Additional Emails',
- 'Edit',
+ $this->t('Type'),
+ $this->t('Expiration Date'),
+ $this->t('Exempt IP Range'),
+ $this->t('Exempt Users'),
+ $this->t('Additional Emails'),
+ $this->t('Edit'),
+ $this->t('Delete'),
],
'#rows' => $rows,
];
}
$markup['add'] = [
- '#type' => 'markup',
- '#markup' => Markup::create("Add Embargo
"),
+ '#type' => 'link',
+ '#title' => $this->t('Add Embargo'),
+ '#link' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.add_form'),
];
- return [
- '#type' => 'markup',
- '#markup' => render($markup),
- ];
+ return $markup;
}
}
diff --git a/src/EmbargoesEmbargoEntityListBuilder.php b/src/EmbargoesEmbargoEntityListBuilder.php
deleted file mode 100644
index 271335b..0000000
--- a/src/EmbargoesEmbargoEntityListBuilder.php
+++ /dev/null
@@ -1,74 +0,0 @@
-t('Embargo ID');
- $header['embargo_type'] = $this->t('Embargo Type');
- $header['expiration_type'] = $this->t('Expiration Type');
- $header['expiration_date'] = $this->t('Expiration Date');
- $header['exempt_ips'] = $this->t('Exempt IP Range');
- $header['exempt_users'] = $this->t('Exempt Users');
- $header['additional_emails'] = $this->t('Additional Emails');
- $header['notification_status'] = $this->t('Notification Status');
- $header['embargoed_node'] = $this->t('Embargoed Node');
- return $header + parent::buildHeader();
- }
-
- /**
- * {@inheritdoc}
- */
- public function buildRow(EntityInterface $entity) {
-
- $formatted_users = [];
- foreach ($entity->getExemptUsers() as $user) {
- $uid = $user['target_id'];
- $user_entity = User::load($uid);
- $user_name = $user_entity->getUserName();
- $formatted_users[] = "{$user_name}";
-
- }
- $formatted_exempt_users_row = Markup::create(implode("
", $formatted_users));
-
- $nid = $entity->getEmbargoedNode();
- $node = node_load($nid);
- $node_title = $node->title->value;
- $formatted_node_row = Markup::create("{$node_title}");
-
- $ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($entity->getExemptIps());
- if (!is_null($ip_range)) {
- $ip_range_label = $ip_range->label();
- $ip_range_formatted = Markup::create("{$ip_range_label}");
- }
- else {
- $ip_range_formatted = "None";
- }
-
- $formatted_emails = Markup::create(implode('
', $entity->getAdditionalEmails()));
-
- $row['id'] = $entity->id();
- $row['embargo_type'] = ($entity->getEmbargoType() == 1 ? 'Node' : 'Files');
- $row['expiration_type'] = ($entity->getExpirationType() == 1 ? 'Scheduled' : 'Indefinite');
- $row['expiration_date'] = (!empty($entity->getExpirationDate()) ? $entity->getExpirationDate() : 'None');
- $row['exempt_ips'] = $ip_range_formatted;
- $row['exempt_users'] = $formatted_exempt_users_row;
- $row['additional_emails'] = $formatted_emails;
- $row['notification_status'] = ucfirst($entity->getNotificationStatus());
- $row['embargoed_node'] = $formatted_node_row;
- return $row + parent::buildRow($entity);
- }
-
-}
diff --git a/src/Entity/EmbargoesEmbargoEntity.php b/src/Entity/EmbargoesEmbargoEntity.php
index 78079e6..bde1729 100644
--- a/src/Entity/EmbargoesEmbargoEntity.php
+++ b/src/Entity/EmbargoesEmbargoEntity.php
@@ -12,7 +12,7 @@
* id = "embargoes_embargo_entity",
* label = @Translation("Embargo"),
* handlers = { * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
- * "list_builder" = "Drupal\embargoes\EmbargoesEmbargoEntityListBuilder",
+ * "list_builder" = "Drupal\embargoes\Controller\EmbargoesEmbargoEntityListBuilder",
* "form" = {
* "add" = "Drupal\embargoes\Form\EmbargoesEmbargoEntityForm",
* "edit" = "Drupal\embargoes\Form\EmbargoesEmbargoEntityForm",
@@ -105,22 +105,6 @@ class EmbargoesEmbargoEntity extends ConfigEntityBase implements EmbargoesEmbarg
*/
protected $notification_status;
- /**
- * Constructor function.
- *
- * @param array $values
- * Associative array of parameters to apply to this entity.
- * @param string $entity_type
- * The type of entity.
- */
- public function __construct(array $values, $entity_type) {
- $uuid = \Drupal::service('uuid')->generate();
- $checksummed_uuid = sha1($uuid);
- $this->uuid = $uuid;
- $this->id = $checksummed_uuid;
- parent::__construct($values, $entity_type);
- }
-
/**
* {@inheritdoc}
*/
diff --git a/src/Entity/EmbargoesIpRangeEntity.php b/src/Entity/EmbargoesIpRangeEntity.php
index 1bb9c89..30f5471 100644
--- a/src/Entity/EmbargoesIpRangeEntity.php
+++ b/src/Entity/EmbargoesIpRangeEntity.php
@@ -12,7 +12,7 @@
* label = @Translation("IP Range"),
* handlers = {
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
- * "list_builder" = "Drupal\embargoes\EmbargoesIpRangeEntityListBuilder",
+ * "list_builder" = "Drupal\embargoes\Controller\EmbargoesIpRangeEntityListBuilder",
* "form" = {
* "add" = "Drupal\embargoes\Form\EmbargoesIpRangeEntityForm",
* "edit" = "Drupal\embargoes\Form\EmbargoesIpRangeEntityForm",
diff --git a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
index 7628bd1..4ee2277 100644
--- a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
+++ b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php
@@ -6,7 +6,6 @@
use Drupal\embargoes\EmbargoesEmbargoesServiceInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
-use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -122,7 +121,7 @@ public function build() {
}
return [
- '#markup' => Markup::create($body),
+ '#markup' => $body,
];
}
diff --git a/src/Plugin/Condition/EmbargoesEmbargoedCondition.php b/src/Plugin/Condition/EmbargoesEmbargoedCondition.php
index 966a530..2209b08 100644
--- a/src/Plugin/Condition/EmbargoesEmbargoedCondition.php
+++ b/src/Plugin/Condition/EmbargoesEmbargoedCondition.php
@@ -5,6 +5,8 @@
use Drupal\node\NodeInterface;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Condition to filter on whether or not a node is embargoed.
@@ -17,14 +19,74 @@
* }
* )
*/
-class EmbargoesEmbargoedCondition extends ConditionPluginBase {
+class EmbargoesEmbargoedCondition extends ConditionPluginBase implements ContainerFactoryPluginInterface {
+
+ /**
+ * A route matching interface.
+ *
+ * @var \Drupal\Core\Routing\RouteMatchInterface
+ */
+ protected $routeMatch;
+
+ /**
+ * An embargoes service.
+ *
+ * @var \Drupal\embargoes\EmbargoesEmbargoesServiceInterface
+ */
+ protected $embargoes;
+
+ /**
+ * The current user.
+ *
+ * @var \Drupal\Core\Session\AccountInterface
+ */
+ protected $currentUser;
+
+ /**
+ * The current request.
+ *
+ * @var \Symfony\Component\HttpFoundation\Request
+ */
+ protected $request;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
- $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
- return $instance;
+ return new static(
+ $configuration,
+ $plugin_id,
+ $plugin_definition,
+ $container->get('current_route_match'),
+ $container->get('embargoes.embargoes'),
+ $container->get('current_user'),
+ $container->get('request_stack'));
+ }
+
+ /**
+ * Create a new embargoed condition.
+ *
+ * @param array $configuration
+ * The condition configuration.
+ * @param string $plugin_id
+ * The plugin ID.
+ * @param string $plugin_definition
+ * The plugin definition.
+ * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
+ * A route matching interface.
+ * @param \Drupal\embargoes\EmbargoesEmbargoesServiceInterface $embargoes
+ * An embargoes service.
+ * @param \Drupal\Core\Session\AccountInterface $current_user
+ * The current user.
+ * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
+ * The current request stack.
+ */
+ public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match, EmbargoesEmbargoesServiceInterface $embargoes, AccountInterface $current_user, RequestStack $request_stack) {
+ parent::__construct($configuration, $plugin_id, $plugin_definition);
+ $this->routeMatch = $route_match;
+ $this->embargoes = $embargoes;
+ $this->currentUser = $current_user;
+ $this->request = $request_stack->getCurrentRequest();
}
/**
@@ -68,27 +130,24 @@ public function defaultConfiguration() {
* TRUE if the condition has been met, FALSE otherwise.
*/
public function evaluate() {
- $node = \Drupal::routeMatch()->getParameter('node');
+ $node = $this->routeMatch->getParameter('node');
if ($node instanceof NodeInterface) {
- $embargo_service = \Drupal::service('embargoes.embargoes');
switch ($this->configuration['filter']) {
case 'off':
$embargoed = TRUE;
break;
case 'all':
- $embargoed = $embargo_service->getAllEmbargoesByNids([$node->id()]);
+ $embargoed = $this->embargoes->getAllEmbargoesByNids([$node->id()]);
break;
case 'current':
- $embargoed = $embargo_service->getCurrentEmbargoesByNids([$node->id()]);
+ $embargoed = $this->embargoes->getCurrentEmbargoesByNids([$node->id()]);
break;
case 'active':
- $ip = \Drupal::request()->getClientIp();
- $user = \Drupal::currentUser();
- $embargoed = $embargo_service->getActiveEmbargoesByNids([$node->id()], $ip, $user);
+ $embargoed = $this->embargoes->getActiveEmbargoesByNids([$node->id()], $this->request->getClientIp(), $this->currentUser);
break;
}
diff --git a/templates/embargoes-ip-access-denied.html.twig b/templates/embargoes-ip-access-denied.html.twig
new file mode 100644
index 0000000..010487d
--- /dev/null
+++ b/templates/embargoes-ip-access-denied.html.twig
@@ -0,0 +1,21 @@
+
+
+{% trans %}Your request for the following resource could not be resolved: {{ requested_resource|placeholder }}{% endtrans %}
+
+{% trans %}Access to this resource is restricted to the following networks:{% endtrans %}
+
+
+ {% for item in ranges %}
+ {% if item.proxy_url is defined %}
+ - {{ item.label }}
+ {% else %}
+ - {{ item.label }}
+ {% endif %}
+ {% endfor %}
+
+
+{% trans %}If any of the listed networks above appear as links, you may be able to reach the resource by authenticating through a proxy.{% endtrans %}
+
+{% if contact_email != '' %}
+If you have any questions about access to this resource, contact {{ contact_email }} for more information.
+{% endif %}
From 20181e89a9481be2b47033f7f30771f471c74be9 Mon Sep 17 00:00:00 2001
From: qadan
Date: Fri, 10 Jul 2020 14:55:06 -0300
Subject: [PATCH 04/12] and a host of fixes
---
.../EmbargoesEmbargoEntityListBuilder.php | 61 ++++++++-----------
.../EmbargoesIpRangeEntityListBuilder.php | 2 +-
src/Controller/EmbargoesLogController.php | 36 ++++-------
.../EmbargoesNodeEmbargoesController.php | 15 +++--
src/Entity/EmbargoesIpRangeEntity.php | 2 +-
src/Form/EmbargoesEmbargoEntityDeleteForm.php | 1 +
src/Form/EmbargoesEmbargoEntityForm.php | 27 +++++++-
src/Form/EmbargoesIpRangeEntityForm.php | 4 +-
8 files changed, 75 insertions(+), 73 deletions(-)
diff --git a/src/Controller/EmbargoesEmbargoEntityListBuilder.php b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
index 83213b0..727e137 100644
--- a/src/Controller/EmbargoesEmbargoEntityListBuilder.php
+++ b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
@@ -7,9 +7,11 @@
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
-use Drupal\Core\Entity\NodeStorageInterface;
-use Drupal\Core\Entity\UserStorageInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
+use Drupal\Core\Url;
+use Drupal\Core\Utility\LinkGeneratorInterface;
+use Drupal\node\NodeStorageInterface;
+use Drupal\user\UserStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -39,11 +41,11 @@ class EmbargoesEmbargoEntityListBuilder extends ConfigEntityListBuilder implemen
protected $ipRanges;
/**
- * URL generator.
+ * Link generating service.
*
- * @var \Drupal\Core\Routing\UrlGeneratorInterface
+ * @var \Drupal\Core\Utility\LinkGeneratorInterface
*/
- protected $urlGenerator;
+ protected $linkGenerator;
/**
* Create an embargo entity list builder.
@@ -52,21 +54,21 @@ class EmbargoesEmbargoEntityListBuilder extends ConfigEntityListBuilder implemen
* An entity type interface for embargoes.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* Entity storage for embargoes.
- * @param \Drupal\Core\Entity\UserStorageInterface $user
+ * @param \Drupal\user\UserStorageInterface $user
* User storage.
- * @param \Drupal\Core\Entity\NodeStorageInterface $node
+ * @param \Drupal\node\NodeStorageInterface $node
* Node storage.
- * @param \Drupal\embargoes\EmbargoesIpRangeEntityInterface $ip_ranges
+ * @param \Drupal\Core\Entity\EntityStorageInterface $ip_ranges
* IP range entity interface.
- * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
- * A URL generator.
+ * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
+ * Link generator.
*/
- public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, UserStorageInterface $user, NodeStorageInterface $node, EmbargoesIpRangeEntityInterface $ip_ranges, UrlGeneratorInterface $url_generator) {
+ public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, UserStorageInterface $user, NodeStorageInterface $node, EntityStorageInterface $ip_ranges, LinkGeneratorInterface $link_generator) {
parent::__construct($entity_type, $storage);
$this->user = $user;
$this->node = $node;
$this->ipRanges = $ip_ranges;
- $this->urlGenerator = $url_generator;
+ $this->linkGenerator = $link_generator;
}
/**
@@ -79,7 +81,7 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
$container->get('entity_type.manager')->getStorage('user'),
$container->get('entity_type.manager')->getStorage('node'),
$container->get('entity_type.manager')->getStorage('embargoes_ip_range_entity'),
- $container->get('url_generator'));
+ $container->get('link_generator'));
}
/**
@@ -107,39 +109,26 @@ public function buildRow(EntityInterface $entity) {
foreach ($entity->getExemptUsers() as $user) {
$uid = $user['target_id'];
$user_entity = $this->user->load($uid);
- $formatted_users[] = [
- '#type' => 'link',
- '#title' => $user_entity->getUserName(),
- '#url' => $this->urlGenerator->generateFromRoute('entity.user.canonical', [
- 'user' => $uid,
- ]),
- ];
-
+ $formatted_users[] = $this->linkGenerator->generate($user_entity->getUserName(), Url::fromRoute('entity.user.canonical', [
+ 'user' => $uid,
+ ]));
}
$formatted_exempt_users_row = ['data' => $formatted_users];
$nid = $entity->getEmbargoedNode();
$node = $this->node->load($nid);
- $formatted_node_row = [
- '#type' => 'link',
- '#title' => $node->title->value,
- '#url' => $this->urlGenerator->generateFromRoute('entity.node.canonical', [
- 'node' => $nid,
- ]),
- ];
+ $formatted_node_row = $this->linkGenerator->generate($node->title->value, Url::fromRoute('entity.node.canonical', [
+ 'node' => $nid,
+ ]));
$ip_range = $this->ipRanges->load($entity->getExemptIps());
if (!is_null($ip_range)) {
- $ip_range_formatted = [
- '#type' => 'link',
- '#title' => $ip_range->label(),
- '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_ip_range_entity.add_form', [
- 'id' => $entity->getExemptIps(),
- ]),
- ];
+ $ip_range_formatted = $this->linkGenerator->generate($ip_range->label(), Url::fromRoute('entity.embargoes_ip_range_entity.add_form', [
+ 'embargoes_ip_range_entity' => $entity->getExemptIps(),
+ ]));
}
else {
- $ip_range_formatted = "None";
+ $ip_range_formatted = $this->t("None");
}
$formatted_emails = [
diff --git a/src/Controller/EmbargoesIpRangeEntityListBuilder.php b/src/Controller/EmbargoesIpRangeEntityListBuilder.php
index 075abd9..15af793 100644
--- a/src/Controller/EmbargoesIpRangeEntityListBuilder.php
+++ b/src/Controller/EmbargoesIpRangeEntityListBuilder.php
@@ -27,7 +27,7 @@ public function buildHeader() {
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['id'] = $entity->id();
- $row['range'] = ['#markup' => implode('
', $entity->getRanges())];
+ $row['range'] = implode(', ', $entity->getRanges());
$row['proxy_url'] = $entity->getProxyUrl();
return $row + parent::buildRow($entity);
}
diff --git a/src/Controller/EmbargoesLogController.php b/src/Controller/EmbargoesLogController.php
index f4486f3..ee4f0da 100644
--- a/src/Controller/EmbargoesLogController.php
+++ b/src/Controller/EmbargoesLogController.php
@@ -4,6 +4,7 @@
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
+use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -58,13 +59,9 @@ public function showRenderedLog() {
$embargo_formatted = ['#markup' => "{$record->embargo}"];
}
else {
- $embargo_formatted = [
- '#type' => 'link',
- '#title' => $record->embargo,
- '#link' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.edit_form', [
- 'id' => $record->embargo,
- ]),
- ];
+ $embargo_formatted = $this->getLinkGenerator()->generate($record->embargo, Url::fromRoute('entity.embargoes_embargo_entity.edit_form', [
+ 'embargoes_embargo_entity' => $record->embargo,
+ ]));
}
$row = [
@@ -72,25 +69,17 @@ public function showRenderedLog() {
'embargo' => $embargo_formatted,
'time' => $formatted_time,
'action' => ucfirst($record->action),
- 'node' => [
- '#type' => 'link',
- '#title' => $node_title,
- '#link' => $this->urlGenerator->generateFromRoute('entity.node.canonical', [
- 'node' => $record->node,
- ]),
- ],
- 'user' => [
- '#type' => 'link',
- '#title' => $username,
- '#link' => $this->urlGenerator->generateFromRoute('entity.user.canonical', [
- 'user' => $record->uid,
- ]),
- ],
+ 'node' => $this->getLinkGenerator()->generate($node_title, Url::fromRoute('entity.node.canonical', [
+ 'node' => $record->node,
+ ])),
+ 'user' => $this->getLinkGenerator()->generate($username, Url::fromRoute('entity.user.canonical', [
+ 'user' => $record->uid,
+ ])),
];
array_push($formatted_log, $row);
}
- $pre_rendered_log = [
+ $log = [
'#type' => 'table',
'#header' => [
$this->t('Event ID'),
@@ -104,8 +93,7 @@ public function showRenderedLog() {
];
return [
- '#type' => 'markup',
- '#markup' => $pre_rendered_log,
+ 'log' => $log,
];
}
diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php
index 3c0282d..cfc331d 100644
--- a/src/Controller/EmbargoesNodeEmbargoesController.php
+++ b/src/Controller/EmbargoesNodeEmbargoesController.php
@@ -5,6 +5,7 @@
use Drupal\embargoes\EmbargoesEmbargoesServiceInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -75,7 +76,7 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$formatted_users[] = [
'#type' => 'link',
'#title' => $user_name,
- '#url' => $this->urlGenerator->generateFromRoute('entity.user.canonical', [
+ '#url' => Url::fromRoute('entity.user.canonical', [
'user' => $uid,
]),
];
@@ -89,7 +90,7 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$ip_range_formatted = [
'#type' => 'link',
'#title' => $ip_range->label(),
- '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_ip_range.edit_form', [
+ '#url' => Url::fromRoute('entity.embargoes_ip_range.edit_form', [
'id' => $embargo->getExemptIps(),
]),
];
@@ -115,14 +116,14 @@ public function showEmbargoes(NodeInterface $node = NULL) {
'edit' => [
'#type' => 'link',
'#title' => $this->t('Edit'),
- '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.edit_form', [
+ '#url' => Url::fromRoute('entity.embargoes_embargo_entity.edit_form', [
'id' => $embargo_id,
]),
],
'delete' => [
'#type' => 'link',
'#title' => $this->t('Delete'),
- '#url' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.delete_form', [
+ '#url' => Url::fromRoute('entity.embargoes_embargo_entity.delete_form', [
'id' => $embargo_id,
]),
],
@@ -145,12 +146,14 @@ public function showEmbargoes(NodeInterface $node = NULL) {
];
}
- $markup['add'] = [
+ $markup['add_embargo'] = [
'#type' => 'link',
'#title' => $this->t('Add Embargo'),
- '#link' => $this->urlGenerator->generateFromRoute('entity.embargoes_embargo_entity.add_form'),
+ '#link' => Url::fromRoute('entity.embargoes_embargo_entity.add_form'),
];
+ ksm($markup);
+
return $markup;
}
diff --git a/src/Entity/EmbargoesIpRangeEntity.php b/src/Entity/EmbargoesIpRangeEntity.php
index 30f5471..539feb8 100644
--- a/src/Entity/EmbargoesIpRangeEntity.php
+++ b/src/Entity/EmbargoesIpRangeEntity.php
@@ -59,7 +59,7 @@ class EmbargoesIpRangeEntity extends ConfigEntityBase implements EmbargoesIpRang
*
* @var string[]
*/
- protected $ranges;
+ protected $ranges = [];
/**
* The IP Range proxy URL.
diff --git a/src/Form/EmbargoesEmbargoEntityDeleteForm.php b/src/Form/EmbargoesEmbargoEntityDeleteForm.php
index 26b439d..e79644a 100644
--- a/src/Form/EmbargoesEmbargoEntityDeleteForm.php
+++ b/src/Form/EmbargoesEmbargoEntityDeleteForm.php
@@ -5,6 +5,7 @@
use Drupal\embargoes\EmbargoesLogServiceInterface;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
diff --git a/src/Form/EmbargoesEmbargoEntityForm.php b/src/Form/EmbargoesEmbargoEntityForm.php
index c42b05b..77fd6bd 100644
--- a/src/Form/EmbargoesEmbargoEntityForm.php
+++ b/src/Form/EmbargoesEmbargoEntityForm.php
@@ -4,6 +4,7 @@
use Drupal\embargoes\EmbargoesIpRangesServiceInterface;
use Drupal\embargoes\EmbargoesLogServiceInterface;
+use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -27,6 +28,13 @@ class EmbargoesEmbargoEntityForm extends EntityForm {
*/
protected $embargoesLog;
+ /**
+ * UUID interface.
+ *
+ * @var \Drupal\Component\Uuid\UuidInterface
+ */
+ protected $uuidGenerator;
+
/**
* Constructor for the node embargo form.
*
@@ -34,10 +42,13 @@ class EmbargoesEmbargoEntityForm extends EntityForm {
* An embargoes IP ranges manager.
* @param \Drupal\embargoes\EmbargoesLogServiceInterface $embargoes_log
* An embargoes logging service.
+ * @param \Drupal\Component\Uuid\UuidInterface $uuid_generator
+ * A UUID generator.
*/
- public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log) {
+ public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log, UuidInterface $uuid_generator) {
$this->ipRanges = $ip_ranges;
$this->embargoesLog = $embargoes_log;
+ $this->uuidGenerator = $uuid_generator;
}
/**
@@ -46,7 +57,8 @@ public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges, Embarg
public static function create(ContainerInterface $container) {
return new static(
$container->get('embargoes.ips'),
- $container->get('embargoes.log'));
+ $container->get('embargoes.log'),
+ $container->get('uuid'));
}
/**
@@ -56,6 +68,12 @@ public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$embargo = $this->entity;
+ $id = $this->entity->id();
+ $form['id'] = [
+ '#type' => 'value',
+ '#value' => isset($id) ? $id : sha1($this->uuidGenerator->generate()),
+ ];
+
$form['embargo_type'] = [
'#type' => 'radios',
'#title' => $this->t('Embargo type'),
@@ -118,12 +136,15 @@ public function form(array $form, FormStateInterface $form_state) {
];
$embargoed_node = $embargo->getEmbargoedNode();
+ if ($embargoed_node) {
+ $embargoed_node = $this->entityTypeManager->getStorage('node')->load($embargoed_node);
+ }
$form['embargoed_node'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#title' => $this->t('Embargoed node'),
'#maxlength' => 255,
- '#default_value' => $embargoed_node ? $embargoed_node : '',
+ '#default_value' => $embargoed_node ? $embargoed_node : [],
'#required' => TRUE,
];
diff --git a/src/Form/EmbargoesIpRangeEntityForm.php b/src/Form/EmbargoesIpRangeEntityForm.php
index 7b442b6..c2abcba 100644
--- a/src/Form/EmbargoesIpRangeEntityForm.php
+++ b/src/Form/EmbargoesIpRangeEntityForm.php
@@ -87,11 +87,11 @@ public function form(array $form, FormStateInterface $form_state) {
*/
public function save(array $form, FormStateInterface $form_state) {
$range = $this->entity;
- $range->setRange($form_state->getValue('range'));
+ $range->setRanges($form_state->getValue('range'));
$range->setProxyUrl($form_state->getValue('proxy_url'));
$status = $range->save();
- $errors = $this->ipRanges->detectIpRangeStringErrors($form_state->getValue('range'));
+ $errors = $this->ipRanges->detectIpRangeStringErrors(array_map('trim', explode('|', trim($form_state->getValue('range')))));
if (!$errors) {
switch ($status) {
case SAVED_NEW:
From 7bbdddc16a7f6697c807b04c9b258af79cc44cab Mon Sep 17 00:00:00 2001
From: qadan
Date: Fri, 10 Jul 2020 14:56:23 -0300
Subject: [PATCH 05/12] and re-run coding standards
---
src/Controller/EmbargoesEmbargoEntityListBuilder.php | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/Controller/EmbargoesEmbargoEntityListBuilder.php b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
index 727e137..9203118 100644
--- a/src/Controller/EmbargoesEmbargoEntityListBuilder.php
+++ b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
@@ -7,7 +7,6 @@
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
-use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\node\NodeStorageInterface;
From 5c01fc6ad6bd417becd08880a2d65325f758a984 Mon Sep 17 00:00:00 2001
From: qadan
Date: Mon, 13 Jul 2020 10:18:20 -0300
Subject: [PATCH 06/12] nasty ksm hiding in there
---
src/Controller/EmbargoesNodeEmbargoesController.php | 2 --
1 file changed, 2 deletions(-)
diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php
index cfc331d..0108b8c 100644
--- a/src/Controller/EmbargoesNodeEmbargoesController.php
+++ b/src/Controller/EmbargoesNodeEmbargoesController.php
@@ -152,8 +152,6 @@ public function showEmbargoes(NodeInterface $node = NULL) {
'#link' => Url::fromRoute('entity.embargoes_embargo_entity.add_form'),
];
- ksm($markup);
-
return $markup;
}
From d49867911ee52e459752623a65d51f05fdd988c1 Mon Sep 17 00:00:00 2001
From: qadan
Date: Mon, 13 Jul 2020 10:20:17 -0300
Subject: [PATCH 07/12] null default
---
src/Form/EmbargoesEmbargoEntityForm.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Form/EmbargoesEmbargoEntityForm.php b/src/Form/EmbargoesEmbargoEntityForm.php
index 77fd6bd..027e029 100644
--- a/src/Form/EmbargoesEmbargoEntityForm.php
+++ b/src/Form/EmbargoesEmbargoEntityForm.php
@@ -144,7 +144,7 @@ public function form(array $form, FormStateInterface $form_state) {
'#target_type' => 'node',
'#title' => $this->t('Embargoed node'),
'#maxlength' => 255,
- '#default_value' => $embargoed_node ? $embargoed_node : [],
+ '#default_value' => $embargoed_node ? $embargoed_node : NULL,
'#required' => TRUE,
];
From e68defaa985bbb54dc7a8f85336de09ac36be7c6 Mon Sep 17 00:00:00 2001
From: qadan
Date: Mon, 20 Jul 2020 13:36:08 -0300
Subject: [PATCH 08/12] fixes for things
---
embargoes.module | 1 +
src/Access/EmbargoedAccessResult.php | 11 ++--
.../EmbargoesNodeEmbargoesController.php | 65 ++++++++++++-------
3 files changed, 46 insertions(+), 31 deletions(-)
diff --git a/embargoes.module b/embargoes.module
index c80bb99..0c9310a 100644
--- a/embargoes.module
+++ b/embargoes.module
@@ -36,6 +36,7 @@ function embargoes_file_access(EntityInterface $file, $operation, AccountInterfa
* Implements hook_node_view().
*/
function embargoes_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
+ \Drupal::service('embargoes.node_access')->isActivelyEmbargoed($entity, \Drupal::currentUser());
$node_embargo = \Drupal::service('embargoes.node_access');
$ip_url = $node_embargo->getIpEmbargoedRedirectUrl($entity);
if ($ip_url) {
diff --git a/src/Access/EmbargoedAccessResult.php b/src/Access/EmbargoedAccessResult.php
index cae2e6b..63cb725 100644
--- a/src/Access/EmbargoedAccessResult.php
+++ b/src/Access/EmbargoedAccessResult.php
@@ -12,6 +12,7 @@
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\HttpFoundation\RequestStack;
+use InvalidArgumentException;
/**
* Base implementation of embargoed access.
@@ -111,19 +112,17 @@ public function __construct(EmbargoesEmbargoesServiceInterface $embargoes, Reque
* @return string
* The entity type this access control should apply to.
*/
- public static function entityType() {
- return '';
- }
+ abstract public static function entityType();
/**
* {@inheritdoc}
*/
public function isActivelyEmbargoed(EntityInterface $entity) {
- $group_type = $entity->getEntityType()->getGroupType();
+ $entity_type = $entity->getEntityType()->id();
$expected = static::entityType();
- if ($group_type !== $expected) {
+ if ($entity_type !== $expected) {
throw new InvalidArgumentException($this->translator->translate('Attempting to check embargoed access status for an entity of type %type (expected: %expected)', [
- '%type' => $group_type,
+ '%type' => $entity_type,
'%expected' => $expected,
]));
}
diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php
index 0108b8c..a6d68da 100644
--- a/src/Controller/EmbargoesNodeEmbargoesController.php
+++ b/src/Controller/EmbargoesNodeEmbargoesController.php
@@ -44,7 +44,6 @@ public static function create(ContainerInterface $container) {
* Renderable array to show the embargoes on a node.
*/
public function showEmbargoes(NodeInterface $node = NULL) {
-
$embargo_ids = $this->embargoes->getAllEmbargoesByNids([$node->id()]);
if (empty($embargo_ids)) {
$markup['embargoes'] = [
@@ -66,7 +65,9 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$formatted_users = [];
$exempt_users = $embargo->getExemptUsers();
if (empty($exempt_users)) {
- $formatted_users[] = "None";
+ $formatted_users = [
+ '#markup' => $this->t('None'),
+ ];
}
else {
foreach ($embargo->getExemptUsers() as $user) {
@@ -88,11 +89,13 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$ip_range = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps());
if (!is_null($ip_range)) {
$ip_range_formatted = [
- '#type' => 'link',
- '#title' => $ip_range->label(),
- '#url' => Url::fromRoute('entity.embargoes_ip_range.edit_form', [
- 'id' => $embargo->getExemptIps(),
- ]),
+ 'data' => [
+ '#type' => 'link',
+ '#title' => $ip_range->label(),
+ '#url' => Url::fromRoute('entity.embargoes_ip_range.edit_form', [
+ 'embargoes_embargo_entity' => $embargo->getExemptIps(),
+ ]),
+ ],
];
}
else {
@@ -113,19 +116,24 @@ public function showEmbargoes(NodeInterface $node = NULL) {
'exempt_ips' => $ip_range_formatted,
'exempt_users' => $formatted_exempt_users_row,
'additional_emails' => $formatted_emails,
- 'edit' => [
- '#type' => 'link',
- '#title' => $this->t('Edit'),
- '#url' => Url::fromRoute('entity.embargoes_embargo_entity.edit_form', [
- 'id' => $embargo_id,
- ]),
- ],
- 'delete' => [
- '#type' => 'link',
- '#title' => $this->t('Delete'),
- '#url' => Url::fromRoute('entity.embargoes_embargo_entity.delete_form', [
- 'id' => $embargo_id,
- ]),
+ 'operations' => [
+ 'data' => [
+ '#type' => 'operations',
+ '#links' => [
+ 'edit' => [
+ 'title' => $this->t('Edit'),
+ 'url' => Url::fromRoute('entity.embargoes_embargo_entity.edit_form', [
+ 'embargoes_embargo_entity' => $embargo_id,
+ ]),
+ ],
+ 'delete' => [
+ 'title' => $this->t('Delete'),
+ 'url' => Url::fromRoute('entity.embargoes_embargo_entity.delete_form', [
+ 'embargoes_embargo_entity' => $embargo_id,
+ ]),
+ ],
+ ],
+ ],
],
];
array_push($rows, $row);
@@ -139,17 +147,24 @@ public function showEmbargoes(NodeInterface $node = NULL) {
$this->t('Exempt IP Range'),
$this->t('Exempt Users'),
$this->t('Additional Emails'),
- $this->t('Edit'),
- $this->t('Delete'),
+ $this->t('Operations'),
],
'#rows' => $rows,
];
+
}
$markup['add_embargo'] = [
- '#type' => 'link',
- '#title' => $this->t('Add Embargo'),
- '#link' => Url::fromRoute('entity.embargoes_embargo_entity.add_form'),
+ '#type' => 'operations',
+ '#links' => [
+ 'add' => [
+ 'title' => $this->t('Add New Embargo'),
+ 'url' => Url::fromRoute('embargoes.node.embargo', [
+ 'node' => $node->id(),
+ 'embargo_id' => 'add',
+ ]),
+ ],
+ ],
];
return $markup;
From cefe83089e82ab90ff14abdd84cbde14f2120248 Mon Sep 17 00:00:00 2001
From: qadan
Date: Tue, 21 Jul 2020 11:00:25 -0300
Subject: [PATCH 09/12] default for ranges query
---
src/Controller/EmbargoesIpAccessDeniedController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controller/EmbargoesIpAccessDeniedController.php b/src/Controller/EmbargoesIpAccessDeniedController.php
index 0e3a1b6..28ec407 100644
--- a/src/Controller/EmbargoesIpAccessDeniedController.php
+++ b/src/Controller/EmbargoesIpAccessDeniedController.php
@@ -60,7 +60,7 @@ public function response() {
$requested_resource = $this->getRequestedResource();
$contact_email = $this->config('embargoes.settings')->get('embargo_contact_email');
$ranges = [];
- foreach ($this->request->query->get('ranges') as $allowed_range) {
+ foreach ($this->request->query->get('ranges', []) as $allowed_range) {
$allowed_range_entity = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($allowed_range);
$proxy_url = $allowed_range_entity->getProxyUrl() != '' ? $allowed_range_entity->getProxyUrl() : NULL;
if ($allowed_range_entity->getProxyUrl() != '') {
From f3c9d003641661a0e0b3aebf27bf51c1b389599e Mon Sep 17 00:00:00 2001
From: qadan
Date: Tue, 21 Jul 2020 12:44:37 -0300
Subject: [PATCH 10/12] random issues with random forms and random screens
---
.../EmbargoesEmbargoEntityListBuilder.php | 40 +++++++++++++++----
src/Entity/EmbargoesEmbargoEntity.php | 2 +-
2 files changed, 34 insertions(+), 8 deletions(-)
diff --git a/src/Controller/EmbargoesEmbargoEntityListBuilder.php b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
index 9203118..20e0146 100644
--- a/src/Controller/EmbargoesEmbargoEntityListBuilder.php
+++ b/src/Controller/EmbargoesEmbargoEntityListBuilder.php
@@ -104,15 +104,33 @@ public function buildHeader() {
*/
public function buildRow(EntityInterface $entity) {
- $formatted_users = [];
+ $users = [
+ 'data' => [
+ '#type' => 'container',
+ ],
+ ];
foreach ($entity->getExemptUsers() as $user) {
$uid = $user['target_id'];
$user_entity = $this->user->load($uid);
- $formatted_users[] = $this->linkGenerator->generate($user_entity->getUserName(), Url::fromRoute('entity.user.canonical', [
- 'user' => $uid,
- ]));
+ if ($user_entity) {
+ $users['data'][$user_entity->getUserName()] = [
+ '#type' => 'link',
+ '#title' => $user_entity->getUserName(),
+ '#url' => Url::fromRoute('entity.user.canonical', [
+ 'user' => $uid,
+ ]),
+ '#suffix' => '
',
+ ];
+ }
+ else {
+ $users['data']["missing-{$uid}"] = [
+ '#markup' => $this->t('Invalid user (%uid)', [
+ '%uid' => (string) $uid,
+ ]),
+ '#suffix' => '
',
+ ];
+ }
}
- $formatted_exempt_users_row = ['data' => $formatted_users];
$nid = $entity->getEmbargoedNode();
$node = $this->node->load($nid);
@@ -131,15 +149,23 @@ public function buildRow(EntityInterface $entity) {
}
$formatted_emails = [
- '#markup' => implode('
', $entity->getAdditionalEmails()),
+ 'data' => [
+ '#type' => 'container',
+ ],
];
+ foreach ($entity->getAdditionalEmails() as $email) {
+ $formatted_emails['data'][$email] = [
+ '#markup' => $email,
+ '#suffix' => '
',
+ ];
+ }
$row['id'] = $entity->id();
$row['embargo_type'] = ($entity->getEmbargoType() == 1 ? 'Node' : 'Files');
$row['expiration_type'] = ($entity->getExpirationType() == 1 ? 'Scheduled' : 'Indefinite');
$row['expiration_date'] = (!empty($entity->getExpirationDate()) ? $entity->getExpirationDate() : 'None');
$row['exempt_ips'] = $ip_range_formatted;
- $row['exempt_users'] = $formatted_exempt_users_row;
+ $row['exempt_users'] = $users;
$row['additional_emails'] = $formatted_emails;
$row['notification_status'] = ucfirst($entity->getNotificationStatus());
$row['embargoed_node'] = $formatted_node_row;
diff --git a/src/Entity/EmbargoesEmbargoEntity.php b/src/Entity/EmbargoesEmbargoEntity.php
index bde1729..5f5c99d 100644
--- a/src/Entity/EmbargoesEmbargoEntity.php
+++ b/src/Entity/EmbargoesEmbargoEntity.php
@@ -235,7 +235,7 @@ public function getAdditionalEmails() {
* {@inheritdoc}
*/
public function setAdditionalEmails($emails) {
- $emails = array_map('trim', explode(',', trim($emails)));
+ $emails = empty($emails) ? [] : array_map('trim', explode(',', trim($emails)));
$this->set('additional_emails', $emails);
return $this;
}
From e85d1cb4562f15730cdcac8d0626f08ae67fd104 Mon Sep 17 00:00:00 2001
From: qadan
Date: Fri, 24 Jul 2020 12:26:19 -0300
Subject: [PATCH 11/12] move some schema stuff, generate ids
---
config/schema/embargoes.schema.yml | 69 ++++++++++++++++++-
.../embargoes_embargo_entity.schema.yml | 42 -----------
.../embargoes_ip_range_entity.schema.yml | 23 -------
src/Form/EmbargoesNodeEmbargoesForm.php | 20 +++++-
4 files changed, 85 insertions(+), 69 deletions(-)
delete mode 100644 config/schema/embargoes_embargo_entity.schema.yml
delete mode 100644 config/schema/embargoes_ip_range_entity.schema.yml
diff --git a/config/schema/embargoes.schema.yml b/config/schema/embargoes.schema.yml
index 5fb6b22..e3ed684 100644
--- a/config/schema/embargoes.schema.yml
+++ b/config/schema/embargoes.schema.yml
@@ -1,10 +1,10 @@
----
condition.plugin.embargoes_embargoed_condition:
type: condition.plugin
mapping:
filter:
type: text
label: 'Embargo Filter'
+
embargoes.settings:
type: config_object
mapping:
@@ -17,3 +17,70 @@ embargoes.settings:
show_embargo_message:
type: boolean
label: 'Whether to display an embargo warning on embargoed nodes'
+
+embargoes.embargoes_embargo_entity.*:
+ type: config_entity
+ label: 'Embargo config'
+ mapping:
+ id:
+ type: string
+ label: 'ID'
+ embargo_type:
+ type: boolean
+ label: 'Embargo Type'
+ expiration_type:
+ type: boolean
+ label: 'Expiration Type'
+ expiration_date:
+ type: string
+ label: 'Expiration Date'
+ exempt_ips:
+ type: string
+ label: 'Exempt IP Ranges'
+ nullable: true
+ exempt_users:
+ type: sequence
+ label: 'Exempt Users'
+ sequence:
+ type: mapping
+ mapping:
+ target_id:
+ type: integer
+ additional_emails:
+ type: sequence
+ label: 'Additional Emails'
+ sequence:
+ type: mapping
+ mapping:
+ additional_email:
+ type: string
+ embargoed_node:
+ type: integer
+ label: 'Embargoed Node'
+ notification_status:
+ type: string
+ label: 'Notification Status'
+
+embargoes.embargoes_ip_range_entity.*:
+ type: config_entity
+ label: 'IP Range config'
+ mapping:
+ id:
+ type: string
+ label: 'ID'
+ label:
+ type: label
+ label: 'Label'
+ ranges:
+ type: sequence
+ label: 'Ranges'
+ sequence:
+ type: mapping
+ mapping:
+ range:
+ type: string
+ proxy_url:
+ type: string
+ label: 'Proxy URL'
+ uuid:
+ type: string
diff --git a/config/schema/embargoes_embargo_entity.schema.yml b/config/schema/embargoes_embargo_entity.schema.yml
deleted file mode 100644
index 6d2659c..0000000
--- a/config/schema/embargoes_embargo_entity.schema.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-embargoes.embargoes_embargo_entity.*:
- type: config_entity
- label: 'Embargo config'
- mapping:
- id:
- type: string
- label: 'ID'
- embargo_type:
- type: boolean
- label: 'Embargo Type'
- expiration_type:
- type: boolean
- label: 'Expiration Type'
- expiration_date:
- type: string
- label: 'Expiration Date'
- exempt_ips:
- type: string
- label: 'Exempt IP Ranges'
- nullable: true
- exempt_users:
- type: sequence
- label: 'Exempt Users'
- sequence:
- type: mapping
- mapping:
- target_id:
- type: integer
- additional_emails:
- type: sequence
- label: 'Additional Emails'
- sequence:
- type: mapping
- mapping:
- additional_email:
- type: string
- embargoed_node:
- type: integer
- label: 'Embargoed Node'
- notification_status:
- type: string
- label: 'Notification Status'
diff --git a/config/schema/embargoes_ip_range_entity.schema.yml b/config/schema/embargoes_ip_range_entity.schema.yml
deleted file mode 100644
index 0d9894c..0000000
--- a/config/schema/embargoes_ip_range_entity.schema.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-embargoes.embargoes_ip_range_entity.*:
- type: config_entity
- label: 'IP Range config'
- mapping:
- id:
- type: string
- label: 'ID'
- label:
- type: label
- label: 'Label'
- ranges:
- type: sequence
- label: 'Ranges'
- sequence:
- type: mapping
- mapping:
- range:
- type: string
- proxy_url:
- type: string
- label: 'Proxy URL'
- uuid:
- type: string
diff --git a/src/Form/EmbargoesNodeEmbargoesForm.php b/src/Form/EmbargoesNodeEmbargoesForm.php
index b6c2edb..69585ab 100644
--- a/src/Form/EmbargoesNodeEmbargoesForm.php
+++ b/src/Form/EmbargoesNodeEmbargoesForm.php
@@ -5,6 +5,7 @@
use Drupal\embargoes\EmbargoesIpRangesServiceInterface;
use Drupal\embargoes\EmbargoesLogServiceInterface;
use Drupal\node\NodeInterface;
+use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
@@ -36,6 +37,13 @@ class EmbargoesNodeEmbargoesForm extends FormBase {
*/
protected $embargoesLog;
+ /**
+ * A UUID generator service.
+ *
+ * @var \Drupal\Component\Uuid\UuidInterface
+ */
+ protected $uuidGenerator;
+
/**
* Constructor for the node embargo form.
*
@@ -45,11 +53,14 @@ class EmbargoesNodeEmbargoesForm extends FormBase {
* An embargoes IP ranges manager.
* @param \Drupal\embargoes\EmbargoesLogServiceInterface $embargoes_log
* An embargoes logging service.
+ * @param \Drupal\Component\Uuid\UuidInterface
+ * A UUID generator.
*/
- public function __construct(EntityTypeManagerInterface $entity_manager, EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log) {
+ public function __construct(EntityTypeManagerInterface $entity_manager, EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log, UuidInterface $uuid_generator) {
$this->entityManager = $entity_manager;
$this->ipRanges = $ip_ranges;
$this->embargoesLog = $embargoes_log;
+ $this->uuidGenerator = $uuid_generator;
}
/**
@@ -59,7 +70,8 @@ public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('embargoes.ips'),
- $container->get('embargoes.log'));
+ $container->get('embargoes.log'),
+ $container->get('uuid'));
}
/**
@@ -180,7 +192,9 @@ public function buildForm(array $form, FormStateInterface $form_state, NodeInter
public function submitForm(array &$form, FormStateInterface $form_state) {
$embargo_id = $form_state->getValue('embargo_id');
if ($embargo_id == 'add') {
- $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->create();
+ $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->create([
+ 'id' => sha1($this->uuidGenerator->generate()),
+ ]);
}
else {
$embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->load($embargo_id);
From 19c563b40cbed467fdd6ba0b92665e5e77bed0b7 Mon Sep 17 00:00:00 2001
From: qadan
Date: Fri, 24 Jul 2020 12:27:08 -0300
Subject: [PATCH 12/12] missing a thing
---
src/Form/EmbargoesNodeEmbargoesForm.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Form/EmbargoesNodeEmbargoesForm.php b/src/Form/EmbargoesNodeEmbargoesForm.php
index 69585ab..f66a185 100644
--- a/src/Form/EmbargoesNodeEmbargoesForm.php
+++ b/src/Form/EmbargoesNodeEmbargoesForm.php
@@ -53,7 +53,7 @@ class EmbargoesNodeEmbargoesForm extends FormBase {
* An embargoes IP ranges manager.
* @param \Drupal\embargoes\EmbargoesLogServiceInterface $embargoes_log
* An embargoes logging service.
- * @param \Drupal\Component\Uuid\UuidInterface
+ * @param \Drupal\Component\Uuid\UuidInterface $uuid_generator
* A UUID generator.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log, UuidInterface $uuid_generator) {