diff --git a/src/Extraction/AbstractHtmlExtractor.php b/src/Extraction/AbstractHtmlExtractor.php index 9c5bed00f..2121371c6 100644 --- a/src/Extraction/AbstractHtmlExtractor.php +++ b/src/Extraction/AbstractHtmlExtractor.php @@ -11,6 +11,8 @@ namespace JoliCode\StructuredData\Extraction; +use JoliCode\StructuredData\JsonLd\Parser\Range; + /** * Base class for extractors that parse structured data from HTML DOM trees. * @@ -41,6 +43,99 @@ protected function loadDocument(string $body): \Dom\HTMLDocument return $this->documentLoader->load($body); } + /** + * Locates, in $body, the elements of the document loadDocument() parsed + * from it. + */ + protected function loadLocator(string $body): HtmlSourceLocator + { + return $this->documentLoader->locator($body); + } + + /** + * The start tag of the element, or its whole line when the start tag + * cannot be located. + */ + protected static function anchorOf(HtmlSourceLocator $locator, \Dom\Element $element): Range + { + return $locator->startTag($element) ?? $locator->line($element); + } + + /** + * Collects the descendants of $root matching $isProperty, in document order, + * as both the microdata and RDFa specifications order property values. The + * descendants of an element for which $stopsAt is true are not visited. + * + * @param callable(\Dom\Element): bool $isProperty + * @param callable(\Dom\Element): bool $stopsAt + * + * @return list<\Dom\Element> + */ + protected static function collectInDocumentOrder(\Dom\Element $root, callable $isProperty, callable $stopsAt): array + { + $propertyNodes = []; + // A stack rather than recursion, for deeply nested pages; children are + // pushed last first, so that the first one is visited first. + $stack = array_reverse(self::childElements($root)); + + while ($stack) { + $node = array_pop($stack); + + if ($isProperty($node)) { + $propertyNodes[] = $node; + } + + if ($stopsAt($node)) { + continue; + } + + foreach (array_reverse(self::childElements($node)) as $child) { + $stack[] = $child; + } + } + + return $propertyNodes; + } + + /** + * Groups the values found for each property name into the properties of an + * item, and the source map of those properties. + * + * A name found once holds its value; a name found several times holds the + * list of its values, in document order. + * + * @param array> $occurrences the values of each name, in document order + * + * @return array{array, SourceMap} + */ + protected static function buildProperties(array $occurrences): array + { + $properties = []; + $sourceMap = new SourceMap(); + + foreach ($occurrences as $name => $values) { + $pointer = SourceMap::pointerSegment($name); + $sourceMap->setKey($pointer, $values[0]['key']); + + if (1 === \count($values)) { + $properties[$name] = $values[0]['value']; + $sourceMap->merge($values[0]['map'], $pointer); + + continue; + } + + $properties[$name] = array_column($values, 'value'); + // The list as a whole is anchored on its first value. + $sourceMap->setValue($pointer, $values[0]['map']->getValue('')); + + foreach ($values as $index => $value) { + $sourceMap->merge($value['map'], $pointer . SourceMap::pointerSegment($index)); + } + } + + return [$properties, $sourceMap]; + } + /** * Builds a human-readable location suffix like " at line 42" or * " at lines 12, 34" from a list of DOM node line numbers. @@ -76,11 +171,12 @@ protected static function lineOf(\Dom\Element $node): int } /** - * Encodes one extracted item into a JsonLdElement anchored on its DOM node. + * Encodes one extracted item into a JsonLdElement anchored on its DOM node, + * whose $sourceMap tells where each of its keys and values comes from. * * @throws ExtractionException when the item cannot be encoded */ - protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string $encodeFailureMessage): JsonLdElement + protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string $encodeFailureMessage, ?SourceMap $sourceMap = null): JsonLdElement { $encoded = json_encode($item, \JSON_UNESCAPED_SLASHES); @@ -89,7 +185,7 @@ protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string } // JsonLdElement counts lines from 0, as the parser does. - return new JsonLdElement($node->getLineNo(), 0, $encoded, $this->getFormat()); + return new JsonLdElement($node->getLineNo(), 0, $encoded, $this->getFormat(), $sourceMap); } /** @@ -126,4 +222,20 @@ protected function formatRanges(array $lineNumbers): string ), ); } + + /** + * @return list<\Dom\Element> + */ + private static function childElements(\Dom\Element $node): array + { + $children = []; + + foreach ($node->childNodes as $childNode) { + if ($childNode instanceof \Dom\Element) { + $children[] = $childNode; + } + } + + return $children; + } } diff --git a/src/Extraction/HtmlDocumentLoader.php b/src/Extraction/HtmlDocumentLoader.php index c885de8b5..6ca6fe847 100644 --- a/src/Extraction/HtmlDocumentLoader.php +++ b/src/Extraction/HtmlDocumentLoader.php @@ -28,6 +28,8 @@ class HtmlDocumentLoader private ?\Dom\HTMLDocument $lastDocument = null; + private ?HtmlSourceLocator $lastLocator = null; + /** * Parses $body as HTML5: malformed markup is recovered from, never refused. * @@ -44,13 +46,26 @@ public function load(string $body): \Dom\HTMLDocument $this->lastBody = $body; $this->lastDocument = $document; + $this->lastLocator = null; return $document; } + /** + * Locates the elements of the document parsed from $body in that body, + * sharing the memoized document and its source scan between extractors. + */ + public function locator(string $body): HtmlSourceLocator + { + $document = $this->load($body); + + return $this->lastLocator ??= new HtmlSourceLocator($body, $document); + } + public function reset(): void { $this->lastBody = null; $this->lastDocument = null; + $this->lastLocator = null; } } diff --git a/src/Extraction/HtmlSourceLocator.php b/src/Extraction/HtmlSourceLocator.php new file mode 100644 index 000000000..4cb0f9080 --- /dev/null +++ b/src/Extraction/HtmlSourceLocator.php @@ -0,0 +1,619 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Extraction; + +use JoliCode\StructuredData\JsonLd\Parser\Position; +use JoliCode\StructuredData\JsonLd\Parser\Range; +use JoliCode\StructuredData\JsonLd\Parser\Utf16; + +/** + * Finds where the elements of a parsed HTML document are written in its source. + * + * Dom\HTMLDocument only tells the line an element starts on, never its column, + * and nothing about its attributes or text. This class scans the source once + * with a small tolerant tokenizer, recording every start tag with the offsets + * of its attributes and of its matching end tag, then pairs each element of + * the DOM with its tag. + * + * An element is paired by its line, its name and its structured data + * attributes, then by its rank among the elements sharing all three: the HTML5 + * parser adds elements of its own (html, body, tbody, clones of misnested + * formatting elements) and moves some (foster parenting), so a plain count of + * the tags would drift. Only elements carrying a structured data attribute are + * paired, the only ones the extractors ask about. An element that cannot be + * paired is not located: callers fall back to its line. + * + * Lines are counted from 1 and columns from 1, in UTF-16 code units, as the + * editors displaying them count them. Ranges end on the column just after + * their last character. + */ +final class HtmlSourceLocator +{ + private const SIGNATURE_ATTRIBUTES = ['itemprop', 'itemscope', 'itemtype', 'itemid', 'property', 'typeof', 'about', 'resource', 'vocab', 'prefix']; + + private const VOID_ELEMENTS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']; + + /** + * Elements whose content is text up to their end tag, never markup. + */ + private const RAW_TEXT_ELEMENTS = ['script', 'style', 'xmp', 'iframe', 'noembed', 'noframes', 'textarea', 'title']; + + private const WHITESPACE = " \t\n\f\r"; + + private const TRIMMED_CHARACTERS = " \t\n\r\0\x0B"; + + /** + * Bytes between two column checkpoints of a line. + */ + private const COLUMN_CHECKPOINT_SPACING = 1024; + + /** + * @var list}>|null + */ + private ?array $tags = null; + + /** + * The offset of the end tag of each start tag that has one, by tag index. + * + * @var array + */ + private array $closeStarts = []; + + /** + * @var list + */ + private array $lineStarts = []; + + /** + * The line found by the last lookup, where the next one starts. + */ + private int $lineCursor = 0; + + /** + * Known columns of each line, as [offset, column] pairs in increasing order. + * + * @var array> + */ + private array $columnCheckpoints = []; + + /** + * Strong references: the DOM extension hands out the same object for a node + * only while one is alive, so the paired elements are kept alive with the + * locator. + * + * @var \SplObjectStorage<\Dom\Element, int>|null + */ + private ?\SplObjectStorage $elementTags = null; + + public function __construct( + private readonly string $body, + private readonly \Dom\HTMLDocument $document, + ) { + } + + /** + * The start tag of the element, from its "<" to its ">". + */ + public function startTag(\Dom\Element $element): ?Range + { + $tag = $this->tagOf($element); + + return null === $tag ? null : $this->range($tag['start'], $tag['end']); + } + + /** + * The whole line the element starts on, for an element that cannot be + * located more precisely. + */ + public function line(\Dom\Element $element): Range + { + $this->tokenize(); + + $lineIndex = min(max(0, $element->getLineNo()), \count($this->lineStarts) - 1); + $lineStart = $this->lineStarts[$lineIndex]; + $lineEnd = $this->lineStarts[$lineIndex + 1] ?? \strlen($this->body); + + // The next line starts after the line break, which is not part of the + // line; a line holds no other "\r" or "\n". + while ($lineEnd > $lineStart && \in_array($this->body[$lineEnd - 1], ["\r", "\n"], true)) { + --$lineEnd; + } + + return $this->range($lineStart, $lineEnd); + } + + /** + * The name of an attribute of the element, "itemtype" in itemtype="…". + */ + public function attributeName(\Dom\Element $element, string $attribute): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + return null === $location ? null : $this->range($location['nameStart'], $location['nameEnd']); + } + + /** + * The value of an attribute of the element, without its quotes and without + * the whitespace around it, as the extractors trim it. + */ + public function attributeValue(\Dom\Element $element, string $attribute): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + if (null === $location || null === $location['valueStart'] || null === $location['valueEnd']) { + return null; + } + + return $this->trimmedRange($location['valueStart'], $location['valueEnd']); + } + + /** + * The $index-th whitespace-separated token of an attribute value, counted + * from 0: one name of itemprop="name alternateName", one type of typeof. + */ + public function attributeToken(\Dom\Element $element, string $attribute, int $index): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + if (null === $location || null === $location['valueStart'] || null === $location['valueEnd']) { + return null; + } + + $rawValue = substr($this->body, $location['valueStart'], $location['valueEnd'] - $location['valueStart']); + + if (!preg_match_all('/[^' . preg_quote(self::WHITESPACE, '/') . ']+/', $rawValue, $matches, \PREG_OFFSET_CAPTURE) || !isset($matches[0][$index])) { + return null; + } + + [$token, $offset] = $matches[0][$index]; + $start = $location['valueStart'] + $offset; + + return $this->range($start, $start + \strlen($token)); + } + + /** + * The text the element holds, from its first to its last non-whitespace + * character: "2010" in 2010 . + * + * The element must have an end tag, and what lies between its tags must + * read as its text content: when the HTML5 parser closed it somewhere else + * (a

without

), its text is not located. + */ + public function text(\Dom\Element $element): ?Range + { + $tagIndex = $this->tagIndexOf($element); + $closeStart = null === $tagIndex ? null : $this->closeStarts[$tagIndex] ?? null; + + if (null === $tagIndex || null === $closeStart || null === $this->tags) { + return null; + } + + $contentStart = $this->tags[$tagIndex]['end']; + $innerSource = substr($this->body, $contentStart, $closeStart - $contentStart); + + if (self::normalizeText(html_entity_decode(strip_tags($innerSource), \ENT_QUOTES | \ENT_HTML5, 'UTF-8')) !== self::normalizeText($element->textContent ?? '')) { + return null; + } + + return $this->trimmedRange($contentStart, $closeStart); + } + + private static function normalizeText(string $text): string + { + return trim((string) preg_replace('/\s+/u', ' ', $text)); + } + + /** + * @return array{name: string, start: int, end: int, attributes: array}|null + */ + private function tagOf(\Dom\Element $element): ?array + { + $tagIndex = $this->tagIndexOf($element); + + return null === $tagIndex ? null : $this->tags[$tagIndex] ?? null; + } + + private function tagIndexOf(\Dom\Element $element): ?int + { + $this->pairElements(); + + if (null === $this->elementTags || !$this->elementTags->offsetExists($element)) { + return null; + } + + return $this->elementTags[$element]; + } + + private function trimmedRange(int $start, int $end): ?Range + { + $value = substr($this->body, $start, $end - $start); + $leading = \strlen($value) - \strlen(ltrim($value, self::TRIMMED_CHARACTERS)); + $trimmedLength = \strlen(trim($value, self::TRIMMED_CHARACTERS)); + + if (0 === $trimmedLength) { + return null; + } + + return $this->range($start + $leading, $start + $leading + $trimmedLength); + } + + private function range(int $startOffset, int $endOffset): Range + { + return new Range($this->position($startOffset), $this->position($endOffset)); + } + + private function position(int $offset): Position + { + $lineIndex = $this->lineIndexOf($offset); + + return new Position($lineIndex + 1, $this->columnOf($lineIndex, $offset)); + } + + /** + * The column of an offset, counted from a checkpoint of its line rather + * than from the line start: on a minified page, the whole document is one + * line, and counting from its start for every position would be quadratic. + */ + private function columnOf(int $lineIndex, int $offset): int + { + $checkpoints = $this->columnCheckpoints[$lineIndex] ?? [[$this->lineStarts[$lineIndex], 1]]; + $last = \count($checkpoints) - 1; + + // The last checkpoint at or before the offset. + $index = $last; + + if ($checkpoints[$last][0] > $offset) { + $low = 0; + $high = $last; + + while ($low < $high) { + $middle = intdiv($low + $high + 1, 2); + + if ($checkpoints[$middle][0] <= $offset) { + $low = $middle; + } else { + $high = $middle - 1; + } + } + + $index = $low; + } + + [$from, $column] = $checkpoints[$index]; + + // Past the last checkpoint, new ones are laid every so often, on the + // first byte of a character so that no character is split in two. + while ($index === $last && $offset - $from > self::COLUMN_CHECKPOINT_SPACING) { + $next = $from + self::COLUMN_CHECKPOINT_SPACING; + + while ($next < $offset && 0x80 === (\ord($this->body[$next]) & 0xC0)) { + ++$next; + } + + $column += Utf16::length(substr($this->body, $from, $next - $from)); + $from = $next; + $checkpoints[] = [$from, $column]; + $index = ++$last; + } + + $this->columnCheckpoints[$lineIndex] = $checkpoints; + + return $column + Utf16::length(substr($this->body, $from, $offset - $from)); + } + + /** + * The line holding the offset, counted from 0. + */ + private function lineIndexOf(int $offset): int + { + // Offsets are mostly asked for in document order: walking forward from + // the line found last is cheaper than a search over the whole page. + $line = $this->lineCursor; + + if ($this->lineStarts[$line] <= $offset) { + $steps = 0; + + while (isset($this->lineStarts[$line + 1]) && $this->lineStarts[$line + 1] <= $offset && ++$steps < 64) { + ++$line; + } + + if (!isset($this->lineStarts[$line + 1]) || $this->lineStarts[$line + 1] > $offset) { + return $this->lineCursor = $line; + } + } + + // The last line starting at or before the offset. + $low = 0; + $high = \count($this->lineStarts) - 1; + + while ($low < $high) { + $middle = intdiv($low + $high + 1, 2); + + if ($this->lineStarts[$middle] <= $offset) { + $low = $middle; + } else { + $high = $middle - 1; + } + } + + return $this->lineCursor = $low; + } + + private function pairElements(): void + { + if (null !== $this->elementTags) { + return; + } + + $this->tokenize(); + $this->elementTags = new \SplObjectStorage(); + + $tagsBySignature = []; + + foreach ($this->tags ?? [] as $index => $tag) { + $signature = $this->sourceSignature($tag); + + if (null !== $signature) { + $tagsBySignature[$signature][] = $index; + } + } + + $ranks = []; + + // In document order; walking the elements is an order of magnitude + // faster than an XPath query testing each attribute. + foreach ($this->document->getElementsByTagName('*') as $element) { + $signature = $element->hasAttributes() ? $this->domSignature($element) : null; + + if (null === $signature) { + continue; + } + + $rank = $ranks[$signature] = ($ranks[$signature] ?? -1) + 1; + + if (isset($tagsBySignature[$signature][$rank])) { + $this->elementTags[$element] = $tagsBySignature[$signature][$rank]; + } + } + } + + /** + * @param array{name: string, start: int, end: int, attributes: array} $tag + */ + private function sourceSignature(array $tag): ?string + { + $attributes = []; + + foreach (self::SIGNATURE_ATTRIBUTES as $attribute) { + $location = $tag['attributes'][$attribute] ?? null; + + if (null === $location) { + continue; + } + + $value = null === $location['valueStart'] || null === $location['valueEnd'] + ? '' + : html_entity_decode(substr($this->body, $location['valueStart'], $location['valueEnd'] - $location['valueStart']), \ENT_QUOTES | \ENT_HTML5, 'UTF-8'); + + $attributes[] = $attribute . '=' . preg_replace('/\r\n?/', "\n", $value); + } + + if ([] === $attributes) { + return null; + } + + return $this->lineIndexOf($tag['start']) . "\0" . $tag['name'] . "\0" . implode("\0", $attributes); + } + + /** + * Null for an element without any structured data attribute, which is + * never paired. + */ + private function domSignature(\Dom\Element $element): ?string + { + $attributes = []; + + foreach (self::SIGNATURE_ATTRIBUTES as $attribute) { + if ($element->hasAttribute($attribute)) { + $attributes[] = $attribute . '=' . $element->getAttribute($attribute); + } + } + + if ([] === $attributes) { + return null; + } + + return $element->getLineNo() . "\0" . strtolower($element->localName) . "\0" . implode("\0", $attributes); + } + + private function tokenize(): void + { + if (null !== $this->tags) { + return; + } + + $body = $this->body; + $length = \strlen($body); + + // Line breaks are "\r\n", "\r" or "\n", as the HTML parser and the + // editors read them. + $this->lineStarts = [0]; + + if (preg_match_all('/\r\n|\r|\n/', $body, $matches, \PREG_OFFSET_CAPTURE)) { + foreach ($matches[0] as [$lineBreak, $offset]) { + $this->lineStarts[] = $offset + \strlen($lineBreak); + } + } + + $tags = []; + // Indexes of the start tags still waiting for their end tag, by name. + $openTags = []; + // The content of a