Last active
April 6, 2024 01:12
-
-
Save wpmudev-sls/0191ddc6ede7a75d12a9269ecfa26262 to your computer and use it in GitHub Desktop.
[Defender Pro] Admin Bar dashboard link fix for Mask Login (Multisite only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: [Defender Pro] Admin Bar dashboard link fix for Mask Login (Multisite only) | |
* Description: Rewrites the Dashboard URL from the Admin Bar to prevent an undesired behavior under certain circumstances | |
* Author: Anderson Salas @ WPMUDEV | |
* Task: SLS-5856 | |
* Author URI: https://premium.wpmudev.org | |
* License: GPLv2 or later | |
*/ | |
add_action( 'plugins_loaded', function() { | |
if ( ! defined( 'DEFENDER_VERSION' ) ) { | |
return; // Defender is not installed/enabled. | |
} | |
if ( ! is_user_logged_in() ) { | |
return; // User is not logged in. | |
} | |
if ( ! is_multisite() ) { | |
return; // Not a multisite installation. | |
} | |
if ( wp_doing_ajax() || wp_doing_cron() ) { | |
return; | |
} | |
$ml_component = wd_di()->get( \WP_Defender\Component\Mask_Login::class ); | |
$ml_model = wd_di()->get( \WP_Defender\Model\Setting\Mask_Login::class ); | |
if ( ! $ml_model->is_active() ) { | |
return; // Mask login is not enabled. | |
} | |
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; | |
$option_name = 'wd_masking_login_settings'; | |
$mask_login = json_decode( get_site_option( $option_name, '{}' ), true )['mask_url'] ?? false; | |
if( $ml_component->is_land_on_masked_url( $mask_login ) && ( $_REQUEST['action'] ?? '' ) !== 'logout') { | |
wp_safe_redirect( str_ireplace( $mask_login, 'wp-admin/', $current_url ) ); | |
die; | |
} | |
add_action( 'admin_bar_menu', function( $admin_bar ) use ( $mask_login ) { | |
if ( ! ( $admin_bar instanceof WP_Admin_Bar ) ) { | |
return; | |
} | |
if ( empty( $mask_login ) || false === $mask_login ) { | |
return; | |
} | |
$target_ids = [ 'dashboard', 'site-name' ]; | |
foreach( $admin_bar->get_nodes() as $id => $node ) { | |
if ( preg_match( '/blog-(\d+-d|\d+)/m', $id, $m ) || in_array( $id , $target_ids ) ) { | |
if ( false === strpos( $node->href, $mask_login ) ) { | |
continue; | |
} | |
$blog_id = in_array( $id , $target_ids ) | |
? get_current_blog_id() | |
: ( ! empty( $m[1] ) ? intval( $m[1] ) : null ); | |
if ( $blog_id !== get_current_blog_id() ) { | |
continue; | |
} | |
$new_url = str_ireplace( $mask_login, 'wp-admin/', $node->href ); | |
$node->href = $new_url; | |
$admin_bar->add_node( $node ); // Replace the node. | |
} | |
} | |
}, 500 ); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment