Files
404-enhancer/includes/class-fe-suggestions.php

315 lines
9.4 KiB
PHP

<?php
/**
* Content suggestion engine for the 404 page.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Derives search terms from the requested URL and builds suggestion queries.
*/
final class FE_Suggestions {
/**
* Common English stopwords excluded from URL tokens.
*
* @var string[]
*/
private static $stopwords = array(
'the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'any', 'can', 'had', 'her', 'was', 'one', 'our', 'out',
'day', 'get', 'has', 'him', 'his', 'how', 'its', 'new', 'now', 'old', 'see', 'way', 'who', 'with', 'www', 'com',
'net', 'org', 'html', 'htm', 'php', 'asp', 'aspx', 'index', 'page',
);
/**
* Returns the raw requested path (no query string), decoded.
*
* @return string
*/
public static function get_requested_path() {
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$path = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
return rawurldecode( $path );
}
/**
* Splits a URL path into meaningful search tokens.
*
* Pure function (no WP calls) so it can be unit tested.
*
* @param string $path URL path, e.g. /blog/my-great-post-2024/.
* @return string[] Tokens, e.g. ['blog', 'great', 'post', '2024'].
*/
public static function tokenize( $path ) {
$path = trim( (string) $path, '/' );
$path = preg_replace( '/\.[a-z0-9]{1,5}$/i', '', $path ); // Strip file extension.
$parts = preg_split( '/[^a-z0-9]+/i', $path, -1, PREG_SPLIT_NO_EMPTY );
if ( ! is_array( $parts ) ) {
return array();
}
$tokens = array();
foreach ( $parts as $part ) {
$part = strtolower( $part );
// Split camelCase and digit boundaries: "post2024" -> "post", "2024".
foreach ( preg_split( '/(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])/i', $part ) as $sub ) {
$sub = strtolower( $sub );
if ( strlen( $sub ) < 3 || in_array( $sub, self::$stopwords, true ) || is_numeric( $sub ) && strlen( $sub ) < 4 ) {
continue;
}
$tokens[] = $sub;
}
}
return array_values( array_unique( $tokens ) );
}
/**
* Builds the human readable search term from URL tokens.
*
* @param string[] $tokens Tokens from tokenize().
* @return string
*/
public static function search_term_from_tokens( array $tokens ) {
return implode( ' ', $tokens );
}
/**
* Returns the last path segment as a slug candidate for "did you mean".
*
* @param string $path URL path.
* @return string
*/
public static function slug_from_path( $path ) {
$path = trim( (string) $path, '/' );
if ( '' === $path ) {
return '';
}
$segments = explode( '/', $path );
$last = (string) end( $segments );
$last = preg_replace( '/\.[a-z0-9]{1,5}$/i', '', $last );
return sanitize_title( $last );
}
/**
* Runs a full-text query for the URL tokens and ranks results by how many
* tokens appear in title/content.
*
* @param string[] $tokens Search tokens.
* @param string[] $post_types Post types to include.
* @param int $count Max results.
* @return WP_Post[] Ranked posts.
*/
public static function get_related( array $tokens, array $post_types, $count ) {
if ( empty( $tokens ) ) {
return array();
}
// WP's default search ANDs the words; for fuzzy URL matching we want OR
// recall, then rank by matched tokens in PHP below.
$or_search = function ( $search, $query ) use ( $tokens ) {
global $wpdb;
if ( ! $query->is_search() ) {
return $search;
}
$likes = array();
foreach ( $tokens as $token ) {
$like = '%' . $wpdb->esc_like( $token ) . '%';
$likes[] = $wpdb->prepare( "($wpdb->posts.post_title LIKE %s OR $wpdb->posts.post_content LIKE %s)", $like, $like );
}
return ' AND (' . implode( ' OR ', $likes ) . ') ';
};
add_filter( 'posts_search', $or_search, 10, 2 );
$query = new WP_Query(
array(
's' => implode( ' ', $tokens ),
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => max( $count * 3, 10 ),
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
remove_filter( 'posts_search', $or_search, 10 );
if ( empty( $query->posts ) ) {
return array();
}
$scored = array();
foreach ( $query->posts as $post ) {
$haystack = strtolower( $post->post_title . ' ' . $post->post_content );
$score = 0;
foreach ( $tokens as $token ) {
if ( false !== strpos( $haystack, $token ) ) {
$score++;
}
}
$scored[] = array( $score, $post );
}
usort(
$scored,
function ( $a, $b ) {
if ( $a[0] === $b[0] ) {
return strcmp( $b[1]->post_date, $a[1]->post_date );
}
return $b[0] - $a[0];
}
);
return array_slice( array_map( function ( $row ) { return $row[1]; }, $scored ), 0, $count );
}
/**
* Finds the published post whose slug is closest to the requested slug.
*
* @param string $requested_slug Slug derived from the URL.
* @param string[] $post_types Post types to consider.
* @return WP_Post|null Closest match, or null when nothing is close enough.
*/
public static function get_did_you_mean( $requested_slug, array $post_types ) {
if ( '' === $requested_slug ) {
return null;
}
/**
* Filters how many recent posts are scanned for slug similarity.
*
* @param int $max_candidates Candidate pool size.
*/
$max_candidates = (int) apply_filters( 'fe_did_you_mean_candidates', 200 );
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => $max_candidates,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
'update_post_term_cache' => false,
'fields' => 'all',
)
);
$best = null;
$best_dist = PHP_INT_MAX;
$threshold = max( 2, (int) ( strlen( $requested_slug ) / 3 ) );
foreach ( $query->posts as $post ) {
if ( strlen( $post->post_name ) > 255 || strlen( $requested_slug ) > 255 ) {
continue;
}
$dist = levenshtein( $requested_slug, $post->post_name );
if ( $dist < $best_dist ) {
$best_dist = $dist;
$best = $post;
}
}
if ( $best && $best_dist <= $threshold ) {
return $best;
}
return null;
}
/**
* Returns posts sharing taxonomy terms with a given post (cross-links).
*
* @param int $post_id Reference post ID.
* @param string[] $post_types Post types to include.
* @param int[] $exclude_ids Post IDs to exclude.
* @param int $count Max results.
* @return WP_Post[]
*/
public static function get_cross_links( $post_id, array $post_types, array $exclude_ids, $count ) {
$taxonomies = get_object_taxonomies( get_post_type( $post_id ), 'names' );
$taxonomies = array_values( array_filter( $taxonomies, 'is_taxonomy_viewable' ) );
if ( empty( $taxonomies ) ) {
return array();
}
$term_ids = array();
foreach ( $taxonomies as $taxonomy ) {
$terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
if ( ! is_wp_error( $terms ) ) {
$term_ids = array_merge( $term_ids, $terms );
}
}
if ( empty( $term_ids ) ) {
return array();
}
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => $count,
'post__not_in' => array_merge( array( $post_id ), $exclude_ids ),
'tax_query' => array(
array(
'taxonomy' => $taxonomies[0],
'field' => 'term_id',
'terms' => $term_ids,
),
),
'no_found_rows' => true,
'update_post_term_cache' => false,
'orderby' => 'date',
'order' => 'DESC',
)
);
return $query->posts;
}
/**
* Returns random published posts of one type using a random offset
* instead of orderby=rand (which sorts the whole table).
*
* @param string $post_type Post type.
* @param int $count Number of posts.
* @return WP_Post[]
*/
public static function get_random( $post_type, $count ) {
$counts = wp_count_posts( $post_type );
$total = isset( $counts->publish ) ? (int) $counts->publish : 0;
if ( $total < 1 ) {
return array();
}
$offset = 0;
if ( $total > $count ) {
$offset = random_int( 0, $total - $count );
}
$query = new WP_Query(
array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => $count,
'offset' => $offset,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
return $query->posts;
}
/**
* Returns the hand-picked featured posts, in the order they were selected.
*
* @param int[] $ids Featured post IDs.
* @param string[] $post_types Allowed post types.
* @return WP_Post[]
*/
public static function get_featured( array $ids, array $post_types ) {
$ids = array_filter( array_map( 'absint', $ids ) );
if ( empty( $ids ) ) {
return array();
}
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'post__in' => $ids,
'orderby' => 'post__in',
'posts_per_page' => count( $ids ),
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
return $query->posts;
}
}