array(), 'block_admin_roles' => array(), 'block_admin_to' => '', 'dashboard_hide' => array(), 'hide_nags' => 0, ); } public static function get() { $saved = get_option( self::OPTION, array() ); return array_merge( self::defaults(), is_array( $saved ) ? $saved : array() ); } public static function dashboard_boxes() { return array( 'welcome' => __( 'Welcome panel', 'ai-guardwall' ), 'dashboard_right_now' => __( 'At a glance', 'ai-guardwall' ), 'dashboard_activity' => __( 'Activity', 'ai-guardwall' ), 'dashboard_quick_press' => __( 'Quick draft', 'ai-guardwall' ), 'dashboard_primary' => __( 'WordPress events and news', 'ai-guardwall' ), 'dashboard_site_health' => __( 'Site health status', 'ai-guardwall' ), ); } /** * Roles that may be kept out of something (never the ones that run the site). * * @return array slug => name */ public static function limitable_roles() { $out = array(); foreach ( wp_roles()->roles as $slug => $role ) { if ( ! empty( $role['capabilities']['manage_options'] ) ) { continue; } $out[ $slug ] = translate_user_role( $role['name'] ); } return $out; } public static function save( array $in ) { $s = self::get(); $roles = array_keys( self::limitable_roles() ); foreach ( $in as $key => $value ) { switch ( $key ) { case 'admin_bar_roles': case 'block_admin_roles': $s[ $key ] = array_values( array_intersect( array_map( 'sanitize_key', (array) $value ), $roles ) ); break; case 'block_admin_to': $value = trim( (string) $value ); $s[ $key ] = '' === $value ? '' : esc_url_raw( 0 === strpos( $value, '/' ) ? home_url( $value ) : $value ); break; case 'dashboard_hide': $s[ $key ] = array_values( array_intersect( array_map( 'sanitize_key', (array) $value ), array_keys( self::dashboard_boxes() ) ) ); break; case 'hide_nags': $s[ $key ] = empty( $value ) || 'false' === $value ? 0 : 1; break; } } update_option( self::OPTION, $s, true ); return $s; } /* ------------------------------ admin area ------------------------------ */ private static function user_in( array $roles ) { if ( ! is_user_logged_in() || current_user_can( 'manage_options' ) ) { return false; } return (bool) array_intersect( (array) wp_get_current_user()->roles, $roles ); } public static function filter_admin_bar( $show ) { return self::user_in( (array) self::get()['admin_bar_roles'] ) ? false : $show; } public static function block_admin() { if ( wp_doing_ajax() || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) { return; } global $pagenow; if ( 'admin-post.php' === $pagenow ) { return; } $s = self::get(); if ( self::user_in( (array) $s['block_admin_roles'] ) ) { wp_safe_redirect( '' !== $s['block_admin_to'] ? $s['block_admin_to'] : home_url( '/' ) ); exit; } } public static function dashboard() { $hide = (array) self::get()['dashboard_hide']; foreach ( $hide as $id ) { if ( 'welcome' === $id ) { remove_action( 'welcome_panel', 'wp_welcome_panel' ); continue; } foreach ( array( 'normal', 'side', 'column3', 'column4' ) as $context ) { remove_meta_box( $id, 'dashboard', $context ); } } } public static function hide_nags() { if ( ! current_user_can( 'update_core' ) ) { remove_action( 'admin_notices', 'update_nag', 3 ); remove_action( 'network_admin_notices', 'update_nag', 3 ); remove_action( 'admin_notices', 'maintenance_nag', 10 ); } } /* ------------------------------ switch to user ------------------------------ */ /** * Whether the current user may switch to another one. * * @param int $user_id Target. * @return true|WP_Error */ public static function can_switch_to( $user_id ) { $target = get_userdata( (int) $user_id ); if ( ! current_user_can( Softvolt_Ai_Bodyguard::cap() ) ) { return new WP_Error( 'svabg_switch', __( 'Only administrators can switch to another user.', 'ai-guardwall' ) ); } if ( ! $target ) { return new WP_Error( 'svabg_switch', __( 'That user does not exist.', 'ai-guardwall' ) ); } if ( get_current_user_id() === $target->ID ) { return new WP_Error( 'svabg_switch', __( 'That is you.', 'ai-guardwall' ) ); } if ( user_can( $target, 'manage_options' ) || is_super_admin( $target->ID ) ) { return new WP_Error( 'svabg_switch', __( 'Switching to another administrator is not allowed, so an administrator\'s actions always stay their own in the log.', 'ai-guardwall' ) ); } if ( ! current_user_can( 'edit_user', $target->ID ) ) { return new WP_Error( 'svabg_switch', __( 'You may not act as this user.', 'ai-guardwall' ) ); } return true; } /** * The switch link (a plain URL: escape it where it is printed). * * @param int $user_id Target. * @return string */ public static function switch_url( $user_id ) { return add_query_arg( array( 'action' => 'svabg_switch_to', 'user' => (int) $user_id, '_wpnonce' => wp_create_nonce( 'svabg_switch_to' ), ), admin_url( 'admin-post.php' ) ); } public static function switch_back_url() { return add_query_arg( array( 'action' => 'svabg_switch_back', '_wpnonce' => wp_create_nonce( 'svabg_switch_back' ), ), admin_url( 'admin-post.php' ) ); } private static function sign( $value ) { return hash_hmac( 'sha256', $value, wp_salt( 'auth' ) ); } /** * Become another user. * * @param int $user_id Target. * @return array|WP_Error from, to, cookie (the value of the way-back cookie). */ public static function switch_to( $user_id ) { $ok = self::can_switch_to( $user_id ); if ( is_wp_error( $ok ) ) { return $ok; } $from = wp_get_current_user(); $target = get_userdata( (int) $user_id ); // The way-back cookie names the administrator's session only by its hash (as WordPress itself stores // sessions), never by the session token: the cookie cannot be turned into a login. $session = self::verifier( wp_get_session_token() ); $exp = time() + 2 * DAY_IN_SECONDS; $value = $from->ID . '|' . $target->ID . '|' . $exp . '|' . $session; $cookie = $value . '|' . self::sign( $value ); wp_clear_auth_cookie(); wp_set_auth_cookie( $target->ID, false ); wp_set_current_user( $target->ID ); if ( ! headers_sent() ) { setcookie( self::SWITCH_COOKIE, $cookie, $exp, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, is_ssl(), true ); } $_COOKIE[ self::SWITCH_COOKIE ] = $cookie; Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'user_switched', sprintf( /* translators: 1: administrator login, 2: user login. */ __( 'Administrator %1$s switched to the account of %2$s.', 'ai-guardwall' ), $from->user_login, $target->user_login ), array(), $from->ID ); return array( 'from' => $from->ID, 'to' => $target->ID, 'cookie' => $cookie, ); } /** * The administrator to switch back to, when the way-back cookie is valid. * * @return WP_User|null */ public static function switched_from() { if ( empty( $_COOKIE[ self::SWITCH_COOKIE ] ) ) { return null; } $parts = explode( '|', isset( $_COOKIE[ self::SWITCH_COOKIE ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::SWITCH_COOKIE ] ) ) : '' ); if ( 5 !== count( $parts ) ) { return null; } list( $from, $to, $exp, $session, $sig ) = $parts; if ( ! hash_equals( self::sign( $from . '|' . $to . '|' . $exp . '|' . $session ), $sig ) || (int) $exp < time() || (int) $to !== get_current_user_id() ) { return null; } $user = get_userdata( (int) $from ); if ( ! $user || ! user_can( $user, 'manage_options' ) || ! self::session_alive( $user->ID, $session ) ) { return null; } return $user; } /** * A session's hash, the way WordPress keys its stored sessions. * * @since 1.5.1 * @param string $token Session token. * @return string */ private static function verifier( $token ) { return function_exists( 'hash' ) ? hash( 'sha256', (string) $token ) : sha1( (string) $token ); } /** * Whether the administrator's session the switch started from still exists (so a log-out, a password * change or "log out everywhere" also ends the way back). * * @since 1.5.1 * @param int $user_id Administrator. * @param string $verifier Session hash. * @return bool */ private static function session_alive( $user_id, $verifier ) { $sessions = get_user_meta( (int) $user_id, 'session_tokens', true ); return is_array( $sessions ) && isset( $sessions[ $verifier ]['expiration'] ) && (int) $sessions[ $verifier ]['expiration'] >= time(); } /** * Go back to the administrator's own session. * * @return WP_User|WP_Error */ public static function switch_back() { $from = self::switched_from(); if ( ! $from ) { return new WP_Error( 'svabg_switch', __( 'There is no account to switch back to (the link expired or the original session ended). Log in again.', 'ai-guardwall' ) ); } $parts = explode( '|', isset( $_COOKIE[ self::SWITCH_COOKIE ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::SWITCH_COOKIE ] ) ) : '' ); $was = wp_get_current_user(); // The session made for the switch ends; the user's own sessions are not touched. The administrator gets // a new session, and the one left behind when switching (its cookie was cleared then) is removed. wp_destroy_current_session(); wp_clear_auth_cookie(); $sessions = get_user_meta( $from->ID, 'session_tokens', true ); if ( is_array( $sessions ) && isset( $sessions[ $parts[3] ] ) ) { unset( $sessions[ $parts[3] ] ); update_user_meta( $from->ID, 'session_tokens', $sessions ); } wp_set_auth_cookie( $from->ID, false ); wp_set_current_user( $from->ID ); self::forget_switch(); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'user_switched_back', sprintf( /* translators: 1: administrator login, 2: user login. */ __( 'Administrator %1$s switched back from the account of %2$s.', 'ai-guardwall' ), $from->user_login, $was->user_login ), array(), $from->ID ); return $from; } public static function forget_switch() { if ( ! headers_sent() ) { setcookie( self::SWITCH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, is_ssl(), true ); } unset( $_COOKIE[ self::SWITCH_COOKIE ] ); } public static function handle_switch_to() { // The capability and the nonce first; the user id is read only after both pass. if ( ! current_user_can( Softvolt_Ai_Bodyguard::cap() ) ) { wp_die( esc_html__( 'You are not allowed to switch users.', 'ai-guardwall' ), esc_html__( 'Switch to user', 'ai-guardwall' ), array( 'response' => 403 ) ); } check_admin_referer( 'svabg_switch_to' ); $uid = isset( $_GET['user'] ) ? absint( $_GET['user'] ) : 0; $result = self::switch_to( $uid ); if ( is_wp_error( $result ) ) { wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Switch to user', 'ai-guardwall' ), array( 'response' => 403, 'back_link' => true ) ); } $target = get_userdata( $uid ); wp_safe_redirect( $target && user_can( $target, 'edit_posts' ) && ! self::blocked( $target ) ? admin_url() : home_url( '/' ) ); exit; } private static function blocked( WP_User $user ) { return (bool) array_intersect( (array) $user->roles, (array) self::get()['block_admin_roles'] ); } public static function handle_switch_back() { check_admin_referer( 'svabg_switch_back' ); $result = self::switch_back(); if ( is_wp_error( $result ) ) { wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Switch back', 'ai-guardwall' ), array( 'response' => 403, 'back_link' => true ) ); } wp_safe_redirect( Softvolt_Ai_Bodyguard_Admin::url( 'tools', 'admin' ) ); exit; } public static function row_action( $actions, $user ) { if ( $user instanceof WP_User && true === self::can_switch_to( $user->ID ) ) { $actions['svabg_switch'] = '' . esc_html__( 'Switch to', 'ai-guardwall' ) . ''; } return $actions; } public static function switch_back_node( $bar ) { $from = self::switched_from(); if ( ! $from ) { return; } $bar->add_node( array( 'id' => 'svabg-switch-back', 'parent' => 'top-secondary', /* translators: %s: the administrator's display name. */ 'title' => esc_html( sprintf( __( 'Switch back to %s', 'ai-guardwall' ), $from->display_name ) ), 'href' => self::switch_back_url(), ) ); } public static function switch_back_notice() { $from = self::switched_from(); if ( ! $from ) { return; } echo '

' . esc_html( sprintf( /* translators: %s: the user's name. */ __( 'You are using the site as %s.', 'ai-guardwall' ), wp_get_current_user()->display_name ) ) . ' ' . esc_html( sprintf( /* translators: %s: administrator. */ __( 'Switch back to %s', 'ai-guardwall' ), $from->display_name ) ) . '

'; } /** A way back on pages without the admin bar. */ public static function switch_back_footer() { if ( is_admin_bar_showing() ) { return; } $from = self::switched_from(); if ( ! $from ) { return; } echo '

' . esc_html( sprintf( /* translators: %s: administrator. */ __( 'Switch back to %s', 'ai-guardwall' ), $from->display_name ) ) . '

'; } /** * Users the current administrator may switch to. * * @param string $search Login, name or email. * @return array */ public static function switch_candidates( $search ) { $args = array( 'number' => 20, 'orderby' => 'login', ); $search = trim( (string) $search ); if ( '' !== $search ) { $args['search'] = '*' . $search . '*'; $args['search_columns'] = array( 'user_login', 'user_email', 'display_name' ); } $out = array(); foreach ( get_users( $args ) as $user ) { $ok = self::can_switch_to( $user->ID ); $out[] = array( 'id' => (int) $user->ID, 'login' => $user->user_login, 'name' => $user->display_name, 'email' => $user->user_email, 'roles' => array_values( array_map( 'translate_user_role', array_intersect_key( wp_roles()->get_names(), array_flip( (array) $user->roles ) ) ) ), 'url' => true === $ok ? self::switch_url( $user->ID ) : '', 'reason' => true === $ok ? '' : $ok->get_error_message(), ); } return array( 'users' => $out ); } /* ------------------------------ scheduled tasks ------------------------------ */ /** * Where a hook's code comes from: WordPress, a plugin, the theme, or nothing. * * @param string $hook Hook. * @return string */ public static function hook_source( $hook ) { global $wp_filter; if ( in_array( $hook, self::CORE_HOOKS, true ) ) { return __( 'WordPress', 'ai-guardwall' ); } if ( 0 === strpos( $hook, 'svabg_' ) ) { return __( 'AI GuardWall', 'ai-guardwall' ); } if ( empty( $wp_filter[ $hook ] ) ) { return ''; } $plugins = Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/plugins' ) . '/'; $theme = Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/themes' ) . '/'; foreach ( $wp_filter[ $hook ]->callbacks as $callbacks ) { foreach ( $callbacks as $cb ) { try { $f = $cb['function']; $ref = is_array( $f ) ? new ReflectionMethod( $f[0], $f[1] ) : ( is_string( $f ) && false !== strpos( $f, '::' ) ? new ReflectionMethod( $f ) : new ReflectionFunction( $f ) ); $file = wp_normalize_path( (string) $ref->getFileName() ); } catch ( Throwable $e ) { continue; } if ( 0 === strpos( $file, $plugins ) ) { $slug = strtok( substr( $file, strlen( $plugins ) ), '/' ); return self::plugin_name( $slug ); } if ( 0 === strpos( $file, $theme ) ) { return __( 'Theme', 'ai-guardwall' ); } if ( 0 === strpos( $file, Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) . '/' . WPINC . '/' ) || 0 === strpos( $file, Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) . '/wp-admin/' ) ) { return __( 'WordPress', 'ai-guardwall' ); } return __( 'Other code', 'ai-guardwall' ); } } return ''; } private static function plugin_name( $slug ) { static $names = null; if ( null === $names ) { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $names = array(); foreach ( get_plugins() as $file => $data ) { $names[ strtok( $file, '/' ) ] = $data['Name']; } } return isset( $names[ $slug ] ) ? $names[ $slug ] : $slug; } /** * Every scheduled event, soonest first. * * @return array */ public static function cron_events() { $schedules = wp_get_schedules(); $out = array(); $now = time(); foreach ( (array) _get_cron_array() as $ts => $hooks ) { foreach ( (array) $hooks as $hook => $events ) { foreach ( (array) $events as $sig => $event ) { $schedule = isset( $event['schedule'] ) ? (string) $event['schedule'] : ''; $source = self::hook_source( $hook ); $out[] = array( 'hook' => (string) $hook, 'sig' => (string) $sig, 'time' => (int) $ts, 'when' => (int) $ts <= $now ? sprintf( /* translators: %s: time span. */ __( 'due %s ago', 'ai-guardwall' ), human_time_diff( (int) $ts, $now ) ) : sprintf( /* translators: %s: time span. */ __( 'in %s', 'ai-guardwall' ), human_time_diff( $now, (int) $ts ) ), 'local' => wp_date( 'Y-m-d H:i:s', (int) $ts ), 'args' => isset( $event['args'] ) ? (array) $event['args'] : array(), 'schedule' => $schedule, 'repeat' => '' === $schedule ? __( 'Once', 'ai-guardwall' ) : ( isset( $schedules[ $schedule ]['display'] ) ? $schedules[ $schedule ]['display'] : $schedule ), 'source' => '' !== $source ? $source : __( 'Nothing (left behind)', 'ai-guardwall' ), 'orphan' => '' === $source, 'core' => in_array( $hook, self::CORE_HOOKS, true ), ); } } } usort( $out, function ( $a, $b ) { return $a['time'] <=> $b['time']; } ); return array( 'events' => $out, 'disabled' => defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON, 'schedules' => count( $schedules ), ); } private static function find_event( $hook, $sig, $time ) { $cron = _get_cron_array(); $time = (int) $time; if ( isset( $cron[ $time ][ $hook ][ $sig ] ) ) { return $cron[ $time ][ $hook ][ $sig ]; } return null; } /** * Run one event now (it stays scheduled). * * @return array|WP_Error */ public static function cron_run( $hook, $sig, $time ) { $event = self::find_event( (string) $hook, (string) $sig, $time ); if ( null === $event ) { return new WP_Error( 'svabg_cron', __( 'That task is not scheduled any more.', 'ai-guardwall' ) ); } // Runs under the server's normal limits; the plugin's long steps (a scan step, a database cleanup, the // link check) ask for more time themselves. $start = microtime( true ); ob_start(); try { do_action_ref_array( (string) $hook, isset( $event['args'] ) ? (array) $event['args'] : array() ); $error = ''; } catch ( Throwable $e ) { $error = $e->getMessage(); } ob_end_clean(); $ms = (int) round( 1000 * ( microtime( true ) - $start ) ); Softvolt_Ai_Bodyguard_Logger::log( '' === $error ? 'info' : 'warning', 'cron_run', sprintf( /* translators: 1: hook, 2: milliseconds. */ __( 'Scheduled task %1$s run by hand (%2$d ms).', 'ai-guardwall' ), $hook, $ms ) ); if ( '' !== $error ) { return new WP_Error( 'svabg_cron', sprintf( /* translators: %s: error message. */ __( 'The task stopped with an error: %s', 'ai-guardwall' ), $error ) ); } return array( 'message' => sprintf( /* translators: %d: milliseconds. */ __( 'Done in %d ms.', 'ai-guardwall' ), $ms ), 'ms' => $ms, ); } /** * Remove one event. * * @return array|WP_Error */ public static function cron_delete( $hook, $sig, $time ) { $event = self::find_event( (string) $hook, (string) $sig, $time ); if ( null === $event ) { return new WP_Error( 'svabg_cron', __( 'That task is not scheduled any more.', 'ai-guardwall' ) ); } $ok = wp_unschedule_event( (int) $time, (string) $hook, isset( $event['args'] ) ? (array) $event['args'] : array(), true ); if ( is_wp_error( $ok ) || ! $ok ) { return is_wp_error( $ok ) ? $ok : new WP_Error( 'svabg_cron', __( 'WordPress did not remove the task.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'cron_deleted', sprintf( /* translators: %s: hook. */ __( 'Scheduled task removed: %s', 'ai-guardwall' ), $hook ) ); return array( 'message' => in_array( $hook, self::CORE_HOOKS, true ) ? __( 'Removed. WordPress schedules this task again by itself.', 'ai-guardwall' ) : __( 'Removed.', 'ai-guardwall' ) ); } }