searches. return $findBareUrls ? array_merge( $links, $this->extractBareUrls( $postContent, $other ) ) : $links; } } $other = array_merge( $this->extractImages( $postContent ), $this->extractVideos( $postContent ) ); $links = array_merge( $this->extractLinksRegex( $postContent ), $other ); return $findBareUrls ? array_merge( $links, $this->extractBareUrls( $postContent, $other ) ) : $links; } /** * Returns the links for URLs written as plain text rather than wrapped in a tag. * * Only the kinds that opt in reach here - see {@see \AIOSEO\BrokenLinkChecker\Objects\ObjectType::findsBareUrls()}. * * NOTE: Tags are stripped before the search, so an attribute URL cannot be picked up here. The passes * that read attributes have already run, and one they skipped was skipped on purpose. * * @since 1.3.1 * * @param string $postContent The content. * @param array $found The links whose URL can also appear as text, e.g. an embed's. * @return array The links. */ private function extractBareUrls( $postContent, $found ) { // Whole anchors go first: stripping tags alone would leave x looking like a bare // URL, and deduping that by URL instead cost a genuine plain-text occurrence of an anchored URL. $withoutAnchors = preg_replace( '#]*>.*?#is', '', (string) $postContent ); $text = wp_strip_all_tags( null === $withoutAnchors ? (string) $postContent : $withoutAnchors ); // Escaped markup in a code sample reads as text by here, and a URL inside an attribute is not one // the reader can click. Decoding before the second strip removes it the way a real tag was removed. $text = wp_strip_all_tags( $this->decodeValue( $text ) ); if ( false === stripos( $text, 'http' ) ) { return []; } $seen = []; foreach ( $found as $link ) { if ( isset( $link['url'] ) ) { $seen[ $link['url'] ] = true; } } preg_match_all( '#\bhttps?://[^\s<>"\'\]]+#i', $text, $matches ); if ( empty( $matches[0] ) ) { return []; } $links = []; foreach ( array_unique( $matches[0] ) as $capturedUrl ) { // Prose punctuation sits against the URL, e.g. "see https://example.com/page." or "(https://x.com)". $capturedUrl = rtrim( $capturedUrl, '.,;:!?' ); if ( substr_count( $capturedUrl, ')' ) > substr_count( $capturedUrl, '(' ) ) { $capturedUrl = rtrim( $capturedUrl, ')' ); } $parsedUrl = $this->parseUrl( $capturedUrl ); if ( empty( $parsedUrl['host'] ) ) { continue; } if ( $this->hasIgnoredExtension( $parsedUrl ) ) { continue; } $urlFields = $this->urlFields( $parsedUrl ); if ( isset( $seen[ $urlFields['url'] ] ) ) { continue; } $seen[ $urlFields['url'] ] = true; // A rich text row must carry its context or it is refused, and these fields are only ever // empty for a value short enough to hold nothing but the address - which is its own context. $paragraph = aioseoBrokenLinkChecker()->main->paragraph->get( $this->contextKey(), $postContent, $capturedUrl ); $paragraphHtml = aioseoBrokenLinkChecker()->main->paragraph->getHtml( $capturedUrl, $paragraph, $postContent ); $links[] = array_merge( $urlFields, [ // The address is what the reader sees, so it is also the anchor the report shows. 'anchor' => $capturedUrl, 'phrase' => $capturedUrl, 'phrase_html' => $capturedUrl, 'paragraph' => $paragraph ? $this->decodeValue( $paragraph ) : $capturedUrl, 'paragraph_html' => $paragraphHtml ? $paragraphHtml : $capturedUrl, 'is_video' => $this->isVideoUrl( $urlFields['url'] ), 'is_image' => false, 'is_embed' => false ] ); } return $links; } /** * Extracts links from post content using BlcHtmlTagProcessor with bookmarks. * * Single-pass approach: iterates tags, uses bookmarks to get byte offsets * for the opener and closer, then extracts anchor text and surrounding sentence * context directly from the original content string. No markers, no regex for * link identification, no content mutation. * * Returns null if the WP_HTML_Tag_Processor bookmark internals have changed, * signalling the caller to fall back to regex-based extraction. * * Requires WP 6.6+ — the caller gates on this version. * * @since 1.3.0 * @version 1.3.1 Dropped the $postId parameter; the object is read from the scan context. * * @param string $postContent The preprocessed content. * @return array|null The links, or null if bookmark internals failed. */ private function extractLinksHtmlApi( $postContent ) { $processor = new BlcHtmlTagProcessor( $postContent ); $links = []; $prevCloserEnd = 0; $seekTo = null; while ( true ) { if ( $seekTo ) { $processor->seek( $seekTo ); $processor->release_bookmark( $seekTo ); $seekTo = null; } elseif ( ! $processor->next_tag( 'a' ) ) { break; } $href = $processor->get_attribute( 'href' ); if ( ! is_string( $href ) || '' === $href || '#' === $href[0] || aioseoBrokenLinkChecker()->helpers->hasUnscannableScheme( $href ) ) { // Advance past the closing so $prevCloserEnd stays accurate. // Without this, the next link's phrase boundary search would scan // through this filtered link's href attributes (e.g. the "." in "tel:+1.555.1234"). $prevCloserEnd = $this->skipPastCloser( $processor, $prevCloserEnd ); continue; } // Bookmark the opening tag to get its byte offsets. $openerBookmark = 'blc_opener'; $processor->set_bookmark( $openerBookmark ); $openerStart = $processor->getBookmarkStart( $openerBookmark ); $openerLength = $processor->getBookmarkLength( $openerBookmark ); $processor->release_bookmark( $openerBookmark ); // If bookmark was set but getters return null, WP core internals have changed. if ( null === $openerStart || null === $openerLength ) { return null; } $openerEnd = $openerStart + $openerLength; // Advance through tokens until we find the closing tag. $closerStart = null; $closerEnd = null; while ( $processor->next_token() ) { $tokenType = $processor->get_token_type(); if ( '#tag' !== $tokenType || 'A' !== $processor->get_tag() ) { continue; } // Nested opener (malformed HTML) — bookmark for reprocessing, stop walking. if ( ! $processor->is_tag_closer() ) { if ( $processor->set_bookmark( 'blc_nested' ) ) { $seekTo = 'blc_nested'; } break; } $processor->set_bookmark( 'blc_closer' ); $closerStart = $processor->getBookmarkStart( 'blc_closer' ); $closerLength = $processor->getBookmarkLength( 'blc_closer' ); $processor->release_bookmark( 'blc_closer' ); // If bookmark was set but getters return null, WP core internals have changed. if ( null === $closerStart || null === $closerLength ) { return null; } $closerEnd = $closerStart + $closerLength; break; } // Skip malformed HTML with no closing . if ( null === $closerEnd ) { continue; } // Extract the inner HTML and anchor text. $innerHtml = substr( $postContent, $openerEnd, $closerStart - $openerEnd ); $anchor = wp_strip_all_tags( $innerHtml ); // Save this link's closer position before any early-continue filters below. // This ensures the next iteration's phrase boundary search won't scan // through this link's href attributes (which contain . ? ! characters). $phraseSearchFrom = $prevCloserEnd; $prevCloserEnd = $closerEnd; $parsedUrl = $this->parseUrl( $href ); if ( empty( $parsedUrl['host'] ) ) { continue; } if ( $this->hasIgnoredExtension( $parsedUrl ) ) { continue; } $urlFields = $this->urlFields( $parsedUrl ); $isVideo = $this->isVideoUrl( $urlFields['url'] ); $phraseHtml = $this->extractPhraseHtml( $postContent, $phraseSearchFrom, $openerStart, $closerEnd ); $phrase = wp_strip_all_tags( $phraseHtml ); $phrase = trim( $phrase ); // An around an image or other markup has no anchor text and often no sentence around it, // but it is a link the reader can click and the scan can report. Only a genuinely empty // is nothing. $wrapsMarkup = '' === $anchor && '' !== trim( $innerHtml ); // Don't continue if the anchor or phrase are empty, e.g. blank link tag. // If it's a video, we don't mandate an anchor or phrase. if ( ( ! $anchor || ! $phrase ) && ! $isVideo && ! $wrapsMarkup ) { continue; } // Only asked for where there is a phrase to find. The paragraph service walks the content per // context key, and a link with no sentence around it - an holding only an image - moved that // walk on without matching anything, which emptied the paragraph of every link after it. $paragraph = '' !== $phrase ? aioseoBrokenLinkChecker()->main->paragraph->get( $this->contextKey(), $postContent, $phrase ) : ''; $paragraphHtml = '' !== $phrase ? aioseoBrokenLinkChecker()->main->paragraph->getHtml( $anchor, $paragraph, $postContent ) : ''; // The text fields carry what the reader sees, so their entities are decoded - but only here, // after the lookups above have matched them against the content as it is stored. $links[] = array_merge( $urlFields, [ 'anchor' => $this->decodeValue( $anchor ), 'phrase' => $this->decodeValue( $phrase ), 'phrase_html' => $phraseHtml, 'paragraph' => $this->decodeValue( $paragraph ), 'paragraph_html' => $paragraphHtml, 'is_video' => $isVideo, 'is_image' => $this->isImageFileUrl( $urlFields['url'] ), 'is_embed' => false ] ); } return $links; } /** * Decodes the HTML entities in a value the report shows as text. * * @since 1.3.1 * * @param string $value The value as it appears in the content. * @return string The decoded value. */ private function decodeValue( $value ) { return aioseoBrokenLinkChecker()->helpers->decodeHtmlEntities( $value ); } /** * Regex-based link extraction for WP < 6.6. * * @since 1.0.0 * @since 1.3.0 Renamed from extractLinks(). * @version 1.3.1 Dropped the $postId parameter; the object is read from the scan context. * * @param string $postContent The preprocessed content. * @return array The links. */ private function extractLinksRegex( $postContent ) { /** * Regex pattern divided into groups: * 0 - Full phrase with link tag. * 2 - Start of the phrase, before the anchor. * 4 - The URL. * 6 - The anchor. * 7 - The oEmbed URL. * 9 - The end of the phrase, after the anchor. * 10 - The ending punctuation mark. */ preg_match_all( '/(([^\r\n.?!]*)]*?href=(\"|\')(?!tel:|mailto:)([^\"\']*?)(\"|\')[^>]*?>([\s\w\W]*?)<\/t?a>||(?:>| |\s)((?:(?:http|ftp|https)\:\/\/)(?:[\w_-]+(?:(?:\.[\w_-]+)+))(?:[\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-]))(?:<| |\s))([^<>.?!\r\n]*)([.?!]?)/i', // phpcs:disable Generic.Files.LineLength.MaxExceeded (string) $postContent, $matches ); if ( empty( $matches[0] ) ) { return []; } $links = []; foreach ( $matches[0] as $k => $v ) { if ( ( empty( $matches[4][ $k ] ) || empty( $matches[6][ $k ] ) ) && // Link tag URL or anchor empty( $matches[7][ $k ] ) // oEmbedded URL ) { continue; } // The attribute is read out of the markup rather than by a parser, so its entities are still // encoded. A block comment's URL is JSON and holds none. $oEmbed = ! empty( $matches[7][ $k ] ) ? true : false; $capturedUrl = $matches[4][ $k ] ? $this->decodeValue( $matches[4][ $k ] ) : $matches[7][ $k ]; $parsedUrl = $this->parseUrl( $capturedUrl ); if ( empty( $parsedUrl['host'] ) ) { continue; } if ( $this->hasIgnoredExtension( $parsedUrl ) ) { continue; } $urlFields = $this->urlFields( $parsedUrl ); $isVideo = $this->isVideoUrl( $urlFields['url'] ); $anchor = wp_strip_all_tags( $matches[6][ $k ] ); // Remove trailing URL tags. The regex isn't sufficient for this. $phrase = wp_strip_all_tags( $matches[0][ $k ] ); $phrase = trim( preg_replace( '/(.*)(].*$)/', '', (string) $phrase ) ?? $phrase ); // As above: an around an image carries no anchor text, and dropping it left the link it // points at unchecked. $wrapsMarkup = '' === $anchor && '' !== trim( (string) $matches[6][ $k ] ); // Don't continue if the anchor or phrase are empty, e.g. blank link tag. // If it's a video, we don't mandate an anchor or phrase. if ( ( ! $anchor || ! $phrase ) && ! $isVideo && ! $wrapsMarkup ) { continue; } $phraseHtml = aioseoBrokenLinkChecker()->helpers->stripIncompleteHtmlTags( $matches[0][ $k ] ); $phraseHtml = aioseoBrokenLinkChecker()->helpers->stripScriptTags( $phraseHtml ); $phraseHtml = aioseoBrokenLinkChecker()->helpers->trimParagraphTags( $phraseHtml ); // oEmbed blocks reduce to an empty phrase once the block comment is stripped, so don't skip videos here. if ( empty( $phraseHtml ) && ! $isVideo ) { continue; } $paragraph = ''; $paragraphHtml = ''; if ( ! $oEmbed ) { // As above: no phrase, no paragraph walk. $paragraph = '' !== $phrase ? aioseoBrokenLinkChecker()->main->paragraph->get( $this->contextKey(), $postContent, $phrase ) : ''; $paragraphHtml = '' !== $phrase ? aioseoBrokenLinkChecker()->main->paragraph->getHtml( $anchor, $paragraph, $postContent ) : ''; } $links[] = array_merge( $urlFields, [ 'anchor' => $this->decodeValue( $anchor ), 'phrase' => $this->decodeValue( $phrase ), 'phrase_html' => $phraseHtml, 'paragraph' => $this->decodeValue( $paragraph ), 'paragraph_html' => $paragraphHtml, 'is_video' => $isVideo, 'is_image' => $this->isImageFileUrl( $urlFields['url'] ), 'is_embed' => false ] ); } return $links; } /** * Checks whether the given URL points to a video based on known provider patterns. * * @since 1.3.0 * * @param string $url The URL to check. * @return bool Whether the URL is a video. */ private function isVideoUrl( $url ) { if ( $this->isVideoFileUrl( $url ) ) { return true; } $videoPatterns = [ '/https?:\/\/((m|www)\.)?youtube\.com\/watch.*/i', '/https?:\/\/((m|www)\.)?youtube\.com\/playlist.*/i', '/https?:\/\/((m|www)\.)?youtube\.com\/shorts\/.*/i', '/https?:\/\/((m|www)\.)?youtube\.com\/live\/.*/i', // What an