Browse Source

refactored

main
astanley 2 days ago
parent
commit
406d429a4c
  1. 58
      README.md
  2. 2
      config/install/islandora_altmetric.settings.yml
  3. 15
      config/schema/islandora_altmetric.schema.yml
  4. 2
      islandora_altmetric.info.yml
  5. 7
      islandora_altmetric.libraries.yml
  6. 6
      islandora_altmetric.links.menu.yml
  7. 26
      js/doi_embed.js
  8. 21
      src/Form/AltmetricSettingForm.php
  9. 99
      src/Plugin/Block/IslandoraAltmetricBlock.php

58
README.md

@ -4,10 +4,10 @@ A custom Drupal module that displays an Altmetric badge on repository object pag
## Requirements
- Drupal 10 or 11 (as declared in the module metadata).
- Drupal 10.2 or later in the 10.x series, or Drupal 11.
- Islandora 2.x (Composer requirement: `drupal/islandora: ^2.0`).
- The `islandora_object` content type with a plain string field containing a DOI.
- Browser access to the external Altmetric script hosts.
- Browser access to the Altmetric embed service.
- Permission to administer site configuration and place blocks.
## Installation
@ -30,7 +30,7 @@ The Composer package name is `roblib/islandora-altmetric`. The module is license
5. Go to Structure > Block layout (`/admin/structure/block`), place the **Islandora Altmetric** block in the desired theme region, and configure visibility as appropriate for repository object pages.
6. Visit a node with a DOI and verify that the badge appears.
The settings route requires `administer site configuration`. The menu link references the Islandora Citations configuration overview; use the direct settings URL if that parent menu is unavailable.
The settings route requires `administer site configuration`. The menu link is under Configuration > System.
### Configuration values
@ -38,10 +38,10 @@ The configuration object is `islandora_altmetric.settings`.
| Key | Purpose | Fallback |
| --- | --- | --- |
| `doi_field` | Machine name of the DOI field | `field_doi` when null |
| `style` | Badge type passed to the embed element | No explicit fallback |
| `doi_field` | Machine name of the DOI field | `field_doi` when unset or empty |
| `style` | Badge type passed to the embed element | `4` when unset or unrecognized |
Settings are shared by all block instances. There is no shipped default configuration file. Inspect saved settings with:
Settings are shared by all block instances. New installations receive default configuration from `config/install/islandora_altmetric.settings.yml`. Existing installations retain their saved configuration; runtime fallbacks also cover missing settings. Inspect saved settings with:
```sh
drush config:get islandora_altmetric.settings
@ -49,7 +49,9 @@ drush config:get islandora_altmetric.settings
## How it works
The block obtains the node from the current route, reads the first value of the configured DOI field, and returns an empty render array if the node or DOI is missing. Otherwise it generates an `altmetric-embed` element with `data-doi`, `data-badge-type`, and a right-positioned popover. The block includes an external script reference and attaches a local Drupal library, which loads another external Altmetric script from CloudFront. The populated block sets its render cache maximum age to zero.
The block obtains the node from the current route, checks that the configured field exists and is viewable, and reads its first value. If no DOI is available, it renders no badge. Otherwise a Drupal `html_tag` render array produces the embed element with escaped attributes. The external library uses Altmetric's stable HTTPS entry point, and a Drupal behavior requests a rescan for newly inserted AJAX/BigPipe badges.
Caching varies by route and content language, with node and configuration cache tags and field access cache metadata. Changing a DOI or the badge settings invalidates cached output, including previously empty blocks. The score itself is fetched by the browser, not cached by Drupal.
## File layout
@ -61,29 +63,43 @@ The block obtains the node from the current route, reads the first value of the
| `islandora_altmetric.libraries.yml` | JavaScript library definition |
| `islandora_altmetric.module` | Module hook file (currently no hooks) |
| `src/Form/AltmetricSettingForm.php` | Active site-wide settings form |
| `src/Form/AltmetricSettingsForm.php` | Alternate form, not referenced by the supplied routing file |
| `src/Plugin/Block/IslandoraAltmetricBlock.php` | Block plugin and badge rendering |
| `js/doi_embed.js` | External script loader |
| `config/schema/islandora_altmetric.schema.yml` | Existing configuration schema |
| `js/doi_embed.js` | AJAX/BigPipe badge refresh behavior |
| `config/schema/islandora_altmetric.schema.yml` | Configuration schema |
| `config/install/islandora_altmetric.settings.yml` | Defaults for new installations |
| `composer.json` | Package metadata and dependency declaration |
## Troubleshooting
- **No badge:** verify the block is placed and visible, the current route has a node, and the configured field contains a valid DOI. A DOI does not guarantee that Altmetric has a badge or tracked activity for it.
- **DOI field missing from settings:** verify the content type, field type and machine name against the selection criteria above.
- **External script not loading:** inspect the browser console and network panel for content security policy restrictions, blockers, or failed requests to `badge.altmetric.com` and `d1bxh8uas1mnw7.cloudfront.net`.
- **External script not loading:** inspect the browser console and network panel for content security policy restrictions, blockers, or failed requests to `embed.altmetric.com` and other hosts listed in the vendor documentation.
- **Configuration menu missing:** use the direct settings URL.
## Maintenance notes
## Upgrading an existing installation
Replace the old module directory (do not merely overlay files, because the duplicate `AltmetricSettingsForm.php` has been removed). Keep the same module machine name. No uninstall or reinstall is necessary. The existing settings object, route, and block plugin ID are unchanged.
```sh
drush cr
drush config:get islandora_altmetric.settings
```
Review and save settings if needed. Export configuration using `drush cex` if this site uses configuration management. If a manually edited configuration contains a numeric style, resaving the form stores it as a string.
## Maintenance and security
- The settings form initializes the parent configuration services, including the typed configuration manager required by Drupal 11.
- The vendor script is external and excluded from Drupal preprocessing. Do not pin its generated asset filenames.
- Review third-party script privacy and CSP requirements. See [Altmetric embed documentation](https://docs.altmetric.com/badges/getting-started/) for current allowed hosts and script initialization guidance.
- The module expects a DOI in a plain string field; it does not verify DOI registration or query Altmetric server-side.
The following existing implementation details warrant review before production deployment. They have been documented rather than changed in this documentation-only revision:
## Manual verification after deployment
- Two similarly named settings form classes exist. Only the singular `AltmetricSettingForm` is routed by this module.
- Both forms supply their own constructor without calling the parent constructor. Compatibility with the installed Drupal version's `ConfigFormBase` services should be tested.
- The schema contains placeholder `example` entries rather than definitions for `doi_field` and `style`.
- The DOI and style are interpolated directly into HTML attributes. Review attribute escaping and validation, and prefer a structured render array. The script tag in `#markup` may also be filtered by Drupal.
- There are two external script-loading paths and a redundant initial render-array assignment. Review whether both loading paths are needed and whether the pinned CloudFront URL remains supported.
- Review cache metadata for empty block returns and consider appropriate node, route and configuration dependencies instead of disabling caching for populated badges.
- Third-party scripts execute in the visitor's browser; review privacy and content security policy requirements.
1. Open the settings page, save each style, and confirm that existing settings persist.
2. Visit two nodes with different DOIs, a node without a DOI, and a non-node route. Confirm the badge appears only as appropriate and is not reused between nodes.
3. Add a DOI to a previously empty node, change a DOI, and change the badge style without clearing caches; verify the new output appears.
4. Check field access with a restricted user if field access controls are installed.
5. Confirm the vendor script loads once, including with aggregation enabled, and test AJAX/BigPipe rendering and any CSP rules.
No live Drupal installation or automated module tests are included in the supplied archive.
PHP and JavaScript syntax and YAML parsing were checked. No live Drupal installation is included; the above integration checks remain to be performed.

2
config/install/islandora_altmetric.settings.yml

@ -0,0 +1,2 @@
doi_field: field_doi
style: '4'

15
config/schema/islandora_altmetric.schema.yml

@ -1,17 +1,16 @@
# Existing placeholder schemas; see README for the actual saved settings.
# The block has no plugin-specific configuration.
block.settings.islandora_altmetric_islandora_altmetric:
type: block_settings
label: 'Islandora Altmetric block'
mapping:
example:
type: string
label: Example
# Schema for the configuration files of the Islandora Altmetric module.
# Site-wide settings shared by all badge blocks.
islandora_altmetric.settings:
type: config_object
label: 'Islandora Altmetric settings'
mapping:
example:
doi_field:
type: string
label: 'DOI field machine name'
style:
type: string
label: 'Example'
label: 'Badge style'

2
islandora_altmetric.info.yml

@ -3,6 +3,6 @@ name: 'Islandora Altmetric'
type: module
description: 'Displays Altmetric Badge in a block'
package: Custom
core_version_requirement: ^10 || ^11
core_version_requirement: ^10.2 || ^11
dependencies:
- islandora:islandora

7
islandora_altmetric.libraries.yml

@ -1,5 +1,8 @@
# Local loader for the external Altmetric badge script.
# Load the vendor's stable entry point once, without aggregation.
islandora_altmetric:
js:
https://embed.altmetric.com/assets/embed.js: { type: external, minified: true, preprocess: false }
js/doi_embed.js: {}
dependencies:
- core/drupal
- core/once

6
islandora_altmetric.links.menu.yml

@ -1,7 +1,7 @@
# Place the settings link beneath the Islandora Citations configuration menu.
# Place the settings link beneath the System configuration menu.
islandora_altmetric.altmetric_settings:
title: Altmetric settings
description: Setting for altmetric Badge
parent: entity.islandora_citations.config_overview
description: Configure the DOI field and badge style
parent: system.admin_config_system
route_name: islandora_altmetric.altmetric_settings
weight: 10

26
js/doi_embed.js

@ -1,10 +1,22 @@
/**
* @file
* Loads the external Altmetric badge JavaScript.
*
* The loader removes an existing script with the same ID, creates a new
* script element (using the document namespace when supported), assigns the
* external URL, and appends it to the head or body. The original compact
* implementation and pinned URL are retained unchanged.
* Refreshes Altmetric badges inserted by Drupal AJAX or BigPipe.
*/
!function(e,t){var d="createElement",c="getElementsByTagName",n="setAttribute",a=document.getElementById(e);a&&a.parentNode&&a.parentNode.removeChild(a),(a=(a=document[d+"NS"]&&document.documentElement.namespaceURI)?document[d+"NS"](a,"script"):document[d]("script"))[n]("id",e),a[n]("src",t),(document[c]("head")[0]||document[c]("body")[0]).appendChild(a)}("altmetric-embed-js","https://d1bxh8uas1mnw7.cloudfront.net/assets/altmetric_badges-e8c6816abd50a76f6c51292a940cd903f1d7767d11fcfee92c0e65948faf4a1b.js");
(function (Drupal, once) {
'use strict';
Drupal.behaviors.islandoraAltmetric = {
attach(context) {
// Altmetric scans the initial document itself. For later fragments,
// request another scan only when a previously unseen badge is present.
const candidates = Array.from(context.querySelectorAll('.altmetric-embed'));
if (context.matches && context.matches('.altmetric-embed')) {
candidates.push(context);
}
const badges = once('islandora-altmetric', candidates);
if (context !== document && badges.length && typeof window._altmetric_embed_init === 'function') {
window._altmetric_embed_init();
}
}
};
})(Drupal, once);

21
src/Form/AltmetricSettingForm.php

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace Drupal\islandora_altmetric\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -27,10 +29,15 @@ final class AltmetricSettingForm extends ConfigFormBase {
/**
* Constructs an AltmetricSettingForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
* The typed configuration manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager service.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager) {
public function __construct(ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config_manager, EntityFieldManagerInterface $entity_field_manager) {
parent::__construct($config_factory, $typed_config_manager);
$this->entityFieldManager = $entity_field_manager;
}
@ -39,7 +46,9 @@ final class AltmetricSettingForm extends ConfigFormBase {
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_field.manager')
$container->get('config.factory'),
$container->get('config.typed'),
$container->get('entity_field.manager'),
);
}
@ -78,7 +87,8 @@ final class AltmetricSettingForm extends ConfigFormBase {
'#title' => $this->t('DOI Field'),
'#options' => $candidate_fields,
'#description' => $this->t("Field from content model with DOI"),
'#default_value' => $this->config('islandora_altmetric.settings')->get('doi_field'),
'#default_value' => $this->config('islandora_altmetric.settings')->get('doi_field') ?? 'field_doi',
'#required' => TRUE,
];
// Map Altmetric badge type values to human-readable labels.
$styles = [
@ -93,7 +103,8 @@ final class AltmetricSettingForm extends ConfigFormBase {
'#title' => $this->t('Badge Style'),
'#options' => $styles,
'#description' => $this->t("Display Style"),
'#default_value' => $this->config('islandora_altmetric.settings')->get('style'),
'#default_value' => $this->config('islandora_altmetric.settings')->get('style') ?? '4',
'#required' => TRUE,
];
return parent::buildForm($form, $form_state);
}
@ -105,7 +116,7 @@ final class AltmetricSettingForm extends ConfigFormBase {
// Persist site-wide settings for use by the block plugin.
$this->config('islandora_altmetric.settings')
->set('doi_field', $form_state->getValue('doi_field'))
->set('style', $form_state->getValue('style'))
->set('style', (string) $form_state->getValue('style'))
->save();
parent::submitForm($form, $form_state);
}

99
src/Plugin/Block/IslandoraAltmetricBlock.php

@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Drupal\islandora_altmetric\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\node\NodeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
@ -25,12 +27,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*/
final class IslandoraAltmetricBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The route match service.
*
@ -54,8 +50,6 @@ final class IslandoraAltmetricBlock extends BlockBase implements ContainerFactor
* The plugin ID.
* @param mixed $plugin_definition
* The plugin definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_typemanager
* The entity type manager (currently retained but unused).
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route, used to retrieve the node.
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
@ -65,12 +59,10 @@ final class IslandoraAltmetricBlock extends BlockBase implements ContainerFactor
array $configuration,
$plugin_id,
$plugin_definition,
EntityTypeManagerInterface $entity_typemanager,
RouteMatchInterface $route_match,
ConfigFactoryInterface $configFactory
) {
$this->routeMatch = $route_match;
$this->entityTypeManager = $entity_typemanager;
$this->configFactory = $configFactory;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
@ -83,7 +75,6 @@ final class IslandoraAltmetricBlock extends BlockBase implements ContainerFactor
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('current_route_match'),
$container->get('config.factory'),
);
@ -92,48 +83,62 @@ final class IslandoraAltmetricBlock extends BlockBase implements ContainerFactor
/**
* {@inheritdoc}
*/
public function build(): array {
// Read the site-wide settings and resolve the current route node.
$config = $this->configFactory->get('islandora_altmetric.settings');
$node = $this->routeMatch->getParameter('node');
// Do not render a badge on routes without a node parameter.
if (!$node) {
return [];
public function getCacheContexts(): array {
// The block varies by route and content translation.
return Cache::mergeContexts(parent::getCacheContexts(), ['route', 'languages:language_content']);
}
// Fall back to field_doi when no source field has been configured.
// Read the first field item through Drupal's field value accessor.
$doi_field = $config->get('doi_field') ?? 'field_doi';
$doi = $node->$doi_field->value ?? null;
// A badge cannot be requested without a DOI.
if (!$doi) {
return [];
/**
* {@inheritdoc}
*/
public function getCacheTags(): array {
// Invalidate even empty blocks when configuration or the node changes.
$tags = Cache::mergeTags(parent::getCacheTags(), $this->configFactory->get('islandora_altmetric.settings')->getCacheTags());
$node = $this->routeMatch->getParameter('node');
return $node instanceof NodeInterface ? Cache::mergeTags($tags, $node->getCacheTags()) : $tags;
}
// Build the embed element and request the external badge script.
// The existing interpolation is preserved; see README security notes.
$style = $config->get('style');
$markup = <<<EOD
<div class="altmetric-embed" data-badge-type='$style' data-badge-popover="right" data-doi="$doi"></div>
<script async src="//badge.altmetric.com/embeds.js"></script>
EOD;
// Initial markup assignment (replaced below by the library-aware array).
$build['content'] = [
'#markup' => $markup,
];
/**
* {@inheritdoc}
*/
public function build(): array {
$config = $this->configFactory->get('islandora_altmetric.settings');
$node = $this->routeMatch->getParameter('node');
$cacheability = (new CacheableMetadata())->setCacheContexts($this->getCacheContexts())->setCacheTags($this->getCacheTags());
$build = [];
// Attach the local loader library alongside the embed markup.
$build['content'] = [
'#markup' => $markup,
'#attached' => [
'library' => [
'islandora_altmetric/islandora_altmetric',
// Preserve cache metadata even when there is no badge to display.
if ($node instanceof NodeInterface) {
$doi_field = $config->get('doi_field') ?: 'field_doi';
if ($node->hasField($doi_field)) {
$field = $node->get($doi_field);
// Respect field access and its cacheability before exposing a DOI.
$access = $field->access('view', NULL, TRUE);
$cacheability->addCacheableDependency($access);
$doi = $access->isAllowed() && !$field->isEmpty() ? trim((string) $field->value) : '';
if ($doi !== '') {
$style = (string) $config->get('style');
if (!in_array($style, ['4', 'donut', 'medium-donut', 'large-donut'], TRUE)) {
$style = '4';
}
// Drupal escapes attribute values when rendering an html_tag.
$build = [
'#type' => 'html_tag',
'#tag' => 'div',
'#attributes' => [
'class' => ['altmetric-embed'],
'data-badge-type' => $style,
'data-badge-popover' => 'right',
'data-doi' => $doi,
],
'#attached' => [
'library' => ['islandora_altmetric/islandora_altmetric'],
],
];
// Disable render caching for the populated, node-specific badge.
$build['#cache'] = [
'max-age' => 0,
];
}
}
}
$cacheability->applyTo($build);
return $build;
}

Loading…
Cancel
Save