roles ) && is_array( $user->roles ) ? $user->roles : array(); foreach ( inspry_toolkit_users_summary_roles() as $role ) { if ( in_array( $role, $roles, true ) ) { return $role; } } return null; } /** * Record the first moment collection was known to be live. * * Written once. add_option() refuses to overwrite an existing value, so two * first requests racing cannot move it. * * @return void */ function inspry_toolkit_users_summary_mark_observing() { if ( ! get_option( 'inspry_toolkit_last_seen_since' ) ) { add_option( 'inspry_toolkit_last_seen_since', time() ); } } add_action( 'admin_init', 'inspry_toolkit_users_summary_heartbeat' ); /** * Stamp the current backend user as seen, at most once per hour. * * A request that reaches admin_init with a valid auth cookie is an interactive * session that got past the login flow, including Kadence Security's forced * two-factor interstitial, which clears the cookie until it completes. * Application-password requests never reach admin_init, so API activity is * never counted as a person. * * @return void */ function inspry_toolkit_users_summary_heartbeat() { if ( ! is_user_logged_in() ) { return; } if ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) { return; } /* * The WordPress Heartbeat API pings from any open tab and is not a person. * admin-ajax.php fires admin_init, so this guard is what stops an idle tab * re-stamping its user every hour. Compared only, never stored or output. */ if ( wp_doing_ajax() ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only request-type check. $ajax_action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : ''; if ( 'heartbeat' === $ajax_action ) { return; } } $user = wp_get_current_user(); // Only backend users are tracked; customers and subscribers get no meta at all. if ( ! $user || ! $user->exists() || null === inspry_toolkit_users_summary_role_for( $user ) ) { return; } $now = time(); $last = (int) get_user_meta( $user->ID, 'inspry_toolkit_last_seen', true ); /* * A stamp in the future (clock skew, or a database moved from a host with a * bad clock) must not silence the heartbeat until real time catches up, so * treat it as invalid and overwrite it. */ if ( $last && $last <= $now && ( $now - $last ) < HOUR_IN_SECONDS ) { return; } update_user_meta( $user->ID, 'inspry_toolkit_last_seen', $now ); inspry_toolkit_users_summary_mark_observing(); } /** * Kadence Security's two-factor API, when it is usable. * * Every entry point into the plugin is guarded so a missing, disabled or * changed Kadence Security can never raise a fatal here. * * @return object|null The two-factor instance, or null when unavailable. */ function inspry_toolkit_users_summary_two_factor_api() { if ( ! class_exists( 'ITSEC_Two_Factor' ) || ! method_exists( 'ITSEC_Two_Factor', 'get_instance' ) ) { return null; } try { $api = ITSEC_Two_Factor::get_instance(); } catch ( \Throwable $e ) { return null; } if ( ! is_object( $api ) || ! method_exists( $api, 'is_user_using_two_factor' ) || ! method_exists( $api, 'is_user_excluded' ) ) { return null; } return $api; } /** * Why the two-factor API is unavailable. * * Distinguishes Kadence Security being absent from its Two-Factor module being * switched off, since the class only loads with the module. * * @return string Either 'module_inactive' or 'plugin_inactive'. */ function inspry_toolkit_users_summary_two_factor_missing_reason() { return class_exists( 'ITSEC_Core' ) ? 'module_inactive' : 'plugin_inactive'; } /** * Build the backend users summary. * * Counts only: no usernames, display names or email addresses leave this * function. The requesting user is excluded so a service account, which never * logs in interactively and has no two-factor, does not read as a stale and * unenrolled administrator on every site. * * @param int $exclude_user_id User ID to leave out of every count. * @return array Summary of roles, last-seen buckets and two-factor enrollment. */ function inspry_toolkit_users_summary_build( $exclude_user_id ) { $limit = 1000; $now = time(); $roles = inspry_toolkit_users_summary_roles(); $query = new WP_User_Query( array( 'role__in' => $roles, // Primes the user and meta caches in two queries. 'fields' => 'all_with_meta', 'number' => $limit, 'orderby' => 'ID', 'order' => 'ASC', /* * Explicit: `truncated` reads get_total(), which is only meaningful * when the count is on. Inheriting the default would turn a future * default change into a silent always-false. */ 'count_total' => true, ) ); $users = $query->get_results(); $total = (int) $query->get_total(); $by_role = array_fill_keys( $roles, 0 ); $seen = array( '0_30' => 0, '31_90' => 0, 'over_90' => 0, 'unobserved' => 0, ); $in_scope = 0; $requester_excluded = false; $with_app_passwords = 0; $tf = inspry_toolkit_users_summary_two_factor_api(); $tf_state = $tf ? 'available' : 'unavailable'; $tf_reason = $tf ? null : inspry_toolkit_users_summary_two_factor_missing_reason(); $enrolled = 0; $not_enrolled = 0; $excluded = 0; $seen_30_gap = 0; $has_app_passwords_api = class_exists( 'WP_Application_Passwords' ) && method_exists( 'WP_Application_Passwords', 'get_user_application_passwords' ); foreach ( $users as $user ) { if ( ! $user instanceof WP_User ) { continue; } $role = inspry_toolkit_users_summary_role_for( $user ); if ( null === $role ) { continue; } /* * Role first, so the flag is true only when the requester would * otherwise have been counted. A super admin with no role on this blog * changes nothing. */ if ( $exclude_user_id && (int) $user->ID === (int) $exclude_user_id ) { $requester_excluded = true; continue; } ++$in_scope; ++$by_role[ $role ]; $stamp = (int) get_user_meta( $user->ID, 'inspry_toolkit_last_seen', true ); $bucket = 'unobserved'; if ( $stamp > 0 ) { $age = max( 0, $now - $stamp ); if ( $age <= 30 * DAY_IN_SECONDS ) { $bucket = '0_30'; } elseif ( $age <= 90 * DAY_IN_SECONDS ) { $bucket = '31_90'; } else { $bucket = 'over_90'; } } ++$seen[ $bucket ]; if ( $has_app_passwords_api ) { $passwords = WP_Application_Passwords::get_user_application_passwords( $user->ID ); if ( is_array( $passwords ) && count( $passwords ) > 0 ) { ++$with_app_passwords; } } if ( 'available' === $tf_state ) { try { $using = $tf->is_user_using_two_factor( $user->ID ); } catch ( \Throwable $e ) { $using = null; $tf_reason = 'api_error'; } /* * Null means two-factor is disabled site-wide * (ITSEC_DISABLE_TWO_FACTOR) or the call failed. Either way the * counts would be fiction, so drop them. */ if ( null === $using ) { $tf_state = 'unavailable'; $tf_reason = $tf_reason ? $tf_reason : 'disabled_site_wide'; continue; } if ( $using ) { ++$enrolled; } else { ++$not_enrolled; try { $is_excluded = (bool) $tf->is_user_excluded( $user ); } catch ( \Throwable $e ) { $is_excluded = false; } if ( $is_excluded ) { ++$excluded; } elseif ( '0_30' === $bucket ) { // Active in wp-admin this month without two-factor and not exempt. ++$seen_30_gap; } } } } $two_factor = array( 'state' => $tf_state ); if ( 'available' === $tf_state ) { $two_factor['enrolled'] = $enrolled; $two_factor['not_enrolled'] = $not_enrolled; $two_factor['not_enrolled_excluded'] = $excluded; $two_factor['seen_30_not_enrolled'] = $seen_30_gap; } else { $two_factor['reason'] = $tf_reason; } $since = (int) get_option( 'inspry_toolkit_last_seen_since' ); return array( 'version' => defined( 'INSPRY_TOOLKIT_CURRENT_VERSION' ) ? INSPRY_TOOLKIT_CURRENT_VERSION : null, 'observing_since' => $since > 0 ? $since : null, 'roles' => $by_role, 'in_scope' => $in_scope, 'requester_excluded' => $requester_excluded, /* * Null, not 0, when WordPress predates application passwords: * "unknown" must never read as "none". */ 'with_app_passwords' => $has_app_passwords_api ? $with_app_passwords : null, 'truncated' => $total > $limit, 'two_factor' => $two_factor, 'last_seen' => $seen, ); } add_action( 'rest_api_init', 'inspry_toolkit_users_summary_register_route' ); /** * Register the summary route. * * @return void */ function inspry_toolkit_users_summary_register_route() { register_rest_route( 'agency-toolkit/v1', '/users-summary', array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'inspry_toolkit_users_summary_rest', 'permission_callback' => 'inspry_toolkit_users_summary_rest_permission', ) ); } /** * Restrict the summary to administrators. * * @return bool Whether the current user may read the summary. */ function inspry_toolkit_users_summary_rest_permission() { return current_user_can( 'manage_options' ); } /** * Serve the summary. * * @return WP_REST_Response Counts-only summary, with caching suppressed. */ function inspry_toolkit_users_summary_rest() { inspry_toolkit_users_summary_mark_observing(); $response = rest_ensure_response( inspry_toolkit_users_summary_build( get_current_user_id() ) ); /* * Never let an edge cache serve one administrator's answer to the next * request. wp_get_nocache_headers() marks Last-Modified as false, meaning * "unset", which must not be sent as an empty header. */ foreach ( wp_get_nocache_headers() as $name => $value ) { if ( false === $value ) { continue; } $response->header( $name, $value ); } return $response; } add_action( 'admin_notices', 'inspry_toolkit_users_summary_notice' ); /** * Explain on the toolkit settings page why two-factor counts are unavailable. * * @return void */ function inspry_toolkit_users_summary_notice() { if ( ! current_user_can( 'manage_options' ) ) { return; } // Read-only screen check; the value is compared, never stored or output. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- not form processing. if ( empty( $_GET['page'] ) || 'inspry-agency-toolkit' !== sanitize_key( wp_unslash( $_GET['page'] ) ) ) { return; } if ( inspry_toolkit_users_summary_two_factor_api() ) { return; } if ( 'module_inactive' === inspry_toolkit_users_summary_two_factor_missing_reason() ) { $message = __( 'Kadence Security is active but its Two-Factor module is switched off, so two-factor enrollment cannot be reported. User counts and last-seen tracking still work; the summary will show two-factor as unavailable until the Two-Factor module is enabled.', 'agency-toolkit' ); } else { $message = __( 'Kadence Security is not active, so two-factor enrollment cannot be reported. User counts and last-seen tracking still work; the summary will show two-factor as unavailable until Kadence Security is installed and its Two-Factor module is enabled.', 'agency-toolkit' ); } ?>