@ -2,26 +2,21 @@
namespace Drupal\islandora_iiif\Plugin\views\style;
namespace Drupal\islandora_iiif\Plugin\views\style;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Url;
use Drupal\Core\Url;
use Drupal\islandora\IslandoraUtils;
use Drupal\taxonomy\TermInterface;
use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\File\FileSystemInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\ServerException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
/**
* Provide serializer format for IIIF Manifest.
* Provide serializer format for IIIF Manifest.
@ -37,13 +32,6 @@ use Symfony\Component\HttpFoundation\Request;
*/
*/
class IIIFManifest extends StylePluginBase {
class IIIFManifest extends StylePluginBase {
/**
* Islandora utility functions.
*
* @var \Drupal\islandora\IslandoraUtils
*/
protected $utils;
/**
/**
* {@inheritdoc}
* {@inheritdoc}
*/
*/
@ -96,13 +84,6 @@ class IIIFManifest extends StylePluginBase {
*/
*/
protected $fileSystem;
protected $fileSystem;
/**
* The Guzzle HTTP Client.
*
* @var \GuzzleHttp\Client
*/
protected $httpClient;
/**
/**
* The messenger.
* The messenger.
*
*
@ -110,31 +91,10 @@ class IIIFManifest extends StylePluginBase {
*/
*/
protected $messenger;
protected $messenger;
/**
* Module Handler for running hooks.
*
* @var \Drupal\Core\Extention\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Memoized structured text term.
*
* @var \Drupal\taxonomy\TermInterface|null
*/
protected ?TermInterface $structuredTextTerm;
/**
* Flag to track if we _have_ attempted a lookup, as the value is nullable.
*
* @var bool
*/
protected bool $structuredTextTermMemoized = FALSE;
/**
/**
* {@inheritdoc}
* {@inheritdoc}
*/
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, Request $request, ImmutableConfig $iiif_config, EntityTypeManagerInterface $entity_type_manager, FileSystemInterface $file_system, Client $http_client, MessengerInterface $messenger, ModuleHandlerInterface $moduleHandler, IslandoraUtils $utils ) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, SerializerInterface $serializer, Request $request, ImmutableConfig $iiif_config, EntityTypeManagerInterface $entity_type_manager, FileSystemInterface $file_system, Client $http_client, MessengerInterface $messenger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->serializer = $serializer;
$this->serializer = $serializer;
@ -144,8 +104,6 @@ class IIIFManifest extends StylePluginBase {
$this->fileSystem = $file_system;
$this->fileSystem = $file_system;
$this->httpClient = $http_client;
$this->httpClient = $http_client;
$this->messenger = $messenger;
$this->messenger = $messenger;
$this->utils = $utils;
$this->moduleHandler = $moduleHandler;
}
}
/**
/**
@ -162,22 +120,10 @@ class IIIFManifest extends StylePluginBase {
$container->get('entity_type.manager'),
$container->get('entity_type.manager'),
$container->get('file_system'),
$container->get('file_system'),
$container->get('http_client'),
$container->get('http_client'),
$container->get('messenger'),
$container->get('messenger')
$container->get('module_handler'),
$container->get('islandora.utils')
);
);
}
}
/**
* Return the request property.
*
* @return \Symfony\Component\HttpFoundation\Request
* The Symfony request object
*/
public function getRequest() {
return $this->request;
}
/**
/**
* {@inheritdoc}
* {@inheritdoc}
*/
*/
@ -190,35 +136,17 @@ class IIIFManifest extends StylePluginBase {
$request_url = $this->request->getRequestUri();
$request_url = $this->request->getRequestUri();
// Strip off the last URI component to get the base ID of the URL.
// Strip off the last URI component to get the base ID of the URL.
// @todo assumming the view is a path like /node/1/manifest.json
// @todo assumming the view is a path like /node/1/manifest.json
$url_components = explode('/', trim( $request_url, '/') );
$url_components = explode('/', $request_url);
array_pop($url_components);
array_pop($url_components);
$content_path = '/' . implode('/', $url_components);
$content_path = implode('/', $url_components);
$iiif_base_id = "{$request_host}{$content_path}";
$iiif_base_id = $request_host . '/' . $content_path;
$display = $this->iiifConfig->get('show_title');
switch ($display) {
case 'none':
$label = '';
break;
case 'view':
$label = $this->view->getTitle();
break;
case 'node':
$label = $this->getEntityTitle($content_path);
break;
default:
$label = $this->t("IIIF Manifest");
}
// @see https://iiif.io/api/presentation/2.1/#manifest
// @see https://iiif.io/api/presentation/2.1/#manifest
$json += [
$json += [
'@type' => 'sc:Manifest',
'@type' => 'sc:Manifest',
'@id' => $request_url,
'@id' => $request_url,
// If the View has a title, set the View title as the manifest label.
// If the View has a title, set the View title as the manifest label.
'label' => $lab el,
'label' => $this->view->getTitle() ?: $this->getEntityTitle($content_path),
'@context' => 'http://iiif.io/api/presentation/2/context.json',
'@context' => 'http://iiif.io/api/presentation/2/context.json',
// @see https://iiif.io/api/presentation/2.1/#sequence
// @see https://iiif.io/api/presentation/2.1/#sequence
'sequences' => [
'sequences' => [
@ -242,12 +170,6 @@ class IIIFManifest extends StylePluginBase {
$content_type = 'json';
$content_type = 'json';
// Add a search endpoint if one is defined.
$this->addSearchEndpoint($json, $url_components);
// Give other modules a chance to alter the manifest.
$this->moduleHandler->alter('islandora_iiif_manifest', $json, $this);
return $this->serializer->serialize($json, $content_type, ['views_style_plugin' => $this]);
return $this->serializer->serialize($json, $content_type, ['views_style_plugin' => $this]);
}
}
@ -269,9 +191,12 @@ class IIIFManifest extends StylePluginBase {
$canvases = [];
$canvases = [];
foreach (array_filter(array_values($this->options['iiif_tile_field'])) as $iiif_tile_field) {
foreach (array_filter(array_values($this->options['iiif_tile_field'])) as $iiif_tile_field) {
$viewsField = $this->view->field[$iiif_tile_field];
$viewsField = $this->view->field[$iiif_tile_field];
$iiif_ocr_file_field = !empty($this->options['iiif_ocr_file_field']) ? array_filter(array_values($this->options['iiif_ocr_file_field'])) : [];
$ocrField = count($iiif_ocr_file_field) > 0 ? $this->view->field[$iiif_ocr_file_field[0]] : NULL;
$entity = $viewsField->getEntity($row);
$entity = $viewsField->getEntity($row);
if (isset($entity->{$viewsField->definition['field_name']})) {
if (isset($entity->{$viewsField->definition['field_name']})) {
/** @var \Drupal\Core\Field\FieldItemListInterface $images */
/** @var \Drupal\Core\Field\FieldItemListInterface $images */
$images = $entity->{$viewsField->definition['field_name']};
$images = $entity->{$viewsField->definition['field_name']};
foreach ($images as $i => $image) {
foreach ($images as $i => $image) {
@ -280,15 +205,14 @@ class IIIFManifest extends StylePluginBase {
continue;
continue;
}
}
// Create the IIIF URL for this file
if (!is_null($ocrField)) {
// Visiting $iiif_url will resolve to the info.json for the image.
$ocrs = $entity->{$ocrField->definition['field_name']};
if ($this->iiifConfig->get('use_relative_paths')) {
$ocr = isset($ocrs[$i]) ? $ocrs[$i] : FALSE;
$file_url = ltrim($image->entity->createFileUrl(TRUE), '/');
}
else {
$file_url = $image->entity->createFileUrl(FALSE);
}
}
// Create the IIIF URL for this file
// Visiting $iiif_url will resolve to the info.json for the image.
$file_url = $image->entity->createFileUrl(FALSE);
$mime_type = $image->entity->getMimeType();
$mime_type = $image->entity->getMimeType();
$iiif_url = rtrim($iiif_address, '/') . '/' . urlencode($file_url);
$iiif_url = rtrim($iiif_address, '/') . '/' . urlencode($file_url);
@ -296,8 +220,35 @@ class IIIFManifest extends StylePluginBase {
$canvas_id = $iiif_base_id . '/canvas/' . $entity->id();
$canvas_id = $iiif_base_id . '/canvas/' . $entity->id();
$annotation_id = $iiif_base_id . '/annotation/' . $entity->id();
$annotation_id = $iiif_base_id . '/annotation/' . $entity->id();
[$width, $height] = $this->getCanvasDimensions($iiif_url, $image, $mime_type);
// Try to fetch the IIIF metadata for the image.
try {
$info_json = $this->httpClient->get($iiif_url)->getBody();
$resource = json_decode($info_json, TRUE);
$width = $resource['width'];
$height = $resource['height'];
}
catch (ClientException | ServerException | ConnectException $e) {
// If we couldn't get the info.json from IIIF
// try seeing if we can get it from Drupal.
if (empty($width) || empty($height)) {
// Get the image properties so we know the image width/height.
$properties = $image->getProperties();
$width = isset($properties['width']) ? $properties['width'] : 0;
$height = isset($properties['height']) ? $properties['height'] : 0;
// If this is a TIFF AND we don't know the width/height
// see if we can get the image size via PHP's core function.
if ($mime_type === 'image/tiff' & & !$width || !$height) {
$uri = $image->entity->getFileUri();
$path = $this->fileSystem->realpath($uri);
$image_size = getimagesize($path);
if ($image_size) {
$width = $image_size[0];
$height = $image_size[1];
}
}
}
}
$tmp_canvas = [
$tmp_canvas = [
// @see https://iiif.io/api/presentation/2.1/#canvas
// @see https://iiif.io/api/presentation/2.1/#canvas
'@id' => $canvas_id,
'@id' => $canvas_id,
@ -328,22 +279,15 @@ class IIIFManifest extends StylePluginBase {
],
],
];
];
if ($ocr_url = $this->getOcrUrl($entity) ) {
if (isset($ocr) & & $ocr != FALSE ) {
$tmp_canvas['seeAlso'] = [
$tmp_canvas['seeAlso'] = [
'@id' => $ocr_url ,
'@id' => $ocr->entity->createFileUrl(FALSE) ,
'format' => 'text/vnd.hocr+html',
'format' => 'text/vnd.hocr+html',
'profile' => 'http://kba.cloud/hocr-spec',
'profile' => 'http://kba.cloud/hocr-spec',
'label' => 'hOCR embedded text',
'label' => 'hOCR embedded text',
];
];
}
}
// Give other modules a chance to alter the canvas.
$alter_options = [
'options' => $this->options,
'views_plugin' => $this,
];
$this->moduleHandler->alter('islandora_iiif_manifest_canvas', $tmp_canvas, $row, $alter_options);
$canvases[] = $tmp_canvas;
$canvases[] = $tmp_canvas;
}
}
}
}
@ -352,98 +296,6 @@ class IIIFManifest extends StylePluginBase {
return $canvases;
return $canvases;
}
}
/**
* Try to fetch the IIIF metadata for the image.
*
* @param string $iiif_url
* Base URL of the canvas.
* @param \Drupal\Core\Field\FieldItemInterface $image
* The image field.
* @param string $mime_type
* The mime type of the image.
*
* @return [string]
* The width and height of the image.
*/
protected function getCanvasDimensions(string $iiif_url, FieldItemInterface $image, string $mime_type) {
if (isset($image->width) & & is_numeric($image->width)
& & isset($image->height) & & is_numeric($image->height)) {
return [intval($image->width), intval($image->height)];
}
try {
$info_json = $this->httpClient->get($iiif_url)->getBody();
$resource = json_decode($info_json, TRUE);
$width = $resource['width'];
$height = $resource['height'];
}
catch (ClientException | ServerException | ConnectException $e) {
// If we couldn't get the info.json from IIIF
// try seeing if we can get it from Drupal.
if (empty($width) || empty($height)) {
// Get the image properties so we know the image width/height.
$properties = $image->getProperties();
$width = isset($properties['width']) ? $properties['width'] : 0;
$height = isset($properties['height']) ? $properties['height'] : 0;
// If this is a TIFF AND we don't know the width/height
// see if we can get the image size via PHP's core function.
if ($mime_type === 'image/tiff' & & (!$width || !$height)) {
$uri = $image->entity->getFileUri();
$path = $this->fileSystem->realpath($uri);
$image_size = getimagesize($path);
if ($image_size) {
$width = $image_size[0];
$height = $image_size[1];
}
}
}
}
return [$width, $height];
}
/**
* Retrieves a URL text with positional data such as hOCR.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity at the current row.
*
* @return string|false
* The absolute URL of the current row's structured text,
* or FALSE if none.
*/
protected function getOcrUrl(EntityInterface $entity) {
$ocr_url = FALSE;
$iiif_ocr_file_field = !empty($this->options['iiif_ocr_file_field']) ? array_filter(array_values($this->options['iiif_ocr_file_field'])) : [];
$ocrField = count($iiif_ocr_file_field) > 0 ? $this->view->field[$iiif_ocr_file_field[0]] : NULL;
if ($ocrField) {
$ocr_entity = $entity;
$ocr_field_name = $ocrField->definition['field_name'];
if (!is_null($ocr_field_name)) {
$ocrs = $ocr_entity->{$ocr_field_name};
$ocr = $ocrs[0] ?? FALSE;
if ($ocr) {
$ocr_url = $ocr->entity->createFileUrl(FALSE);
}
}
}
elseif ($structured_text_term = $this->getStructuredTextTerm()) {
$parent_node = $this->utils->getParentNode($entity);
$ocr_entity_array = $this->utils->getMediaReferencingNodeAndTerm($parent_node, $structured_text_term);
$ocr_entity_id = is_array($ocr_entity_array) ? array_shift($ocr_entity_array) : NULL;
$ocr_entity = $ocr_entity_id ? $this->entityTypeManager->getStorage('media')->load($ocr_entity_id) : NULL;
if ($ocr_entity) {
$ocr_file_source = $ocr_entity->getSource();
$ocr_fid = $ocr_file_source->getSourceFieldValue($ocr_entity);
$ocr_file = $this->entityTypeManager->getStorage('file')->load($ocr_fid);
$ocr_url = $ocr_file->createFileUrl(FALSE);
}
}
return $ocr_url;
}
/**
/**
* Pull a title from the node or media passed to this view.
* Pull a title from the node or media passed to this view.
*
*
@ -484,29 +336,6 @@ class IIIFManifest extends StylePluginBase {
return $options;
return $options;
}
}
/**
* Add the configured search endpoint to the manifest.
*
* @param array $json
* The IIIF manifest.
* @param array $url_components
* The search endpoint URL as array.
*/
protected function addSearchEndpoint(array & $json, array $url_components) {
$url_base = $this->getRequest()->getSchemeAndHttpHost();
$hocr_search_path = $this->options['search_endpoint'];
$hocr_search_url = $url_base . '/' . ltrim($hocr_search_path, '/');
$hocr_search_url = str_replace('%node', $url_components[1], $hocr_search_url);
$json['service'][] = [
"@context" => "http://iiif.io/api/search/0/context.json",
"@id" => $hocr_search_url,
"profile" => "http://iiif.io/api/search/0/search",
"label" => t("Search inside this work"),
];
}
/**
/**
* {@inheritdoc}
* {@inheritdoc}
*/
*/
@ -563,27 +392,10 @@ class IIIFManifest extends StylePluginBase {
'#title' => $this->t('Structured OCR data file field'),
'#title' => $this->t('Structured OCR data file field'),
'#type' => 'checkboxes',
'#type' => 'checkboxes',
'#default_value' => $this->options['iiif_ocr_file_field'],
'#default_value' => $this->options['iiif_ocr_file_field'],
'#description' => $this->t("If the hOCR is a field on the same entity as the image source field above, select it here. If it's found in a related entity via the term below, leave this blank." ),
'#description' => $this->t('The source of structured OCR text for each entity.' ),
'#options' => $field_options,
'#options' => $field_options,
'#required' => FALSE,
'#required' => FALSE,
];
];
$form['structured_text_term'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'taxonomy_term',
'#title' => $this->t('Structured OCR text term'),
'#default_value' => $this->getStructuredTextTerm(),
'#required' => FALSE,
'#description' => $this->t('Term indicating the media that holds structured text, such as hOCR, for the given object. Use this if the text is on a separate media from the tile source.'),
];
$form['search_endpoint'] = [
'#type' => 'textfield',
'#title' => $this->t("Search endpoint path."),
'#description' => $this->t("If there is a search endpoint to search within the book that returns IIIF annotations, put it here. Use %node substitution where needed.< br > E.g., paged-content-search/%node"),
'#default_value' => $this->options['search_endpoint'],
'#required' => FALSE,
];
}
}
/**
/**
@ -596,41 +408,4 @@ class IIIFManifest extends StylePluginBase {
return ['json' => 'json'];
return ['json' => 'json'];
}
}
/**
* Submit handler for options form.
*
* Used to store the structured text media term by URL instead of Ttid.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state object.
*/
// @codingStandardsIgnoreStart
public function submitOptionsForm(& $form, FormStateInterface $form_state) {
// @codingStandardsIgnoreEnd
$style_options = $form_state->getValue('style_options');
$tid = $style_options['structured_text_term'];
unset($style_options['structured_text_term']);
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
$style_options['structured_text_term_uri'] = $this->utils->getUriForTerm($term);
$form_state->setValue('style_options', $style_options);
parent::submitOptionsForm($form, $form_state);
}
/**
* Get the structured text term.
*
* @return \Drupal\taxonomy\TermInterface|null
* The term if it could be found; otherwise, NULL.
*/
protected function getStructuredTextTerm() : ?TermInterface {
if (!$this->structuredTextTermMemoized) {
$this->structuredTextTermMemoized = TRUE;
$this->structuredTextTerm = $this->utils->getTermForUri($this->options['structured_text_term_uri']);
}
return $this->structuredTextTerm;
}
}
}