Initial import of 404 Enhacer
This commit is contained in:
@@ -0,0 +1,411 @@
|
||||
<?php
|
||||
/**
|
||||
* Admin settings page for 404 Enhancer.
|
||||
*
|
||||
* @package 404_Enhancer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the settings page, settings fields, sanitizers and admin assets.
|
||||
*/
|
||||
final class FE_Settings {
|
||||
|
||||
const OPTION_MESSAGE = 'fe_custom_message';
|
||||
const OPTION_IMAGE = 'fe_featured_image_id';
|
||||
const OPTION_POSTTYPES = 'fe_enabled_post_types';
|
||||
const OPTION_FEATURED = 'fe_featured_post_ids';
|
||||
const OPTION_PER_PAGE = 'fe_suggestions_per_page';
|
||||
|
||||
/**
|
||||
* Registers all admin hooks.
|
||||
*/
|
||||
public static function init() {
|
||||
add_action( 'admin_menu', array( __CLASS__, 'add_menu_page' ) );
|
||||
add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
|
||||
add_action( 'wp_ajax_fe_search_posts', array( __CLASS__, 'ajax_search_posts' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the settings page under the Settings menu.
|
||||
*/
|
||||
public static function add_menu_page() {
|
||||
add_options_page(
|
||||
__( '404 Enhancer Settings', '404-enhancer' ),
|
||||
__( '404 Enhancer', '404-enhancer' ),
|
||||
'manage_options',
|
||||
'fe-settings',
|
||||
array( __CLASS__, 'render_settings_page' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers settings, sections and fields with sanitize callbacks.
|
||||
*/
|
||||
public static function register_settings() {
|
||||
register_setting(
|
||||
'fe_settings_group',
|
||||
self::OPTION_MESSAGE,
|
||||
array(
|
||||
'type' => 'string',
|
||||
'sanitize_callback' => 'wp_kses_post',
|
||||
'default' => '',
|
||||
)
|
||||
);
|
||||
register_setting(
|
||||
'fe_settings_group',
|
||||
self::OPTION_IMAGE,
|
||||
array(
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => 'absint',
|
||||
'default' => 0,
|
||||
)
|
||||
);
|
||||
register_setting(
|
||||
'fe_settings_group',
|
||||
self::OPTION_POSTTYPES,
|
||||
array(
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => array( __CLASS__, 'sanitize_post_types' ),
|
||||
'default' => array( 'post' ),
|
||||
)
|
||||
);
|
||||
register_setting(
|
||||
'fe_settings_group',
|
||||
self::OPTION_FEATURED,
|
||||
array(
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => array( __CLASS__, 'sanitize_post_ids' ),
|
||||
'default' => array(),
|
||||
)
|
||||
);
|
||||
register_setting(
|
||||
'fe_settings_group',
|
||||
self::OPTION_PER_PAGE,
|
||||
array(
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => array( __CLASS__, 'sanitize_per_page' ),
|
||||
'default' => 6,
|
||||
)
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'fe_section_display',
|
||||
__( 'Display', '404-enhancer' ),
|
||||
'__return_null',
|
||||
'fe-settings'
|
||||
);
|
||||
add_settings_field(
|
||||
self::OPTION_MESSAGE,
|
||||
__( 'Custom message', '404-enhancer' ),
|
||||
array( __CLASS__, 'field_message' ),
|
||||
'fe-settings',
|
||||
'fe_section_display'
|
||||
);
|
||||
add_settings_field(
|
||||
self::OPTION_IMAGE,
|
||||
__( 'Featured image', '404-enhancer' ),
|
||||
array( __CLASS__, 'field_image' ),
|
||||
'fe-settings',
|
||||
'fe_section_display'
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'fe_section_content',
|
||||
__( 'Content suggestions', '404-enhancer' ),
|
||||
'__return_null',
|
||||
'fe-settings'
|
||||
);
|
||||
add_settings_field(
|
||||
self::OPTION_POSTTYPES,
|
||||
__( 'Post types to suggest', '404-enhancer' ),
|
||||
array( __CLASS__, 'field_post_types' ),
|
||||
'fe-settings',
|
||||
'fe_section_content'
|
||||
);
|
||||
add_settings_field(
|
||||
self::OPTION_FEATURED,
|
||||
__( 'Featured content', '404-enhancer' ),
|
||||
array( __CLASS__, 'field_featured_posts' ),
|
||||
'fe-settings',
|
||||
'fe_section_content'
|
||||
);
|
||||
add_settings_field(
|
||||
self::OPTION_PER_PAGE,
|
||||
__( 'Suggestions per section', '404-enhancer' ),
|
||||
array( __CLASS__, 'field_per_page' ),
|
||||
'fe-settings',
|
||||
'fe_section_content'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the enabled post types list against existing public post types.
|
||||
*
|
||||
* @param mixed $value Raw submitted value.
|
||||
* @return string[] Sanitized post type names.
|
||||
*/
|
||||
public static function sanitize_post_types( $value ) {
|
||||
$value = is_array( $value ) ? $value : array();
|
||||
$valid = get_post_types( array( 'public' => true ), 'names' );
|
||||
$sanitized = array();
|
||||
foreach ( $value as $post_type ) {
|
||||
$post_type = sanitize_key( (string) $post_type );
|
||||
if ( '' !== $post_type && in_array( $post_type, $valid, true ) ) {
|
||||
$sanitized[] = $post_type;
|
||||
}
|
||||
}
|
||||
return array_values( array_unique( $sanitized ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the featured post ID list.
|
||||
*
|
||||
* @param mixed $value Raw submitted value.
|
||||
* @return int[] Attachment/post IDs greater than zero.
|
||||
*/
|
||||
public static function sanitize_post_ids( $value ) {
|
||||
$value = is_array( $value ) ? $value : array();
|
||||
$ids = array_map( 'absint', $value );
|
||||
return array_values( array_unique( array_filter( $ids ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes the per-section suggestion count.
|
||||
*
|
||||
* @param mixed $value Raw submitted value.
|
||||
* @return int Clamped between 1 and 24.
|
||||
*/
|
||||
public static function sanitize_per_page( $value ) {
|
||||
$value = absint( $value );
|
||||
if ( $value < 1 ) {
|
||||
$value = 1;
|
||||
}
|
||||
if ( $value > 24 ) {
|
||||
$value = 24;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues media library and admin script only on the settings page.
|
||||
*
|
||||
* @param string $hook_suffix Current admin page hook.
|
||||
*/
|
||||
public static function enqueue_assets( $hook_suffix ) {
|
||||
if ( 'settings_page_fe-settings' !== $hook_suffix ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_media();
|
||||
wp_enqueue_script(
|
||||
'fe-admin',
|
||||
FE_PLUGIN_URL . 'assets/js/fe-admin.js',
|
||||
array( 'jquery' ),
|
||||
FE_VERSION,
|
||||
true
|
||||
);
|
||||
wp_localize_script(
|
||||
'fe-admin',
|
||||
'FEAdmin',
|
||||
array(
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'nonce' => wp_create_nonce( 'fe_admin_nonce' ),
|
||||
'action' => 'fe_search_posts',
|
||||
'i18n' => array(
|
||||
'chooseImage' => __( 'Select or upload an image', '404-enhancer' ),
|
||||
'useImage' => __( 'Use this image', '404-enhancer' ),
|
||||
'searchPh' => __( 'Search posts to feature…', '404-enhancer' ),
|
||||
'noResults' => __( 'No matching published content.', '404-enhancer' ),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the settings page.
|
||||
*/
|
||||
public static function render_settings_page() {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
|
||||
<form method="post" action="options.php">
|
||||
<?php
|
||||
settings_fields( 'fe_settings_group' );
|
||||
do_settings_sections( 'fe-settings' );
|
||||
submit_button();
|
||||
?>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the custom message editor field.
|
||||
*/
|
||||
public static function field_message() {
|
||||
$message = get_option( self::OPTION_MESSAGE, '' );
|
||||
wp_editor(
|
||||
$message,
|
||||
self::OPTION_MESSAGE,
|
||||
array(
|
||||
'textarea_rows' => 5,
|
||||
'media_buttons' => false,
|
||||
'teeny' => true,
|
||||
)
|
||||
);
|
||||
echo '<p class="description">' . esc_html__( 'Shown near the top of the 404 page, above the search form.', '404-enhancer' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the featured image picker field.
|
||||
*/
|
||||
public static function field_image() {
|
||||
$image_id = absint( get_option( self::OPTION_IMAGE, 0 ) );
|
||||
$image_url = $image_id ? wp_get_attachment_url( $image_id ) : '';
|
||||
?>
|
||||
<img id="fe-featured-preview" src="<?php echo esc_url( $image_url ? $image_url : '' ); ?>" alt="" style="max-width: 300px; display: <?php echo $image_id ? 'block' : 'none'; ?>; margin-bottom: 10px;">
|
||||
<input type="hidden" id="fe_featured_image_id" name="<?php echo esc_attr( self::OPTION_IMAGE ); ?>" value="<?php echo esc_attr( $image_id ); ?>">
|
||||
<button type="button" class="button" id="fe-upload-btn"><?php esc_html_e( 'Choose image', '404-enhancer' ); ?></button>
|
||||
<button type="button" class="button" id="fe-remove-btn" style="display: <?php echo $image_id ? 'inline-block' : 'none'; ?>;"><?php esc_html_e( 'Remove', '404-enhancer' ); ?></button>
|
||||
<p class="description"><?php esc_html_e( 'Optional image shown on the 404 page.', '404-enhancer' ); ?></p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the post type checkbox field.
|
||||
*/
|
||||
public static function field_post_types() {
|
||||
$post_types = get_post_types( array( 'public' => true ), 'objects' );
|
||||
$enabled = self::get_enabled_post_types();
|
||||
// Hidden empty value guarantees the option is submitted even when nothing is checked.
|
||||
echo '<input type="hidden" name="' . esc_attr( self::OPTION_POSTTYPES ) . '[]" value="">';
|
||||
foreach ( $post_types as $pt ) {
|
||||
printf(
|
||||
'<label style="display: block; margin-bottom: 4px;"><input type="checkbox" name="%1$s[]" value="%2$s" %3$s> %4$s</label>',
|
||||
esc_attr( self::OPTION_POSTTYPES ),
|
||||
esc_attr( $pt->name ),
|
||||
checked( in_array( $pt->name, $enabled, true ), true, false ),
|
||||
esc_html( $pt->labels->name )
|
||||
);
|
||||
}
|
||||
echo '<p class="description">' . esc_html__( 'Content from these post types is used for URL-based suggestions and random picks.', '404-enhancer' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the featured content AJAX picker field.
|
||||
*/
|
||||
public static function field_featured_posts() {
|
||||
$featured = self::get_featured_post_ids();
|
||||
// Hidden empty value so the option is submitted when no posts are selected.
|
||||
echo '<input type="hidden" name="' . esc_attr( self::OPTION_FEATURED ) . '[]" value="">';
|
||||
?>
|
||||
<div id="fe-featured-picker">
|
||||
<ul id="fe-featured-list" style="margin: 0 0 8px;">
|
||||
<?php foreach ( $featured as $post_id ) : ?>
|
||||
<?php $post = get_post( $post_id ); ?>
|
||||
<?php if ( $post ) : ?>
|
||||
<li class="fe-chip" data-id="<?php echo esc_attr( $post_id ); ?>">
|
||||
<?php echo esc_html( get_the_title( $post ) ); ?>
|
||||
<?php printf( '<span class="fe-chip-type">%s</span>', esc_html( get_post_type_object( $post->post_type )->labels->singular_name ) ); ?>
|
||||
<input type="hidden" name="<?php echo esc_attr( self::OPTION_FEATURED ); ?>[]" value="<?php echo esc_attr( $post_id ); ?>">
|
||||
<button type="button" class="fe-chip-remove" aria-label="<?php esc_attr_e( 'Remove', '404-enhancer' ); ?>">×</button>
|
||||
</li>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<input type="search" id="fe-post-search" class="regular-text" placeholder="<?php esc_attr_e( 'Search posts to feature…', '404-enhancer' ); ?>" autocomplete="off">
|
||||
<ul id="fe-search-results" style="display: none;"></ul>
|
||||
</div>
|
||||
<p class="description"><?php esc_html_e( 'Hand-picked content shown first on the 404 page, in the order selected.', '404-enhancer' ); ?></p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the suggestions-per-section number field.
|
||||
*/
|
||||
public static function field_per_page() {
|
||||
$value = self::get_per_page();
|
||||
printf(
|
||||
'<input type="number" min="1" max="24" name="%s" value="%d">',
|
||||
esc_attr( self::OPTION_PER_PAGE ),
|
||||
esc_attr( $value )
|
||||
);
|
||||
echo '<p class="description">' . esc_html__( 'How many items each suggestion section on the 404 page shows.', '404-enhancer' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX endpoint returning published posts matching a search string.
|
||||
*/
|
||||
public static function ajax_search_posts() {
|
||||
check_ajax_referer( 'fe_admin_nonce', 'nonce' );
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
|
||||
}
|
||||
$term = isset( $_POST['s'] ) ? sanitize_text_field( wp_unslash( $_POST['s'] ) ) : '';
|
||||
$post_types = self::get_enabled_post_types();
|
||||
if ( empty( $post_types ) ) {
|
||||
$post_types = array( 'post' );
|
||||
}
|
||||
$query = new WP_Query(
|
||||
array(
|
||||
's' => $term,
|
||||
'post_type' => $post_types,
|
||||
'post_status' => 'publish',
|
||||
'posts_per_page' => 10,
|
||||
'orderby' => 'title',
|
||||
'order' => 'ASC',
|
||||
'no_found_rows' => true,
|
||||
)
|
||||
);
|
||||
$results = array();
|
||||
foreach ( $query->posts as $post ) {
|
||||
$results[] = array(
|
||||
'id' => $post->ID,
|
||||
'title' => get_the_title( $post ),
|
||||
'type' => get_post_type_object( $post->post_type )->labels->singular_name,
|
||||
'url' => get_permalink( $post ),
|
||||
);
|
||||
}
|
||||
wp_send_json_success( array( 'posts' => $results ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the enabled post types with a sensible fallback.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_enabled_post_types() {
|
||||
$enabled = get_option( self::OPTION_POSTTYPES, array( 'post' ) );
|
||||
$enabled = is_array( $enabled ) ? $enabled : array( 'post' );
|
||||
if ( empty( $enabled ) ) {
|
||||
$enabled = array( 'post' );
|
||||
}
|
||||
return $enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the featured post IDs.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public static function get_featured_post_ids() {
|
||||
$ids = get_option( self::OPTION_FEATURED, array() );
|
||||
return is_array( $ids ) ? array_map( 'absint', $ids ) : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the suggestions-per-section setting.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function get_per_page() {
|
||||
return self::sanitize_per_page( get_option( self::OPTION_PER_PAGE, 6 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
<?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();
|
||||
}
|
||||
$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,
|
||||
)
|
||||
);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/**
|
||||
* Swaps in the custom 404 template and enqueues its assets.
|
||||
*
|
||||
* @package 404_Enhancer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the front-end 404 template.
|
||||
*/
|
||||
final class FE_Template {
|
||||
|
||||
/**
|
||||
* Registers front-end hooks.
|
||||
*/
|
||||
public static function init() {
|
||||
add_action( 'template_redirect', array( __CLASS__, 'handle_404' ) );
|
||||
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* On 404 requests: send no-cache headers and swap the template.
|
||||
*/
|
||||
public static function handle_404() {
|
||||
if ( ! is_404() ) {
|
||||
return;
|
||||
}
|
||||
nocache_headers();
|
||||
add_filter( 'template_include', array( __CLASS__, 'include_template' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the template path for 404 requests.
|
||||
*
|
||||
* Themes can override the template via the `fe_404_template` filter.
|
||||
*
|
||||
* @param string $template Current template path.
|
||||
* @return string
|
||||
*/
|
||||
public static function include_template( $template ) {
|
||||
$custom = FE_PLUGIN_DIR . 'templates/404.php';
|
||||
/**
|
||||
* Filters the 404 template path.
|
||||
*
|
||||
* @param string $custom Default template inside the plugin.
|
||||
*/
|
||||
return apply_filters( 'fe_404_template', $custom );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues the 404 stylesheet only on 404 pages.
|
||||
*/
|
||||
public static function enqueue_assets() {
|
||||
if ( ! is_404() ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_style(
|
||||
'fe-404',
|
||||
FE_PLUGIN_URL . 'assets/css/fe-404.css',
|
||||
array(),
|
||||
FE_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
/**
|
||||
* Self-hosted plugin updater for a Gitea instance (rudrastyh-style).
|
||||
*
|
||||
* Configuration, in order of precedence:
|
||||
* 1. Constants: FE_GITEA_API_URL, FE_GITEA_OWNER, FE_GITEA_REPO, FE_GITEA_TOKEN.
|
||||
* 2. The `fe_updater_config` filter returning an array with keys
|
||||
* api_url, owner, repo, token.
|
||||
*
|
||||
* The updater is a no-op until api_url/owner/repo are set.
|
||||
*
|
||||
* @package 404_Enhancer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a Gitea repository for releases and injects them into the
|
||||
* WordPress update transients.
|
||||
*/
|
||||
final class FE_Updater {
|
||||
|
||||
const CACHE_KEY = 'fe_gitea_latest_release';
|
||||
const CACHE_TTL = 6 * HOUR_IN_SECONDS;
|
||||
|
||||
/**
|
||||
* Registers update hooks.
|
||||
*/
|
||||
public static function init() {
|
||||
add_filter( 'pre_set_site_transient_update_plugins', array( __CLASS__, 'check_for_updates' ) );
|
||||
add_filter( 'plugins_api', array( __CLASS__, 'plugin_info' ), 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the updater configuration.
|
||||
*
|
||||
* @return array{api_url: string, owner: string, repo: string, token: string}
|
||||
*/
|
||||
private static function config() {
|
||||
$config = array(
|
||||
'api_url' => defined( 'FE_GITEA_API_URL' ) ? (string) FE_GITEA_API_URL : '',
|
||||
'owner' => defined( 'FE_GITEA_OWNER' ) ? (string) FE_GITEA_OWNER : '',
|
||||
'repo' => defined( 'FE_GITEA_REPO' ) ? (string) FE_GITEA_REPO : '',
|
||||
'token' => defined( 'FE_GITEA_TOKEN' ) ? (string) FE_GITEA_TOKEN : '',
|
||||
);
|
||||
/**
|
||||
* Filters the Gitea updater configuration.
|
||||
*
|
||||
* @param array $config Keys: api_url, owner, repo, token.
|
||||
*/
|
||||
return wp_parse_args( apply_filters( 'fe_updater_config', $config ), $config );
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the updater has enough configuration to run.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private static function is_configured() {
|
||||
$config = self::config();
|
||||
return '' !== $config['api_url'] && '' !== $config['owner'] && '' !== $config['repo'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the latest usable release from the Gitea API (cached).
|
||||
*
|
||||
* @return array|null Keys: version, tag, name, body, html_url, package. Null on failure.
|
||||
*/
|
||||
private static function get_latest_release() {
|
||||
if ( ! self::is_configured() ) {
|
||||
return null;
|
||||
}
|
||||
$config = self::config();
|
||||
$cache = get_transient( self::CACHE_KEY );
|
||||
if ( false !== $cache && is_array( $cache ) ) {
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$url = trailingslashit( $config['api_url'] ) . 'repos/' . rawurlencode( $config['owner'] ) . '/' . rawurlencode( $config['repo'] ) . '/releases?limit=30';
|
||||
$args = array(
|
||||
'timeout' => 10,
|
||||
'headers' => array( 'Accept' => 'application/json' ),
|
||||
);
|
||||
if ( '' !== $config['token'] ) {
|
||||
$args['headers']['Authorization'] = 'token ' . $config['token'];
|
||||
}
|
||||
$response = wp_remote_get( $url, $args );
|
||||
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
|
||||
return null;
|
||||
}
|
||||
$releases = json_decode( (string) wp_remote_retrieve_body( $response ), true );
|
||||
if ( ! is_array( $releases ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$api_host = (string) wp_parse_url( $config['api_url'], PHP_URL_HOST );
|
||||
$best = null;
|
||||
foreach ( $releases as $release ) {
|
||||
if ( ! empty( $release['draft'] ) || ! empty( $release['prerelease'] ) ) {
|
||||
continue;
|
||||
}
|
||||
$version = ltrim( (string) ( $release['tag_name'] ?? '' ), 'vV' );
|
||||
if ( '' === $version || ! preg_match( '/^\d+(\.\d+)*/', $version ) ) {
|
||||
continue;
|
||||
}
|
||||
$package = '';
|
||||
if ( ! empty( $release['assets'] ) && is_array( $release['assets'] ) ) {
|
||||
foreach ( $release['assets'] as $asset ) {
|
||||
$name = (string) ( $asset['name'] ?? '' );
|
||||
$link = (string) ( $asset['browser_download_url'] ?? '' );
|
||||
if ( '.zip' === substr( strtolower( $name ), -4 ) && self::same_host( $link, $api_host ) ) {
|
||||
// Prefer an asset named after the plugin slug.
|
||||
if ( FE_SLUG . '.zip' === strtolower( $name ) ) {
|
||||
$package = $link;
|
||||
break;
|
||||
}
|
||||
if ( '' === $package ) {
|
||||
$package = $link;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( '' === $package ) {
|
||||
continue;
|
||||
}
|
||||
$candidate = array(
|
||||
'version' => $version,
|
||||
'tag' => (string) $release['tag_name'],
|
||||
'name' => (string) ( $release['name'] ?: $release['tag_name'] ),
|
||||
'body' => (string) ( $release['body'] ?? '' ),
|
||||
'html_url' => (string) ( $release['html_url'] ?? '' ),
|
||||
'package' => $package,
|
||||
);
|
||||
if ( null === $best || version_compare( $candidate['version'], $best['version'], '>' ) ) {
|
||||
$best = $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if ( null !== $best ) {
|
||||
set_transient( self::CACHE_KEY, $best, self::CACHE_TTL );
|
||||
}
|
||||
return $best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a URL belongs to the configured Gitea host.
|
||||
*
|
||||
* @param string $url Candidate URL.
|
||||
* @param string $api_host Expected host.
|
||||
* @return bool
|
||||
*/
|
||||
private static function same_host( $url, $api_host ) {
|
||||
$host = wp_parse_url( $url, PHP_URL_HOST );
|
||||
return is_string( $host ) && strtolower( $host ) === strtolower( (string) $api_host );
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects the remote version into the update_plugins transient.
|
||||
*
|
||||
* @param object $transient Update transient value.
|
||||
* @return object
|
||||
*/
|
||||
public static function check_for_updates( $transient ) {
|
||||
if ( ! is_object( $transient ) ) {
|
||||
$transient = new stdClass();
|
||||
}
|
||||
$release = self::get_latest_release();
|
||||
if ( null === $release ) {
|
||||
return $transient;
|
||||
}
|
||||
if ( version_compare( $release['version'], FE_VERSION, '>' ) ) {
|
||||
$transient->response[ FE_SLUG ] = (object) array(
|
||||
'slug' => FE_SLUG,
|
||||
'plugin' => plugin_basename( FE_PLUGIN_FILE ),
|
||||
'new_version' => $release['version'],
|
||||
'url' => $release['html_url'],
|
||||
'package' => $release['package'],
|
||||
'tested' => get_bloginfo( 'version' ),
|
||||
);
|
||||
}
|
||||
return $transient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves plugin information for the "View details" modal.
|
||||
*
|
||||
* @param mixed $result Result object or false.
|
||||
* @param string $action plugins_api action.
|
||||
* @param object $args Request args.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function plugin_info( $result, $action, $args ) {
|
||||
if ( 'plugin_information' !== $action || ! isset( $args->slug ) || FE_SLUG !== $args->slug ) {
|
||||
return $result;
|
||||
}
|
||||
$release = self::get_latest_release();
|
||||
if ( null === $release ) {
|
||||
return $result;
|
||||
}
|
||||
return (object) array(
|
||||
'name' => __( '404 Enhancer', '404-enhancer' ),
|
||||
'slug' => FE_SLUG,
|
||||
'version' => $release['version'],
|
||||
'author' => 'Your Name',
|
||||
'homepage' => $release['html_url'],
|
||||
'download_link' => $release['package'],
|
||||
'tested' => get_bloginfo( 'version' ),
|
||||
'sections' => array(
|
||||
'description' => __( 'Enhances the 404 page with a custom message, featured image, hand-picked content, search and URL-based suggestions.', '404-enhancer' ),
|
||||
'changelog' => $release['body'] ? wp_kses_post( nl2br( $release['body'] ) ) : __( 'No changelog provided.', '404-enhancer' ),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user