table_name = $wpdb->prefix . 'adminease_http_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['http_request_log_enabled'] ) ) { add_filter( 'pre_http_request', [ $this, 'pre_http_request' ], 10, 3 ); add_action( 'http_api_debug', [ $this, 'http_api_debug' ], 10, 5 ); add_action( 'adminease_cleanup_http_request_logs', [ $this, 'cleanup_old_logs' ] ); add_action( 'wp_ajax_adminease_get_http_request_log', [ $this, 'ajax_get_http_request_log' ] ); add_action( 'wp_ajax_adminease_clear_http_request_log', [ $this, 'ajax_clear_http_request_log' ] ); if( !wp_next_scheduled( 'adminease_cleanup_http_request_logs' ) ) { wp_schedule_event( time(), 'hourly', 'adminease_cleanup_http_request_logs' ); } } } /** * Adds the HTTP Request Log fields to the Debug tab. * * @param array $fields Associative array of existing settings fields. * * @return array Modified settings fields array. */ public function adminease_settings_fields( array $fields ): array { $max_entries = apply_filters( 'adminease_default_http_request_log_max_entries', $this->settings['http_request_log_max_entries'] ?? '1000' ); $fields['debug']['fields'][] = [ 'type' => 'switch', 'id' => 'http-request-log-enabled', 'name' => 'adminease[debug][http_request_log_enabled]', 'value' => $this->settings['http_request_log_enabled'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Outgoing HTTP Request Log', 'adminease' ), 'description' => __( 'Plugins and themes quietly call outside servers in the background to check licences, fetch feeds, sync orders or phone home. Each call blocks the page that triggered it, so a slow or dead endpoint can make the whole site crawl. This log records every outgoing request with its destination, response code and how long it took, which is usually the fastest way to find out what is really making a site slow.', 'adminease' ), 'child_fields' => [ [ 'type' => 'switch', 'id' => 'http-request-log-errors-only', 'name' => 'adminease[debug][http_request_log_errors_only]', 'value' => $this->settings['http_request_log_errors_only'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Log Failed Requests Only', 'adminease' ), 'description' => __( 'Only record requests that returned an error or a response code of 400 and above.', 'adminease' ), 'attributes' => [ 'data-parent' => 'http-request-log-enabled', ], ], [ 'type' => 'switch', 'id' => 'http-request-log-store-response', 'name' => 'adminease[debug][http_request_log_store_response]', 'value' => $this->settings['http_request_log_store_response'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Store Response Body', 'adminease' ), 'description' => __( 'Keep the first 50KB of each response. Very useful for debugging, but it grows the database quickly and responses can contain private data.', 'adminease' ), 'attributes' => [ 'data-parent' => 'http-request-log-enabled', ], ], [ 'type' => 'switch', 'id' => 'http-request-log-auto-load', 'name' => 'adminease[debug][http_request_log_auto_load]', 'value' => $this->settings['http_request_log_auto_load'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Load HTTP Request Log', 'adminease' ), 'field_description' => __( 'Automatically load the request log when the AdminEase admin page is opened.', 'adminease' ), 'attributes' => [ 'data-parent' => 'http-request-log-enabled', ], ], [ 'type' => 'number', 'id' => 'http-request-log-max-entries', 'name' => 'adminease[debug][http_request_log_max_entries]', 'value' => $max_entries, 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Maximum Log Entries', 'adminease' ), 'description' => __( 'Maximum number of entries to keep in the log (100-100000).', 'adminease' ), 'attributes' => [ 'data-parent' => 'http-request-log-enabled', 'min' => '100', 'max' => '100000', ], ], [ 'type' => 'select', 'id' => 'http-request-log-auto-clear', 'name' => 'adminease[debug][http_request_log_auto_clear]', 'value' => $this->settings['http_request_log_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. Busy sites can make thousands of requests a day, so a short period is recommended.', 'adminease' ), 'options' => [ '1_hour' => __( '1 Hour', 'adminease' ), '24_hours' => __( '24 Hours', 'adminease' ), '7_days' => __( '7 Days', 'adminease' ), '30_days' => __( '30 Days', 'adminease' ), 'never' => __( 'Never', 'adminease' ), ], 'attributes' => [ 'data-parent' => 'http-request-log-enabled', ], ], [ 'type' => 'textarea', 'id' => 'http-request-log-exclude-hosts', 'name' => 'adminease[debug][http_request_log_exclude_hosts]', 'value' => $this->settings['http_request_log_exclude_hosts'] ?? '', 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Exclude Hosts', 'adminease' ), 'description' => __( 'Hosts to leave out of the log, one per line, for example api.wordpress.org.', 'adminease' ), 'attributes' => [ 'data-parent' => 'http-request-log-enabled', 'rows' => '4', ], ], ], ]; return $fields; } /** * Enqueues the scripts and styles for the request log on the admin page. * * @param string $hook The current admin page hook suffix. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'HttpRequestLog', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseHttpRequestLog.css', [ ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseHttpRequestLog.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'HttpRequestLog', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseHttpRequestLog.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseHttpRequestLog.js' ), true ); $security = [ 'refreshHttpRequestLog' => wp_create_nonce( 'adminease_get_http_request_log' ), 'clearHttpRequestLog' => wp_create_nonce( 'adminease_clear_http_request_log' ), ]; $i18n = [ 'confirmClear' => esc_html__( 'Are you sure you want to clear the whole HTTP request log?', 'adminease' ), 'logCleared' => esc_html__( 'HTTP request log cleared successfully.', 'adminease' ), 'loadFailed' => esc_html__( 'Failed to load the HTTP request log.', 'adminease' ), 'clearFailed' => esc_html__( 'Failed to clear the HTTP request log.', 'adminease' ), 'refreshedEmpty' => esc_html__( 'HTTP request log refreshed. No requests found.', 'adminease' ), 'networkError' => esc_html__( 'Network error', 'adminease' ), /* translators: 1: current page, 2: total pages */ 'paginationInfo' => esc_html__( 'Page %1$s of %2$s', 'adminease' ), /* translators: 1: start number, 2: end number, 3: total count */ 'requestCount' => esc_html__( 'Showing %1$s-%2$s of %3$s requests', 'adminease' ), 'btnProcessing' => esc_html__( 'Processing…', 'adminease' ), 'btnComplete' => esc_html__( 'Complete!', 'adminease' ), 'detailLabels' => [ 'requestInfo' => esc_html__( 'Request Information', 'adminease' ), 'timestamp' => esc_html__( 'Timestamp', 'adminease' ), 'url' => esc_html__( 'URL', 'adminease' ), 'method' => esc_html__( 'Method', 'adminease' ), 'statusCode' => esc_html__( 'Response Code', 'adminease' ), 'duration' => esc_html__( 'Duration', 'adminease' ), 'context' => esc_html__( 'Triggered By', 'adminease' ), 'user' => esc_html__( 'User', 'adminease' ), 'errorMessage' => esc_html__( 'Error Message', 'adminease' ), 'requestArgs' => esc_html__( 'Request Arguments', 'adminease' ), 'responseHeaders' => esc_html__( 'Response Headers', 'adminease' ), 'responseBody' => esc_html__( 'Response Body', 'adminease' ), 'notStored' => esc_html__( 'Not stored.', 'adminease' ), ], ]; wp_localize_script( ADMINEASE_NAME . 'HttpRequestLog', ADMINEASE_NAME . 'HttpRequestLogAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => $security, 'i18n' => $i18n, 'autoLoad' => !empty( $this->settings['http_request_log_auto_load'] ), ] ); } /** * Refreshes the cached settings and creates the log table once the feature is on. * * @param array $sanitized_settings Associative array containing sanitized settings. * * @return void */ public function adminease_settings_saved( array $sanitized_settings ): void { $this->settings = $sanitized_settings['debug'] ?? []; if( !empty( $sanitized_settings['debug']['http_request_log_enabled'] ) ) { $this->create_table(); } } /** * Renders the request log panel underneath the feature switch. * * @param array $field The field information. * * @return void */ public function adminease_after_field_render( array $field ): void { if( 'http-request-log-enabled' !== $field['id'] ) { return; } $settings = $this->settings; include_once ADMINEASE_DIR . 'partials/http-request-log.php'; } /** * Records when a request starts so its duration can be measured. * * @param false|array|WP_Error $preempt The preemptive response, untouched here. * @param array $parsed_args The request arguments. * @param string $url The request URL. * * @return false|array|WP_Error The unmodified preemptive response. */ public function pre_http_request( $preempt, $parsed_args, $url ) { $this->start_times[ md5( (string) $url ) ][] = microtime( true ); return $preempt; } /** * Writes a finished request to the log. * * @param array|WP_Error $response The response or error returned by the transport. * @param string $context The context of the call, 'response' once complete. * @param string $class The transport class name. * @param array $parsed_args The request arguments. * @param string $url The request URL. * * @return void */ public function http_api_debug( $response, $context, $class, $parsed_args, $url ): void { if( 'response' !== $context ) { return; } $duration = $this->pull_duration( (string) $url ); if( !$this->should_log( $response, (string) $url ) ) { return; } $is_error = is_wp_error( $response ); $status_code = $is_error ? 0 : (int) wp_remote_retrieve_response_code( $response ); $error_message = $is_error ? $response->get_error_message() : ''; $this->insert_log_entry( [ 'timestamp' => current_time( 'mysql', true ), 'url' => $url, 'host' => (string) wp_parse_url( $url, PHP_URL_HOST ), 'method' => strtoupper( (string) ( $parsed_args['method'] ?? 'GET' ) ), 'status_code' => $status_code, 'duration' => $duration, 'is_error' => ( $is_error || $status_code >= 400 ) ? 1 : 0, 'error_message' => $error_message, 'request_args' => $this->format_request_args( (array) $parsed_args ), 'response_headers' => $is_error ? '' : $this->format_response_headers( $response ), 'response_body' => $this->maybe_store_body( $response, $is_error ), 'context' => $this->detect_context(), 'user_id' => get_current_user_id(), ] ); $this->enforce_max_entries(); } /** * Reads back and removes the recorded start time for a URL. * * @param string $url The request URL. * * @return float The elapsed time in milliseconds. */ private function pull_duration( string $url ): float { $key = md5( $url ); if( empty( $this->start_times[ $key ] ) ) { return 0.0; } $start = array_shift( $this->start_times[ $key ] ); if( empty( $this->start_times[ $key ] ) ) { unset( $this->start_times[ $key ] ); } return round( ( microtime( true ) - (float) $start ) * 1000, 2 ); } /** * Decides whether a finished request belongs in the log. * * @param array|WP_Error $response The response or error returned by the transport. * @param string $url The request URL. * * @return bool True when the request should be logged. */ private function should_log( $response, string $url ): bool { $host = (string) wp_parse_url( $url, PHP_URL_HOST ); if( '' === $host ) { return false; } foreach( $this->get_excluded_hosts() as $excluded ) { if( $host === $excluded || substr( $host, -strlen( '.' . $excluded ) ) === '.' . $excluded ) { return false; } } if( empty( $this->settings['http_request_log_errors_only'] ) ) { return true; } if( is_wp_error( $response ) ) { return true; } return (int) wp_remote_retrieve_response_code( $response ) >= 400; } /** * Reads the excluded host list from the settings. * * @return array List of host names. */ private function get_excluded_hosts(): array { $raw = (string) ( $this->settings['http_request_log_exclude_hosts'] ?? '' ); if( '' === trim( $raw ) ) { return []; } $hosts = preg_split( '/[\r\n]+/', $raw ); $hosts = array_map( 'trim', (array) $hosts ); $hosts = array_map( 'strtolower', $hosts ); return array_filter( $hosts ); } /** * Builds a readable, credential-free copy of the request arguments. * * @param array $parsed_args The request arguments. * * @return string JSON encoded arguments. */ private function format_request_args( array $parsed_args ): string { unset( $parsed_args['cookies'], $parsed_args['stream'], $parsed_args['filename'] ); if( isset( $parsed_args['headers'] ) && is_array( $parsed_args['headers'] ) ) { foreach( $parsed_args['headers'] as $header => $value ) { if( in_array( strtolower( (string) $header ), [ 'authorization', 'cookie', 'x-api-key' ], true ) ) { $parsed_args['headers'][ $header ] = '***'; } } } if( isset( $parsed_args['body'] ) && !is_scalar( $parsed_args['body'] ) ) { $parsed_args['body'] = wp_json_encode( $parsed_args['body'] ); } if( isset( $parsed_args['body'] ) && mb_strlen( (string) $parsed_args['body'] ) > 5000 ) { $parsed_args['body'] = mb_substr( (string) $parsed_args['body'], 0, 5000 ) . '…'; } $json = wp_json_encode( $parsed_args, JSON_PRETTY_PRINT ); return false === $json ? '' : $json; } /** * Flattens the response headers into one header per line. * * @param array $response The response returned by the transport. * * @return string The formatted headers. */ private function format_response_headers( $response ): string { $headers = wp_remote_retrieve_headers( $response ); if( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) { $headers = $headers->getAll(); } if( !is_array( $headers ) ) { return ''; } $lines = []; foreach( $headers as $name => $value ) { $lines[] = $name . ': ' . ( is_array( $value ) ? implode( ', ', $value ) : $value ); } return implode( PHP_EOL, $lines ); } /** * Stores the start of the response body when the setting allows it. * * @param array|WP_Error $response The response or error returned by the transport. * @param bool $is_error Whether the response is a WP_Error. * * @return string The stored body. */ private function maybe_store_body( $response, bool $is_error ): string { if( $is_error || empty( $this->settings['http_request_log_store_response'] ) ) { return ''; } $body = (string) wp_remote_retrieve_body( $response ); if( mb_strlen( $body ) > 51200 ) { $body = mb_substr( $body, 0, 51200 ) . '…'; } return $body; } /** * Works out which plugin, theme or core file triggered the request. * * @return string A readable origin. */ private function detect_context(): string { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- The call stack is the only way to attribute a request to its caller. $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 25 ); foreach( $backtrace as $frame ) { if( empty( $frame['file'] ) ) { continue; } $file = wp_normalize_path( $frame['file'] ); if( false !== strpos( $file, '/plugins/adminease' ) ) { continue; } if( preg_match( '#/plugins/([^/]+)/#', $file, $matches ) ) { /* translators: %s: plugin folder name */ return sprintf( __( 'Plugin: %s', 'adminease' ), $matches[1] ); } if( preg_match( '#/themes/([^/]+)/#', $file, $matches ) ) { /* translators: %s: theme folder name */ return sprintf( __( 'Theme: %s', 'adminease' ), $matches[1] ); } } if( wp_doing_cron() ) { return __( 'WordPress cron', 'adminease' ); } return __( 'WordPress core', 'adminease' ); } /** * Inserts a single entry into the log table. * * @param array $data The 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'], 'url' => $data['url'], 'host' => $data['host'], 'method' => $data['method'], 'status_code' => $data['status_code'], 'duration' => $data['duration'], 'is_error' => $data['is_error'], 'error_message' => $data['error_message'], 'request_args' => $data['request_args'], 'response_headers' => $data['response_headers'], 'response_body' => $data['response_body'], 'context' => $data['context'], 'user_id' => $data['user_id'] > 0 ? $data['user_id'] : null, ], [ '%s', '%s', '%s', '%s', '%d', '%f', '%d', '%s', '%s', '%s', '%s', '%s', '%d', ] ); } /** * Trims the table down to the configured maximum number of entries. * * @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 $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. * * @return int The maximum number of entries. */ private function get_max_entries(): int { return !empty( $this->settings['http_request_log_max_entries'] ) ? (int) $this->settings['http_request_log_max_entries'] : 1000; } /** * Retrieves the auto-clear period. * * @return string The auto-clear period value. */ private function get_auto_clear_period(): string { return !empty( $this->settings['http_request_log_auto_clear'] ) ? $this->settings['http_request_log_auto_clear'] : '24_hours'; } /** * Deletes entries older than the configured auto-clear period. * * @return void */ public function cleanup_old_logs(): void { $auto_clear = $this->get_auto_clear_period(); if( 'never' === $auto_clear ) { return; } global $wpdb; $time_map = [ '1_hour' => 3600, '24_hours' => 86400, '7_days' => 604800, '30_days' => 2592000, ]; $seconds = $time_map[ $auto_clear ] ?? 86400; $cutoff_time = gmdate( 'Y-m-d H:i:s', time() - $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 page of logged requests. * * @param array $args Query arguments. * * @return array Array of log entries. */ public function get_requests( array $args = [] ): array { global $wpdb; $defaults = [ 'per_page' => 50, 'page' => 1, 'status' => '', 'method' => '', 'search' => '', 'orderby' => 'timestamp', 'order' => 'DESC', ]; $args = wp_parse_args( $args, $defaults ); $allowed_orderby = [ 'timestamp', 'host', 'method', 'status_code', 'duration' ]; $orderby = in_array( $args['orderby'], $allowed_orderby, true ) ? $args['orderby'] : 'timestamp'; $order = 'ASC' === strtoupper( $args['order'] ) ? 'ASC' : 'DESC'; $per_page = (int) $args['per_page']; $offset = ( (int) $args['page'] - 1 ) * $per_page; $where = []; $where_values = []; if( 'error' === $args['status'] ) { $where[] = 'is_error = 1'; } elseif( 'success' === $args['status'] ) { $where[] = 'is_error = 0'; } if( !empty( $args['method'] ) ) { $where[] = 'method = %s'; $where_values[] = $args['method']; } if( !empty( $args['search'] ) ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $where[] = '(url LIKE %s OR context LIKE %s OR error_message LIKE %s)'; $where_values[] = $like; $where_values[] = $like; $where_values[] = $like; } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; $params = array_merge( $where_values, [ $per_page, $offset ] ); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT * FROM {$this->table_name} $where_clause ORDER BY $orderby $order LIMIT %d OFFSET %d", $params ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return $wpdb->get_results( $query, ARRAY_A ); } /** * Retrieves the total number of logged requests matching the filters. * * @param array $args Query arguments. * * @return int Total count. */ public function get_total_count( array $args = [] ): int { global $wpdb; $where = []; $where_values = []; if( isset( $args['status'] ) && 'error' === $args['status'] ) { $where[] = 'is_error = 1'; } elseif( isset( $args['status'] ) && 'success' === $args['status'] ) { $where[] = 'is_error = 0'; } if( !empty( $args['method'] ) ) { $where[] = 'method = %s'; $where_values[] = $args['method']; } if( !empty( $args['search'] ) ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $where[] = '(url LIKE %s OR context LIKE %s OR error_message LIKE %s)'; $where_values[] = $like; $where_values[] = $like; $where_values[] = $like; } if( empty( $where ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); } $where_clause = 'WHERE ' . implode( ' AND ', $where ); if( empty( $where_values ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name} $where_clause" ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} $where_clause", $where_values ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter return (int) $wpdb->get_var( $query ); } /** * Empties the log table. * * @return bool True if successful, false otherwise. */ public function clear_requests(): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Intentional log clearing return false !== $wpdb->query( "TRUNCATE TABLE {$this->table_name}" ); } /** * AJAX handler that returns a rendered page of the request log. * * @return void */ public function ajax_get_http_request_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_get_http_request_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' ) ) ); } $args = [ 'page' => isset( $_POST['page'] ) ? (int) $_POST['page'] : 1, 'per_page' => isset( $_POST['per_page'] ) ? (int) $_POST['per_page'] : 50, 'status' => isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '', 'method' => isset( $_POST['method'] ) ? sanitize_text_field( wp_unslash( $_POST['method'] ) ) : '', 'search' => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '', ]; $requests = $this->get_requests( $args ); $total = $this->get_total_count( $args ); foreach( $requests as &$request ) { $request['formatted_time'] = $this->format_timestamp( (string) ( $request['timestamp'] ?? '' ) ); if( !empty( $request['user_id'] ) ) { $user = get_userdata( (int) $request['user_id'] ); $request['username_text'] = $user ? $user->user_login : esc_html__( 'Unknown', 'adminease' ); } else { $request['username_text'] = esc_html__( 'System', 'adminease' ); } } unset( $request ); wp_send_json_success( [ 'table_html' => $this->render_log_table( $requests ), 'total' => $total, 'page' => $args['page'], 'per_page' => $args['per_page'], ] ); } /** * AJAX handler that empties the request log. * * @return void */ public function ajax_clear_http_request_log(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_clear_http_request_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' ) ) ); } if( $this->clear_requests() ) { wp_send_json_success( esc_html__( 'HTTP request log cleared successfully.', 'adminease' ) ); } wp_send_json_error( new WP_Error( 'clear_failed', __( 'Failed to clear the HTTP request log.', 'adminease' ) ) ); } /** * Renders the log table rows. * * @param array $requests Array of log entries. * * @return string The rendered HTML rows. */ public function render_log_table( array $requests ): string { if( empty( $requests ) ) { return ''; } ob_start(); foreach( $requests as $request ) { $url = $request['url'] ?? ''; $short_url = mb_strlen( $url ) > 70 ? mb_substr( $url, 0, 70 ) . '...' : $url; $duration = (float) ( $request['duration'] ?? 0 ); ?> get_status_label( $request ) ); ?> getTimestamp() ); } /** * Picks the badge colour for a response code. * * @param array $request A log entry. * * @return string CSS class. */ private function get_status_class( array $request ): string { if( !empty( $request['is_error'] ) ) { return 'pwp-badge-fail'; } $code = (int) ( $request['status_code'] ?? 0 ); if( $code >= 300 && $code < 400 ) { return 'pwp-badge-citron'; } return 'pwp-badge-success'; } /** * Builds the text shown in the response code column. * * @param array $request A log entry. * * @return string The response code or a failure label. */ private function get_status_label( array $request ): string { $code = (int) ( $request['status_code'] ?? 0 ); if( $code > 0 ) { return (string) $code; } return __( 'Failed', 'adminease' ); } /** * Picks the highlight class for how long a request took. * * @param float $duration Duration in milliseconds. * * @return string CSS class. */ private function get_duration_class( float $duration ): string { if( $duration >= 3000 ) { return 'duration-slow'; } if( $duration >= 1000 ) { return 'duration-medium'; } return ''; } /** * 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, url text NOT NULL, host varchar(191) DEFAULT NULL, method varchar(10) DEFAULT 'GET', status_code smallint(5) unsigned DEFAULT 0, duration float DEFAULT 0, is_error tinyint(1) DEFAULT 0, error_message text DEFAULT NULL, request_args longtext DEFAULT NULL, response_headers text DEFAULT NULL, response_body longtext DEFAULT NULL, context varchar(255) DEFAULT NULL, user_id bigint(20) unsigned DEFAULT NULL, PRIMARY KEY (id), KEY timestamp (timestamp), KEY host (host), KEY is_error (is_error), KEY method (method) ) {$charset_collate};"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * 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 $wpdb->query( "DROP TABLE IF EXISTS {$this->table_name}" ); } }