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 end and this opener,
// to avoid finding delimiters inside previous links' href attributes
// (e.g. the "." in "alpha.com" would produce a garbled phrase).
$textBefore = substr( $postContent, $phraseSearchFrom, $openerStart - $phraseSearchFrom );
$phraseStart = $phraseSearchFrom;
foreach ( [ '.', '?', '!', "\r", "\n" ] as $delimiter ) {
$pos = strrpos( $textBefore, $delimiter );
if ( false !== $pos ) {
// Start after the delimiter.
$phraseStart = max( $phraseStart, $phraseSearchFrom + $pos + 1 );
}
}
// A delimiter can sit inside markup rather than in the text - the "!" of a block comment, a "."
// in an attribute - and a phrase starting mid-tag is one kses then mangles beyond ever matching.
$untilOpener = substr( $postContent, $phraseStart, $openerStart - $phraseStart );
$tagCloses = strpos( $untilOpener, '>' );
$tagOpens = strpos( $untilOpener, '<' );
if ( false !== $tagCloses && ( false === $tagOpens || $tagCloses < $tagOpens ) ) {
$phraseStart += $tagCloses + 1;
}
// Find sentence boundary after the link.
$textAfter = substr( $postContent, $closerEnd );
$boundaryLen = strcspn( $textAfter, '<>.?!' . "\r\n" );
$phraseEnd = $closerEnd + $boundaryLen;
// Include trailing punctuation if present.
if ( $phraseEnd < strlen( $postContent ) && false !== strpos( '.?!', $postContent[ $phraseEnd ] ) ) {
$phraseEnd++;
}
$phraseHtml = substr( $postContent, $phraseStart, $phraseEnd - $phraseStart );
$phraseHtml = aioseoBrokenLinkChecker()->helpers->stripIncompleteHtmlTags( $phraseHtml );
$phraseHtml = aioseoBrokenLinkChecker()->helpers->stripScriptTags( $phraseHtml );
$phraseHtml = aioseoBrokenLinkChecker()->helpers->trimParagraphTags( $phraseHtml );
return $phraseHtml;
}
/**
* Advances the processor past the closing tag for a filtered link.
*
* Used when a link is skipped (tel:, mailto:, etc.) to keep $prevCloserEnd
* accurate so that subsequent phrase boundary searches don't scan through
* this link's href attributes.
*
* @since 1.3.0
*
* @param BlcHtmlTagProcessor $processor The processor, positioned on an opener.
* @param int $prevCloserEnd The current closer-end byte offset.
* @return int The updated closer-end byte offset.
*/
private function skipPastCloser( $processor, $prevCloserEnd ) {
while ( $processor->next_token() ) {
if ( '#tag' !== $processor->get_token_type() || 'A' !== $processor->get_tag() ) {
continue;
}
// Found a closing — bookmark to get its end offset.
if ( $processor->is_tag_closer() ) {
$processor->set_bookmark( 'blc_skip_closer' );
$start = $processor->getBookmarkStart( 'blc_skip_closer' );
$length = $processor->getBookmarkLength( 'blc_skip_closer' );
$processor->release_bookmark( 'blc_skip_closer' );
if ( null !== $start && null !== $length ) {
return $start + $length;
}
}
// Nested opener or bookmark failure — stop walking.
break;
}
return $prevCloserEnd;
}
/**
* Returns the site's hostname, in the form a resolved URL carries it.
*
* @since 1.0.0
* @version 1.3.1 Canonicalises the host, so it compares with what resolution produces.
*
* @return string The hostname.
*/
private function getHostname() {
static $siteHost = null;
if ( null === $siteHost ) {
$siteUrl = get_site_url();
$parts = Url::parts( $siteUrl, $siteUrl );
$siteHost = isset( $parts['host'] ) ? $parts['host'] : '';
}
return $siteHost;
}
/**
* Returns the parsed URL, resolved against the URL of the object it was written on.
*
* NOTE: Resolution is the browser's {@see \AIOSEO\BrokenLinkChecker\Links\Url::parts()}, which hands
* back the parts it computed rather than a string to parse again. Reading its output back with
* wp_parse_url() undid it: a non-Latin host lost every 0x80-0x9F byte to an underscore.
*
* @since 1.0.0
* @version 1.1.1 Renamed method.
* @version 1.3.0 Added $postId parameter; resolves relative URLs against the post permalink.
* @version 1.3.1 Dropped the $postId parameter; the base URL comes from the scan context.
* @version 1.3.1 Returns {@see \AIOSEO\BrokenLinkChecker\Links\Url::parts()}, including the URL.
*
* @param string $url The URL as it was written.
* @return array The resolved parts, including the URL under `url`.
*/
private function parseUrl( $url ) {
$url = trim( (string) $url );
// A bare fragment addresses the page it is on, so it is not a link the scan has anything to say
// about - and every caller that reads an attribute drops it already.
if ( '' === $url || '#' === $url[0] ) {
return [];
}
$baseUrl = ! empty( $this->context['baseUrl'] ) ? $this->context['baseUrl'] : get_site_url();
return Url::parts( $url, $baseUrl );
}
/**
* Returns the posts to scan.
*
* NOTE: A modification date in the future does not make a post due. WordPress stamps a scheduled
* post's post_modified_gmt with its publish date, so one of those would be due on every tick, the
* queue would never empty, and {@see Links::scanPosts()} only sweeps the other sources once it
* does - which is how a single scheduled post stopped menus, terms, bios, patterns and templates
* from ever being indexed. It becomes due again of its own accord when that date arrives.
*
* @since 1.0.0
* @version 1.3.0 Count distinct post IDs so legacy duplicate rows in aioseo_blc_posts don't inflate the count and stall the scan percentage.
* @version 1.3.1 A modification date in the future no longer makes a post due.
*
* @param bool $countOnly Whether to return only the count.
* @return array|int The posts to scan or a count.
*/
public function getPostsToScan( $countOnly = false ) {
$postsPerScan = apply_filters( 'aioseo_blc_links_posts_per_scan', 50 );
$postTypes = aioseoBrokenLinkChecker()->helpers->getScannablePostTypes();
$postStatuses = aioseoBrokenLinkChecker()->helpers->getPublicPostStatuses( true );
// phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
$minimumLinkScanDate = esc_sql( aioseoBrokenLinkChecker()->scanState->getMinimumLinkScanDate() ?: date( 'Y-m-d H:i:s' ) );
$query = aioseoBrokenLinkChecker()->core->db->start( 'posts as p' )
->leftJoin( 'aioseo_blc_posts as abp', 'p.ID = abp.post_id' )
->whereIn( 'p.post_status', $postStatuses )
->whereIn( 'p.post_type', $postTypes )
->whereRaw( "(
abp.post_id IS NULL OR
( abp.link_scan_date < p.post_modified_gmt AND p.post_modified_gmt <= UTC_TIMESTAMP() ) OR
abp.link_scan_date IS NULL OR
abp.link_scan_date < '$minimumLinkScanDate'
)" );
if ( $countOnly ) {
return $query->count( 'DISTINCT p.ID' );
}
// Only the ID is needed — the scan hydrates each post through get_post().
$postsToScan = $query
->select( 'DISTINCT p.ID' )
->limit( $postsPerScan )
->run()
->result();
return $postsToScan;
}
/**
* Returns the total number of scannable posts.
*
* @since 1.0.0
*
* @return int The total number of scannable posts.
*/
private function getTotalScannablePosts() {
$postTypes = aioseoBrokenLinkChecker()->helpers->getScannablePostTypes();
$postStatuses = aioseoBrokenLinkChecker()->helpers->getPublicPostStatuses( true );
$query = aioseoBrokenLinkChecker()->core->db->start( 'posts as p' )
->whereIn( 'p.post_status', $postStatuses )
->whereIn( 'p.post_type', $postTypes );
return $query->count();
}
/**
* Returns the scan percentage.
*
* @since 1.0.0
*
* @return int The scan percentage.
*/
public function getScanPercentage() {
return $this->getScanProgress()['percent'];
}
/**
* Returns how far the post scan has got, as counts as well as a percentage.
*
* @since 1.3.1
*
* @return array{done: int, total: int, percent: int} How far it has got.
*/
public function getScanProgress() {
$postsToScan = $this->getPostsToScan( true );
$totalScannablePosts = $this->getTotalScannablePosts();
// The other sources are swept from a cursor, so how much of them is left isn't a number we have.
// Holding the bar just short of done is more honest than reporting a finish that hasn't happened.
$objectsPending = aioseoBrokenLinkChecker()->main->objectScan->isPending();
if ( 0 === $postsToScan || 0 === $totalScannablePosts ) {
return [
'done' => $totalScannablePosts,
'total' => $totalScannablePosts,
'percent' => $objectsPending ? 99 : 100
];
}
$percentage = ceil( 100 - ( ( $postsToScan / $totalScannablePosts ) * 100 ) );
return [
'done' => max( 0, $totalScannablePosts - $postsToScan ),
'total' => $totalScannablePosts,
'percent' => $objectsPending ? min( 99, $percentage ) : $percentage
];
}
/**
* Sets the ignored extensions.
*
* NOTE: `com` is not on the list. It is an MS-DOS executable extension, effectively extinct on the
* web, and it collides with the commonest TLD - so `/whois/example.com` and `/go/wordpress.com`
* were never stored, never checked and never counted.
*
* @since 1.0.0
* @version 1.3.1 Dropped `com` from the list.
*
* @return void
*/
private function setIgnoredExtensions() {
$this->ignoredExtensions = apply_filters( 'aioseo_blc_ignored_extensions', [
// Executable files
'apk',
'bat',
'bin',
'cgi',
'exe',
'gadget',
'jar',
'py',
'wsf',
] );
}
}