diff --git a/src/Controller/AnnotationController.php b/src/Controller/AnnotationController.php index 5ce1370d..87806e2a 100644 --- a/src/Controller/AnnotationController.php +++ b/src/Controller/AnnotationController.php @@ -98,7 +98,7 @@ final class AnnotationController extends ControllerBase { if (is_array($annotation)) { $items[] = [ 'canvasId' => $row->canvas_id, - 'annotation' => $annotation, + 'annotation' => $this->normalizeAnnotation($annotation), ]; } } @@ -224,9 +224,48 @@ final class AnnotationController extends ControllerBase { $canvas_id = $target_canvas_id; } + // Normalize annotation body text before storing new or edited records. + $annotation = $this->normalizeAnnotation($annotation); + return [$canvas_id, $annotation]; } + /** + * Replaces non-breaking spaces in IIIF annotation body values. + * + * Supports both a single body object and an array of body objects. + * Leaves targets, identifiers, and other annotation metadata unchanged. + */ + private function normalizeAnnotation(array $annotation): array { + if (!isset($annotation['body']) || !is_array($annotation['body'])) { + return $annotation; + } + + if (isset($annotation['body']['value']) && is_string($annotation['body']['value'])) { + $annotation['body']['value'] = $this->normalizeBodyText($annotation['body']['value']); + } + else { + foreach ($annotation['body'] as $key => $body) { + if (is_array($body) && isset($body['value']) && is_string($body['value'])) { + $annotation['body'][$key]['value'] = $this->normalizeBodyText($body['value']); + } + } + } + + return $annotation; + } + + /** + * Converts HTML-encoded and literal Unicode NBSP characters into spaces. + */ + private function normalizeBodyText(string $value): string { + return str_replace( + "\u{00A0}", + ' ', + str_ireplace([' ', ' ', ' '], ' ', $value) + ); + } + /** * Returns the canvas targeted by a Web Annotation. */ @@ -296,7 +335,7 @@ final class AnnotationController extends ControllerBase { try { $annotation = json_decode($row->annotation_json, TRUE, 512, JSON_THROW_ON_ERROR); if (is_array($annotation)) { - $items[] = $annotation; + $items[] = $this->normalizeAnnotation($annotation); } } catch (\JsonException) {