roles, (array) $settings['excluded_roles'] ); } /** * Whether activity tracking is enabled. * * @return bool */ public static function is_tracking_enabled() { $settings = Activitysignature_Helpers::get_settings(); /** * Filter whether tracking should run for this request. * * @param bool $enabled Whether tracking is enabled. */ return (bool) apply_filters( 'activitysignature_should_track', ! empty( $settings['tracking_enabled'] ) ); } /** * Get merged plugin settings. * * @return array */ public static function get_settings() { return wp_parse_args( get_option( self::OPTION_SETTINGS, array() ), self::get_default_settings() ); } /** * Default plugin settings. * * @return array */ public static function get_default_settings() { return array( 'tracking_enabled' => true, 'track_failed_logins' => true, 'enabled_events' => self::get_default_activity_type_keys(), 'excluded_roles' => array(), 'excluded_users' => array(), 'failed_alert_count' => 0, 'failed_alert_email' => '', 'retention_days' => 30, 'items_per_page' => 20, 'woocommerce_orders' => false, ); } /** * Activity type keys, without loading translations. * * Activation stores these keys before init. Labels are translated later. * * @return string[] */ public static function get_default_activity_type_keys() { return array( 'user_created', 'user_updated', 'user_login', 'user_login_failed', 'user_role_changed', 'user_deleted', ); } /** * Known activity types and labels. * * @return array */ public static function get_activity_types() { $types = array( 'user_created' => __( 'User created', 'activitysignature' ), 'user_updated' => __( 'Profile updated', 'activitysignature' ), 'user_login' => __( 'Login', 'activitysignature' ), 'user_login_failed' => __( 'Failed login', 'activitysignature' ), 'user_role_changed' => __( 'Role changed', 'activitysignature' ), 'user_deleted' => __( 'User deleted', 'activitysignature' ), ); /** * Filter registered activity type labels. * * @param array $types Type key => label. */ return apply_filters( 'activitysignature_activity_types', $types ); } /** * Admin page base URL. * * @param string $tab Optional tab. * * @return string */ public static function get_admin_url( $tab = '' ) { $url = admin_url( 'options-general.php?page=' . Activitysignature_Helpers::get_admin_page_slug() ); if ( $tab ) { $url = add_query_arg( 'tab', $tab, $url ); } return $url; } /** * Admin page slug under Settings. * * @return string */ public static function get_admin_page_slug() { return 'activitysignature'; } /** * Run schema upgrades when the stored DB version is behind. */ public static function maybe_upgrade() { if ( (string) get_option( self::OPTION_DB_VERSION, '' ) === self::get_db_version() ) { return; } self::install_schema(); } /** * Remove plugin transients for the current site. */ public static function delete_site_transients() { delete_transient( self::TRANSIENT_BACKFILL_RUNNING ); delete_transient( self::TRANSIENT_BACKFILL_DONE ); global $wpdb; $likes = array( $wpdb->esc_like( '_transient_' . self::TRANSIENT_FAIL_PREFIX ) . '%', $wpdb->esc_like( '_transient_timeout_' . self::TRANSIENT_FAIL_PREFIX ) . '%', $wpdb->esc_like( '_transient_' . self::TRANSIENT_DELETE_SKIP ) . '%', $wpdb->esc_like( '_transient_timeout_' . self::TRANSIENT_DELETE_SKIP ) . '%', ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Uninstall removes rate-limit and batch transients by prefix. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s', $wpdb->options, $likes[0], $likes[1], $likes[2], $likes[3] ) ); } /** * Current activity-table schema version. * * @return string */ public static function get_db_version() { return '1'; } /** * Create or update the activity table schema. */ public static function install_schema() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = self::get_table_name(); $sql = "CREATE TABLE $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, user_id bigint(20) NOT NULL DEFAULT 0, user_login varchar(60) NOT NULL DEFAULT '', user_email varchar(100) NOT NULL DEFAULT '', actor_user_id bigint(20) NOT NULL DEFAULT 0, ip_address varchar(45) NOT NULL DEFAULT '', activity_type varchar(50) NOT NULL, activity_data longtext NOT NULL, activity_date datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY user_id (user_id), KEY user_login (user_login), KEY user_email (user_email), KEY actor_user_id (actor_user_id), KEY ip_address (ip_address), KEY activity_type (activity_type), KEY activity_date (activity_date), KEY activity_type_date (activity_type, activity_date) ) $charset_collate;"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( self::OPTION_DB_VERSION, self::get_db_version(), false ); } /** * Ensure the daily cleanup event is scheduled. */ public static function maybe_schedule_cleanup() { if ( ! wp_next_scheduled( self::HOOK_CLEANUP ) ) { wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK_CLEANUP ); } } /** * Best-effort client IP (REMOTE_ADDR only by default). * * @return string */ public static function get_client_ip() { $ip = ''; if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) { $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); } /** * Filter detected client IP (e.g. when behind a trusted reverse proxy). * * @param string $ip Detected IP. */ return (string) apply_filters( 'activitysignature_client_ip', $ip ); } /** * Insert an activity row. * * @param int $user_id User ID (0 allowed for unknown failed logins). * @param string $activity_type Activity type key. * @param array $activity_data Extra data. * @param string $activity_date Optional MySQL datetime. * * @return int|false Insert ID or false on failure. */ public static function insert_activity( $user_id, $activity_type, $activity_data = array(), $activity_date = '' ) { global $wpdb; $activity_type = sanitize_key( $activity_type ); $activity_data = is_array( $activity_data ) ? $activity_data : array(); if ( ! isset( self::get_activity_types()[ $activity_type ] ) ) { return false; } if ( '' === $activity_date ) { $activity_date = current_time( 'mysql' ); } $parsed_date = DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', $activity_date, wp_timezone() ); $date_errors = DateTimeImmutable::getLastErrors(); if ( false === $parsed_date || ( false !== $date_errors && ( $date_errors['warning_count'] || $date_errors['error_count'] ) ) ) { return false; } $activity_date = $parsed_date->format( 'Y-m-d H:i:s' ); $user_login = ''; if ( isset( $activity_data['user_login'] ) ) { $user_login = sanitize_user( (string) $activity_data['user_login'] ); } $user_email = isset( $activity_data['user_email'] ) ? sanitize_email( (string) $activity_data['user_email'] ) : ''; if ( '' === $user_email && $user_id > 0 ) { $user = get_userdata( $user_id ); if ( $user ) { $user_email = sanitize_email( $user->user_email ); } } $actor_user_id = isset( $activity_data['actor_user_id'] ) ? absint( $activity_data['actor_user_id'] ) : get_current_user_id(); unset( $activity_data['actor_user_id'] ); $ip_address = isset( $activity_data['ip_address'] ) ? sanitize_text_field( $activity_data['ip_address'] ) : ''; if ( $ip_address && ! filter_var( $ip_address, FILTER_VALIDATE_IP ) ) { $ip_address = ''; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom activity table has no WP insert API. $result = $wpdb->insert( Activitysignature_Helpers::get_table_name(), array( 'user_id' => (int) $user_id, 'user_login' => $user_login, 'user_email' => $user_email, 'actor_user_id' => $actor_user_id, 'ip_address' => $ip_address, 'activity_type' => $activity_type, 'activity_data' => wp_json_encode( $activity_data ), 'activity_date' => $activity_date, ), array( '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' ) ); $insert_id = false === $result ? false : (int) $wpdb->insert_id; /** * Fires after an activity row is inserted. * * @param int|false $insert_id Insert ID or false. * @param int $user_id User ID. * @param string $activity_type Activity type. * @param array $activity_data Activity payload. */ if ( false !== $insert_id ) { self::flush_activity_caches(); do_action( 'activitysignature_activity_inserted', $insert_id, (int) $user_id, $activity_type, $activity_data ); } return $insert_id; } /** * Drop object-cache entries derived from the activity table. */ public static function flush_activity_caches() { $blog_id = get_current_blog_id(); wp_cache_delete( 'activitysignature_dashboard_stats_' . $blog_id . '_' . current_time( 'Y-m-d' ), self::CACHE_GROUP ); wp_cache_delete( 'activitysignature_activity_count_' . $blog_id, self::CACHE_GROUP ); wp_cache_delete( 'activitysignature_failed_login_summary_' . $blog_id, self::CACHE_GROUP ); } /** * Activity table name. * * @return string */ public static function get_table_name() { global $wpdb; return $wpdb->prefix . self::TABLE_SUFFIX; } /** * Delete activity rows by primary key. * * @param int[] $ids Row IDs. * * @return int|false Number of rows deleted, or false on failure. */ public static function delete_rows_by_ids( array $ids ) { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ); if ( empty( $ids ) ) { return 0; } $table = self::get_table_name(); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Dynamic IN (%d) list; custom table delete has no WP API / caching. $result = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE id IN (' . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')', ...array_merge( array( $table ), $ids ) ) ); if ( false !== $result && $result > 0 ) { self::flush_activity_caches(); } return $result; } /** * Format a datetime for admin display. * * Returns an unescaped string. Escape at the point of output with esc_html(). * * @param string $datetime MySQL datetime or empty. * * @return string Unescaped display string. */ public static function format_datetime( $datetime ) { if ( empty( $datetime ) ) { return __( 'Never', 'activitysignature' ); } $date = DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', $datetime, wp_timezone() ); if ( false === $date || $date->format( 'Y-m-d H:i:s' ) !== $datetime ) { return '—'; } $errors = DateTimeImmutable::getLastErrors(); if ( false !== $errors && ( ! empty( $errors['warning_count'] ) || ! empty( $errors['error_count'] ) ) ) { return '—'; } return wp_date( 'Y-m-d H:i:s', $date->getTimestamp(), wp_timezone() ); } /** * Validate an optional YYYY-MM-DD value. * * @param string $date Date value. * * @return bool */ public static function is_valid_date( $date ) { if ( '' === $date ) { return true; } $parsed = DateTimeImmutable::createFromFormat( '!Y-m-d', $date ); if ( false === $parsed || $parsed->format( 'Y-m-d' ) !== $date ) { return false; } // PHP < 8.2 returns an errors array even on success; 8.2+ returns false when clean. $errors = DateTimeImmutable::getLastErrors(); return false === $errors || ( empty( $errors['warning_count'] ) && empty( $errors['error_count'] ) ); } /** * Dashboard summary stats. * * @return array{total_users:int,logins_today:int,failed_today:int,never_logged_in:int,recent_count:int} */ public static function get_dashboard_stats() { $cache_key = 'activitysignature_dashboard_stats_' . get_current_blog_id() . '_' . current_time( 'Y-m-d' ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached && is_array( $cached ) ) { return $cached; } global $wpdb; $table = Activitysignature_Helpers::get_table_name(); $today_start = current_time( 'Y-m-d' ) . ' 00:00:00'; $counts = count_users(); $total_users = isset( $counts['total_users'] ) ? (int) $counts['total_users'] : 0; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table; result cached via wp_cache_* below. $activity_counts = $wpdb->get_row( $wpdb->prepare( 'SELECT COUNT(*) AS recent_count, SUM(activity_type = %s) AS logins_today, SUM(activity_type = %s) AS failed_today FROM %i WHERE activity_date >= %s', 'user_login', 'user_login_failed', $table, $today_start ), ARRAY_A ); $logins_today = isset( $activity_counts['logins_today'] ) ? (int) $activity_counts['logins_today'] : 0; $failed_today = isset( $activity_counts['failed_today'] ) ? (int) $activity_counts['failed_today'] : 0; $recent_count = isset( $activity_counts['recent_count'] ) ? (int) $activity_counts['recent_count'] : 0; $never_q = new WP_User_Query( array( 'fields' => 'ID', 'number' => 1, 'count_total' => true, 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query array( 'key' => self::get_user_meta_key( 'last_login' ), 'compare' => 'NOT EXISTS', ), ), ) ); $never_logged_in = (int) $never_q->get_total(); $stats = array( 'total_users' => $total_users, 'logins_today' => $logins_today, 'failed_today' => $failed_today, 'never_logged_in' => $never_logged_in, 'recent_count' => $recent_count, ); wp_cache_set( $cache_key, $stats, self::CACHE_GROUP, 5 * MINUTE_IN_SECONDS ); return $stats; } /** * Get a site-specific user metadata key. * * @param string $name Metadata name without a prefix. * * @return string */ public static function get_user_meta_key( $name ) { $name = sanitize_key( $name ); if ( is_multisite() ) { return '_activitysignature_' . get_current_blog_id() . '_' . $name; } return '_activitysignature_' . $name; } }