is_enabled( 'frontend_performance', 'emojis' ) ) {
$this->disable_emojis();
}
if ( $this->is_enabled( 'frontend_performance', 'embed' ) ) {
$this->disable_embed();
}
if ( $this->is_enabled( 'frontend_performance', 'heartbeat' ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'disable_heartbeat_outside_editor' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'disable_heartbeat_outside_editor' ) );
}
if ( $this->is_enabled( 'frontend_performance', 'dashicons' ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'disable_dashicons_logged_out' ) );
}
if ( $this->is_enabled( 'frontend_performance', 'block_library' ) ) {
add_action(
'wp_print_styles',
static function () {
wp_dequeue_style( 'wp-block-library' );
},
100
);
}
if ( $this->is_enabled( 'frontend_performance', 'oembed' ) ) {
add_action(
'init',
static function () {
wp_deregister_script( 'wp-embed' );
},
20
);
}
if ( $this->is_enabled( 'frontend_performance', 'dns_prefetch' ) ) {
remove_action( 'wp_head', 'wp_resource_hints', 2 );
}
if ( $this->is_enabled( 'frontend_performance', 'custom_css' ) ) {
add_filter( 'wp_get_custom_css', '__return_empty_string' );
// Priority 20: core registers the 'custom_css' section itself at
// the default priority (10), so removing it must run later.
add_action( 'customize_register', array( $this, 'remove_custom_css_section' ), 20 );
}
// --- HTML Head Cleanup -------------------------------------------.
if ( $this->is_enabled( 'head_cleanup', 'generator' ) ) {
remove_action( 'wp_head', 'wp_generator' );
add_filter( 'the_generator', '__return_empty_string' );
}
if ( $this->is_enabled( 'head_cleanup', 'rsd_link' ) ) {
remove_action( 'wp_head', 'rsd_link' );
}
if ( $this->is_enabled( 'head_cleanup', 'wlw_manifest' ) ) {
remove_action( 'wp_head', 'wlwmanifest_link' );
}
if ( $this->is_enabled( 'head_cleanup', 'shortlink' ) ) {
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10 );
remove_action( 'template_redirect', 'wp_shortlink_header', 11 );
}
if ( $this->is_enabled( 'head_cleanup', 'rss_feeds' ) ) {
$this->disable_rss_feeds();
}
if ( $this->is_enabled( 'head_cleanup', 'adjacent_posts' ) ) {
remove_action( 'wp_head', 'adjacent_posts_rel_link', 10 );
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10 );
}
// Front end only: in wp-admin, nobody outside can fingerprint the
// versions, and without ?ver= browsers keep serving old admin CSS
// and JS after every plugin update.
if ( $this->is_enabled( 'head_cleanup', 'version_strings' ) && ! is_admin() ) {
add_filter( 'style_loader_src', array( $this, 'strip_version_query_arg' ), 9999 );
add_filter( 'script_loader_src', array( $this, 'strip_version_query_arg' ), 9999 );
}
if ( $this->is_enabled( 'head_cleanup', 'capital_p_dangit' ) ) {
remove_filter( 'the_title', 'capital_P_dangit', 11 );
remove_filter( 'the_content', 'capital_P_dangit', 11 );
remove_filter( 'comment_text', 'capital_P_dangit', 31 );
}
// --- Admin Experience ---------------------------------------------.
if ( $this->is_enabled( 'admin_experience', 'remove_howdy' ) ) {
// After core adds the account item (priority 9991 since WP 6.x).
add_action( 'admin_bar_menu', array( $this, 'replace_howdy' ), 9992 );
}
if ( $this->is_enabled( 'admin_experience', 'remove_adminbar_items' ) ) {
add_action( 'admin_bar_menu', array( $this, 'remove_adminbar_clutter' ), 9999 );
}
if ( $this->is_enabled( 'admin_experience', 'screen_options' ) ) {
add_action( 'admin_head', array( $this, 'remove_help_tabs' ) );
add_filter( 'screen_options_show_screen', '__return_false' );
}
// --- Hardening (Settings → Security) ------------------------------.
if ( $this->is_enabled( 'security_access', 'application_passwords' ) ) {
add_filter( 'wp_is_application_passwords_available', '__return_false' );
}
if ( $this->is_enabled( 'security_access', 'core_privacy_tools' ) ) {
$this->disable_core_privacy_tools();
}
if ( $this->is_enabled( 'security_access', 'xmlrpc' ) ) {
$this->block_xmlrpc_request();
add_filter( 'xmlrpc_enabled', '__return_false' );
add_filter( 'pings_open', '__return_false', 9999 );
add_filter( 'wp_headers', array( $this, 'remove_pingback_header' ) );
}
if ( $this->is_enabled( 'security_access', 'rest_api' ) && ! is_admin() ) {
add_filter( 'rest_authentication_errors', array( $this, 'require_rest_authentication' ), 20 );
}
if ( $this->is_enabled( 'security_access', 'site_health' ) ) {
add_action( 'admin_menu', array( $this, 'remove_site_health_menu' ) );
add_action( 'current_screen', array( $this, 'block_site_health_screen' ) );
}
if ( $this->is_enabled( 'security_access', 'block_user_enumeration' ) && ! is_admin() ) {
$this->block_user_enumeration();
}
if ( $this->is_enabled( 'security_access', 'seo_author_sitemaps' ) && ! is_admin() ) {
$this->hide_seo_author_sitemaps();
}
if ( $this->is_enabled( 'security_access', 'plugin_theme_editor' ) && ! defined( 'DISALLOW_FILE_EDIT' ) ) {
define( 'DISALLOW_FILE_EDIT', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- this is WordPress core's own constant (wp-admin checks for it directly), not one this plugin defines for itself.
}
// --- Maintenance -----------------------------------------------------.
if ( $this->is_enabled( 'maintenance', 'core_update_email' ) ) {
add_filter( 'auto_core_update_send_email', '__return_false' );
}
add_action( 'aiou_empty_trash_cron', array( $this, 'run_empty_trash_cleanup' ) );
$this->sync_empty_trash_cron( $this->is_enabled( 'maintenance', 'empty_trash' ) );
$revisions = (string) aiou_get_setting( 'performance', 'maintenance', 'revisions_limit', '' );
if ( '' !== $revisions ) {
add_filter( 'wp_revisions_to_keep', static fn(): int => max( 0, (int) $revisions ), 10 );
}
$heartbeat = (int) aiou_get_setting( 'performance', 'frontend_performance', 'heartbeat_interval', 0 );
if ( $heartbeat ) {
$set_interval = static function () use ( $heartbeat ): void {
self::slow_heartbeat( max( 15, min( 300, $heartbeat ) ) );
};
add_action( 'wp_enqueue_scripts', $set_interval, 100 );
add_action( 'admin_enqueue_scripts', $set_interval, 100 );
}
if ( $this->is_enabled( 'maintenance', 'pdf_thumbnails' ) ) {
add_filter( 'fallback_intermediate_image_sizes', '__return_empty_array' );
}
if ( $this->is_enabled( 'maintenance', 'remote_block_patterns' ) ) {
add_filter( 'should_load_remote_block_patterns', '__return_false' );
}
}
/**
* Disable emoji support (scripts, styles, TinyMCE plugin, feed/email staticizing).
*
* @return void
*/
private function disable_emojis(): void {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'emoji_svg_url', '__return_false' );
add_filter(
'tiny_mce_plugins',
static function ( $plugins ) {
return array_diff( (array) $plugins, array( 'wpemoji' ) );
}
);
}
/**
* Disable oEmbed/embed support: discovery links, the REST route, and
* the rewrite rules that power the ?embed=true view.
*
* @return void
*/
private function disable_embed(): void {
global $wp;
if ( isset( $wp->public_query_vars ) ) {
$wp->public_query_vars = array_diff( $wp->public_query_vars, array( 'embed' ) );
}
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'wp_head', 'wp_oembed_add_host_js' );
remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 );
add_filter( 'embed_oembed_discover', '__return_false' );
add_filter(
'rewrite_rules_array',
static function ( $rules ) {
foreach ( $rules as $rule => $rewrite ) {
if ( str_contains( $rewrite, 'embed=true' ) ) {
unset( $rules[ $rule ] );
}
}
return $rules;
}
);
}
/**
* Remove the Customizer's "Additional CSS" section.
*
* @param \WP_Customize_Manager $wp_customize The Customizer manager instance.
* @return void
*/
public function remove_custom_css_section( \WP_Customize_Manager $wp_customize ): void {
$wp_customize->remove_section( 'custom_css' );
}
/**
* Deregister the Heartbeat script outside the post editor screens.
*
* @return void
*/
public function disable_heartbeat_outside_editor(): void {
global $pagenow;
if ( 'post.php' !== $pagenow && 'post-new.php' !== $pagenow ) {
wp_deregister_script( 'heartbeat' );
}
}
/**
* Make Heartbeat check in every $seconds, and never faster.
*
* This is not done through the `heartbeat_settings` filter: core applies
* it once, when the script registry is first built, and that is often
* before `init` (any plugin that registers a script early triggers it),
* so the filter silently never runs. Instead the value is merged into
* `heartbeatSettings` just before heartbeat.js reads it.
*
* `minimalInterval` matters as much as `interval`: core speeds Heartbeat
* up at runtime (10 seconds on the classic editor for post locks, 5 when
* a connection drops), and minimalInterval is the floor it can't go
* below.
*
* @param int $seconds Interval, 15 to 300.
* @return void
*/
private static function slow_heartbeat( int $seconds ): void {
if ( ! wp_script_is( 'heartbeat', 'registered' ) ) {
return;
}
wp_add_inline_script(
'heartbeat',
sprintf(
'window.heartbeatSettings = Object.assign( window.heartbeatSettings || {}, { interval: %1$d, minimalInterval: %1$d } );',
$seconds
),
'before'
);
}
/**
* Deregister Dashicons for logged-out visitors.
*
* @return void
*/
public function disable_dashicons_logged_out(): void {
if ( ! is_user_logged_in() ) {
wp_dequeue_style( 'dashicons' );
wp_deregister_style( 'dashicons' );
}
}
/**
* Remove the feed links and redirect feed requests to the homepage.
*
* When the dedicated Feeds section (Modules\DisableFeeds) is on, it
* decides what happens to feed requests (redirect or 404, keeping the
* main feeds or not), so the blunt redirect here steps aside; otherwise
* it would override that section's "Keep the main site feeds".
*
* @return void
*/
private function disable_rss_feeds(): void {
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
add_action(
'template_redirect',
static function () {
if ( ! is_feed() || aiou_get_setting( 'performance', 'feeds', 'enabled', 0 ) ) {
return;
}
wp_safe_redirect( home_url( '/' ), 301 );
exit;
},
1
);
}
/**
* Strip the `?ver=` query arg from an enqueued asset URL.
*
* @param string $src Asset URL.
* @return string
*/
public function strip_version_query_arg( string $src ): string {
if ( str_contains( $src, 'ver=' ) ) {
return remove_query_arg( 'ver', $src );
}
return $src;
}
/**
* Replace the "Howdy, {name}" toolbar item with "My Profile".
*
* @param \WP_Admin_Bar $wp_admin_bar The admin bar instance.
* @return void
*/
public function replace_howdy( \WP_Admin_Bar $wp_admin_bar ): void {
$node = $wp_admin_bar->get_node( 'my-account' );
if ( ! $node ) {
return;
}
$meta = (array) $node->meta;
$meta['menu_title'] = __( 'My Profile', 'all-in-one-utilities' );
$wp_admin_bar->add_node(
array(
'id' => 'my-account',
'title' => esc_html__( 'My Profile', 'all-in-one-utilities' ) . get_avatar( get_current_user_id(), 28 ),
'meta' => $meta,
)
);
}
/**
* Remove redundant admin bar items.
*
* @param \WP_Admin_Bar $wp_admin_bar The admin bar instance.
* @return void
*/
public function remove_adminbar_clutter( \WP_Admin_Bar $wp_admin_bar ): void {
$wp_admin_bar->remove_node( 'wp-logo' );
$wp_admin_bar->remove_node( 'new-content' );
$wp_admin_bar->remove_node( 'comments' );
$wp_admin_bar->remove_node( 'updates' );
}
/**
* Remove contextual help tabs from the current screen.
*
* @return void
*/
public function remove_help_tabs(): void {
$screen = get_current_screen();
if ( $screen ) {
$screen->remove_help_tabs();
}
}
/**
* Removes the capabilities behind Tools → Export/Erase Personal Data
* and Settings → Privacy. The Privacy Policy page itself stays set
* (its links on the login page, footer and checkout keep working),
* and core keeps deleting old export files, which hold personal data.
*
* @return void
*/
private function disable_core_privacy_tools(): void {
add_filter( 'map_meta_cap', array( $this, 'deny_privacy_capabilities' ), 10, 2 );
}
/**
* Deny the core privacy tool capabilities.
*
* @param string[] $caps User's capabilities.
* @param string $cap Capability being checked.
* @return string[]
*/
public function deny_privacy_capabilities( array $caps, string $cap ): array {
if ( in_array( $cap, array( 'export_others_personal_data', 'erase_others_personal_data', 'manage_privacy_options' ), true ) ) {
$caps[] = 'do_not_allow';
}
return $caps;
}
/**
* Remove the X-Pingback response header.
*
* @param array $headers Response headers.
* @return array
*/
public function remove_pingback_header( array $headers ): array {
unset( $headers['X-Pingback'] );
return $headers;
}
/**
* Require authentication for REST API requests: visitors who aren't
* logged in get a 401, except on the public routes below. Logged-in
* requests (the block editor, application passwords) pass through;
* core's cookie nonce check still runs after this, at priority 100.
*
* @param \WP_Error|null|true $result Existing authentication result.
* @return \WP_Error|null|true
*/
public function require_rest_authentication( $result ) {
if ( ! empty( $result ) || is_user_logged_in() || self::is_public_rest_route() ) {
return $result;
}
return new \WP_Error(
'rest_not_logged_in',
__( 'The REST API is restricted to logged-in requests on this site.', 'all-in-one-utilities' ),
array( 'status' => 401 )
);
}
/**
* Whether this REST request is for a route that visitors must reach
* for the site to work, e.g. WooCommerce's Store API, which runs the
* cart and checkout blocks for shoppers who aren't logged in.
*
* @return bool
*/
private static function is_public_rest_route(): bool {
$route = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : '';
/**
* Filters the REST route prefixes that stay open to visitors who
* aren't logged in while the REST API is restricted.
*
* @param string[] $prefixes Route prefixes, e.g. '/wc/store/'.
*/
$prefixes = (array) apply_filters( 'aiou_public_rest_routes', array( '/wc/store/' ) );
foreach ( $prefixes as $prefix ) {
if ( '' !== (string) $prefix && str_starts_with( trailingslashit( $route ), (string) $prefix ) ) {
return true;
}
}
return false;
}
/**
* Remove the Site Health submenu.
*
* @return void
*/
public function remove_site_health_menu(): void {
remove_submenu_page( 'tools.php', 'site-health.php' );
}
/**
* Redirect away from the Site Health screen if reached directly.
*
* @return void
*/
public function block_site_health_screen(): void {
$screen = get_current_screen();
if ( $screen && 'site-health' === $screen->id ) {
wp_safe_redirect( admin_url() );
exit;
}
}
/**
* Refuse requests to xmlrpc.php outright. The `xmlrpc_enabled` filter
* alone only switches off methods that need a login; this also stops
* pingbacks and `system.multicall` from being used at all.
*
* @return void
*/
private function block_xmlrpc_request(): void {
if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
return;
}
status_header( 403 );
header( 'Content-Type: text/plain; charset=utf-8' );
echo esc_html__( 'XML-RPC services are disabled on this site.', 'all-in-one-utilities' );
exit;
}
/**
* Make usernames harder to discover: the ?author=N lookup, the REST
* API users list and the users sitemap (for visitors who aren't logged
* in), and login errors that say which part was wrong.
*
* @return void
*/
private function block_user_enumeration(): void {
if ( isset( $_SERVER['QUERY_STRING'] )
&& preg_match( '/(^|&)author=\d+/i', sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) ) ) {
wp_die( esc_html__( 'Forbidden', 'all-in-one-utilities' ), 403 );
}
add_filter(
'redirect_canonical',
static function ( $redirect, $requested ) {
return preg_match( '/\?author=(\d+)/i', $requested ) ? false : $redirect;
},
10,
2
);
add_filter(
'rest_endpoints',
static function ( $endpoints ) {
if ( ! is_user_logged_in() ) {
foreach ( array_keys( (array) $endpoints ) as $route ) {
if ( str_starts_with( (string) $route, '/wp/v2/users' ) ) {
unset( $endpoints[ $route ] );
}
}
}
return $endpoints;
}
);
add_filter(
'wp_sitemaps_add_provider',
static fn( $provider, $name ) => 'users' === $name ? false : $provider,
10,
2
);
add_filter( 'authenticate', array( $this, 'generic_login_error' ), 98 );
}
/**
* Author sitemap file names, relative to the site root: Yoast SEO,
* Rank Math and All in One SEO use author-sitemap.xml (then
* author-sitemap2.xml, ...), SEOPress uses author.xml.
*
* @var string
*/
private const AUTHOR_SITEMAP_PATTERN = '(?:author-sitemap\d*|author)\.xml';
/**
* Hide SEO plugins' author sitemaps: answer them with a 404 and take
* them out of the sitemap index. Runs on `init`, before any SEO
* plugin serves its sitemap.
*
* @return void
*/
private function hide_seo_author_sitemaps(): void {
// Yoast SEO leaves the author sitemap out of its index when no users are left.
add_filter( 'wpseo_sitemap_exclude_author', '__return_empty_array' );
$path = self::request_path();
// Yoast SEO and Rank Math without pretty permalinks: ?sitemap=author.
$query_type = isset( $_GET['sitemap'] ) ? sanitize_key( wp_unslash( $_GET['sitemap'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only routing check.
if ( preg_match( '#^' . self::AUTHOR_SITEMAP_PATTERN . '$#i', $path ) || 'author' === $query_type ) {
status_header( 404 );
nocache_headers();
header( 'Content-Type: text/plain; charset=utf-8' );
echo esc_html__( 'Not Found', 'all-in-one-utilities' );
exit;
}
// The other plugins have no shared filter, and an index cached
// before this was switched on still lists the author sitemap, so
// strip the entry from the index output itself.
if ( preg_match( '#^(?:sitemap_index|sitemap|sitemaps)\.xml$#i', $path ) ) {
ob_start(
static fn( string $xml ): string => (string) preg_replace(
'#\s*[^<]*/' . self::AUTHOR_SITEMAP_PATTERN . '.*?\s*#is',
'',
$xml
)
);
}
}
/**
* The requested path relative to the site root, without slashes or
* a query string, e.g. "author-sitemap.xml".
*
* @return string
*/
private static function request_path(): string {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$path = (string) wp_parse_url( $uri, PHP_URL_PATH );
$home = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH );
if ( '' !== $home && str_starts_with( $path, $home ) ) {
$path = substr( $path, strlen( $home ) );
}
return trim( $path, '/' );
}
/**
* Replace "unknown username" / "wrong password for user X" login
* errors with one message that doesn't say which part was wrong.
*
* @param \WP_User|\WP_Error|null $user Result so far.
* @return \WP_User|\WP_Error|null
*/
public function generic_login_error( $user ) {
if ( ! $user instanceof \WP_Error || ! array_intersect( $user->get_error_codes(), array( 'invalid_username', 'invalid_email', 'incorrect_password' ) ) ) {
return $user;
}
return new \WP_Error(
'incorrect_password',
sprintf(
/* translators: %s: lost password URL */
__( 'Error: The username, email address, or password is incorrect. Lost your password?', 'all-in-one-utilities' ),
esc_url( wp_lostpassword_url() )
)
);
}
/**
* Number of days after which trashed posts are permanently deleted when
* the "Empty Trash Sooner" toggle is on.
*
* @var int
*/
private const EMPTY_TRASH_AFTER_DAYS = 7;
/**
* Cron hook used to permanently delete old trashed posts.
*
* @var string
*/
private const EMPTY_TRASH_CRON_HOOK = 'aiou_empty_trash_cron';
/**
* Schedule or unschedule the empty-trash cron to match the toggle.
*
* WordPress core defines the `EMPTY_TRASH_DAYS` constant itself (with
* its own default of 30) while loading `wp-settings.php`, long before
* any plugin code runs -- by the time even the earliest plugin hook
* fires, `defined( 'EMPTY_TRASH_DAYS' )` is already true, so a plugin
* attempting to define it via a normal action hook has no effect
* whatsoever (confirmed: this is exactly what v1 did, and it never
* worked). A WP-Cron job that directly deletes old trashed posts,
* independent of that constant, is the only way a plugin can actually
* deliver on "empty trash sooner" after the fact.
*
* @param bool $enabled Whether the toggle is on.
* @return void
*/
private function sync_empty_trash_cron( bool $enabled ): void {
$scheduled = wp_next_scheduled( self::EMPTY_TRASH_CRON_HOOK );
if ( $enabled && ! $scheduled ) {
wp_schedule_event( time(), 'daily', self::EMPTY_TRASH_CRON_HOOK );
} elseif ( ! $enabled && $scheduled ) {
wp_clear_scheduled_hook( self::EMPTY_TRASH_CRON_HOOK );
}
}
/**
* Permanently delete trashed posts older than the configured window.
*
* @return void
*/
public function run_empty_trash_cleanup(): void {
$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( self::EMPTY_TRASH_AFTER_DAYS * DAY_IN_SECONDS ) );
$old_trashed_posts = get_posts(
array(
'post_type' => 'any',
'post_status' => 'trash',
// phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_posts_per_page -- deliberate batch cap for a daily cron job, not a page of results; a site with more than 200 old trashed posts simply finishes over several days rather than risking one slow cron run.
'posts_per_page' => 200,
'fields' => 'ids',
'date_query' => array(
array(
'column' => 'post_modified_gmt',
'before' => $cutoff,
),
),
)
);
foreach ( $old_trashed_posts as $post_id ) {
wp_delete_post( $post_id, true );
}
}
}