diff --git a/README.md b/README.md index 5e176ff..227f970 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,41 @@ # Embargoes -Drupal 8 module for managing embargo policies with access restrictions on content + +Adds the ability to manage embargo policies with access restrictions on content. ## Requirements -Embargoes requires no other Drupal modules to work. + +This module requires the following modules/libraries: + +* [Menu UI](https://www.drupal.org/docs/core-modules-and-themes/core-modules/menu-ui-module) + +## Installation + +Install as +[usual](https://www.drupal.org/docs/8/extending-drupal-8/installing-drupal-8-modules). + +## Configuration + +Configuration options can be set at `admin/config/content/embargoes/settings`, +including notification options and IP range settings that can apply to +embargoes. + +To add an IP range for use on embargoes, navigate to +`admin/config/content/embargoes/settings/ips` and click 'Add IP range'. Ranges +created via this method can then be used as IP address whitelists when creating +embargoes. + +## Usage + +### Applying an embargo + +An embargo can be applied to an existing node by navigating to +`node/{node_id}/embargoes`. From here, an embargo can be applied if it doesn't +already exist, and existing embargoes can be modified or removed. + +## Maintainers/Sponsors + +* [FSU Library](https://github.com/fsulib/embargoes) +* [discoverygarden](http://support.discoverygarden.ca) ## License [GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt) diff --git a/composer.json b/composer.json index 2344475..e15ad1e 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,9 @@ "keywords": ["Drupal"], "homepage": "https://github.com/fsulib/embargoes", "license": "GPL-2.0+", + "replace": { + "drupal/embargoes":"*" + }, "authors": [ { "name": "Bryan J. Brown", diff --git a/config/install/embargoes.settings.yml b/config/install/embargoes.settings.yml new file mode 100644 index 0000000..3f90071 --- /dev/null +++ b/config/install/embargoes.settings.yml @@ -0,0 +1,5 @@ +--- +embargo_contact_email: null +add_contact_to_notifications: true +show_embargo_message: true +embargo_notification_message: 'Access to this resource is restricted.' diff --git a/config/schema/embargoes.schema.yml b/config/schema/embargoes.schema.yml index 7393a51..a4739f3 100644 --- a/config/schema/embargoes.schema.yml +++ b/config/schema/embargoes.schema.yml @@ -4,3 +4,83 @@ condition.plugin.embargoes_embargoed_condition: filter: type: text label: 'Embargo Filter' + +embargoes.settings: + type: config_object + mapping: + embargo_contact_email: + type: email + label: 'Contact email for embargo notifications' + add_contact_to_notifications: + type: boolean + label: 'Whether to add contact information to embargo notifications' + 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: integer + 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 bca5cbd..0000000 --- a/config/schema/embargoes_embargo_entity.schema.yml +++ /dev/null @@ -1,36 +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' - exempt_users: - type: sequence - label: 'Exempt Users' - sequence: - type: mapping - mapping: - target_id: - type: integer - additional_emails: - type: string - label: 'Additional Emails' - 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 ce296c8..0000000 --- a/config/schema/embargoes_ip_range_entity.schema.yml +++ /dev/null @@ -1,18 +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' - range: - type: string - label: 'Range' - proxy_url: - type: string - label: 'Proxy URL' - uuid: - type: string diff --git a/embargoes.info.yml b/embargoes.info.yml index 575a699..87e13d3 100644 --- a/embargoes.info.yml +++ b/embargoes.info.yml @@ -1,6 +1,6 @@ name: Embargoes description: 'A module for managing embargo policies with access restrictions on content.' type: module -core: 8.x +core_version_requirement: ^8 || ^9 dependencies: - menu_ui diff --git a/embargoes.install b/embargoes.install index f8ab0bb..01762db 100644 --- a/embargoes.install +++ b/embargoes.install @@ -1,13 +1,15 @@ 'Embargo log table.', @@ -22,15 +24,14 @@ function embargoes_schema() { 'not null' => TRUE, ], 'action' => [ - 'type' => 'varchar', - 'length' => 255, + 'type' => 'int', 'not null' => TRUE, ], 'node' => [ 'type' => 'int', 'not null' => TRUE, ], - 'user' => [ + 'uid' => [ 'type' => 'int', 'not null' => TRUE, ], @@ -41,6 +42,32 @@ function embargoes_schema() { ], ], 'primary key' => ['id'], + 'indexes' => [ + 'action' => ['action'], + 'uid' => ['uid'], + 'node' => ['node'], + ], ]; return $schema; } + +/** + * Update the 'user' column to be called 'uid'. + */ +function embargoes_update_8001(&$sandbox) { + Database::getConnection()->schema()->changeField('embargoes_log', 'user', 'uid', [ + 'not null' => TRUE, + 'type' => 'int', + ]); +} + +/** + * Add indices. + */ +function embargoes_update_8002(&$sandbox) { + $schema = Database::getConnection()->schema(); + $embargoes_schema = embargoes_schema(); + $schema->addIndex('embargoes_log', 'action', ['action'], $embargoes_schema['embargoes_log']); + $schema->addIndex('embargoes_log', 'uid', ['uid'], $embargoes_schema['embargoes_log']); + $schema->addIndex('embargoes_log', 'node', ['node'], $embargoes_schema['embargoes_log']); +} 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.links.task.yml b/embargoes.links.task.yml index 6898d15..9f000e4 100644 --- a/embargoes.links.task.yml +++ b/embargoes.links.task.yml @@ -22,12 +22,6 @@ entity.embargoes_embargo_entity.collection: base_route: embargoes.settings weight: 3 -embargoes.settings.log: - route_name: embargoes.settings.log - title: 'Log' - base_route: embargoes.settings - weight: 4 - embargoes.node.embargoes: route_name: embargoes.node.embargoes title: 'Embargoes' diff --git a/embargoes.module b/embargoes.module index 2ba2e54..0fbc013 100644 --- a/embargoes.module +++ b/embargoes.module @@ -1,167 +1,57 @@ 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(). + * Implements hook_ENTITY_TYPE_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}"); - $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'); - } - } - } +function embargoes_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) { + \Drupal::service('embargoes.node_access')->setEmbargoMessage($node); } /** * 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}"); - $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'); - } - } +function embargoes_media_view(array &$build, EntityInterface $media, EntityViewDisplayInterface $display, $view_mode) { + \Drupal::service('embargoes.media_access')->setEmbargoMessage($media); +} + +/** + * Implements hook_entity_type_alter(). + */ +function embargoes_entity_type_alter(array &$entity_types) { + if (isset($entity_types['file'])) { + $entity_types['file']->setHandlerClass('access', EmbargoesFileAccessHandler::class); } } @@ -172,17 +62,49 @@ 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}"); - $response->send(); + $file = reset($files); + if ($file instanceof EntityInterface) { + $access = \Drupal::service('embargoes.file_access')->isActivelyEmbargoed($file, \Drupal::currentUser()); + if ($access->isForbidden()) { + return -1; + } } - return NULL; +} + +/** + * Implements hook_theme(). + */ +function embargoes_theme($existing, $type, $theme, $path) { + return [ + 'embargoes_ip_access_denied' => [ + 'template' => 'embargoes-ip-access-denied', + 'variables' => [ + 'requested_resource' => NULL, + // Indexed array of ranges containing a 'proxy URL' (NULL if none exist) + // and a display 'label'. + 'ranges' => [ + [ + 'label' => NULL, + 'proxy_url' => NULL, + ], + ], + 'contact_email' => NULL, + ], + ], + 'embargoes_policies' => [ + 'template' => 'embargoes-policies', + 'variables' => [ + 'count' => NULL, + 'embargo_info' => [], + ], + ], + 'embargoes_notifications' => [ + 'template' => 'embargoes-notifications', + 'variables' => [ + 'count' => NULL, + 'embargo_info' => [], + 'message' => NULL, + ], + ], + ]; } diff --git a/embargoes.permissions.yml b/embargoes.permissions.yml index 753a170..a43c2b5 100644 --- a/embargoes.permissions.yml +++ b/embargoes.permissions.yml @@ -1,12 +1,16 @@ administer embargoes settings: title: 'Administer Embargoes settings' description: 'Access and manage configuration for the Embargoes module' - restrict access: TRUE + restrict access: true manage embargoes: title: 'Manage Embargoes' description: 'Apply, update and lift embargo policies on content' - restrict access: TRUE + restrict access: true bypass embargoes restrictions: title: 'Bypass Embargoes restrictions' description: 'Bypass access restrictions on content put in place by embargo policies' - restrict access: TRUE + restrict access: true +access embargoes logs: + title: 'Access embargoes logs' + description: 'View logs from the creation, updating, and deleting of embargoes' + restrict access: true diff --git a/embargoes.routing.yml b/embargoes.routing.yml index 88b33e4..ad7a7de 100644 --- a/embargoes.routing.yml +++ b/embargoes.routing.yml @@ -14,14 +14,6 @@ embargoes.settings.notifications: requirements: _permission: 'administer embargoes settings' -embargoes.settings.log: - path: '/admin/config/content/embargoes/settings/log' - defaults: - _controller: '\Drupal\embargoes\Controller\EmbargoesLogController::showRenderedLog' - _title: 'Embargo Activity Log' - requirements: - _permission: 'administer embargoes settings' - embargoes.node.embargoes: path: '/node/{node}/embargoes' defaults: @@ -29,6 +21,11 @@ embargoes.node.embargoes: _title: 'View Embargoes' requirements: _permission: 'manage embargoes' + options: + no_cache: true + parameters: + node: + type: entity:node embargoes.node.embargo: path: '/node/{node}/embargoes/{embargo_id}' @@ -37,6 +34,10 @@ embargoes.node.embargo: _title: 'Edit Embargo' requirements: _permission: 'manage embargoes' + options: + parameters: + node: + type: entity:node embargoes.ip_access_denied: path: '/embargoes/ip-access-denied' diff --git a/embargoes.services.yml b/embargoes.services.yml index 69b67f2..aeba584 100644 --- a/embargoes.services.yml +++ b/embargoes.services.yml @@ -4,10 +4,56 @@ services: arguments: ['embargoes'] embargoes.log: class: Drupal\embargoes\EmbargoesLogService - arguments: [] + arguments: ['@database'] embargoes.embargoes: class: Drupal\embargoes\EmbargoesEmbargoesService - arguments: [] + arguments: + - '@entity_type.manager' + - '@entity_field.manager' + - '@embargoes.ips' + - '@string_translation' 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' + ip_redirect_attacher: + class: '\Drupal\embargoes\EventSubscriber\IpRedirectAttacher' + arguments: + - '@embargoes.node_access' + - '@embargoes.media_access' + - '@embargoes.file_access' + - '@current_user' + tags: + - { name: 'event_subscriber' } 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/modules/embargoes_log_views/LICENSE b/modules/embargoes_log_views/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/modules/embargoes_log_views/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/modules/embargoes_log_views/README.md b/modules/embargoes_log_views/README.md new file mode 100644 index 0000000..e1298c0 --- /dev/null +++ b/modules/embargoes_log_views/README.md @@ -0,0 +1,30 @@ +# Embargoes Log Views + +Provides views functionality and a default view for embargo logs. + +## Requirements + +This module requires the following modules/libraries: + +* Embargoes +* The core Drupal views implementation + +## Installation + +Install as +[usual](https://www.drupal.org/docs/8/extending-drupal-8/installing-drupal-8-modules). + +If Embargoes has already been installed and in use, run Drupal database updates +to ensure the database is current. + +## Usage + +The default view can be accessed at `admin/reports/embargoes_logs`. It can be +edited at `admin/structure/views/view/embargoes_logs`. + +You can create more log views by navigating to `admin/structure/views/add` and +selecting 'Embargoes log entries' from the 'Show:' drop-down menu under 'View +Settings'. + +## License +[GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt) diff --git a/modules/embargoes_log_views/config/optional/views.view.embargoes_logs.yml b/modules/embargoes_log_views/config/optional/views.view.embargoes_logs.yml new file mode 100644 index 0000000..d41cf97 --- /dev/null +++ b/modules/embargoes_log_views/config/optional/views.view.embargoes_logs.yml @@ -0,0 +1,579 @@ +uuid: d43fe284-7186-40fb-9d51-d6ad582f5850 +langcode: en +status: true +dependencies: + config: + - system.menu.admin + module: + - embargoes + - embargoes_log_views + - node + - user +id: embargoes_logs +label: 'Embargoes Logs' +module: views +description: '' +tag: '' +base_table: embargoes_log +base_field: id +display: + default: + display_plugin: default + id: default + display_title: Master + position: 0 + display_options: + access: + type: perm + options: + perm: 'access embargoes logs' + cache: + type: tag + options: { } + query: + type: views_query + options: + disable_sql_rewrite: false + distinct: false + replica: false + query_comment: '' + query_tags: { } + exposed_form: + type: basic + options: + submit_button: Apply + reset_button: false + reset_button_label: Reset + exposed_sorts_label: 'Sort by' + expose_sort_order: true + sort_asc_label: Asc + sort_desc_label: Desc + pager: + type: mini + options: + items_per_page: 20 + offset: 0 + id: 0 + total_pages: null + expose: + items_per_page: false + items_per_page_label: 'Items per page' + items_per_page_options: '5, 10, 25, 50' + items_per_page_options_all: false + items_per_page_options_all_label: '- All -' + offset: false + offset_label: Offset + tags: + previous: ‹‹ + next: ›› + style: + type: table + options: + grouping: { } + row_class: '' + default_row_class: true + override: true + sticky: false + caption: '' + summary: '' + description: '' + columns: + action: action + embargo: embargo + time: time + title: title + name: name + info: + action: + sortable: true + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + embargo: + sortable: false + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + time: + sortable: true + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + title: + sortable: true + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + name: + sortable: true + default_sort_order: asc + align: '' + separator: '' + empty_column: false + responsive: '' + default: time + empty_table: false + row: + type: fields + fields: + action: + id: action + table: embargoes_log + field: action + relationship: none + group_type: group + admin_label: '' + label: 'Action Taken' + exclude: false + alter: + alter_text: false + text: '' + make_link: false + path: '' + absolute: false + external: false + replace_spaces: false + path_case: none + trim_whitespace: false + alt: '' + rel: '' + link_class: '' + prefix: '' + suffix: '' + target: '' + nl2br: false + max_length: 0 + word_boundary: true + ellipsis: true + more_link: false + more_link_text: '' + more_link_path: '' + strip_tags: false + trim: false + preserve_tags: '' + html: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: true + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_empty: false + empty_zero: false + hide_alter_empty: true + replace_action_integer: 1 + plugin_id: standard + embargo: + id: embargo + table: embargoes_log + field: embargo + relationship: none + group_type: group + admin_label: '' + label: 'Embargo ID' + exclude: false + alter: + alter_text: false + text: '' + make_link: true + path: '/admin/config/content/embargoes/settings/embargoes/{{ embargo }}' + absolute: false + external: false + replace_spaces: false + path_case: none + trim_whitespace: false + alt: '' + rel: '' + link_class: '' + prefix: '' + suffix: '' + target: '' + nl2br: false + max_length: 0 + word_boundary: true + ellipsis: true + more_link: false + more_link_text: '' + more_link_path: '' + strip_tags: false + trim: false + preserve_tags: '' + html: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: true + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_empty: false + empty_zero: false + hide_alter_empty: true + plugin_id: standard + time: + id: time + table: embargoes_log + field: time + relationship: none + group_type: group + admin_label: '' + label: Timestamp + exclude: false + alter: + alter_text: false + text: '' + make_link: false + path: '' + absolute: false + external: false + replace_spaces: false + path_case: none + trim_whitespace: false + alt: '' + rel: '' + link_class: '' + prefix: '' + suffix: '' + target: '' + nl2br: false + max_length: 0 + word_boundary: true + ellipsis: true + more_link: false + more_link_text: '' + more_link_path: '' + strip_tags: false + trim: false + preserve_tags: '' + html: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: true + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_empty: false + empty_zero: false + hide_alter_empty: true + date_format: fallback + custom_date_format: '' + timezone: '' + plugin_id: date + title: + id: title + table: node_field_data + field: title + relationship: node + group_type: group + admin_label: '' + label: 'Embargoed Node' + exclude: false + alter: + alter_text: false + text: '' + make_link: false + path: '' + absolute: false + external: false + replace_spaces: false + path_case: none + trim_whitespace: false + alt: '' + rel: '' + link_class: '' + prefix: '' + suffix: '' + target: '' + nl2br: false + max_length: 0 + word_boundary: true + ellipsis: true + more_link: false + more_link_text: '' + more_link_path: '' + strip_tags: false + trim: false + preserve_tags: '' + html: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: false + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_empty: false + empty_zero: false + hide_alter_empty: true + click_sort_column: value + type: string + settings: + link_to_entity: true + group_column: value + group_columns: { } + group_rows: true + delta_limit: 0 + delta_offset: 0 + delta_reversed: false + delta_first_last: false + multi_type: separator + separator: ', ' + field_api_classes: false + entity_type: node + entity_field: title + plugin_id: field + name: + id: name + table: users_field_data + field: name + relationship: uid + group_type: group + admin_label: '' + label: 'Created By' + exclude: false + alter: + alter_text: false + text: '' + make_link: false + path: '' + absolute: false + external: false + replace_spaces: false + path_case: none + trim_whitespace: false + alt: '' + rel: '' + link_class: '' + prefix: '' + suffix: '' + target: '' + nl2br: false + max_length: 0 + word_boundary: true + ellipsis: true + more_link: false + more_link_text: '' + more_link_path: '' + strip_tags: false + trim: false + preserve_tags: '' + html: false + element_type: '' + element_class: '' + element_label_type: '' + element_label_class: '' + element_label_colon: true + element_wrapper_type: '' + element_wrapper_class: '' + element_default_classes: true + empty: '' + hide_empty: false + empty_zero: false + hide_alter_empty: true + click_sort_column: value + type: user_name + settings: + link_to_entity: true + group_column: value + group_columns: { } + group_rows: true + delta_limit: 0 + delta_offset: 0 + delta_reversed: false + delta_first_last: false + multi_type: separator + separator: ', ' + field_api_classes: false + entity_type: user + entity_field: name + plugin_id: field + filters: + action: + id: action + table: embargoes_log + field: action + relationship: none + group_type: group + admin_label: '' + operator: in + value: { } + group: 1 + exposed: true + expose: + operator_id: action_op + label: 'Filter to Action' + description: 'One or more actions by which to filter the logs' + use_operator: false + operator: action_op + operator_limit_selection: false + operator_list: { } + identifier: action + required: false + remember: false + multiple: true + remember_roles: + authenticated: authenticated + anonymous: '0' + reviewer: '0' + editor: '0' + ingester: '0' + submitter: '0' + repository_administrator: '0' + site_administrator: '0' + administrator: '0' + reduce: 0 + is_grouped: false + group_info: + label: '' + description: '' + identifier: '' + optional: true + widget: select + multiple: false + remember: false + default_group: All + default_group_multiple: { } + group_items: { } + plugin_id: embargoes_log_status + uid: + id: uid + table: users_field_data + field: uid + relationship: uid + group_type: group + admin_label: '' + operator: in + value: { } + group: 1 + exposed: true + expose: + operator_id: uid_op + label: 'Filter to User(s)' + description: 'One or more comma-separated users to filter the logs' + use_operator: false + operator: uid_op + operator_limit_selection: false + operator_list: { } + identifier: uid + required: false + remember: false + multiple: false + remember_roles: + authenticated: authenticated + anonymous: '0' + reviewer: '0' + editor: '0' + ingester: '0' + submitter: '0' + repository_administrator: '0' + site_administrator: '0' + administrator: '0' + reduce: false + is_grouped: false + group_info: + label: '' + description: '' + identifier: '' + optional: true + widget: select + multiple: false + remember: false + default_group: All + default_group_multiple: { } + group_items: { } + entity_type: user + entity_field: uid + plugin_id: user_name + sorts: + time: + id: time + table: embargoes_log + field: time + relationship: none + group_type: group + admin_label: '' + order: ASC + exposed: false + expose: + label: '' + granularity: second + plugin_id: date + title: 'Embargoes Logs' + header: { } + footer: { } + empty: { } + relationships: + node: + id: node + table: embargoes_log + field: node + relationship: none + group_type: group + admin_label: 'Embargoed node' + required: false + plugin_id: standard + uid: + id: uid + table: embargoes_log + field: uid + relationship: none + group_type: group + admin_label: uid + required: false + plugin_id: standard + arguments: { } + display_extenders: { } + cache_metadata: + max-age: -1 + contexts: + - 'languages:language_content' + - 'languages:language_interface' + - url + - url.query_args + - user.permissions + tags: { } + page_1: + display_plugin: page + id: page_1 + display_title: Page + position: 1 + display_options: + display_extenders: { } + path: admin/reports/embargoes-logs + menu: + type: normal + title: 'Embargoes Logs' + description: 'List of all actions taken against embargoes on the site.' + expanded: false + parent: system.admin_reports + weight: 0 + context: '0' + menu_name: admin + cache_metadata: + max-age: -1 + contexts: + - 'languages:language_content' + - 'languages:language_interface' + - url + - url.query_args + - user.permissions + tags: { } + diff --git a/modules/embargoes_log_views/embargoes_log_views.info.yml b/modules/embargoes_log_views/embargoes_log_views.info.yml new file mode 100644 index 0000000..dbdd9d1 --- /dev/null +++ b/modules/embargoes_log_views/embargoes_log_views.info.yml @@ -0,0 +1,7 @@ +name: Embargoes Log Views +description: 'Provides views for embargo logs.' +type: module +core_version_requirement: ^8 || ^9 +dependencies: + - embargoes + - views diff --git a/modules/embargoes_log_views/embargoes_log_views.views.inc b/modules/embargoes_log_views/embargoes_log_views.views.inc new file mode 100644 index 0000000..6b4d0f2 --- /dev/null +++ b/modules/embargoes_log_views/embargoes_log_views.views.inc @@ -0,0 +1,130 @@ + [ + 'table' => [ + 'group' => t('Embargoes logs'), + 'provider' => 'embargoes', + 'wizard_id' => 'embargoes_log_data', + 'base' => [ + 'field' => 'id', + 'title' => t('Embargoes log entries'), + 'help' => t('Contains a list of embargoes logs.'), + ], + ], + ], + ]; + + // Implement individual columns. + $data['embargoes_log']['id'] = [ + 'title' => t('Log ID'), + 'help' => t('The ID of the log in the database.'), + 'field' => [ + 'id' => 'numeric', + ], + 'sort' => [ + 'id' => 'standard', + ], + 'filter' => [ + 'id' => 'numeric', + ], + 'argument' => [ + 'id' => 'numeric', + ], + ]; + $data['embargoes_log']['time'] = [ + 'title' => t('Timestamp'), + 'help' => t('The time the log entry was created.'), + 'field' => [ + 'id' => 'date', + ], + 'sort' => [ + 'id' => 'date', + ], + 'filter' => [ + 'id' => 'date', + ], + ]; + $data['embargoes_log']['action'] = [ + 'title' => t('Action Taken'), + 'help' => t('The action that was taken for the log entry.'), + 'field' => [ + 'id' => 'embargoes_log_status', + ], + 'sort' => [ + 'id' => 'standard', + ], + 'filter' => [ + 'id' => 'embargoes_log_status', + ], + 'argument' => [ + 'id' => 'numeric', + ], + ]; + $data['embargoes_log']['node'] = [ + 'title' => t('Embargoed Node'), + 'help' => t('The node this embargo log applies to.'), + 'field' => [ + 'id' => 'standard', + ], + 'filter' => [ + 'id' => 'numeric', + ], + 'argument' => [ + 'id' => 'numeric', + ], + 'relationship' => [ + 'base' => 'node_field_data', + 'base field' => 'nid', + 'id' => 'standard', + 'label' => t('Embargoed node'), + ], + ]; + $data['embargoes_log']['uid'] = [ + 'title' => t('UID'), + 'help' => t('The user that this log was created by.'), + 'field' => [ + 'id' => 'standard', + ], + 'filter' => [ + 'id' => 'numeric', + ], + 'argument' => [ + 'id' => 'numeric', + ], + 'relationship' => [ + 'base' => 'users_field_data', + 'base field' => 'uid', + 'id' => 'standard', + 'title' => t('Log Creator'), + ], + ]; + $data['embargoes_log']['embargo'] = [ + 'title' => t('Embargo ID'), + 'help' => t('The ID of the embargo this log applies to.'), + 'field' => [ + 'id' => 'standard', + ], + 'sort' => [ + 'id' => 'standard', + ], + 'filter' => [ + 'id' => 'string', + ], + 'argument' => [ + 'id' => 'string', + ], + ]; + + return $data; +} diff --git a/modules/embargoes_log_views/src/Plugin/views/field/EmbargoesLogStatus.php b/modules/embargoes_log_views/src/Plugin/views/field/EmbargoesLogStatus.php new file mode 100644 index 0000000..3b8d0d3 --- /dev/null +++ b/modules/embargoes_log_views/src/Plugin/views/field/EmbargoesLogStatus.php @@ -0,0 +1,114 @@ +embargoes = $embargoes; + $this->embargoesStorage = $embargoes_storage; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('embargoes.embargoes'), + $container->get('entity_type.manager')->getStorage('embargoes_embargo_entity')); + } + + /** + * {@inheritdoc} + */ + protected function defineOptions() { + $options = parent::defineOptions(); + $options['replace_action_integer'] = [ + 'default' => TRUE, + ]; + return $options; + } + + /** + * {@inheritdoc} + */ + public function buildOptionsForm(&$form, FormStateInterface $form_state) { + parent::buildOptionsForm($form, $form_state); + $form['replace_action_integer'] = [ + '#title' => $this->t("Replace action integer"), + '#description' => $this->t("The action that was taken with an embargo is stored as an integer; replace this with the actual name."), + '#type' => 'checkbox', + '#default_value' => $this->options['replace_action_integer'], + ]; + } + + /** + * {@inheritdoc} + */ + public function render(ResultRow $values) { + $value = $this->getValue($values); + if ($this->options['replace_action_integer']) { + $embargo = NULL; + if (isset($values->embargoes_log_embargo)) { + $embargo = $this->embargoesStorage->load($values->embargoes_log_embargo); + } + if (!$embargo) { + // XXX: Create a dummy embargo so we can load appropriate actions as + // best we can. This embargo will not be saved. + $embargo = $this->embargoesStorage->create(); + } + $map = $this->embargoes->getNotificationStatusesAsFormOptions($embargo); + if (isset($map[$value])) { + $value = $map[$value]; + } + } + return $this->sanitizeValue($value); + } + +} diff --git a/modules/embargoes_log_views/src/Plugin/views/filter/EmbargoesLogStatus.php b/modules/embargoes_log_views/src/Plugin/views/filter/EmbargoesLogStatus.php new file mode 100644 index 0000000..6ca1eb6 --- /dev/null +++ b/modules/embargoes_log_views/src/Plugin/views/filter/EmbargoesLogStatus.php @@ -0,0 +1,77 @@ +embargoes = $embargoes; + $this->embargoesStorage = $embargoes_storage; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('embargoes.embargoes'), + $container->get('entity_type.manager')->getStorage('embargoes_embargo_entity')); + } + + /** + * {@inheritdoc} + */ + public function getValueOptions() { + if (!isset($this->valueOptions)) { + // XXX: Create a dummy entity; this will allow us to get the appropriate + // list of options for the current embargoes_embargo_entity class without + // having to access an existing embargo. The object will not be saved. + $dummy = $this->embargoesStorage->create(); + $this->valueOptions = $this->embargoes->getNotificationStatusesAsFormOptions($dummy); + } + return $this->valueOptions; + } + +} diff --git a/modules/embargoes_log_views/src/Plugin/views/wizard/EmbargoesLog.php b/modules/embargoes_log_views/src/Plugin/views/wizard/EmbargoesLog.php new file mode 100644 index 0000000..4e14053 --- /dev/null +++ b/modules/embargoes_log_views/src/Plugin/views/wizard/EmbargoesLog.php @@ -0,0 +1,38 @@ +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; + } + + /** + * Return the type of entity this should apply to. + * + * @return string + * The entity type this access control should apply to. + */ + abstract public static function entityType(); + + /** + * {@inheritdoc} + */ + public function isActivelyEmbargoed(EntityInterface $entity, AccountInterface $user) { + $entity_type = $entity->getEntityType()->id(); + $expected = static::entityType(); + 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' => $entity_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 ? $ip_range->label() : '', + ]; + // 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, AccountInterface $user) { + 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..08a855f --- /dev/null +++ b/src/Access/EmbargoedFileAccess.php @@ -0,0 +1,52 @@ +embargoes->getParentNidsOfFileEntity($file); + $embargoes = $this->embargoes->getActiveEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $user); + if (!empty($embargoes)) { + $state = AccessResult::forbidden(); + $state->addCacheableDependency($file); + $state->addCacheableDependency($user); + } + return $state; + } + + /** + * {@inheritdoc} + */ + public function getIpEmbargoedRedirectUrl(EntityInterface $file, AccountInterface $user) { + $parent_nodes = $this->embargoes->getParentNidsOfFileEntity($file); + $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $user); + $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes); + if (!empty($embargoes) && !empty($ip_allowed_embargoes)) { + return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [ + 'label' => $file->label(), + 'ranges' => $ip_allowed_embargoes, + ]); + } + return NULL; + } + +} diff --git a/src/Access/EmbargoedMediaAccess.php b/src/Access/EmbargoedMediaAccess.php new file mode 100644 index 0000000..6531f10 --- /dev/null +++ b/src/Access/EmbargoedMediaAccess.php @@ -0,0 +1,52 @@ +embargoes->getMediaParentNids($media->id()); + $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $user); + if (!empty($embargoes) && empty($this->embargoes->getIpAllowedEmbargoes($embargoes))) { + $state = AccessResult::forbidden(); + $state->addCacheableDependency($media); + $state->addCacheableDependency($user); + } + return $state; + } + + /** + * {@inheritdoc} + */ + public function getIpEmbargoedRedirectUrl(EntityInterface $media, AccountInterface $user) { + $parent_nodes = $this->embargoes->getMediaParentNids($media->id()); + $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids($parent_nodes, $this->request->getClientIp(), $user); + $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes); + if (!empty($embargoes) && !empty($ip_allowed_embargoes)) { + return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [ + 'label' => $media->label(), + 'ranges' => $ip_allowed_embargoes, + ]); + } + return NULL; + } + +} diff --git a/src/Access/EmbargoedNodeAccess.php b/src/Access/EmbargoedNodeAccess.php new file mode 100644 index 0000000..9d3af95 --- /dev/null +++ b/src/Access/EmbargoedNodeAccess.php @@ -0,0 +1,50 @@ +embargoes->getActiveNodeEmbargoesByNids([$node->id()], $this->request->getClientIp(), $user); + if (!empty($embargoes) && empty($this->embargoes->getIpAllowedEmbargoes($embargoes))) { + $state = AccessResult::forbidden(); + $state->addCacheableDependency($node); + $state->addCacheableDependency($user); + } + return $state; + } + + /** + * {@inheritdoc} + */ + public function getIpEmbargoedRedirectUrl(EntityInterface $node, AccountInterface $user) { + $embargoes = $this->embargoes->getActiveNodeEmbargoesByNids([$node->id()], $this->request->getClientIp(), $user); + $ip_allowed_embargoes = $this->embargoes->getIpAllowedEmbargoes($embargoes); + if (!empty($embargoes) && !empty($ip_allowed_embargoes)) { + return $this->urlGenerator->generateFromRoute('embargoes.ip_access_denied', [ + 'label' => $node->label(), + 'ranges' => $ip_allowed_embargoes, + ]); + } + return NULL; + } + +} diff --git a/src/Access/EmbargoesFileAccessHandler.php b/src/Access/EmbargoesFileAccessHandler.php new file mode 100644 index 0000000..5c6ca9c --- /dev/null +++ b/src/Access/EmbargoesFileAccessHandler.php @@ -0,0 +1,25 @@ +isActivelyEmbargoed($entity, $account); + if ($embargoed->isForbidden()) { + return $embargoed; + } + return parent::checkAccess($entity, $operation, $account); + } + +} diff --git a/src/Controller/EmbargoesEmbargoEntityListBuilder.php b/src/Controller/EmbargoesEmbargoEntityListBuilder.php new file mode 100644 index 0000000..a4158f9 --- /dev/null +++ b/src/Controller/EmbargoesEmbargoEntityListBuilder.php @@ -0,0 +1,184 @@ +user = $user; + $this->node = $node; + $this->ipRanges = $ip_ranges; + $this->linkGenerator = $link_generator; + $this->embargoes = $embargoes_service; + } + + /** + * {@inheritdoc} + */ + public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) { + return new static( + $entity_type, + $container->get('entity_type.manager')->getStorage($entity_type->id()), + $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('link_generator'), + $container->get('embargoes.embargoes')); + } + + /** + * {@inheritdoc} + */ + public function buildHeader() { + $header['id'] = $this->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) { + + $users = [ + 'data' => [ + '#type' => 'container', + ], + ]; + foreach ($entity->getExemptUsers() as $user) { + $uid = $user['target_id']; + $user_entity = $this->user->load($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' => '
', + ]; + } + } + + $nid = $entity->getEmbargoedNode(); + $node = $this->node->load($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 = $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 = $this->t("None"); + } + + $formatted_emails = [ + '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'] = $users; + $row['additional_emails'] = $formatted_emails; + $notification_status = $entity->getNotificationStatus(); + if (isset($this->embargoes->getNotificationStatusesAsFormOptions($entity)[$notification_status])) { + $notification_status = $this->embargoes->getNotificationStatusesAsFormOptions($entity)[$notification_status]; + } + $row['notification_status'] = $notification_status; + $row['embargoed_node'] = $formatted_node_row; + return $row + parent::buildRow($entity); + } + +} diff --git a/src/Controller/EmbargoesIpAccessDeniedController.php b/src/Controller/EmbargoesIpAccessDeniedController.php index ed411bb..c6444b4 100644 --- a/src/Controller/EmbargoesIpAccessDeniedController.php +++ b/src/Controller/EmbargoesIpAccessDeniedController.php @@ -3,42 +3,73 @@ 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. + * Controller for displaying an IP access denied message. */ class EmbargoesIpAccessDeniedController extends ControllerBase { - public function response() { + /** + * The HTTP request. + * + * @var Symfony\Component\HttpFoundation\Request + */ + protected $request; - $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'); - - $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); - if ($allowed_range_entity->getProxyUrl() != '') { - $message .= "
  • {$allowed_range_entity->label()}
  • "; - } - else { - $message .= "
  • {$allowed_range_entity->label()}
  • "; + /** + * 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()); + } + + /** + * Formats a response for an IP access denied page. + * + * @return array + * Renderable array of markup for IP access denied. + */ + public function response() { + $ranges = []; + $cache_tags = []; + foreach ((array) $this->request->query->get('ranges', []) as $allowed_range) { + $allowed_range_entity = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($allowed_range); + if ($allowed_range_entity) { + $proxy_url = $allowed_range_entity->getProxyUrl() != '' ? $allowed_range_entity->getProxyUrl() : NULL; + $ranges[] = [ + 'proxy_url' => $proxy_url, + 'label' => $allowed_range_entity->label(), + ]; + $cache_tags[] = "embargoes_ip_range_entity:{$allowed_range_entity->id()}"; } } - $message .= "

"; - $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' => array("max-age" => 0), + '#theme' => 'embargoes_ip_access_denied', + '#requested_resource' => $this->request->query->get('label', ''), + '#ranges' => $ranges, + '#contact_email' => $this->config('embargoes.settings')->get('embargo_contact_email'), + '#cache' => [ + 'contexts' => [ + 'user', + 'url.path', + 'url.query_args', + ], + 'tags' => $cache_tags, + ], ]; } diff --git a/src/EmbargoesIpRangeEntityListBuilder.php b/src/Controller/EmbargoesIpRangeEntityListBuilder.php similarity index 84% rename from src/EmbargoesIpRangeEntityListBuilder.php rename to src/Controller/EmbargoesIpRangeEntityListBuilder.php index 6f7a218..15af793 100644 --- a/src/EmbargoesIpRangeEntityListBuilder.php +++ b/src/Controller/EmbargoesIpRangeEntityListBuilder.php @@ -1,10 +1,9 @@ label(); $row['id'] = $entity->id(); - $row['range'] = Markup::create(str_replace('|', '
', $entity->getRange())); + $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 deleted file mode 100644 index dd94496..0000000 --- a/src/Controller/EmbargoesLogController.php +++ /dev/null @@ -1,52 +0,0 @@ -query('SELECT * FROM {embargoes_log} ORDER BY time DESC;'); - - $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->user)->getUsername(); - if ($record->action == "deleted") { - $embargo_formatted = Markup::create("{$record->embargo}"); - } - else { - $embargo_formatted = Markup::create("{$record->embargo}"); - } - - $row = [ - 'id' => $record->id, - 'embargo' => $embargo_formatted, - 'time' => $formatted_time, - 'action' => ucfirst($record->action), - 'node' => Markup::create("$node_title"), - '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'], - '#rows' => $formatted_log, - ]; - - return [ - '#type' => 'markup', - '#markup' => render($pre_rendered_log), - ]; - } - -} diff --git a/src/Controller/EmbargoesNodeEmbargoesController.php b/src/Controller/EmbargoesNodeEmbargoesController.php index 13ec296..2226005 100644 --- a/src/Controller/EmbargoesNodeEmbargoesController.php +++ b/src/Controller/EmbargoesNodeEmbargoesController.php @@ -2,87 +2,174 @@ namespace Drupal\embargoes\Controller; +use Drupal\embargoes\EmbargoesEmbargoesServiceInterface; +use Drupal\node\NodeInterface; use Drupal\Core\Controller\ControllerBase; -use Drupal\Core\Render\Markup; +use Drupal\Core\Url; +use Symfony\Component\DependencyInjection\ContainerInterface; /** - * Class EmbargoesLogController. + * Controller for displaying node embargoes. */ class EmbargoesNodeEmbargoesController extends ControllerBase { - public function showEmbargoes($node = NULL) { + /** + * Embargoes service. + * + * @var \Drupal\embargoes\EmbargoesEmbargoesServiceInterface + */ + protected $embargoes; - $embargo_ids = \Drupal::service('embargoes.embargoes')->getAllEmbargoesByNids(array($node)); + /** + * 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 = $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 { $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 ) { - $expiry = 'Indefinite'; - } else { + if ($embargo->getExpirationType() == 0) { + $expiry = $this->t('Indefinite'); + } + else { $expiry = $embargo->getExpirationDate(); } $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){ + foreach ($embargo->getExemptUsers() as $user) { $uid = $user['target_id']; - $user_entity = \Drupal\user\Entity\User::load($uid); - $user_name = $user_entity->getUserName(); - $formatted_users[] = "{$user_name}"; + $user_entity = $this->entityTypeManager()->getStorage('user')->load($uid); + $user_name = $user_entity ? $user_entity->getUserName() : $this->t('Missing User'); + $formatted_users[] = [ + '#type' => 'link', + '#title' => $user_name, + '#url' => Url::fromRoute('entity.user.canonical', [ + 'user' => $uid, + ]), + ]; } } - $formatted_exempt_users_row = Markup::create(implode("
", $formatted_users)); + $formatted_exempt_users_row = ['data' => $formatted_users]; - if ($embargo->getExemptIps() != 'none') { - $ip_range = \Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps()); - $ip_range_label = $ip_range->label(); - $ip_range_formatted = Markup::create("{$ip_range_label}"); + if (!is_null($embargo->getExemptIps())) { + $ip_range = $this->entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps()); + if (!is_null($ip_range)) { + $ip_range_formatted = [ + 'data' => [ + '#type' => 'link', + '#title' => $ip_range->label(), + '#url' => Url::fromRoute('entity.embargoes_ip_range_entity.edit_form', [ + 'embargoes_ip_range_entity' => $embargo->getExemptIps(), + ]), + ], + ]; + } + else { + $ip_range_formatted = $this->t('None'); + } } else { - $ip_range_formatted = "None"; + $ip_range_formatted = $this->t('None'); } - $formatted_emails = Markup::create(str_replace(',', '
', str_replace(' ', '', $embargo->getAdditionalEmails()))); + $formatted_emails = [ + 'data' => [ + '#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"), + '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); } $markup['embargoes'] = [ '#type' => 'table', - '#header' => ['Type', 'Expiration Date', 'Exempt IP Range', 'Exempt Users', 'Additional Emails', 'Edit'], + '#header' => [ + $this->t('Type'), + $this->t('Expiration Date'), + $this->t('Exempt IP Range'), + $this->t('Exempt Users'), + $this->t('Additional Emails'), + $this->t('Operations'), + ], '#rows' => $rows, ]; + } - $markup['add'] = [ - '#type' => 'markup', - '#markup' => Markup::create("

Add Embargo

"), + $markup['add_embargo'] = [ + '#type' => 'operations', + '#links' => [ + 'add' => [ + 'title' => $this->t('Add New Embargo'), + 'url' => Url::fromRoute('embargoes.node.embargo', [ + 'node' => $node->id(), + 'embargo_id' => 'add', + ]), + ], + ], ]; - return [ - '#type' => 'markup', - '#markup' => render($markup), - ]; + return $markup; } } diff --git a/src/EmbargoesEmbargoEntityListBuilder.php b/src/EmbargoesEmbargoEntityListBuilder.php deleted file mode 100644 index 8216b3d..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 = \Drupal\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(str_replace(',', '
', str_replace(' ', '', $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/EmbargoesEmbargoesService.php b/src/EmbargoesEmbargoesService.php index 65ec040..79261e7 100644 --- a/src/EmbargoesEmbargoesService.php +++ b/src/EmbargoesEmbargoesService.php @@ -2,32 +2,94 @@ namespace Drupal\embargoes; +use Drupal\embargoes\Entity\EmbargoesEmbargoEntityInterface; +use Drupal\file\FileInterface; +use Drupal\field\Entity\FieldStorageConfig; +use Drupal\Component\Utility\NestedArray; +use Drupal\Core\Entity\EntityFieldManagerInterface; +use Drupal\Core\Entity\EntityStorageInterface; +use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\Session\AccountInterface; +use Drupal\Core\StringTranslation\TranslationInterface; + /** * 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; + + /** + * Translation service. + * + * @var \Drupal\Core\StringTranslation\TranslationInterface + */ + protected $translation; /** * 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. + * @param \Drupal\Core\StringTranslation\TranslationInterface $translation + * Translation manager. */ - public function __construct() { + public function __construct(EntityTypeManagerInterface $manager, EntityFieldManagerInterface $field_manager, EmbargoesIpRangesServiceInterface $ip_ranges, TranslationInterface $translation) { + $this->entityManager = $manager; + $this->fieldManager = $field_manager; + $this->ipRanges = $ip_ranges; + $this->translation = $translation; } - 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 +104,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 (!empty($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 +153,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 +170,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 (!empty($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 +212,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 +246,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,25 +283,26 @@ public function getMediaParentNids($mid) { return $nids; } - public function getParentNidsOfFileEntity($file) { - $relationships = file_get_file_references($file); - if (!$relationships) { - $nids = NULL; - } - else { + /** + * {@inheritdoc} + */ + public function getParentNidsOfFileEntity(FileInterface $file) { + $relationships = NestedArray::mergeDeep( + file_get_file_references($file), + file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_REVISION, 'image')); + $nids = []; + if ($relationships) { foreach ($relationships as $relationship) { - if (!$relationship) { - $nids = NULL; - } - else { + if ($relationship) { 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; } } @@ -192,4 +312,17 @@ public function getParentNidsOfFileEntity($file) { return $nids; } + /** + * {@inheritdoc} + */ + public function getNotificationStatusesAsFormOptions(EmbargoesEmbargoEntityInterface $embargo) { + return [ + $embargo::STATUS_CREATED => $this->translation->translate('Created'), + $embargo::STATUS_UPDATED => $this->translation->translate('Updated'), + $embargo::STATUS_WARNED => $this->translation->translate('Warned'), + $embargo::STATUS_EXPIRED => $this->translation->translate('Expired'), + $embargo::STATUS_DELETED => $this->translation->translate('Deleted'), + ]; + } + } diff --git a/src/EmbargoesEmbargoesServiceInterface.php b/src/EmbargoesEmbargoesServiceInterface.php index 066ae52..be00827 100644 --- a/src/EmbargoesEmbargoesServiceInterface.php +++ b/src/EmbargoesEmbargoesServiceInterface.php @@ -2,21 +2,161 @@ namespace Drupal\embargoes; +use Drupal\embargoes\Entity\EmbargoesEmbargoEntityInterface; +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); + + /** + * Gets a list of valid notification statuses with accompanying names. + * + * @param Drupal\embargoes\Entity\EmbargoesEmbargoEntityInterface $embargo + * The embargo to get valid notification statuses for. + * + * @return array + * Array mapping notification status IDs to their human-readable names. + */ + public function getNotificationStatusesAsFormOptions(EmbargoesEmbargoEntityInterface $embargo); } diff --git a/src/EmbargoesIpRangesService.php b/src/EmbargoesIpRangesService.php index 9144734..3049904 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(); - $response = FALSE; - if (!\Drupal::service('embargoes.ips')->detectIpRangeStringErrors($range_string)) { - $ranges = explode('|', trim($range_string)); + $response = FALSE; + if (!empty($range_name)) { + $ranges = $this->rangeStorage->load($range_name)->getRanges(); + 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 6b8ec4b..c471476 100644 --- a/src/EmbargoesLogService.php +++ b/src/EmbargoesLogService.php @@ -2,23 +2,48 @@ namespace Drupal\embargoes; +use Drupal\Core\Database\Connection; + /** * Class EmbargoesLogService. */ class EmbargoesLogService implements EmbargoesLogServiceInterface { /** - * Constructs a new EmbargoesLogService object. + * Database connection. + * + * @var \Drupal\Core\Database\Connection */ - public function __construct() { + 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) { - $time = time(); - $database = \Drupal::database(); - $result = $database->query("INSERT INTO {embargoes_log} (time, action, node, user, embargo) VALUES ('{$time}', '{$values['action']}', '{$values['node']}', '{$values['user']}','{$values['embargo_id']}');"); - return $result; + /** + * 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) + ->execute(); } } 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 9cc40ca..c9bc874 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; /** @@ -10,8 +11,9 @@ * @ConfigEntityType( * id = "embargoes_embargo_entity", * label = @Translation("Embargo"), - * handlers = { * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder", - * "list_builder" = "Drupal\embargoes\EmbargoesEmbargoEntityListBuilder", + * handlers = { + * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder", + * "list_builder" = "Drupal\embargoes\Controller\EmbargoesEmbargoEntityListBuilder", * "form" = { * "add" = "Drupal\embargoes\Form\EmbargoesEmbargoEntityForm", * "edit" = "Drupal\embargoes\Form\EmbargoesEmbargoEntityForm", @@ -22,12 +24,26 @@ * }, * }, * config_prefix = "embargoes_embargo_entity", - * admin_permission = "administer site configuration", + * admin_permission = "manage embargoes", * entity_keys = { * "id" = "id", * "label" = "label", * "uuid" = "uuid" * }, + * config_export = { + * "id" = "id", + * "label" = "label", + * "uuid" = "uuid", + * "embargo_type" = "embargo_type", + * "expiration_type" = "expiration_type", + * "expiration_date" = "expiration_date", + * "exempt_ips" = "exempt_ips", + * "exempt_users" = "exempt_users", + * "additional_emails" = "additional_emails", + * "notification_status" = "notification_status", + * "embargoed_node" = "embargoed_node", + * "notification_status" = "notification_status", + * }, * links = { * "canonical" = "/admin/config/content/embargoes/settings/embargoes/{embargoes_embargo_entity}", * "add-form" = "/admin/config/content/embargoes/settings/embargoes/add", @@ -46,126 +62,237 @@ 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; + /** + * The ID of a configured IP exemption range, or NULL. + * + * @var string|null + */ protected $exempt_ips; - protected $exempt_users; + /** + * An array of user UIDs exempt from the embargo. + * + * @var int[] + */ + protected $exempt_users = []; - protected $additional_emails; + /** + * 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; - 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); - } - - public function save() { - parent::save(); - drupal_flush_all_caches(); - } - - 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'); } - public function setExemptIps($range){ + /** + * {@inheritdoc} + */ + public function setExemptIps($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; } - public function setExemptUsers($users){ + /** + * {@inheritdoc} + */ + public function setExemptUsers($users) { + if (!$users) { + $users = []; + } $this->set('exempt_users', $users); return $this; } + /** + * {@inheritdoc} + */ public function getAdditionalEmails() { return $this->get('additional_emails'); } - public function setAdditionalEmails($emails){ + /** + * {@inheritdoc} + */ + public function setAdditionalEmails($emails) { + $emails = empty($emails) ? [] : array_map('trim', explode(',', trim($emails))); $this->set('additional_emails', $emails); return $this; } + /** + * {@inheritdoc} + */ public function getEmbargoedNode() { return $this->get('embargoed_node'); } - public function setEmbargoedNode($node){ + /** + * {@inheritdoc} + */ + public function setEmbargoedNode($node) { $this->set('embargoed_node', $node); return $this; } + /** + * {@inheritdoc} + */ public function getNotificationStatus() { return $this->get('notification_status'); } - public function setNotificationStatus($status){ + /** + * {@inheritdoc} + */ + public function getValidNotificationStatuses() { + return [ + self::STATUS_CREATED, + self::STATUS_UPDATED, + self::STATUS_WARNED, + self::STATUS_EXPIRED, + self::STATUS_DELETED, + ]; + } + + /** + * {@inheritdoc} + */ + public function setNotificationStatus($status) { + $valid_statuses = $this->getValidNotificationStatuses(); + if (!in_array($status, $valid_statuses)) { + throw new \InvalidArgumentException('The notification status must be one of ' . implode(', ', $valid_statuses)); + } $this->set('notification_status', $status); return $this; } + /** + * {@inheritdoc} + */ + public function getCacheTagsToInvalidate() { + $tags = parent::getCacheTagsToInvalidate(); + $tags[] = "node:{$this->getEmbargoedNode()}"; + return $tags; + } + } diff --git a/src/Entity/EmbargoesEmbargoEntityInterface.php b/src/Entity/EmbargoesEmbargoEntityInterface.php index 559ae9a..1ea07d5 100644 --- a/src/Entity/EmbargoesEmbargoEntityInterface.php +++ b/src/Entity/EmbargoesEmbargoEntityInterface.php @@ -9,31 +9,193 @@ */ interface EmbargoesEmbargoEntityInterface extends ConfigEntityInterface { + // Constants for notification statuses. + const STATUS_CREATED = 0; + const STATUS_UPDATED = 1; + const STATUS_WARNED = 2; + const STATUS_EXPIRED = 3; + const STATUS_DELETED = 4; + + /** + * 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. + */ public function getNotificationStatus(); + + /** + * Gets the list of valid notification statuses. + * + * @return array + * A list of valid notification statuses. + */ + public function getValidNotificationStatuses(); + + /** + * Sets the current notification status of the embargo. + * + * @param string $status + * The current notification status of the embargo. + * + * @return string + * The new notification status. + */ public function setNotificationStatus($status); } diff --git a/src/Entity/EmbargoesIpRangeEntity.php b/src/Entity/EmbargoesIpRangeEntity.php index 95954e3..616e2d6 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", @@ -29,6 +29,13 @@ * "label" = "label", * "uuid" = "uuid" * }, + * config_export = { + * "id" = "id", + * "label" = "label", + * "uuid" = "uuid", + * "ranges" = "ranges", + * "proxy_url" = "proxy_url", + * }, * links = { * "canonical" = "/admin/config/content/embargoes/settings/ips/{embargoes_ip_range_entity}", * "add-form" = "/admin/config/content/embargoes/settings/ips/add", @@ -55,11 +62,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 +75,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/EventSubscriber/IpRedirectAttacher.php b/src/EventSubscriber/IpRedirectAttacher.php new file mode 100644 index 0000000..79a6df8 --- /dev/null +++ b/src/EventSubscriber/IpRedirectAttacher.php @@ -0,0 +1,98 @@ +nodeAccess = $node_access; + $this->mediaAccess = $media_access; + $this->fileAccess = $file_access; + $this->user = $user; + } + + /** + * Attaches an IP redirect to requests that require one. + * + * @param Symfony\Component\HttpKernel\Event\GetResponseEvent $response + * The initial response. + */ + public function attachIpRedirect(GetResponseEvent $response) { + $redirect_url = NULL; + // Cycle through all attributes; the first one we get back that's restricted + // means redirection is necessary. + foreach ($response->getRequest()->attributes->all() as $attribute) { + if ($attribute instanceof NodeInterface) { + $redirect_url = $this->nodeAccess->getIpEmbargoedRedirectUrl($attribute, $this->user); + break; + } + if ($attribute instanceof MediaInterface) { + $redirect_url = $this->mediaAccess->getIpEmbargoedRedirectUrl($attribute, $this->user); + break; + } + if ($attribute instanceof FileInterface) { + $redirect_url = $this->fileAccess->getIpEmbargoedRedirectUrl($attribute, $this->user); + break; + } + } + if ($redirect_url) { + $response->setResponse(new RedirectResponse($redirect_url)); + } + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() { + return [ + KernelEvents::REQUEST => [ + ['attachIpRedirect'], + ], + ]; + } + +} diff --git a/src/Form/EmbargoesEmbargoEntityDeleteForm.php b/src/Form/EmbargoesEmbargoEntityDeleteForm.php index 8876c42..aad4050 100644 --- a/src/Form/EmbargoesEmbargoEntityDeleteForm.php +++ b/src/Form/EmbargoesEmbargoEntityDeleteForm.php @@ -2,15 +2,54 @@ namespace Drupal\embargoes\Form; +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; /** * Builds the form to delete Embargo entities. */ class EmbargoesEmbargoEntityDeleteForm extends EntityConfirmFormBase { + /** + * Embargoes logging service. + * + * @var \Drupal\embargoes\EmbargoesLogServiceInterface + */ + protected $logger; + + /** + * Messaging interface. + * + * @var \Drupal\Core\Messenger\MessengerInterface + */ + protected $messenger; + + /** + * Creates the delete form. + * + * @param \Drupal\embargoes\EmbargoesLogServiceInterface $log_service + * An embargoes logging service. + * @param \Drupal\Core\Messenger\MessengerInterface $messenger + * Messaging interface. + */ + public function __construct(EmbargoesLogServiceInterface $log_service, MessengerInterface $messenger) { + $this->logger = $log_service; + $this->messenger = $messenger; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('embargoes.log'), + $container->get('messenger')); + } + /** * {@inheritdoc} */ @@ -37,12 +76,14 @@ public function getConfirmText() { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $log_values['node'] = $this->entity->getEmbargoedNode(); - $log_values['user'] = \Drupal::currentUser()->id(); - $log_values['embargo_id'] = $this->entity->id(); - $log_values['action'] = 'deleted'; - \Drupal::messenger()->addMessage("Your embargo has been {$log_values['action']}."); - \Drupal::service('embargoes.log')->logEmbargoEvent($log_values); + $log_values = [ + 'node' => $this->entity->getEmbargoedNode(), + 'uid' => $this->currentUser()->id(), + 'embargo' => $this->entity->id(), + 'action' => $this->entity::STATUS_DELETED, + ]; + $this->messenger()->addMessage($this->t("Your embargo has been deleted.")); + $this->logger->logEmbargoEvent($log_values); $this->entity->delete(); $form_state->setRedirectUrl($this->getCancelUrl()); } diff --git a/src/Form/EmbargoesEmbargoEntityForm.php b/src/Form/EmbargoesEmbargoEntityForm.php index 45668d4..42aca26 100644 --- a/src/Form/EmbargoesEmbargoEntityForm.php +++ b/src/Form/EmbargoesEmbargoEntityForm.php @@ -2,14 +2,89 @@ namespace Drupal\embargoes\Form; +use Drupal\embargoes\EmbargoesEmbargoesServiceInterface; +use Drupal\embargoes\EmbargoesIpRangesServiceInterface; +use Drupal\embargoes\EmbargoesLogServiceInterface; +use Drupal\Component\Uuid\UuidInterface; use Drupal\Core\Entity\EntityForm; use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Messenger\MessengerInterface; +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; + + /** + * UUID interface. + * + * @var \Drupal\Component\Uuid\UuidInterface + */ + protected $uuidGenerator; + + /** + * Messaging interface. + * + * @var \Drupal\Core\Messenger\MessengerInterface + */ + protected $messenger; + + /** + * Embargoes service. + * + * @var \Drupal\embargoes\EmbargoesEmbargoesServiceInterface + */ + protected $embargoes; + + /** + * 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. + * @param \Drupal\Component\Uuid\UuidInterface $uuid_generator + * A UUID generator. + * @param \Drupal\Core\Messenger\MessengerInterface $messenger + * Messaging interface. + * @param \Drupal\embargoes\EmbargoesEmbargoesServiceInterface $embargoes_service + * An embargoes service. + */ + public function __construct(EmbargoesIpRangesServiceInterface $ip_ranges, EmbargoesLogServiceInterface $embargoes_log, UuidInterface $uuid_generator, MessengerInterface $messenger, EmbargoesEmbargoesServiceInterface $embargoes_service) { + $this->ipRanges = $ip_ranges; + $this->embargoesLog = $embargoes_log; + $this->uuidGenerator = $uuid_generator; + $this->messenger = $messenger; + $this->embargoes = $embargoes_service; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('embargoes.ips'), + $container->get('embargoes.log'), + $container->get('uuid'), + $container->get('messenger'), + $container->get('embargoes.embargoes')); + } + /** * {@inheritdoc} */ @@ -17,30 +92,36 @@ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); $embargo = $this->entity; - $form['embargo_type'] = array( + $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'), '#default_value' => $embargo->getEmbargoTypeAsInt(), '#options' => [ - '0' => t('Files'), - '1' => t('Node'), + '0' => $this->t('Files'), + '1' => $this->t('Node'), ], - ); + ]; - $form['expiration_type'] = array( + $form['expiry_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 +133,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,34 +151,34 @@ 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()), + ]; - $form['embargoed_node'] = array( + $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'), - '#default_value' => node_load($embargo->getEmbargoedNode()), + '#maxlength' => 255, + '#default_value' => $embargoed_node ? $embargoed_node : NULL, '#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', - ], + '#options' => $this->embargoes->getNotificationStatusesAsFormOptions($embargo), '#required' => TRUE, - ); + ]; return $form; } @@ -108,8 +189,15 @@ public function form(array $form, FormStateInterface $form_state) { public function save(array $form, FormStateInterface $form_state) { $embargo = $this->entity; $embargo->setEmbargoType($form_state->getValue('embargo_type')); - $embargo->setExpirationType($form_state->getValue('expiration_type')); - $embargo->setExpirationDate($form_state->getValue('expiration_date')); + $expiry_type = $form_state->getValue('expiry_type'); + $embargo->setExpirationType($expiry_type); + // Clear expiry date for indefinite embargoes. + if ($expiry_type === '0') { + $embargo->setExpirationDate(''); + } + else { + $embargo->setExpirationDate($form_state->getValue('expiration_date')); + } $embargo->setExemptIps($form_state->getValue('exempt_ips')); $embargo->setExemptUsers($form_state->getValue('exempt_users')); $embargo->setAdditionalEmails($form_state->getValue('additional_emails')); @@ -118,18 +206,19 @@ public function save(array $form, FormStateInterface $form_state) { $status = $embargo->save(); $log_values['node'] = $embargo->getEmbargoedNode(); - $log_values['user'] = \Drupal::currentUser()->id(); - $log_values['embargo_id'] = $embargo->id(); + $log_values['uid'] = $this->currentUser()->id(); + $log_values['embargo'] = $embargo->id(); if ($status == SAVED_NEW) { - $log_values['action'] = 'created'; + $log_values['action'] = $embargo::STATUS_CREATED; + $this->messenger->addMessage($this->t('Your embargo has been created.')); } else { - $log_values['action'] = 'updated'; + $log_values['action'] = $embargo::STATUS_UPDATED; + $this->messenger->addMessage($this->t('Your embargo has been updated.')); } - \Drupal::messenger()->addMessage("Your embargo has been {$log_values['action']}."); - \Drupal::service('embargoes.log')->logEmbargoEvent($log_values); + $this->embargoesLog->logEmbargoEvent($log_values); $form_state->setRedirectUrl($embargo->toUrl('collection')); } diff --git a/src/Form/EmbargoesIpRangeEntityForm.php b/src/Form/EmbargoesIpRangeEntityForm.php index c53bd06..85e2621 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} */ @@ -33,15 +59,19 @@ public function form(array $form, FormStateInterface $form_state) { '#default_value' => $range->label(), '#description' => $this->t("Label for the IP range."), '#required' => TRUE, + '#id' => 'ip-range-label', ]; $form['range'] = [ '#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, + '#element_validate' => [ + '::validateIpRanges', + ], ]; $form['proxy_url'] = [ @@ -55,30 +85,40 @@ public function form(array $form, FormStateInterface $form_state) { return $form; } + /** + * Validates the IP range entered. + * + * @param array $element + * An array representing the element. + * @param Drupal\Core\Form\FormStateInterface $form_state + * The Drupal form state. + */ + public function validateIpRanges(array $element, FormStateInterface $form_state) { + $errors = $this->ipRanges->detectIpRangeStringErrors(array_map('trim', explode('|', trim($form_state->getValue('range'))))); + if (!empty($errors)) { + $form_state->setError($element, $this->t('Problems detected with the %label IP Range.
Errors: %errors', [ + '%label' => $this->entity->label(), + '%errors' => implode(", ", $errors), + ])); + } + } + /** * {@inheritdoc} */ 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 = \Drupal::service('embargoes.ips')->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()])); - } - } - else { - drupal_set_message("Problems detected with the {$range->label()} IP Range.", 'error'); - foreach ($errors as $error) { - drupal_set_message("Error: {$error}.", 'error'); - } + 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()])); } $form_state->setRedirectUrl($range->toUrl('collection')); } diff --git a/src/Form/EmbargoesNodeEmbargoesForm.php b/src/Form/EmbargoesNodeEmbargoesForm.php index 1ee575e..327417c 100644 --- a/src/Form/EmbargoesNodeEmbargoesForm.php +++ b/src/Form/EmbargoesNodeEmbargoesForm.php @@ -2,14 +2,78 @@ namespace Drupal\embargoes\Form; +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; +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; + + /** + * A UUID generator service. + * + * @var \Drupal\Component\Uuid\UuidInterface + */ + protected $uuidGenerator; + + /** + * 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. + * @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) { + $this->entityManager = $entity_manager; + $this->ipRanges = $ip_ranges; + $this->embargoesLog = $embargoes_log; + $this->uuidGenerator = $uuid_generator; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('entity_type.manager'), + $container->get('embargoes.ips'), + $container->get('embargoes.log'), + $container->get('uuid')); + } + /** * {@inheritdoc} */ @@ -20,62 +84,61 @@ public function getFormId() { /** * {@inheritdoc} */ - public function buildForm(array $form, FormStateInterface $form_state, $node = NULL, $embargo_id = NULL) { - + 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, - ); + '#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'], @@ -84,39 +147,36 @@ public function buildForm(array $form, FormStateInterface $form_state, $node = N ':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()) ? NULL : $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', @@ -126,28 +186,30 @@ public function buildForm(array $form, FormStateInterface $form_state, $node = N 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([ + 'id' => sha1($this->uuidGenerator->generate()), + ]); } 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')); - $embargo->setExpirationType($form_state->getValue('expiry_type')); - $embargo->setExpirationDate($form_state->getValue('expiry_date')); + $expiry_type = $form_state->getValue('expiry_type'); + $embargo->setExpirationType($expiry_type); + // Clear expiry date for indefinite embargoes. + if ($expiry_type === '0') { + $embargo->setExpirationDate(''); + } + else { + $embargo->setExpirationDate($form_state->getValue('expiry_date')); + } $embargo->setExemptIps($form_state->getValue('exempt_ips')); $embargo->setExemptUsers($form_state->getValue('exempt_users')); $embargo->setAdditionalEmails($form_state->getValue('additional_emails')); @@ -155,18 +217,20 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $embargo->save(); $log_values['node'] = $embargo->getEmbargoedNode(); - $log_values['user'] = \Drupal::currentUser()->id(); - $log_values['embargo_id'] = $embargo->id(); + $log_values['uid'] = $this->currentUser()->id(); + $log_values['embargo'] = $embargo->id(); if ($embargo_id == 'add') { - $log_values['action'] = 'created'; + $log_values['action'] = $embargo::STATUS_CREATED; + $action = 'created'; } else { - $log_values['action'] = 'updated'; + $log_values['action'] = $embargo::STATUS_UPDATED; + $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 {$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..1cdcad4 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' => $config->get('embargo_contact_email'), ]; $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' => $config->get('add_contact_to_notifications'), ]; $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' => $config->get('show_embargo_message'), + ]; + + $form['embargo_notification_message'] = [ + '#type' => 'textarea', + '#title' => $this->t('Embargo notification messsage.'), + '#description' => $this->t('Notification text displayed to the user when an object or its files are under embargo. Use the "@contact" string to include the configured contact email, if available.'), + '#default_value' => $config->get('embargo_notification_message'), ]; return $form; @@ -62,9 +70,9 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $config->set('show_embargo_message', $form_state->getValue('show_embargo_message')); $config->set('add_contact_to_notifications', $form_state->getValue('add_contact_to_notifications')); $config->set('embargo_contact_email', $form_state->getValue('embargo_contact_email')); + $config->set('embargo_notification_message', $form_state->getValue('embargo_notification_message')); $config->save(); parent::submitForm($form, $form_state); - drupal_flush_all_caches(); } } diff --git a/src/Plugin/Block/EmbargoesEmbargoNotificationBlock.php b/src/Plugin/Block/EmbargoesEmbargoNotificationBlock.php new file mode 100644 index 0000000..263ca5c --- /dev/null +++ b/src/Plugin/Block/EmbargoesEmbargoNotificationBlock.php @@ -0,0 +1,230 @@ +get('current_route_match'), + $container->get('config.factory'), + $container->get('embargoes.embargoes'), + $container->get('entity_type.manager') + ); + } + + /** + * Construct embargo notification 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\Core\Config\ConfigFactoryInterface $config_factory + * A configuration factory 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, ConfigFactoryInterface $config_factory, EmbargoesEmbargoesServiceInterface $embargoes, EntityTypeManagerInterface $entity_manager) { + parent::__construct($configuration, $plugin_id, $plugin_definition); + $this->adminMail = $config_factory->get('embargoes.settings')->get('embargo_contact_email'); + $this->notificationMessage = $config_factory->get('embargoes.settings')->get('embargo_notification_message'); + $this->entityManager = $entity_manager; + $this->embargoes = $embargoes; + $this->routeMatch = $route_match; + } + + /** + * {@inheritdoc} + */ + public function build() { + $node = $this->routeMatch->getParameter('node'); + if ($node instanceof NodeInterface) { + $embargoes = $this->embargoes->getCurrentEmbargoesByNids([$node->id()]); + $num_embargoes = count($embargoes); + + if ($num_embargoes > 0) { + $t = $this->getStringTranslation(); + $embargoes_info = []; + $cache_tags = [ + "node:{$node->id()}", + "extensions", + "env", + ]; + $embargoes_count = $t->formatPlural( + $num_embargoes, + 'This resource is under 1 embargo:', + 'This resource is under @count embargoes:' + ); + + $contact_message = ""; + foreach ($embargoes as $embargo_id) { + + $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->load($embargo_id); + $embargo_info = []; + + // Expiration string. + if (!$embargo->getExpirationType()) { + $embargo_info['expiration'] = $t->translate('Indefinitely'); + $embargo_info['has_duration'] = FALSE; + } + else { + $embargo_info['expiration'] = $t->translate('Expires @duration', [ + '@duration' => $embargo->getExpirationDate(), + ]); + $embargo_info['has_duration'] = TRUE; + } + + // Embargo type string, including a message for the given type. + if (!$embargo->getEmbargoType()) { + $embargo_info['type'] = 'Files'; + $embargo_info['type_message'] = $t->translate('Access to all associated files of this resource is restricted'); + } + else { + $embargo_info['type'] = 'Node'; + $embargo_info['type_message'] = $t->translate('Access to this resource and all associated files is restricted'); + } + + // Exempt IP string. + if (!($embargo->getExemptIps())) { + $embargo_info['exempt_ips'] = ''; + } + else { + $embargo_info['exempt_ips'] = $t->translate('Allowed Networks: @network', [ + '@network' => $this->entityManager->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps())->label(), + ]); + } + + // Determine if given user is exempt or not. If not, prepare a message + // the user can use to request access. + $exempt_users = $embargo->getExemptUsers(); + $embargo_info['user_exempt'] = FALSE; + foreach ($exempt_users as $user) { + if ($user['target_id'] == \Drupal::currentUser()->id()) { + $embargo_info['user_exempt'] = TRUE; + } + } + if (!$embargo_info['user_exempt']) { + $contact_message = $t->translate( + $this->notificationMessage, + ['@contact' => $this->adminMail] + ); + } + + $embargo_info['dom_id'] = Html::getUniqueId('embargo_notification'); + $embargoes_info[] = $embargo_info; + + array_push( + $cache_tags, + "config:embargoes.embargoes_embargo_entity.{$embargo->id()}" + ); + + } + + return [ + '#theme' => 'embargoes_notifications', + '#count' => $embargoes_count, + '#message' => $contact_message, + '#embargo_info' => $embargoes_info, + '#cache' => [ + 'tags' => $cache_tags, + ], + ]; + } + } + + return []; + } + + /** + * {@inheritdoc} + */ + public function getCacheTags() { + // When the given node changes (route), the block should rebuild. + if ($node = \Drupal::routeMatch()->getParameter('node')) { + return Cache::mergeTags( + parent::getCacheTags(), + array('node:' . $node->id()) + ); + } + + // Return default tags, if not on a node page. + return parent::getCacheTags(); + } + + /** + * {@inheritdoc} + */ + public function getCacheContexts() { + // Ensure that with every new node/route, this block will be rebuilt. + return Cache::mergeContexts(parent::getCacheContexts(), array('route')); + } + +} diff --git a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php index de94b7d..78f364c 100644 --- a/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php +++ b/src/Plugin/Block/EmbargoesEmbargoPoliciesBlock.php @@ -2,8 +2,13 @@ namespace Drupal\embargoes\Plugin\Block; +use Drupal\node\NodeInterface; +use Drupal\embargoes\EmbargoesEmbargoesServiceInterface; use Drupal\Core\Block\BlockBase; -use Drupal\Core\Render\Markup; +use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\Routing\ResettableStackedRouteMatchInterface; +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a "Embargo Policies" block. @@ -14,57 +19,127 @@ * 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())); - $embargo_count = count($embargoes); + $node = $this->routeMatch->getParameter('node'); + if ($node instanceof NodeInterface) { + $embargoes = $this->embargoes->getCurrentEmbargoesByNids([$node->id()]); 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 .= "
    "; - $embargo = \Drupal::entityTypeManager()->getStorage('embargoes_embargo_entity')->load($embargo_id); + $t = $this->getStringTranslation(); + $embargoes_info = []; + $cache_tags = [ + "node:{$node->id()}", + ]; + $embargoes_count = $t->formatPlural(count($embargoes), + 'This resource has 1 embargo:', + 'This resource has @count embargoes:'); - if ($embargo->getExpirationType() == 0 ) { - $embargo_expiry = 'Indefinite'; - } + foreach ($embargoes as $embargo_id) { + $embargo = $this->entityManager->getStorage('embargoes_embargo_entity')->load($embargo_id); + $embargo_info = []; + // Expiration string. + if (!$embargo->getExpirationType()) { + $embargo_info['expiration'] = $t->translate('Duration: Indefinite'); + } else { - $embargo_expiry = "Until {$embargo->getExpirationDate()}"; + $embargo_info['expiration'] = $t->translate('Duration: Until @duration', [ + '@duration' => $embargo->getExpirationDate(), + ]); } - $embargo_expiry_string = "
  • Duration: {$embargo_expiry}
  • "; - $body .= $embargo_expiry_string; - - $embargo_type = ($embargo->getEmbargoType() == 1 ? 'Resource' : 'Resource Files'); - $embargo_type_string = "
  • Disallow Access To: {$embargo_type}
  • "; - $body .= $embargo_type_string; - - if ($embargo->getExemptIps() == 'none') { - $embargo_ips_string = ""; + // Embargo type string. + if (!$embargo->getEmbargoType()) { + $embargo_info['type'] = $t->translate('Disallow Access To: Resource Files'); + } + else { + $embargo_info['type'] = $t->translate('Disallow Access To: Resource'); + } + // Exempt IP string. + if (!($embargo->getExemptIps())) { + $embargo_info['exempt_ips'] = ''; } else { - $embargo_ips =\Drupal::entityTypeManager()->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps())->label(); - $embargo_ips_string = "
  • Allowed Networks: {$embargo_ips}
  • "; + $embargo_info['exempt_ips'] = $t->translate('Allowed Networks: @network', [ + '@network' => $this->entityManager->getStorage('embargoes_ip_range_entity')->load($embargo->getExemptIps())->label(), + ]); } - $body .= $embargo_ips_string; + $embargoes_info[] = $embargo_info; - $body .= "
"; + $cache_tags[] = "embargoes_embargo_entity:{$embargo->id()}"; } + + return [ + '#theme' => 'embargoes_policies', + '#count' => $embargoes_count, + '#embargo_info' => $embargoes_info, + '#cache' => [ + 'tags' => $cache_tags, + ], + ]; } } - return [ - '#markup' => Markup::create($body), - ]; - } - - public function getCacheMaxAge() { - return 0; + return []; } } diff --git a/src/Plugin/Condition/EmbargoesEmbargoedCondition.php b/src/Plugin/Condition/EmbargoesEmbargoedCondition.php index 5c0dbc4..7644a27 100644 --- a/src/Plugin/Condition/EmbargoesEmbargoedCondition.php +++ b/src/Plugin/Condition/EmbargoesEmbargoedCondition.php @@ -2,12 +2,18 @@ namespace Drupal\embargoes\Plugin\Condition; +use Symfony\Component\HttpFoundation\RequestStack; +use Drupal\Core\Session\AccountInterface; +use Drupal\embargoes\EmbargoesEmbargoesServiceInterface; +use Drupal\Core\Routing\RouteMatchInterface; +use Drupal\node\NodeInterface; use Drupal\Core\Condition\ConditionPluginBase; use Drupal\Core\Form\FormStateInterface; -use Drupal\Core\Plugin\Context\ContextDefinition; +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; /** - * Provides a 'Node is embargoed (embargoes)' condition to enable a condition based in module selected status. + * Condition to filter on whether or not a node is embargoed. * * @Condition( * id = "embargoes_embargoed_condition", @@ -16,16 +22,75 @@ * "node" = @ContextDefinition("entity:node", required = TRUE , label = @Translation("Node")) * } * ) - * */ -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(); } /** @@ -38,10 +103,10 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta '#default_value' => $this->configuration['filter'], '#description' => $this->t('Select the scope of embargo to trigger on.'), '#options' => [ - 'off' => 'Always trigger regardless of embargo status', - 'all' => 'All embargoes on node', - 'current' => 'Current embargoes on node (ignore expired)', - 'active' => 'Active embargoes on node (ignore bypassed)', + 'off' => $this->t('Always trigger regardless of embargo status'), + 'all' => $this->t('All embargoes on node'), + 'current' => $this->t('Current embargoes on node (ignore expired)'), + 'active' => $this->t('Active embargoes on node (ignore bypassed)'), ], ]; return parent::buildConfigurationForm($form, $form_state); @@ -69,24 +134,24 @@ public function defaultConfiguration() { * TRUE if the condition has been met, FALSE otherwise. */ public function evaluate() { - $node = \Drupal::routeMatch()->getParameter('node'); - if ($node instanceof \Drupal\node\NodeInterface) { + $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(array($node->id())); + $embargoed = $this->embargoes->getAllEmbargoesByNids([$node->id()]); break; + case 'current': - $embargoed = $embargo_service->getCurrentEmbargoesByNids(array($node->id())); + $embargoed = $this->embargoes->getCurrentEmbargoesByNids([$node->id()]); break; + case 'active': - $ip = \Drupal::request()->getClientIp(); - $user = \Drupal::currentUser(); - $embargoed = $embargo_service->getActiveEmbargoesByNids(array($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..6b1ba31 --- /dev/null +++ b/templates/embargoes-ip-access-denied.html.twig @@ -0,0 +1,21 @@ + + +

{{ 'Your request for the following resource could not be resolved:'|t }} {{ requested_resource }}

+ +

{{ 'Access to this resource is restricted to the following networks:'|t }}

+ +
    + {% for item in ranges %} + {% if item.proxy_url is null %} +
  • {{ item.label }}
  • + {% else %} +
  • {{ item.label }}
  • + {% endif %} + {% endfor %} +
+ +

{{ 'If any of the listed networks above appear as links, you may be able to reach the resource by authenticating through a proxy.'|t }}

+ +{% if contact_email != '' %} +

{{ 'If you have any questions about access to this resource, contact the following for more information:'|t }} {{ contact_email }}

+{% endif %} diff --git a/templates/embargoes-notifications.html.twig b/templates/embargoes-notifications.html.twig new file mode 100644 index 0000000..1f72fe4 --- /dev/null +++ b/templates/embargoes-notifications.html.twig @@ -0,0 +1,26 @@ +{# + /** + * @file + * Formats an IP restricted page. + * + * Available variables: + * - 'count': the count to display + * - 'embargoes_info': an indexed array containing any information required to + * display each individual embargo. + * - 'message': Configured message to request access. + */ +#} + +{{ count }} + +
    +{% for info in embargo_info %} +
  • + {{ info.type_message }} + {{ info.message }} +
    +
  • +{% endfor %} +
+ +

{{ message }}

diff --git a/templates/embargoes-policies.html.twig b/templates/embargoes-policies.html.twig new file mode 100644 index 0000000..f3b1812 --- /dev/null +++ b/templates/embargoes-policies.html.twig @@ -0,0 +1,22 @@ +{# + /** + * @file + * Formats an IP restricted page. + * + * Available variables: + * - 'count': the count to display + * - 'embargoes_info': an indexed array containing any information required to + * display each individual embargo. + */ +#} + +{{ count }} + +{% for info in embargoes_info %} +
+
    +
  • {{ info.expiration }}
  • +
  • {{ info.type }}
  • +
  • {{ info.exempt_ips }}
  • +
+{% endfor %}