false,
'phase' => 'idle',
'cursor' => 0,
'posts' => 0,
'checked' => 0,
'force' => false,
'started' => 0,
'finished' => 0,
)
);
}
/* ------------------------------ collecting ------------------------------ */
/**
* Links in a piece of HTML.
*
* @return array url => anchor text
*/
public static function extract( $html ) {
$out = array();
if ( preg_match_all( '#]*?href\s*=\s*(["\'])(.*?)\1[^>]*>(.*?)#is', (string) $html, $m, PREG_SET_ORDER ) ) {
foreach ( $m as $a ) {
$url = self::normalize( $a[2] );
if ( '' !== $url && ! isset( $out[ $url ] ) ) {
$out[ $url ] = Softvolt_Ai_Bodyguard_Helpers::trim_text( trim( wp_strip_all_tags( $a[3] ) ), 80 );
}
}
}
if ( Softvolt_Ai_Bodyguard_Modules::get( 'links_images' ) && preg_match_all( '#
]*?src\s*=\s*(["\'])(.*?)\1#is', (string) $html, $m, PREG_SET_ORDER ) ) {
foreach ( $m as $img ) {
$url = self::normalize( $img[2] );
if ( '' !== $url && ! isset( $out[ $url ] ) ) {
$out[ $url ] = __( '(image)', 'ai-guardwall' );
}
}
}
return $out;
}
/**
* An absolute http(s) address without its #fragment, or '' for anything not worth checking.
*/
public static function normalize( $url ) {
$url = trim( html_entity_decode( (string) $url, ENT_QUOTES, 'UTF-8' ) );
if ( '' === $url || '#' === $url[0] || preg_match( '#^(mailto|tel|sms|javascript|data|skype|whatsapp|callto|fax|ftp|file):#i', $url ) || false !== strpos( $url, '{' ) || false !== strpos( $url, '[' ) ) {
return '';
}
$hash = strpos( $url, '#' );
if ( false !== $hash ) {
$url = substr( $url, 0, $hash );
}
if ( 0 === strpos( $url, '//' ) ) {
$url = ( is_ssl() ? 'https:' : 'http:' ) . $url;
} elseif ( '/' === $url[0] ) {
// Root-relative: relative to the host, not to the WordPress folder.
$parts = wp_parse_url( home_url() );
$url = $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ) . $url;
} elseif ( ! preg_match( '#^https?://#i', $url ) ) {
return '';
}
return strlen( $url ) > 2000 ? '' : $url;
}
private static function source_entry( $post, $text ) {
return array(
'p' => (int) $post->ID,
't' => (string) $text,
);
}
/**
* Record the links of one post.
*/
public static function collect_post( $post ) {
global $wpdb;
$post = get_post( $post );
if ( ! $post ) {
return 0;
}
$links = self::extract( $post->post_content );
$table = self::table();
$now = current_time( 'mysql', true );
foreach ( $links as $url => $text ) {
$hash = md5( $url );
$row = $wpdb->get_row( $wpdb->prepare( "SELECT id, sources FROM %i WHERE url_hash = %s", $table, $hash ), ARRAY_A );
if ( $row ) {
$sources = json_decode( (string) $row['sources'], true );
$sources = is_array( $sources ) ? $sources : array();
$found = false;
foreach ( $sources as $s ) {
if ( (int) $s['p'] === (int) $post->ID ) {
$found = true;
break;
}
}
if ( ! $found && count( $sources ) < 50 ) {
$sources[] = self::source_entry( $post, $text );
}
$wpdb->update( $table, array( 'sources' => wp_json_encode( $sources ), 'seen' => 1 ), array( 'id' => (int) $row['id'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
} else {
$wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$table,
array(
'url_hash' => $hash,
'url' => $url,
'state' => 'pending',
'sources' => wp_json_encode( array( self::source_entry( $post, $text ) ) ),
'seen' => 1,
'created_at' => $now,
)
);
}
}
return count( $links );
}
/**
* Forget which links a post had (before it is collected again, or when it is deleted).
*/
private static function drop_post( $post_id ) {
global $wpdb;
$table = self::table();
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, sources FROM %i WHERE sources LIKE %s", $table, '%"p":' . (int) $post_id . ',%' ), ARRAY_A );
foreach ( (array) $rows as $row ) {
$sources = json_decode( (string) $row['sources'], true );
$sources = array_values(
array_filter(
is_array( $sources ) ? $sources : array(),
function ( $s ) use ( $post_id ) {
return (int) $s['p'] !== (int) $post_id;
}
)
);
if ( $sources ) {
$wpdb->update( $table, array( 'sources' => wp_json_encode( $sources ) ), array( 'id' => (int) $row['id'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
} else {
$wpdb->delete( $table, array( 'id' => (int) $row['id'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
}
}
}
public static function on_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) || ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! in_array( $post->post_type, self::types(), true ) ) {
return;
}
self::drop_post( $post_id );
if ( 'publish' === $post->post_status ) {
self::collect_post( $post );
if ( ! wp_next_scheduled( self::TICK ) ) {
wp_schedule_single_event( time() + 60, self::TICK );
}
}
}
/* ------------------------------ checking ------------------------------ */
/**
* Check one address.
*
* @return array state (ok|redirect|warning|broken), status, error, redirect_to
*/
public static function check_url( $url ) {
$internal = self::check_internal( $url );
if ( $internal ) {
return $internal;
}
$args = array(
'timeout' => 12,
'redirection' => 5,
'user-agent' => 'Mozilla/5.0 (compatible; AI-GuardWall-LinkChecker/' . SOFTVOLT_AI_BODYGUARD_VERSION . '; +' . home_url() . ')',
'headers' => array( 'Accept' => 'text/html,application/xhtml+xml,*/*;q=0.8' ),
);
$res = wp_remote_head( $url, $args );
$code = is_wp_error( $res ) ? 0 : (int) wp_remote_retrieve_response_code( $res );
if ( is_wp_error( $res ) || in_array( $code, array( 0, 400, 403, 404, 405, 406, 429, 500, 501, 503 ), true ) ) {
// Many servers answer HEAD badly; ask for the page itself before deciding.
$res = wp_remote_get( $url, array_merge( $args, array( 'limit_response_size' => 16384 ) ) );
$code = is_wp_error( $res ) ? 0 : (int) wp_remote_retrieve_response_code( $res );
}
if ( is_wp_error( $res ) ) {
$msg = $res->get_error_message();
$state = preg_match( '/timed out|timeout|SSL|certificate/i', $msg ) ? 'warning' : 'broken';
return array( 'state' => $state, 'status' => 0, 'error' => Softvolt_Ai_Bodyguard_Helpers::trim_text( $msg, 250 ), 'redirect_to' => '' );
}
$final = '';
if ( isset( $res['http_response'] ) && is_object( $res['http_response'] ) && method_exists( $res['http_response'], 'get_response_object' ) ) {
$obj = $res['http_response']->get_response_object();
$final = isset( $obj->url ) ? (string) $obj->url : '';
}
$redirected = '' !== $final && untrailingslashit( $final ) !== untrailingslashit( $url );
if ( $code >= 200 && $code < 400 ) {
return array( 'state' => $redirected ? 'redirect' : 'ok', 'status' => $code, 'error' => '', 'redirect_to' => $redirected ? $final : '' );
}
$state = in_array( $code, array( 401, 403, 405, 406, 429, 999 ), true ) ? 'warning' : 'broken';
return array( 'state' => $state, 'status' => $code, 'error' => get_status_header_desc( $code ), 'redirect_to' => $redirected ? $final : '' );
}
/**
* Links to this site: answered from the database or the disk when possible.
*/
private static function check_internal( $url ) {
$host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) );
if ( $host !== strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ) ) {
return null;
}
$uploads = wp_upload_dir( null, false );
$base = set_url_scheme( $uploads['baseurl'], 'http' );
$plain = set_url_scheme( strtok( $url, '?' ), 'http' );
if ( 0 === strpos( $plain, $base . '/' ) ) {
$file = $uploads['basedir'] . '/' . rawurldecode( substr( $plain, strlen( $base ) + 1 ) );
return file_exists( $file )
? array( 'state' => 'ok', 'status' => 200, 'error' => '', 'redirect_to' => '' )
: array( 'state' => 'broken', 'status' => 404, 'error' => __( 'The file is not in the uploads folder.', 'ai-guardwall' ), 'redirect_to' => '' );
}
$path = (string) wp_parse_url( $url, PHP_URL_PATH );
if ( '' === trim( $path, '/' ) || untrailingslashit( $plain ) === untrailingslashit( set_url_scheme( home_url(), 'http' ) ) ) {
return array( 'state' => 'ok', 'status' => 200, 'error' => '', 'redirect_to' => '' );
}
$id = url_to_postid( $url );
if ( ! $id && class_exists( 'Softvolt_Ai_Bodyguard_Permalinks' ) && Softvolt_Ai_Bodyguard_Modules::enabled( 'permalinks' ) ) {
$map = Softvolt_Ai_Bodyguard_Permalinks::map();
$key = strtolower( trim( $path, '/' ) );
$id = isset( $map[ $key ] ) ? (int) $map[ $key ] : 0;
}
if ( $id ) {
$status = get_post_status( $id );
return 'publish' === $status
? array( 'state' => 'ok', 'status' => 200, 'error' => '', 'redirect_to' => '' )
: array( 'state' => 'broken', 'status' => 404, 'error' => sprintf( /* translators: %s: post status. */ __( 'The linked item is not published (%s).', 'ai-guardwall' ), $status ), 'redirect_to' => '' );
}
return null; // Archives, custom routes: ask over HTTP.
}
private static function save_result( $id, $result ) {
global $wpdb;
$wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
self::table(),
array(
'state' => $result['state'],
'status' => (int) $result['status'],
'error' => substr( (string) $result['error'], 0, 255 ),
'redirect_to' => (string) $result['redirect_to'],
'checked_at' => current_time( 'mysql', true ),
),
array( 'id' => (int) $id )
);
}
/* ------------------------------ the run ------------------------------ */
public static function start( $force = true ) {
global $wpdb;
Softvolt_Ai_Bodyguard_Db::install_if_missing( 'links' );
$table = self::table();
$wpdb->query( $wpdb->prepare( "UPDATE %i SET seen = 0, sources = '[]'", $table ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$state = array(
'running' => true,
'phase' => 'collect',
'cursor' => 0,
'posts' => 0,
'checked' => 0,
'force' => (bool) $force,
'started' => time(),
'finished' => self::state()['finished'],
);
update_option( self::STATE, $state, false );
return self::progress();
}
/**
* Work for up to $budget seconds.
*/
public static function step( $budget = 15 ) {
global $wpdb;
$state = self::state();
if ( ! $state['running'] ) {
return self::progress();
}
Softvolt_Ai_Bodyguard_Helpers::raise_limits( $budget + 30 );
$start = microtime( true );
$table = self::table();
$types = self::types();
while ( microtime( true ) - $start < $budget ) {
if ( 'collect' === $state['phase'] ) {
if ( ! $types ) {
$state['phase'] = 'check';
continue;
}
$in = implode( ',', array_fill( 0, count( $types ), '%s' ) );
$posts = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ID > %d AND post_status = 'publish' AND post_type IN ({$in}) ORDER BY ID ASC LIMIT 40", array_merge( array( (int) $state['cursor'] ), $types ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! $posts ) {
$wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE seen = 0", $table ) );
$state['phase'] = 'check';
continue;
}
foreach ( $posts as $p ) {
self::collect_post( (int) $p->ID );
$state['cursor'] = (int) $p->ID;
$state['posts']++;
}
continue;
}
// Check: never checked, due again, or (forced run) not checked since the run started.
$due = gmdate( 'Y-m-d H:i:s', time() - (int) Softvolt_Ai_Bodyguard_Modules::get( 'links_recheck' ) * DAY_IN_SECONDS );
$from = gmdate( 'Y-m-d H:i:s', (int) $state['started'] );
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, url FROM %i WHERE ignored = 0 AND ( checked_at IS NULL OR checked_at < %s ) ORDER BY checked_at IS NULL DESC, checked_at ASC LIMIT 5", $table, $state['force'] ? $from : $due ), ARRAY_A );
if ( ! $rows ) {
$state['running'] = false;
$state['phase'] = 'done';
$state['finished'] = time();
break;
}
foreach ( $rows as $row ) {
self::save_result( $row['id'], self::check_url( $row['url'] ) );
$state['checked']++;
if ( microtime( true ) - $start >= $budget ) {
break;
}
}
}
update_option( self::STATE, $state, false );
if ( 'done' === $state['phase'] && ! $state['running'] ) {
$broken = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE state = 'broken' AND ignored = 0", $table ) );
Softvolt_Ai_Bodyguard_Logger::log( $broken ? 'warning' : 'info', 'links_checked', sprintf( /* translators: 1: links checked, 2: broken links. */ __( 'Link check finished: %1$d checked, %2$d broken.', 'ai-guardwall' ), (int) $state['checked'], $broken ) );
}
return self::progress();
}
public static function progress() {
global $wpdb;
$state = self::state();
$table = self::table();
$counts = array( 'total' => 0, 'ok' => 0, 'redirect' => 0, 'warning' => 0, 'broken' => 0, 'pending' => 0, 'ignored' => 0 );
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT state, ignored, COUNT(*) AS n FROM %i GROUP BY state, ignored", $table ), ARRAY_A ) as $r ) {
$counts['total'] += (int) $r['n'];
if ( (int) $r['ignored'] ) {
$counts['ignored'] += (int) $r['n'];
} elseif ( isset( $counts[ $r['state'] ] ) ) {
$counts[ $r['state'] ] += (int) $r['n'];
}
}
}
$done = $counts['total'] - $counts['pending'];
$percent = 'collect' === $state['phase'] ? 5 : ( $counts['total'] ? (int) floor( 100 * $done / max( 1, $counts['total'] ) ) : 100 );
return array(
'running' => (bool) $state['running'],
'phase' => $state['phase'],
'posts' => (int) $state['posts'],
'checked' => (int) $state['checked'],
'counts' => $counts,
'percent' => $state['running'] ? min( 99, $percent ) : 100,
'finished_h' => $state['finished'] ? human_time_diff( (int) $state['finished'] ) : '',
);
}
public static function cron() {
$state = self::state();
if ( ! $state['running'] ) {
self::start( false );
}
self::tick();
}
public static function tick() {
// Short steps in the background, so a host with few PHP workers keeps serving visitors.
$progress = self::step( 8 );
if ( $progress['running'] && ! wp_next_scheduled( self::TICK ) ) {
wp_schedule_single_event( time() + 60, self::TICK );
}
}
/* ------------------------------ results and actions ------------------------------ */
/**
* Rows for the Broken links tab.
*
* @param array $args state (broken|warning|redirect|ok|pending|ignored|all), search, page.
*/
public static function rows( $args ) {
global $wpdb;
$table = self::table();
$where = array( '1=1' );
$vals = array();
$state = isset( $args['state'] ) ? sanitize_key( $args['state'] ) : 'broken';
if ( 'ignored' === $state ) {
$where[] = 'ignored = 1';
} elseif ( 'all' !== $state ) {
$where[] = 'ignored = 0 AND state = %s';
$vals[] = $state;
}
if ( ! empty( $args['search'] ) ) {
$where[] = 'url LIKE %s';
$vals[] = '%' . $wpdb->esc_like( (string) $args['search'] ) . '%';
}
$per = 50;
$page = max( 1, isset( $args['page'] ) ? (int) $args['page'] : 1 );
$sql_w = implode( ' AND ', $where );
$count = $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE {$sql_w}", array_merge( array( $table ), $vals ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- The interpolated part holds fixed column names and placeholders only; every value goes through prepare().
$list = $wpdb->prepare( "SELECT * FROM %i WHERE {$sql_w} ORDER BY FIELD(state,'broken','warning','pending','redirect','ok'), checked_at DESC LIMIT %d, %d", array_merge( array( $table ), $vals, array( ( $page - 1 ) * $per, $per ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- The interpolated part holds fixed column names and placeholders only; every value goes through prepare().
$total = (int) $wpdb->get_var( $count ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$rows = array();
foreach ( (array) $wpdb->get_results( $list, ARRAY_A ) as $r ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$rows[] = self::format_row( $r );
}
return array( 'rows' => $rows, 'total' => $total, 'page' => $page, 'pages' => (int) ceil( $total / $per ), 'progress' => self::progress() );
}
private static function format_row( $r ) {
$sources = json_decode( (string) $r['sources'], true );
$out = array();
foreach ( is_array( $sources ) ? $sources : array() as $s ) {
$post = get_post( (int) $s['p'] );
if ( ! $post ) {
continue;
}
$out[] = array(
'id' => (int) $post->ID,
'title' => '' !== get_the_title( $post ) ? get_the_title( $post ) : '#' . $post->ID,
'text' => (string) $s['t'],
'edit' => (string) get_edit_post_link( $post->ID, 'raw' ),
'view' => (string) get_permalink( $post ),
'builder' => 'builder' === get_post_meta( $post->ID, '_elementor_edit_mode', true ),
);
}
return array(
'id' => (int) $r['id'],
'url' => $r['url'],
'state' => $r['state'],
'status' => (int) $r['status'],
'error' => (string) $r['error'],
'redirect_to' => (string) $r['redirect_to'],
'checked_h' => $r['checked_at'] ? human_time_diff( strtotime( $r['checked_at'] . ' UTC' ) ) : '',
'ignored' => (bool) $r['ignored'],
'sources' => $out,
);
}
private static function get_row( $id ) {
global $wpdb;
$table = self::table();
return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d", $table, (int) $id ), ARRAY_A );
}
/**
* unlink, replace, ignore, unignore, recheck.
*/
public static function action( $id, $action, $new_url = '' ) {
global $wpdb;
$row = self::get_row( $id );
if ( ! $row ) {
return new WP_Error( 'svabg_links', __( 'That link is no longer in the list. Check the links again.', 'ai-guardwall' ) );
}
$table = self::table();
switch ( $action ) {
case 'ignore':
case 'unignore':
$wpdb->update( $table, array( 'ignored' => 'ignore' === $action ? 1 : 0 ), array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
return array( 'message' => 'ignore' === $action ? __( 'Ignored: it will not be reported again.', 'ai-guardwall' ) : __( 'Reported again.', 'ai-guardwall' ), 'row' => self::format_row( self::get_row( $id ) ) );
case 'recheck':
self::save_result( $id, self::check_url( $row['url'] ) );
return array( 'message' => __( 'Checked again.', 'ai-guardwall' ), 'row' => self::format_row( self::get_row( $id ) ) );
case 'unlink':
case 'replace':
if ( 'replace' === $action ) {
$new_url = esc_url_raw( trim( (string) $new_url ) );
if ( '' === $new_url ) {
return new WP_Error( 'svabg_links', __( 'Enter the new address.', 'ai-guardwall' ) );
}
}
$sources = json_decode( (string) $row['sources'], true );
$changed = 0;
$skipped = array();
foreach ( is_array( $sources ) ? $sources : array() as $s ) {
$post = get_post( (int) $s['p'] );
if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
continue;
}
if ( 'builder' === get_post_meta( $post->ID, '_elementor_edit_mode', true ) ) {
$skipped[] = get_the_title( $post );
continue;
}
$content = self::rewrite( $post->post_content, $row['url'], 'replace' === $action ? $new_url : null );
if ( $content !== $post->post_content ) {
$kses = current_user_can( 'unfiltered_html' );
if ( $kses ) {
kses_remove_filters();
}
wp_update_post( wp_slash( array( 'ID' => $post->ID, 'post_content' => $content ) ) );
if ( $kses ) {
kses_init_filters();
}
$changed++;
}
}
if ( ! $skipped ) {
$wpdb->delete( $table, array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
}
Softvolt_Ai_Bodyguard_Logger::log( 'info', 'link_' . $action, sprintf( 'unlink' === $action ? /* translators: 1: address, 2: number of posts. */ __( 'Link removed: %1$s (%2$d posts)', 'ai-guardwall' ) : /* translators: 1: address, 2: number of posts. */ __( 'Link replaced: %1$s (%2$d posts)', 'ai-guardwall' ), $row['url'], $changed ) );
$msg = sprintf( _n( '%d post updated (a revision keeps the old version).', '%d posts updated (revisions keep the old versions).', $changed, 'ai-guardwall' ), $changed );
if ( $skipped ) {
$msg .= ' ' . sprintf( /* translators: %s: titles. */ __( 'Built with a page builder, edit by hand: %s', 'ai-guardwall' ), implode( ', ', $skipped ) );
}
if ( ! wp_next_scheduled( self::TICK ) ) {
wp_schedule_single_event( time() + 60, self::TICK );
}
return array( 'message' => $msg, 'removed' => ! $skipped );
}
return new WP_Error( 'svabg_links', __( 'Unknown action.', 'ai-guardwall' ) );
}
/**
* Remove the links to $url from HTML (keeping their text), or point them at $new.
*/
public static function rewrite( $html, $url, $new = null ) {
$out = preg_replace_callback(
'#]*?)href\s*=\s*(["\'])(.*?)\2([^>]*)>(.*?)#is',
function ( $m ) use ( $url, $new ) {
if ( Softvolt_Ai_Bodyguard_Link_Checker::normalize( $m[3] ) !== $url ) {
return $m[0];
}
if ( null === $new ) {
return $m[5];
}
return '' . $m[5] . '';
},
(string) $html
);
if ( null !== $new && Softvolt_Ai_Bodyguard_Modules::get( 'links_images' ) ) {
$out = preg_replace_callback(
'#(
]*?src\s*=\s*)(["\'])(.*?)\2#is',
function ( $m ) use ( $url, $new ) {
return Softvolt_Ai_Bodyguard_Link_Checker::normalize( $m[3] ) === $url ? $m[1] . $m[2] . esc_attr( $new ) . $m[2] : $m[0];
},
$out
);
}
return null === $out ? (string) $html : $out;
}
}