table_name = $wpdb->prefix . 'adminease_network_viewer_log'; $this->settings = Plugin::get_settings( 'debug' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] ); add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] ); if( !empty( $this->settings['network_viewer_enabled'] ) ) { $this->maybe_upgrade_table(); add_action( 'shutdown', [ $this, 'log_request' ], 999 ); add_action( 'adminease_cleanup_network_viewer_logs', [ $this, 'cleanup_old_logs' ] ); add_action( 'wp_ajax_adminease_get_network_viewer_log', [ $this, 'ajax_get_network_viewer_log' ] ); add_action( 'wp_ajax_adminease_get_network_viewer_entry', [ $this, 'ajax_get_network_viewer_entry' ] ); add_action( 'wp_ajax_adminease_clear_network_viewer_log', [ $this, 'ajax_clear_network_viewer_log' ] ); if( !wp_next_scheduled( 'adminease_cleanup_network_viewer_logs' ) ) { wp_schedule_event( time(), 'hourly', 'adminease_cleanup_network_viewer_logs' ); } } } /** * Updates the settings fields array with additional configuration options for the AdminEase plugin. * * @param array $fields Associative array of existing settings fields. Each key represents a settings section, and its value is an array of fields under that section. * - A new set of fields is added under the 'debug' section, with each field containing parameters such as: * - type: string Field input type (e.g., 'switch', 'number', 'select', 'textarea'). * - id: string Unique identifier for the field. * - name: string HTML name attribute for the field. * - value: mixed Current value of the field, or a default value if not set. * - label_class: string CSS class for the field label. * - input_class: string CSS class for the input element. * - wrapper_class: string CSS class for the field wrapper (optional). * - label: string Field label text. * -*/ public function adminease_settings_fields( array $fields ): array { $max_entries_ceiling = $this->get_max_entries_ceiling(); $max_entries = $this->get_max_entries(); $fields['debug']['fields'][] = [ 'type' => 'switch', 'id' => 'network-viewer-enabled', 'name' => 'adminease[debug][network_viewer_enabled]', 'value' => $this->settings['network_viewer_enabled'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Network Viewer', 'adminease' ), 'description' => __( "Real-time HTTP request logging. See exactly who's connecting to your site, where they're from, what they're accessing, and when. Identify security threats before they become problems, debug connection issues with precision, and gain valuable insights into visitor behavior, all from a single, powerful interface.

Tip: Strange-looking Full URIs (like /-/-/-/-/) are automated internet scanners probing your site for vulnerabilities - this is normal internet noise and does not mean your site has been compromised.", 'adminease' ), 'child_fields' => [ [ 'type' => 'switch', 'id' => 'network-viewer-auto-refresh', 'name' => '', 'value' => 0, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Refresh Network Viewer', 'adminease' ), 'description' => __( 'Automatically reload network requests at a chosen interval. State resets on page reload.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'select', 'id' => 'network-viewer-auto-refresh-interval', 'name' => 'adminease[debug][network_viewer_auto_refresh_interval]', 'value' => $this->settings['network_viewer_auto_refresh_interval'] ?? '10', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Network Viewer Log Auto-Refresh Interval', 'adminease' ), 'description' => __( 'Set the interval for auto-refreshing the network viewer viewer.', 'adminease' ), 'options' => [ /* translators: %d: number of seconds for the auto-refresh interval */ '3' => sprintf( __( 'Every %d seconds', 'adminease' ), 3 ), /* translators: %d: number of seconds for the auto-refresh interval */ '5' => sprintf( __( 'Every %d seconds', 'adminease' ), 5 ), /* translators: %d: number of seconds for the auto-refresh interval */ '10' => sprintf( __( 'Every %d seconds', 'adminease' ), 10 ), /* translators: %d: number of seconds for the auto-refresh interval */ '30' => sprintf( __( 'Every %d seconds', 'adminease' ), 30 ), /* translators: %d: number of seconds for the auto-refresh interval */ '60' => sprintf( __( 'Every %d seconds', 'adminease' ), 60 ), ], 'attributes' => [ 'data-parent' => 'network-viewer-auto-refresh', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-log-ajax', 'name' => 'adminease[debug][network_viewer_log_ajax]', 'value' => $this->settings['network_viewer_log_ajax'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log WP AJAX Requests', 'adminease' ), 'description' => __( 'Enable logging of WordPress AJAX requests (admin-ajax.php).', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-log-cron', 'name' => 'adminease[debug][network_viewer_log_cron]', 'value' => $this->settings['network_viewer_log_cron'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log Cron Requests', 'adminease' ), 'description' => __( 'Enable logging of WordPress cron requests (wp-cron.php).', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-log-rest-api', 'name' => 'adminease[debug][network_viewer_log_rest_api]', 'value' => $this->settings['network_viewer_log_rest_api'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log REST API Requests', 'adminease' ), 'description' => __( 'Enable logging of WordPress REST API requests.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-auto-load', 'name' => 'adminease[debug][network_viewer_auto_load]', 'value' => $this->settings['network_viewer_auto_load'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Load Network Viewer', 'adminease' ), 'field_description' => __( 'Automatically load the network viewer log when the AdminEase admin page is opened.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'number', 'id' => 'network-viewer-max-entries', 'name' => 'adminease[debug][network_viewer_max_entries]', 'value' => $max_entries, 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Maximum Log Entries', 'adminease' ), 'description' => sprintf( /* translators: %s: maximum number of log entries allowed, e.g. "100,000" */ __( 'Maximum number of entries to keep in the log (100-%s).', 'adminease' ), number_format_i18n( $max_entries_ceiling ) ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', 'min' => '100', 'max' => $max_entries_ceiling, ], ], [ 'type' => 'select', 'id' => 'network-viewer-auto-clear', 'name' => 'adminease[debug][network_viewer_auto_clear]', 'value' => $this->settings['network_viewer_auto_clear'] ?? '24_hours', 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto Clear Logs After', 'adminease' ), 'description' => __( 'Automatically delete logs older than this period.', 'adminease' ), 'options' => [ '1_hour' => __( '1 Hour', 'adminease' ), '24_hours' => __( '24 Hours', 'adminease' ), '7_days' => __( '7 Days', 'adminease' ), 'never' => __( 'Never', 'adminease' ), ], 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'textarea', 'id' => 'network-viewer-exclude-ips', 'name' => 'adminease[debug][network_viewer_exclude_ips]', 'value' => $this->get_excluded_ips(), 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Exclude IP Addresses', 'adminease' ), 'description' => __( 'Enter IP addresses to exclude from logging (one per line). CIDR ranges (192.168.1.0/24) and wildcards (192.168.1.*) are supported.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', 'rows' => '4', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-trust-proxy', 'name' => 'adminease[debug][network_viewer_trust_proxy]', 'value' => $this->settings['network_viewer_trust_proxy'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'My site is behind a proxy or CDN', 'adminease' ), 'description' => __( 'Enable this only if your site sits behind a reverse proxy, load balancer or CDN (Cloudflare, Sucuri, Fastly, a Kubernetes ingress, and so on). Visitor IPs are then read from the forwarding headers your proxy sends. Leave this off if your site is reached directly, because on a direct connection those headers can be faked by anyone, which would let visitors disguise their IP address in the log and slip past the exclusion list. AdminEase already detects the common proxy setups on its own, so most sites never need this.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], [ 'type' => 'switch', 'id' => 'network-viewer-resolve-hostname', 'name' => 'adminease[debug][network_viewer_resolve_hostname]', 'value' => $this->settings['network_viewer_resolve_hostname'] ?? 1, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Resolve Hostnames', 'adminease' ), 'description' => __( 'Look up the hostname behind each visitor IP address, so the log can show crawl-66-249-66-1.googlebot.com instead of just a number. Each answer is remembered for 24 hours, so a given IP is only looked up once a day. Turn this off on busy sites: the lookup is a network call your server waits for while the visitor\'s request finishes, and a site seeing many different IP addresses pays that wait over and over. Existing entries keep their hostname; only new ones are left blank.', 'adminease' ), 'attributes' => [ 'data-parent' => 'network-viewer-enabled', ], ], ], ]; return $fields; } /** * Enqueues the necessary scripts and styles for the admin page. * * @param string $hook The current admin page hook suffix. Used to determine if scripts should be enqueued. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'NetworkViewer', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseNetworkViewer.css', [ ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseNetworkViewer.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'NetworkViewer', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseNetworkViewer.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseNetworkViewer.js' ), true ); $security = [ 'refreshNetworkViewerLog' => wp_create_nonce( 'adminease_refresh_network_viewer_log' ), 'clearNetworkViewerLog' => wp_create_nonce( 'adminease_clear_network_viewer_log' ), 'getNetworkViewerEntry' => wp_create_nonce( 'adminease_get_network_viewer_entry' ), ]; $i18n = [ 'confirmClearNetworkViewerLog' => esc_html__( 'Are you sure you want to clear all network viewer logs?', 'adminease' ), 'networkViewerLogCleared' => esc_html__( 'Network viewer log cleared successfully.', 'adminease' ), 'networkViewerRefreshError' => esc_html__( 'Failed to refresh network viewer log.', 'adminease' ), 'clearNetworkViewerLogFailed' => esc_html__( 'Failed to clear network viewer log.', 'adminease' ), 'loadingEntry' => esc_html__( 'Loading…', 'adminease' ), 'loadEntryFailed' => esc_html__( 'Failed to load connection details.', 'adminease' ), /* translators: 1: start number, 2: end number, 3: total count */ 'connectionCount' => esc_html__( 'Showing %1$s-%2$s of %3$s connections', 'adminease' ), 'processing' => esc_html__( 'Processing…', 'adminease' ), 'complete' => esc_html__( 'Complete!', 'adminease' ), 'networkError' => esc_html__( 'Network error', 'adminease' ), 'byteUnits' => [ esc_html__( 'Bytes', 'adminease' ), esc_html__( 'KB', 'adminease' ), esc_html__( 'MB', 'adminease' ), esc_html__( 'GB', 'adminease' ), ], ]; wp_localize_script( ADMINEASE_NAME . 'NetworkViewer', ADMINEASE_NAME . 'NetworkViewerAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => $security, 'i18n' => $i18n, 'autoLoad' => !empty( $this->settings['network_viewer_auto_load'] ), 'isMobile' => wp_is_mobile(), ] ); } /** * Handles the saving of AdminEase settings and updates internal properties accordingly. * * @param array $sanitized_settings Associative array containing sanitized settings. Expected keys include: * - debug: array|null Debug settings, including: * - network_viewer_enabled: bool Indicates whether the network viewer feature is enabled. * * @return void */ public function adminease_settings_saved( array $sanitized_settings ): void { $this->settings = $sanitized_settings['debug'] ?? []; if( !empty( $sanitized_settings['debug']['network_viewer_enabled'] ) ) { $this->create_table(); } else { wp_clear_scheduled_hook( 'adminease_cleanup_network_viewer_logs' ); } } /** * Handles the after render logic for the specified field. * * @param array $field The field information, including the 'id' property used for conditional logic. * * @return void */ public function adminease_after_field_render( array $field ) { if( 'network-viewer-enabled' !== $field['id'] ) { return; } $settings = $this->settings; include_once ADMINEASE_DIR . 'partials/network-viewer-log.php'; } /** * Capture and log network connection data if logging is enabled and the request meets criteria. * Runs on shutdown so the captured response code is the one really sent to the client. * @return void */ public function log_request(): void { if( empty( $this->settings['network_viewer_enabled'] ) ) { return; } if( !$this->should_log_request() ) { return; } $data = $this->get_request_data(); $this->insert_log_entry( $data ); } /** * Determines whether the current request should be logged. * This method checks various conditions to exclude certain types of requests, * such as internal AJAX calls, cron jobs, REST API requests, static asset requests, * and requests from excluded IP addresses, from being logged. * @return bool True if the request should be logged, false otherwise. */ private function should_log_request(): bool { if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { if( empty( $this->settings['network_viewer_log_ajax'] ) ) { return false; } } if( defined( 'DOING_CRON' ) && DOING_CRON ) { if( empty( $this->settings['network_viewer_log_cron'] ) ) { return false; } } if( defined( 'REST_REQUEST' ) && REST_REQUEST ) { if( empty( $this->settings['network_viewer_log_rest_api'] ) ) { return false; } } $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; $request_path = (string) wp_parse_url( $request_uri, PHP_URL_PATH ); $extension = strtolower( (string) pathinfo( $request_path, PATHINFO_EXTENSION ) ); $static_extensions = [ 'css', 'js', 'jpg', 'jpeg', 'png', 'gif', 'svg', 'ico', 'woff', 'woff2', 'ttf', 'eot' ]; if( '' !== $extension && in_array( $extension, $static_extensions, true ) ) { return false; } $excluded_ips = $this->get_excluded_ips(); if( '' !== $excluded_ips && Utils::ip_in_allowlist( Utils::get_client_ip(), $excluded_ips ) ) { return false; } return true; } /** * Returns the configured IP exclusion list as a newline-separated string. * The settings sanitiser collapses newlines into spaces on save, so any run of * whitespace is normalised back into the newline-separated form the textarea renders * and Utils::ip_in_allowlist() consumes. * @return string Newline-separated exclusion list, or an empty string when unset. */ private function get_excluded_ips(): string { $excluded_ips = trim( (string) ( $this->settings['network_viewer_exclude_ips'] ?? '' ) ); if( '' === $excluded_ips ) { return ''; } return implode( PHP_EOL, preg_split( '/\s+/', $excluded_ips ) ); } /** * Retrieve data related to the current request. * @return array An associative array containing request details. */ private function get_request_data(): array { $country_code = Utils::get_client_country(); $country_name = ''; if( !empty( $country_code ) ) { $countries = Utils::get_countries_iso(); $country_name = $countries[ $country_code ] ?? $country_code; } $request_uri = isset( $_SERVER['REQUEST_URI'] ) && '' !== $_SERVER['REQUEST_URI'] ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '/'; $parsed_url = wp_parse_url( $request_uri ); $user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; $browser_info = $this->parse_user_agent( $user_agent ); $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : ''; $request_type = $this->get_request_type(); $cron_ip = ''; $cron_hostname = ''; if( 'cron' === $request_type ) { $request_method = 'CRON'; $request_uri = 'wp-cron.php'; $user_agent = 'WordPress Cron'; $browser_info = [ 'browser' => 'WordPress', 'device' => 'Server', 'is_bot' => false, ]; $cron_hostname = (string) gethostname(); $resolved_ip = '' !== $cron_hostname ? gethostbyname( $cron_hostname ) : ''; $validated_ip = '' !== $resolved_ip ? filter_var( $resolved_ip, FILTER_VALIDATE_IP ) : false; $cron_ip = ( false !== $validated_ip && $validated_ip !== $cron_hostname ) ? (string) $validated_ip : ''; if ( '' !== $cron_ip && function_exists( 'geoip_country_code_by_name' ) ) { $cron_cc = geoip_country_code_by_name( $cron_hostname ); if ( ! empty( $cron_cc ) ) { $country_code = (string) $cron_cc; $countries = Utils::get_countries_iso(); $country_name = $countries[ $country_code ] ?? $country_code; } } $parsed_url = wp_parse_url( $request_uri ); } $post_data = $this->get_post_data( $request_method ); return [ 'timestamp' => current_time( 'mysql' ), 'ip_address' => ( 'cron' === $request_type && '' !== $cron_ip ) ? $cron_ip : Utils::get_client_ip(), 'country' => $country_name, 'hostname' => ( 'cron' === $request_type && '' !== $cron_hostname ) ? $cron_hostname : $this->get_hostname(), 'request_method' => $request_method, 'request_uri' => $request_uri, 'request_type' => $request_type, 'query_string' => $parsed_url['query'] ?? '', 'post_data' => $post_data, 'user_agent' => $user_agent, 'browser' => $browser_info['browser'], 'device' => $browser_info['device'], 'is_bot' => $browser_info['is_bot'] ? 1 : 0, 'referer' => isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '', 'response_code' => $this->get_response_code(), 'request_size' => isset( $_SERVER['CONTENT_LENGTH'] ) ? (int) $_SERVER['CONTENT_LENGTH'] : null, 'protocol' => 'cron' === $request_type ? 'CLI' : ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_PROTOCOL'] ) ) : '' ), 'port' => 'cron' === $request_type ? 0 : ( isset( $_SERVER['SERVER_PORT'] ) ? (int) $_SERVER['SERVER_PORT'] : null ), 'user_id' => get_current_user_id(), 'user_role' => $this->get_user_role(), 'session_id' => $this->get_session_id(), ]; } /** * Get the type of request. * @return string Request type. */ private function get_request_type(): string { if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return 'ajax'; } if( defined( 'DOING_CRON' ) && DOING_CRON ) { return 'cron'; } if( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return 'rest_api'; } $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; if( false !== strpos( $request_uri, '/wp-json/' ) || strpos( $request_uri, '?rest_route=' ) !== false ) { return 'rest_api'; } if( is_admin() ) { return 'admin'; } return 'frontend'; } /** * Get current user's role. * @return string User role or empty string. */ private function get_user_role(): string { if( !is_user_logged_in() ) { return ''; } $user = wp_get_current_user(); return !empty( $user->roles ) ? implode( ', ', $user->roles ) : ''; } /** * Get session ID. * @return string Session ID or empty string. */ private function get_session_id(): string { if( session_id() ) { return session_id(); } if( function_exists( 'WC' ) && WC()->session ) { return WC()->session->get_customer_id(); } return ''; } /** * Capture POST data for POST/PUT/DELETE/PATCH requests. * * @param string $request_method The HTTP request method. * * @return string JSON-encoded POST data or empty string. */ private function get_post_data( string $request_method ): string { $allowed_methods = [ 'POST', 'PUT', 'DELETE', 'PATCH' ]; if( !in_array( strtoupper( $request_method ), $allowed_methods, true ) ) { return ''; } $post_data = []; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Required to capture raw POST data for network logging $raw_input = file_get_contents( 'php://input' ); if( !empty( $raw_input ) ) { $json_data = json_decode( $raw_input, true ); if( JSON_ERROR_NONE === json_last_error() && is_array( $json_data ) ) { $post_data = $json_data; } else { parse_str( $raw_input, $parsed_data ); if( !empty( $parsed_data ) ) { $post_data = $parsed_data; } else { $post_data = [ 'raw' => sprintf( /* translators: %s: formatted size of the request body, e.g. "2 KB" */ __( '[not stored: %s of unrecognised request body]', 'adminease' ), size_format( strlen( $raw_input ) ) ), ]; } } } elseif ( ! empty( $_POST ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Network logging, not form processing $post_data = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Network logging, not form processing } if( empty( $post_data ) ) { return ''; } $post_data = $this->sanitize_post_data( $post_data ); $json_encoded = wp_json_encode( $post_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); $max_size = apply_filters( 'adminease_network_viewer_post_data_max_size', 65536 ); if( strlen( $json_encoded ) > $max_size ) { $json_encoded = substr( $json_encoded, 0, $max_size ) . "\n... (truncated)"; } return $json_encoded; } /** * Remove sensitive data from POST data before storing. * * @param array $data The POST data array. * * @return array Sanitized POST data. */ private function sanitize_post_data( array $data ): array { $sensitive_keys = [ 'password', 'pwd', 'pass', 'passwd', 'password_confirmation', 'new_password', 'old_password', 'token', 'access_token', 'refresh_token', 'api_key', 'apikey', 'api_secret', 'secret', 'secret_key', 'private_key', 'auth', 'authorization', 'credit_card', 'card_number', 'cvv', 'ssn', ]; $sensitive_keys = apply_filters( 'adminease_network_viewer_sensitive_keys', $sensitive_keys ); foreach( $data as $key => $value ) { $key_lower = strtolower( $key ); foreach( $sensitive_keys as $sensitive_key ) { if( false !== strpos( $key_lower, $sensitive_key ) ) { $data[ $key ] = '***REDACTED***'; break; } } if( is_array( $value ) ) { $data[ $key ] = $this->sanitize_post_data( $value ); } } return $data; } /** * Detect if the user agent is a bot. * * @param string $user_agent User agent string. * * @return bool True if bot, false if human. */ private function is_bot( string $user_agent ): bool { $categorized_bots = Utils::get_categorized_bots(); $user_agent_lower = strtolower( $user_agent ); foreach( $categorized_bots as $category_data ) { foreach( array_keys( $category_data['bots'] ) as $bot_key ) { if( false !== strpos( $user_agent_lower, strtolower( (string) $bot_key ) ) ) { return true; } } } return false; } /** * Parse user agent string to extract browser and device info. * * @param string $user_agent User agent string. * * @return array Array with 'browser', 'device', and 'is_bot' keys. */ private function parse_user_agent( string $user_agent ): array { try { if( null === self::$ua_parser ) { self::$ua_parser = Parser::create(); } $result = self::$ua_parser->parse( $user_agent ); $browser = 'Other' !== $result->ua->family ? $result->ua->family : 'Unknown'; $device_family = $result->device->family; $device = 'Desktop'; if( 'Other' !== $device_family ) { if( false !== stripos( $device_family, 'tablet' ) || false !== stripos( $device_family, 'ipad' ) ) { $device = 'Tablet'; } elseif( false !== stripos( $device_family, 'phone' ) || null !== $result->device->brand ) { $device = 'Mobile'; } } elseif( wp_is_mobile() ) { if( false !== strpos( $user_agent, 'iPad' ) ) { $device = 'Tablet'; } else { $device = 'Mobile'; } } $is_bot = 'Spider' === $result->device->family || 'Bot' === $result->ua->family || $this->is_bot( $user_agent ); return [ 'browser' => $browser, 'device' => $device, 'is_bot' => $is_bot, ]; } catch( \Exception $e ) { return [ 'browser' => 'Unknown', 'device' => wp_is_mobile() ? 'Mobile' : 'Desktop', 'is_bot' => $this->is_bot( $user_agent ), ]; } } /** * Whether reverse DNS lookups are wanted for this request. * * An absent setting means on, not off: the lookup predates the setting, so every site * that upgrades into it has no saved value and must keep the hostnames it already has. * An explicit 0 is honoured — the switch always posts a value, so a saved 0 is a real * choice rather than a missing key. The filter runs last and overrides either way, so * code that already sets it keeps working. * * @return bool True when the lookup should run. */ private function resolves_hostname(): bool { $enabled = !isset( $this->settings['network_viewer_resolve_hostname'] ) || !empty( $this->settings['network_viewer_resolve_hostname'] ); return (bool) apply_filters( 'adminease_network_viewer_resolve_hostname', $enabled ); } /** * Get the hostname from the IP address. * The reverse DNS lookup is a blocking network call, so results are cached per IP for * a day. Sites that would rather not pay the first-sight cost at all can switch the * lookup off with the "Resolve Hostnames" setting or the * adminease_network_viewer_resolve_hostname filter. * @return string The hostname or empty string if unable to resolve. */ private function get_hostname(): string { if( !$this->resolves_hostname() ) { return ''; } $ip_address = Utils::get_client_ip(); if( empty( $ip_address ) ) { return ''; } $cache_key = 'adminease_rdns_' . md5( $ip_address ); $cached = get_transient( $cache_key ); if( false !== $cached ) { return (string) $cached; } $hostname = gethostbyaddr( $ip_address ); $hostname = ( false !== $hostname && $hostname !== $ip_address ) ? $hostname : ''; set_transient( $cache_key, $hostname, DAY_IN_SECONDS ); return $hostname; } /** * Get the HTTP response code. * Captured on shutdown, so this is the status actually sent to the client. * @return int The HTTP response code, defaults to 200. */ private function get_response_code(): int { $response_code = 200; $status = http_response_code(); if( false !== $status ) { $response_code = $status; } return $response_code; } /** * Inserts a log entry into the database. * * @param array $data Associative array containing log entry data. * * @return void */ private function insert_log_entry( array $data ): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Real-time logging requires direct insert $wpdb->insert( $this->table_name, [ 'timestamp' => $data['timestamp'], 'ip_address' => $data['ip_address'], 'country' => $data['country'], 'hostname' => $data['hostname'], 'request_method' => $data['request_method'], 'request_uri' => $data['request_uri'], 'request_type' => $data['request_type'], 'query_string' => $data['query_string'], 'post_data' => $data['post_data'] ?? '', 'user_agent' => $data['user_agent'], 'browser' => $data['browser'], 'device' => $data['device'], 'is_bot' => $data['is_bot'], 'referer' => $data['referer'], 'response_code' => $data['response_code'], 'request_size' => $data['request_size'], 'protocol' => $data['protocol'], 'port' => $data['port'], 'user_id' => $data['user_id'] > 0 ? $data['user_id'] : null, 'user_role' => $data['user_role'], 'session_id' => $data['session_id'], ], [ '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%s', '%d', '%d', '%s', '%s', ] ); } /** * Enforces the maximum number of entries in the log table by removing the oldest entries when the count exceeds the allowed maximum. * The method checks the total number of entries in the log table and deletes the oldest entries if the count exceeds the maximum * number of allowed entries as defined by the `get_max_entries` method. * @return void */ private function enforce_max_entries(): void { global $wpdb; $max_entries = $this->get_max_entries(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Count check for log maintenance, table name is safe $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); if( $count > $max_entries ) { $delete_count = $count - $max_entries; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Log cleanup operation $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} ORDER BY timestamp ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $delete_count ) ); } } /** * Retrieves the maximum number of entries allowed for network viewer. * This is the site's own setting, clamped to the range the UI advertises so the number * enforced here can never drift from the number the settings screen accepts. * @return int The maximum number of entries. */ private function get_max_entries(): int { $max_entries = !empty( $this->settings['network_viewer_max_entries'] ) ? (int) $this->settings['network_viewer_max_entries'] : 1000; return max( 100, min( $max_entries, $this->get_max_entries_ceiling() ) ); } /** * Retrieves the highest value the "Maximum Log Entries" setting may be set to. * Add-ons raise this through the filter; it is a ceiling, not a default, and must never * be used as the field's value. * @return int The maximum allowed setting value. */ private function get_max_entries_ceiling(): int { $ceiling = (int) apply_filters( 'adminease_default_network_viewer_max_entries', self::MAX_ENTRIES_CEILING ); return max( 100, $ceiling ); } /** * Formats a moment relative to now as a site-local MySQL datetime. * Log rows are written with current_time( 'mysql' ), i.e. in the site's local frame, so * every cutoff compared against them has to be built in that same frame. Deriving one * from gmdate()/time() instead shifts the whole window by the site's UTC offset, which * on a UTC+N site deletes rows that are still inside the retention period. * * @param int $seconds_ago How many seconds before now the cutoff sits. * * @return string Cutoff formatted as 'Y-m-d H:i:s' in the site's timezone. */ private function get_local_cutoff( int $seconds_ago ): string { $timestamp = time() - $seconds_ago; $cutoff = wp_date( 'Y-m-d H:i:s', $timestamp ); return false !== $cutoff ? $cutoff : gmdate( 'Y-m-d H:i:s', $timestamp ); } /** * Cleans up old logs from the database based on the configured auto-clear period. * The auto-clear period determines the time range for retaining logs * and can be set to intervals like 1 hour, 24 hours, or 7 days. * If the auto-clear period is set to 'never', no logs will be deleted. * @return void */ public function cleanup_old_logs(): void { $this->enforce_max_entries(); $auto_clear = $this->get_auto_clear_period(); if( 'never' === $auto_clear ) { return; } global $wpdb; $time_map = [ '1_hour' => HOUR_IN_SECONDS, '24_hours' => DAY_IN_SECONDS, '7_days' => WEEK_IN_SECONDS, ]; $seconds = $time_map[ $auto_clear ] ?? DAY_IN_SECONDS; $cutoff_time = $this->get_local_cutoff( $seconds ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Scheduled log cleanup operation $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "DELETE FROM {$this->table_name} WHERE timestamp < %s", $cutoff_time ) ); } /** * Retrieves a list of connections from the database based on the provided arguments. * * @param array $args Optional. Associative array of arguments to filter and paginate the query: * - per_page: int Number of records to fetch per page. Default 50. * - page: int Current page number for pagination. Default 1. * - method: string HTTP request method to filter by (e.g., GET, POST). Default empty. * - status: string HTTP status code range (2xx, 3xx, 4xx, 5xx). Default empty. * - type: string Request type to filter by (frontend, admin, ajax, rest_api, cron). Default empty. * - location: string Country name to filter by. Default empty. * - ip: string IP address or partial IP to filter by. Default empty. * - path: string URL path to search for. Default empty. * - visitor: string Visitor type (human, bot). Default empty. * - orderby: string Column to sort results by. Default 'timestamp'. * - order: string Sorting order, either 'ASC' or 'DESC'. Default 'DESC'. * * @return array Array of connections matching the provided filters and pagination options. */ public function get_connections( array $args = [] ): array { global $wpdb; $defaults = [ 'per_page' => 50, 'page' => 1, 'method' => '', 'status' => '', 'type' => '', 'location' => '', 'ip' => '', 'path' => '', 'visitor' => '', 'orderby' => 'timestamp', 'order' => 'DESC', ]; $args = wp_parse_args( $args, $defaults ); $allowed_orderby = [ 'timestamp', 'ip_address', 'request_method', 'response_code', 'request_type' ]; $orderby = in_array( $args['orderby'], $allowed_orderby, true ) ? $args['orderby'] : 'timestamp'; $order = 'ASC' === strtoupper( $args['order'] ) ? 'ASC' : 'DESC'; $per_page = max( 1, min( self::MAX_PER_PAGE, (int) $args['per_page'] ) ); $page = max( 1, (int) $args['page'] ); $offset = ( $page - 1 ) * $per_page; $where = []; $where_values = []; if( !empty( $args['method'] ) ) { $where[] = 'request_method = %s'; $where_values[] = $args['method']; } if( !empty( $args['status'] ) ) { $status_map = [ '2xx' => [ 200, 299 ], '3xx' => [ 300, 399 ], '4xx' => [ 400, 499 ], '5xx' => [ 500, 599 ], ]; if( isset( $status_map[ $args['status'] ] ) ) { $where[] = 'response_code BETWEEN %d AND %d'; $where_values[] = $status_map[ $args['status'] ][0]; $where_values[] = $status_map[ $args['status'] ][1]; } } if( !empty( $args['type'] ) ) { $where[] = 'request_type = %s'; $where_values[] = $args['type']; } if( !empty( $args['location'] ) ) { $where[] = 'country LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['location'] ) . '%'; } if( !empty( $args['ip'] ) ) { $where[] = 'ip_address LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['ip'] ) . '%'; } if( !empty( $args['path'] ) ) { $where[] = 'request_uri LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['path'] ) . '%'; } if( !empty( $args['visitor'] ) ) { if( 'bot' === $args['visitor'] ) { $where[] = 'is_bot = %d'; $where_values[] = 1; } elseif( 'human' === $args['visitor'] ) { $where[] = 'is_bot = %d'; $where_values[] = 0; } } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name and orderby/order are validated above $query = "SELECT * FROM {$this->table_name} {$where_clause} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d"; $where_values[] = $per_page; $where_values[] = $offset; $query = $wpdb->prepare( $query, $where_values ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Real-time log viewing, orderby/order validated against whitelist, all user inputs properly escaped $results = $wpdb->get_results( $query, ARRAY_A ); return is_array( $results ) ? $results : []; } /** * Retrieves the total count of records from the database based on the specified conditions. * * @param array $args Optional associative array to filter the query. Possible keys: * - method: string HTTP request method to filter by (e.g., GET, POST). * - status: string HTTP status code range (2xx, 3xx, 4xx, 5xx). * - type: string Request type to filter by (frontend, admin, ajax, rest_api, cron). * - location: string Country name to filter by. * - ip: string IP address or partial IP address to filter by. * - path: string URL path to search for. * - visitor: string Visitor type (human, bot). * * @return int The total number of matching records. */ public function get_total_count( array $args = [] ): int { global $wpdb; $where = []; $where_values = []; if( !empty( $args['method'] ) ) { $where[] = 'request_method = %s'; $where_values[] = $args['method']; } if( !empty( $args['status'] ) ) { $status_map = [ '2xx' => [ 200, 299 ], '3xx' => [ 300, 399 ], '4xx' => [ 400, 499 ], '5xx' => [ 500, 599 ], ]; if( isset( $status_map[ $args['status'] ] ) ) { $where[] = 'response_code BETWEEN %d AND %d'; $where_values[] = $status_map[ $args['status'] ][0]; $where_values[] = $status_map[ $args['status'] ][1]; } } if( !empty( $args['type'] ) ) { $where[] = 'request_type = %s'; $where_values[] = $args['type']; } if( !empty( $args['location'] ) ) { $where[] = 'country LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['location'] ) . '%'; } if( !empty( $args['ip'] ) ) { $where[] = 'ip_address LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['ip'] ) . '%'; } if( !empty( $args['path'] ) ) { $where[] = 'request_uri LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['path'] ) . '%'; } if( !empty( $args['visitor'] ) ) { if( 'bot' === $args['visitor'] ) { $where[] = 'is_bot = %d'; $where_values[] = 1; } elseif( 'human' === $args['visitor'] ) { $where[] = 'is_bot = %d'; $where_values[] = 0; } } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe, the query is properly prepared below $query = "SELECT COUNT(*) FROM {$this->table_name} {$where_clause}"; if( !empty( $where_values ) ) { $query = $wpdb->prepare( $query, $where_values ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Real-time count for pagination, all user inputs properly escaped via wpdb::prepare() return (int) $wpdb->get_var( $query ); } /** * Clears all entries from the connections table. * Uses DELETE rather than TRUNCATE: TRUNCATE is a DDL statement requiring the DROP * privilege, which many managed hosts withhold, so Clear failed there with no * explanation. DELETE only needs the DELETE privilege the plugin already relies on. * @return bool True if the operation was successful, false otherwise. */ public function clear_connections(): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Intentional log clearing operation, table name is built from $wpdb->prefix return false !== $wpdb->query( "DELETE FROM {$this->table_name}" ); } /** * Retrieves the auto-clear period for the network viewer. * This method checks the `network_viewer_auto_clear` setting in the class's settings property * and returns its value if it is defined and not empty. If the setting is not defined or is empty, * a default value of '24_hours' is returned. * @return string The auto-clear period value, either from the settings or the default '24_hours'. */ private function get_auto_clear_period(): string { return !empty( $this->settings['network_viewer_auto_clear'] ) ? $this->settings['network_viewer_auto_clear'] : '24_hours'; } /** * Handles an AJAX request to clear network connections logs. * Validates the user's permissions and nonce before performing the action. * @return void Outputs a JSON response indicating success or failure. */ public function ajax_clear_network_viewer_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_clear_network_viewer_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $result = $this->clear_connections(); if( $result ) { wp_send_json_success( esc_html__( 'Network viewer log cleared successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'clear_failed', __( 'Failed to clear network viewer log.', 'adminease' ) ) ); } } /** * Handles the AJAX request to refresh connection data. * Checks user permissions, verifies nonce, and retrieves connection data based * on the provided parameters. Returns a JSON response containing connection * details and pagination info. * @return void */ public function ajax_get_network_viewer_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_refresh_network_viewer_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $page = isset( $_POST['page'] ) ? max( 1, (int) $_POST['page'] ) : 1; $per_page = isset( $_POST['per_page'] ) ? (int) $_POST['per_page'] : 50; $per_page = max( 1, min( self::MAX_PER_PAGE, $per_page ) ); $method = isset( $_POST['method'] ) ? sanitize_text_field( wp_unslash( $_POST['method'] ) ) : ''; $status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : ''; $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : ''; $location = isset( $_POST['location'] ) ? sanitize_text_field( wp_unslash( $_POST['location'] ) ) : ''; $ip = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : ''; $path = isset( $_POST['path'] ) ? sanitize_text_field( wp_unslash( $_POST['path'] ) ) : ''; $visitor = isset( $_POST['visitor'] ) ? sanitize_text_field( wp_unslash( $_POST['visitor'] ) ) : ''; $args = [ 'page' => $page, 'per_page' => $per_page, 'method' => $method, 'status' => $status, 'type' => $type, 'location' => $location, 'ip' => $ip, 'path' => $path, 'visitor' => $visitor, ]; $connections = $this->get_connections( $args ); $total = $this->get_total_count( $args ); foreach( $connections as &$connection ) { $connection['formatted_time'] = $this->format_timestamp( (string) ( $connection['timestamp'] ?? '' ) ); } unset( $connection ); $total_pages = (int) ceil( $total / $per_page ); wp_send_json_success( [ 'table_html' => $this->render_network_viewer_log_table( $connections ), 'pagination_html' => $this->render_pagination_html( $page, $total_pages ), 'total' => $total, 'page' => $page, 'per_page' => $per_page, ] ); } /** * Handles the AJAX request for a single log entry's full details. * The log table used to carry all of this in 23 data-* attributes per row, including * the request body, which meant a 1000-row refresh could ship tens of megabytes of * markup to render a modal the user might never open. * @return void */ public function ajax_get_network_viewer_entry(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_get_network_viewer_entry' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $entry_id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; if( 0 === $entry_id ) { wp_send_json_error( new WP_Error( 'invalid_id', esc_html__( 'Invalid connection ID.', 'adminease' ) ) ); } $entry = $this->get_connection( $entry_id ); if( empty( $entry ) ) { wp_send_json_error( new WP_Error( 'not_found', esc_html__( 'Connection not found. It may have been cleared from the log.', 'adminease' ) ), 404 ); } wp_send_json_success( $this->prepare_entry_for_display( $entry ) ); } /** * Retrieves a single connection row by ID. * * @param int $entry_id The log entry ID. * * @return array The row as an associative array, or an empty array when not found. */ public function get_connection( int $entry_id ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Real-time log viewing, ID is cast to int and prepared $row = $wpdb->get_row( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT * FROM {$this->table_name} WHERE id = %d", $entry_id ), ARRAY_A ); return is_array( $row ) ? $row : []; } /** * Expands a raw log row into the fields the details modal renders. * * @param array $entry Raw database row. * * @return array Display-ready entry. Contains no HTML: the JS assigns every value with * .text()/.attr(), so escaping happens at the point of output. */ private function prepare_entry_for_display( array $entry ): array { $country = (string) ( $entry['country'] ?? '' ); $country_code = '' !== $country ? strtolower( Utils::get_country_code_by_name( $country ) ) : ''; $user_id = (int) ( $entry['user_id'] ?? 0 ); $username = esc_html__( 'Guest', 'adminease' ); $user_edit = ''; if( $user_id > 0 ) { $user = get_userdata( $user_id ); $username = $user ? $user->user_email : esc_html__( 'Unknown', 'adminease' ); $user_edit = $user ? (string) get_edit_user_link( $user->ID ) : ''; } $response_code = (int) ( $entry['response_code'] ?? 200 ); $browser = (string) ( $entry['browser'] ?? '' ); $device = (string) ( $entry['device'] ?? '' ); $method = (string) ( $entry['request_method'] ?? '' ); $size = $entry['request_size'] ?? null; return [ 'id' => (int) ( $entry['id'] ?? 0 ), 'formatted_time' => $this->format_timestamp( (string) ( $entry['timestamp'] ?? '' ) ), 'timestamp' => (string) ( $entry['timestamp'] ?? '' ), 'request_method' => $method, 'method_class' => $this->get_method_class( $method ), 'request_type' => ucfirst( str_replace( '_', ' ', (string) ( $entry['request_type'] ?? '' ) ) ), 'protocol' => (string) ( $entry['protocol'] ?? '' ), 'port' => (string) ( $entry['port'] ?? '' ), 'request_uri' => (string) ( $entry['request_uri'] ?? '' ), 'query_string' => (string) ( $entry['query_string'] ?? '' ), 'post_data' => (string) ( $entry['post_data'] ?? '' ), 'ip_address' => (string) ( $entry['ip_address'] ?? '' ), 'hostname' => (string) ( $entry['hostname'] ?? '' ), 'country' => $country, 'country_flag_url' => '' !== $country_code ? 'https://flagcdn.com/' . $country_code . '.svg' : '', 'browser' => $browser, 'browser_icon_url' => ADMINEASE_PLUGIN_URL . 'assets/img/browsers/' . $this->get_browser_icon_file( $browser ), 'device' => $device, 'user_agent' => (string) ( $entry['user_agent'] ?? '' ), 'response_code' => $response_code, 'response_class' => $this->get_response_class( $response_code ), 'request_size' => null !== $size ? size_format( (int) $size ) : '', 'referer' => (string) ( $entry['referer'] ?? '' ), 'user_role' => (string) ( $entry['user_role'] ?? '' ), 'session_id' => (string) ( $entry['session_id'] ?? '' ), 'username_text' => $username, 'user_edit_url' => $user_edit, ]; } /** * Formats a stored log timestamp for display. * Rows are written in the site's local frame, so the string has to be read back in that * same timezone. Passing it through strtotime() alone made PHP read it as UTC — WordPress * pins the process timezone to UTC — and date_i18n() then added the site's offset a * second time, showing every request that many hours in the future. * * @param string $timestamp MySQL datetime as stored. * * @return string Localised date and time, or the raw value if it cannot be parsed. */ private function format_timestamp( string $timestamp ): string { if( '' === $timestamp ) { return ''; } $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); try { $datetime = new \DateTimeImmutable( $timestamp, wp_timezone() ); } catch( \Exception $e ) { return $timestamp; } return (string) wp_date( $format, $datetime->getTimestamp() ); } /** * Renders the numbered pagination control for the log table. * * At most seven page slots are drawn, with an ellipsis standing in for the pages that * are skipped, so the control stays the same width whether the log holds three pages or * three hundred. A single page renders nothing, which empties the container the script * writes into. * * @param int $current_page Current page number. * @param int $total_pages Total number of pages. * * @return string The rendered pagination markup, or an empty string when there is only one page. */ public function render_pagination_html( int $current_page, int $total_pages ): string { if( $total_pages <= 1 ) { return ''; } $current_page = max( 1, min( $current_page, $total_pages ) ); $max_visible = 7; if( $total_pages <= $max_visible ) { $pages_to_show = range( 1, $total_pages ); } elseif( $current_page <= 4 ) { $pages_to_show = [ 1, 2, 3, 4, 5, '...', $total_pages ]; } elseif( $current_page >= $total_pages - 3 ) { $pages_to_show = [ 1, '...', $total_pages - 4, $total_pages - 3, $total_pages - 2, $total_pages - 1, $total_pages ]; } else { $pages_to_show = [ 1, '...', $current_page - 1, $current_page, $current_page + 1, '...', $total_pages ]; } $is_first = ( 1 === $current_page ); $is_last = ( $total_pages === $current_page ); $html = ''; return $html; } /** * Renders an HTML table displaying network viewer log data. * * The table is always rendered, headings included, even for an empty result set: the * markup replaces the wrapper's contents wholesale, so returning an empty string left * the page with no table to refresh into. The "no connections" message is a separate * element the script toggles. * * @param array $connections Array of connection log entries. * * @return string The rendered HTML table as a string. */ public function render_network_viewer_log_table( array $connections ): string { ob_start(); ?> get_country_flag( $connection['country'] ?? '' ); $response_code = (int) ( $connection['response_code'] ?? 200 ); $response_class = $this->get_response_class( $response_code ); $method_class = $this->get_method_class( $connection['request_method'] ?? '' ); $type_class = $this->get_type_class( $connection['request_type'] ?? '' ); $path = $connection['request_uri'] ?? ''; $is_bot = !empty( $connection['is_bot'] ); ?>
'chrome.svg', 'Safari' => 'safari.svg', 'Mobile Safari' => 'safari.svg', 'Edge' => 'microsoftedge.svg', 'Firefox' => 'firefox-browser.svg', 'Samsung Internet' => 'samsung.svg', 'Opera' => 'opera.svg', 'UC Browser' => 'ucbrowser.svg', 'Android' => 'android-webview.svg', 'Android Browser' => 'android-webview.svg', 'QQ Browser' => 'qq.png', 'Yandex Browser' => 'yandex.png', 'WordPress' => 'wordpress.svg', 'UptimeRobot' => 'uptimerobot.svg', 'default' => 'question.svg', ]; return $icon_map[ $browser ] ?? $icon_map['default']; } /** * Retrieve the flag emoji or image representation for a given country. * * @param string $country_name The name of the country for which to retrieve the flag. * * @return string The country flag or an empty string if the flag cannot be determined. */ public function get_country_flag( string $country_name ): string { if( empty( $country_name ) ) { return ''; } $country_code = strtolower( Utils::get_country_code_by_name( $country_name ) ); if( '' === $country_code ) { return ''; } return sprintf( '%2$s', esc_url( 'https://flagcdn.com/' . $country_code . '.svg' ), esc_attr( $country_name ) ); } /** * Get CSS class for response code. * * @param int $code Response code. * * @return string CSS class. */ private function get_response_class( int $code ): string { if( $code >= 200 && $code < 300 ) { return 'pwp-badge-success'; } if( $code >= 300 && $code < 400 ) { return 'pwp-badge-info'; } if( $code >= 400 && $code < 500 ) { return 'pwp-badge-warn'; } if( $code >= 500 ) { return 'pwp-badge-danger'; } return 'pwp-badge-muted'; } /** * Get CSS class for request method. * * @param string $method Request method. * * @return string CSS class. */ private function get_method_class( string $method ): string { $classes = [ 'GET' => 'pwp-badge-success', 'POST' => 'pwp-badge-citron', 'PUT' => 'pwp-badge-citron', 'DELETE' => 'pwp-badge-danger', 'PATCH' => 'pwp-badge-citron', ]; return $classes[ $method ] ?? 'pwp-badge-muted'; } /** * Get the CSS class for the request type. * * @param string $type Request type. * * @return string CSS class. */ private function get_type_class( string $type ): string { $classes = [ 'frontend' => 'pwp-badge-success', 'admin' => 'pwp-badge-primary', 'ajax' => 'pwp-badge-citron', 'rest_api' => 'pwp-badge-info', 'cron' => 'pwp-badge-muted', ]; return $classes[ $type ] ?? 'pwp-badge-muted'; } /** * Create the database table if it does not already exist. * @return void */ public function create_table(): void { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$this->table_name} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, timestamp datetime NOT NULL, ip_address varchar(45) NOT NULL, country varchar(255) DEFAULT NULL, hostname varchar(255) DEFAULT NULL, request_method varchar(10) NOT NULL, request_uri text NOT NULL, request_type varchar(20) DEFAULT NULL, query_string text DEFAULT NULL, post_data longtext DEFAULT NULL, user_agent text DEFAULT NULL, browser varchar(50) DEFAULT NULL, device varchar(50) DEFAULT NULL, is_bot tinyint(1) DEFAULT 0, referer text DEFAULT NULL, response_code int(3) DEFAULT 200, request_size int(11) DEFAULT NULL, protocol varchar(20) DEFAULT NULL, port int(5) DEFAULT NULL, user_id bigint(20) unsigned DEFAULT NULL, user_role varchar(50) DEFAULT NULL, session_id varchar(255) DEFAULT NULL, PRIMARY KEY (id), KEY timestamp (timestamp), KEY ip_address (ip_address), KEY user_id (user_id), KEY request_method (request_method), KEY response_code (response_code), KEY request_type (request_type), KEY is_bot (is_bot) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( self::DB_VERSION_OPTION, self::DB_VERSION ); } /** * Check if table needs upgrading and upgrade if necessary. * Gated on a stored version rather than a schema query: the previous check ran * SHOW COLUMNS on the log table on every single request, including every front-end * page view, to answer a question that changes about once per release. * @return void */ private function maybe_upgrade_table(): void { if( self::DB_VERSION === get_option( self::DB_VERSION_OPTION ) ) { return; } $this->create_table(); } /** * Drop the database table if it exists. * @return void */ public function drop_table(): void { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Intentional schema change for plugin uninstallation $wpdb->query( "DROP TABLE IF EXISTS {$this->table_name}" ); delete_option( self::DB_VERSION_OPTION ); } }