$headings Heading level by selector, for elements that are written as headings. */ public function __construct( private Selector $selector, private array $strip = self::DEFAULT_STRIP, private array $headings = array() ) {} /** * Makes a copy that removes more elements and writes more elements as headings. * * @param string[] $selectors Extra selectors of elements to remove. * @param array $headings Extra heading levels by selector. * @return self The new extractor. */ public function with_extra( array $selectors, array $headings = array() ): self { return new self( $this->selector, array_merge( $this->strip, $selectors ), array_merge( $this->headings, $headings ) ); } /** * Finds the content area, removes what is left out and makes the addresses absolute. * * @param string $html HTML of the page. * @param string $selector Selectors of the content area, separated by commas. * @param string $base_url Address of the page, for relative links. * @return DOMElement|null The cleaned content area, or null when the HTML cannot be read or has no content. */ public function extract( string $html, string $selector, string $base_url ): ?DOMElement { $dom = $this->load( $html ); if ( null === $dom ) { return null; } $xpath = new DOMXPath( $dom ); $node = $this->find( $xpath, $selector ); if ( null === $node ) { return null; } $this->strip( $xpath, $node ); $this->promote( $xpath, $node ); $this->prepare_media( $xpath, $node ); $this->absolutize( $xpath, $node, $base_url ); return $node; } /** * Text blocks of the content area, split into those kept and those removed by the exclusions. * * @param string $html HTML of the page. * @param string $selector Selectors of the content area, separated by commas. * @return array{kept: string[], excluded: string[]} The blocks of text. */ public function text_blocks( string $html, string $selector ): array { $empty = array( 'kept' => array(), 'excluded' => array(), ); $dom = $this->load( $html ); if ( null === $dom ) { return $empty; } $xpath = new DOMXPath( $dom ); $node = $this->find( $xpath, $selector ); if ( null === $node ) { return $empty; } $all_blocks = array(); $this->collect( $node, $all_blocks ); $this->strip( $xpath, $node ); $kept = array(); $this->collect( $node, $kept ); $unmatched = array_count_values( $kept ); $removed = array(); foreach ( $all_blocks as $block ) { if ( ! empty( $unmatched[ $block ] ) ) { --$unmatched[ $block ]; } else { $removed[] = $block; } } return array( 'kept' => $kept, 'excluded' => $removed, ); } /** * Collects the text blocks under a node, skipping hidden elements and elements that hold no page text. * * @param DOMNode $node Node to read. * @param string[] $blocks Collected text blocks, added to by reference. * @return void */ private function collect( DOMNode $node, array &$blocks ): void { $text = ''; foreach ( $node->childNodes as $child ) { if ( XML_TEXT_NODE === $child->nodeType || XML_CDATA_SECTION_NODE === $child->nodeType ) { $text .= $child->nodeValue; continue; } if ( ! $child instanceof DOMElement ) { continue; } $tag = strtolower( $child->nodeName ); if ( in_array( $tag, self::SKIP_TAGS, true ) || $this->is_hidden( $child ) ) { continue; } if ( 'br' === $tag ) { $text .= ' '; continue; } if ( in_array( $tag, self::INLINE_TAGS, true ) && $this->is_inline_only( $child ) ) { $text .= ' ' . $child->textContent . ' '; continue; } $this->add_block( $text, $blocks ); $text = ''; $this->collect( $child, $blocks ); } $this->add_block( $text, $blocks ); } /** * Adds a block of text when it holds at least two letters or digits in a row. * * @param string $text Text of the block. * @param string[] $blocks Collected text blocks, added to by reference. * @return void */ private function add_block( string $text, array &$blocks ): void { $text = trim( (string) preg_replace( '/\s+/u', ' ', str_replace( "\xc2\xa0", ' ', $text ) ) ); if ( 1 === preg_match( '/[\p{L}\p{N}]{2}/u', $text ) ) { $blocks[] = $text; } } /** * Whether an element holds only elements that stay inside a line of text. * * @param DOMElement $element Element to check. * @return bool True when it does. */ private function is_inline_only( DOMElement $element ): bool { foreach ( $element->getElementsByTagName( '*' ) as $descendant ) { if ( ! in_array( strtolower( $descendant->nodeName ), self::INLINE_TAGS, true ) ) { return false; } } return true; } /** * Whether an element is hidden by an attribute or an inline style. * * @param DOMElement $element Element to check. * @return bool True when it is hidden. */ private function is_hidden( DOMElement $element ): bool { return $element->hasAttribute( 'hidden' ) || 'true' === strtolower( $element->getAttribute( 'aria-hidden' ) ) || 1 === preg_match( '/display\s*:\s*none|visibility\s*:\s*hidden/i', $element->getAttribute( 'style' ) ); } /** * Parses HTML. * * @param string $html HTML of the page. * @return DOMDocument|null The document, or null when the HTML is empty or cannot be parsed. */ private function load( string $html ): ?DOMDocument { if ( '' === trim( $html ) || ! class_exists( DOMDocument::class ) ) { return null; } $dom = new DOMDocument(); $previous = libxml_use_internal_errors( true ); $loaded = $dom->loadHTML( '' . $html, LIBXML_NONET | LIBXML_COMPACT | LIBXML_NOWARNING | LIBXML_NOERROR ); libxml_clear_errors(); libxml_use_internal_errors( $previous ); if ( ! $loaded ) { return null; } foreach ( iterator_to_array( $dom->childNodes ) as $child ) { if ( XML_PI_NODE === $child->nodeType ) { $dom->removeChild( $child ); } } return $dom; } /** * Finds the first element that matches the selectors and has content. The page body is the last choice. * * @param DOMXPath $xpath Query object for the document. * @param string $selector Selectors separated by commas. * @return DOMElement|null The element, or null when none has content. */ private function find( DOMXPath $xpath, string $selector ): ?DOMElement { $queries = $this->selector->to_xpaths( $selector ); $queries[] = '//body'; foreach ( $queries as $query ) { $list = $xpath->query( $query ); if ( false === $list ) { continue; } foreach ( $list as $candidate ) { if ( $candidate instanceof DOMElement && $this->has_content( $candidate ) ) { return $candidate; } } } return null; } /** * Whether an element has text, an image, a frame or media. * * @param DOMElement $element Element to check. * @return bool True when it does. */ private function has_content( DOMElement $element ): bool { if ( '' !== trim( $element->textContent ) ) { return true; } foreach ( array( 'img', 'iframe', 'video', 'audio' ) as $tag ) { if ( $element->getElementsByTagName( $tag )->length > 0 ) { return true; } } return false; } /** * Removes comments, page headers and footers, and the elements that match the strip selectors. * * @param DOMXPath $xpath Query object for the document. * @param DOMElement $root Content area. * @return void */ private function strip( DOMXPath $xpath, DOMElement $root ): void { $relative = array_merge( array( './/comment()' ), self::STRIP_XPATHS ); $document = array(); foreach ( $this->strip as $selector ) { $document = array_merge( $document, $this->selector->to_xpaths( $selector ) ); } foreach ( $relative as $query ) { $this->remove( $xpath->query( $query, $root ), $root ); } foreach ( $document as $query ) { $this->remove( $xpath->query( $query ), $root ); } } /** * Writes the elements chosen in the settings as headings. Headings, and elements that hold other blocks, are left as they are. * * @param DOMXPath $xpath Query object for the document. * @param DOMElement $root Content area. * @return void */ private function promote( DOMXPath $xpath, DOMElement $root ): void { foreach ( $this->headings as $selector => $level ) { foreach ( $this->selector->to_xpaths( (string) $selector ) as $query ) { $nodes = $xpath->query( $query ); foreach ( false === $nodes ? array() : iterator_to_array( $nodes ) as $node ) { if ( $node instanceof DOMElement && $node !== $root && $this->is_inside( $node, $root ) ) { $this->make_heading( $xpath->document, $node, $level ); } } } } } /** * Writes one element as a heading, keeping a link or emphasis that is the whole text. * * @param DOMDocument $document The document. * @param DOMElement $element The element. * @param int $level Heading level, 1 to 6. * @return void */ private function make_heading( DOMDocument $document, DOMElement $element, int $level ): void { if ( ! $element->parentNode instanceof DOMElement || $this->in_heading( $element ) || $this->has_blocks( $element ) ) { return; } $text = $this->text_of( $element ); $target = $element; while ( '' !== $text && $this->is_inline( $target ) && $target->parentNode instanceof DOMElement && $this->is_inline( $target->parentNode ) && $this->text_of( $target->parentNode ) === $text ) { $target = $target->parentNode; } $parent = $target->parentNode; if ( '' === $text || ! $parent instanceof DOMElement || ( $this->is_inline( $target ) && $this->text_of( $parent ) !== $text ) ) { return; } $heading = $document->createElement( 'h' . $level ); if ( $this->is_inline( $target ) ) { $parent->replaceChild( $heading, $target ); $heading->appendChild( $target ); return; } while ( $target->childNodes->length > 0 ) { $heading->appendChild( $target->childNodes->item( 0 ) ); } $parent->replaceChild( $heading, $target ); } /** * Whether an element is a heading or sits inside one. * * @param DOMElement $element The element. * @return bool True when it is part of a heading. */ private function in_heading( DOMElement $element ): bool { for ( $node = $element; $node instanceof DOMElement; $node = $node->parentNode ) { if ( 1 === preg_match( '/^h[1-6]$/', strtolower( $node->nodeName ) ) ) { return true; } } return false; } /** * Whether an element holds anything that is not inline, such as a paragraph or a list. * * @param DOMElement $element The element. * @return bool True when it holds a block. */ private function has_blocks( DOMElement $element ): bool { foreach ( $element->getElementsByTagName( '*' ) as $child ) { if ( ! in_array( strtolower( $child->nodeName ), self::INLINE_TAGS, true ) ) { return true; } } return false; } /** * Whether an element stays inside a line of text. * * @param DOMElement $element The element. * @return bool True for inline elements. */ private function is_inline( DOMElement $element ): bool { return in_array( strtolower( $element->nodeName ), self::INLINE_TAGS, true ); } /** * Text of an element with the spaces tidied. * * @param DOMElement $element The element. * @return string The text. */ private function text_of( DOMElement $element ): string { return trim( (string) preg_replace( '/\s+/u', ' ', $element->textContent ) ); } /** * Removes nodes that sit inside the content area. * * @param DOMNodeList|false $nodes Nodes to remove when they sit inside the root. * @param DOMElement $root Content area. * @return void */ private function remove( $nodes, DOMElement $root ): void { if ( false === $nodes ) { return; } foreach ( iterator_to_array( $nodes ) as $node ) { if ( $node !== $root && $node->parentNode instanceof DOMNode && $this->is_inside( $node, $root ) ) { $node->parentNode->removeChild( $node ); } } } /** * Whether a node is inside the content area. * * @param DOMNode $node Node to check. * @param DOMElement $root Content area. * @return bool True when it is a descendant of the root. */ private function is_inside( DOMNode $node, DOMElement $root ): bool { $parent = $node->parentNode; while ( null !== $parent ) { if ( $parent === $root ) { return true; } $parent = $parent->parentNode; } return false; } /** * Replaces the address of lazy-loaded images, frames and videos with the real one, which lazy-loading scripts keep in a data attribute while src holds a placeholder. * * @param DOMXPath $xpath Query object for the document. * @param DOMElement $root Content area. * @return void */ private function prepare_media( DOMXPath $xpath, DOMElement $root ): void { $images = $xpath->query( './/img | .//iframe | .//video', $root ); foreach ( false === $images ? array() : $images as $image ) { if ( ! $image instanceof DOMElement ) { continue; } foreach ( self::LAZY_ATTRIBUTES as $attribute ) { $lazy = trim( $image->getAttribute( $attribute ) ); if ( '' !== $lazy && 0 !== strpos( $lazy, 'data:' ) ) { $image->setAttribute( 'src', $lazy ); break; } } } } /** * Makes the links and image addresses absolute. Addresses with an unsupported scheme are removed. * * @param DOMXPath $xpath Query object for the document. * @param DOMElement $root Content area. * @param string $base_url Address of the page. * @return void */ private function absolutize( DOMXPath $xpath, DOMElement $root, string $base_url ): void { $nodes = $xpath->query( './/*[@href or @src]', $root ); foreach ( false === $nodes ? array() : $nodes as $node ) { if ( ! $node instanceof DOMElement ) { continue; } foreach ( array( 'href', 'src' ) as $attribute ) { if ( ! $node->hasAttribute( $attribute ) ) { continue; } $resolved = UrlResolver::resolve( $base_url, trim( $node->getAttribute( $attribute ) ) ); if ( '' === $resolved ) { $node->removeAttribute( $attribute ); } else { $node->setAttribute( $attribute, $resolved ); } } } } }