$item ) { $clean[ $key ] = preg_match( '/api.?key|password|authorization|token|nonce|cookie|text|content|title|prompt|input|output|messages|body|response|user.?agent|(?:^|_)ip(?:_address)?$|user_?id|session/i', (string) $key ) ? '[REDACTED]' : accessibility_audio_tts_sanitize_log_data( $item ); } return $clean; } if ( ! is_string( $value ) ) { return $value; } if ( preg_match( '/(?:request|response)\s+body\s*:|"(?:text|content|input|output|messages|prompt)"\s*:/i', $value ) ) { return 'Sensitive diagnostic payload omitted.'; } // Preview labels must not bypass filtering merely because the article says "failed". if ( preg_match( '/\b(?:first\s+[0-9]+\s+char(?:acter)?s?|sentence\s+[0-9]+|chunk\s+[0-9]+\s+preview|(?:post\s+)?title|prompt(?:\s+preview)?(?:\s*\([^)]*\))?)\s*:/i', $value ) ) { return 'Sensitive diagnostic preview omitted.'; } $value = preg_replace( '/\b(?:api[ _-]?key|xi-api-key|password|authorization|cookie|token|nonce)\b[^\r\n:=]*[:=]\s*[^\r\n]+/i', '[REDACTED CREDENTIAL]', $value ); $value = preg_replace( '/\bBearer\s+[a-zA-Z0-9._-]+/i', 'Bearer [REDACTED]', $value ); $value = preg_replace( '/\b(?:original|optimized|input|output|prepared|processed)?\s*text(?:\s+preview|\s+content)?\s*[:=].*$/is', 'text: [REDACTED]', $value ); $value = preg_replace( '/[a-zA-Z0-9.!#$%&\x27*+\/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', '[REDACTED EMAIL]', $value ); $value = preg_replace( '/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/', '[REDACTED IP]', $value ); $value = preg_replace( '~/(?:Users|home)/[^/\s]+/~', '/[REDACTED HOME]/', $value ); return substr( $value, 0, 2000 ); } if ( ! function_exists( 'accessibility_audio_tts_debug_log' ) ) { /** * Safe debug logging function for production environments * * Provides secure logging with automatic sanitization of sensitive data, * noise filtering, and deduplication. Only logs when WP_DEBUG is enabled * and filters to show only critical messages in production. * * @since 1.0.0 * @param string|array $message Debug message or data to log. * @param bool $force Force logging (deprecated, kept for BC). * @return void. */ function accessibility_audio_tts_debug_log( $message, $force = false ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- Kept for backward compatibility. // Only log when WP_DEBUG is enabled. if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) { return; // Do not log anything when core debugging is off. } // Remove unused production/force logic – logging controlled solely by WP_DEBUG. // Safe logging with sanitization. $clean = accessibility_audio_tts_sanitize_log_data( $message ); $sanitized_message = is_string( $clean ) ? $clean : wp_json_encode( $clean ); // Skip very verbose modules unless explicitly enabled. if ( strpos( $sanitized_message, '[Text_Fine_Tuner]' ) !== false ) { return; // Ignore extremely verbose fine-tuner logs. } // Suppress repetitive/noisy lines from cache, tracker, etc. $noisy_patterns = array( '[Settings_Manager] Voice cache', 'Voice cache:', 'Returning cached voices', 'REAL-TIME TRACKER', '[ElevenLabs BEFORE:', '[ElevenLabs AFTER:', ); foreach ( $noisy_patterns as $pattern ) { if ( strpos( $sanitized_message, $pattern ) !== false ) { return; // Skip noisy line. } } // Deduplicate identical messages in the same request. static $seen_messages = array(); if ( isset( $seen_messages[ $sanitized_message ] ) ) { return; // Already logged in this request. } $seen_messages[ $sanitized_message ] = true; // ---------- FINAL NOISE FILTER ----------. // Allow only critical messages (Error/Exception/Failed/Fatal). $critical_patterns = array( 'error', 'exception', 'fatal', 'failed', 'cannot', 'unable' ); $is_critical = false; foreach ( $critical_patterns as $pattern ) { if ( stripos( $sanitized_message, $pattern ) !== false ) { $is_critical = true; break; } } // If not critical, skip. if ( ! $is_critical ) { return; // Skip non-critical lines. } // ------------ Build log entry (EN-only, no [FORCE]) ------------. $timestamp = gmdate( 'Y-m-d H:i:s' ); $log_entry = "[{$timestamp}] AAT: {$sanitized_message}" . PHP_EOL; // Log to plugin-specific log file (WordPress Guidelines compliant). if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { $upload_dir = wp_upload_dir(); $plugin_log_file = $upload_dir['basedir'] . '/accessibility-audio-tts/debug.log'; accessibility_audio_tts_write_to_plugin_log( $log_entry, $plugin_log_file ); } } } // Provide minimal stubs if settings helpers are not defined elsewhere. if ( ! function_exists( 'accessibility_audio_tts_get_settings' ) ) { /** * Get plugin settings * * @return array Plugin settings. */ function accessibility_audio_tts_get_settings() { return get_option( 'accessibility_audio_tts_settings', array() ); } } if ( ! function_exists( 'accessibility_audio_tts_sanitize_settings' ) ) { /** * Sanitize plugin settings * * @param array $settings Settings to sanitize. * @return array Sanitized settings. */ function accessibility_audio_tts_sanitize_settings( $settings ) { return array_map( 'sanitize_text_field', is_array( $settings ) ? $settings : array() ); } } /** * Safely write to plugin-specific log file (WordPress Guidelines compliant) * * Ensures secure file writing within WordPress uploads directory with * automatic log rotation when files exceed size limits. Includes path * validation to prevent directory traversal attacks. * * @since 1.0.0 * @param string $log_entry Log entry to write. * @param string $log_file Path to log file. * @return void. */ function accessibility_audio_tts_write_to_plugin_log( $log_entry, $log_file ) { try { if ( ! class_exists( '\\Accessibility_Audio_TTS\\Core\\Privacy_Lifecycle' ) ) { return; } $directory = \Accessibility_Audio_TTS\Core\Privacy_Lifecycle::log_directory(); // Date-based files allow old records to expire even while today's log is active. $log_file = $directory . '/debug-' . gmdate( 'Y-m-d' ) . '.log'; if ( is_link( $log_file ) || is_dir( $log_file ) ) { return; } $result = @file_put_contents( $log_file, $log_entry, FILE_APPEND | LOCK_EX ); if ( false !== $result ) { @chmod( $log_file, 0600 ); clearstatcache( true, $log_file ); if ( filesize( $log_file ) > 5 * 1024 * 1024 ) { accessibility_audio_tts_rotate_log_file( $log_file ); } } } catch ( \Throwable $error ) { /* Fail closed: diagnostics never fall back to public storage. */ } } /** * Rotate log file when it gets too large * * Creates a backup of the current log file and starts a new one * to prevent log files from consuming excessive disk space. * * @since 1.0.0 * @param string $log_file Path to log file to rotate. * @return void. */ function accessibility_audio_tts_rotate_log_file( $log_file ) { try { if ( realpath( dirname( $log_file ) ) !== realpath( \Accessibility_Audio_TTS\Core\Privacy_Lifecycle::log_directory() ) || ! preg_match( '/^debug-[0-9]{4}-[0-9]{2}-[0-9]{2}\.log$/D', basename( $log_file ) ) || is_link( $log_file ) || is_link( $log_file . '.old' ) ) { return; } } catch ( \Throwable $error ) { return; } $backup_file = $log_file . '.old'; // Remove old backup if exists. if ( file_exists( $backup_file ) ) { wp_delete_file( $backup_file ); } // Initialize WP_Filesystem if not available. global $wp_filesystem; if ( ! $wp_filesystem ) { require_once ABSPATH . 'wp-admin/includes/file.php'; WP_Filesystem(); } // Move current log to backup using WP_Filesystem. if ( $wp_filesystem && $wp_filesystem->exists( $log_file ) ) { $wp_filesystem->move( $log_file, $backup_file, true ); } // Create new empty log file. if ( $wp_filesystem ) { $wp_filesystem->put_contents( $log_file, '' ); } } /** * Production-safe error logging * * Always logs errors regardless of debug settings, but sanitizes * sensitive data like API keys and passwords. Includes contextual * information for better debugging. * * @since 1.0.0 * @param string|array $message Error message or data to log. * @param array $context Additional context information. * @return void. */ function accessibility_audio_tts_error_log( $message, $context = array() ) { $clean = accessibility_audio_tts_sanitize_log_data( $message ); $sanitized_message = is_string( $clean ) ? $clean : wp_json_encode( $clean ); $timestamp = gmdate( 'Y-m-d H:i:s' ); $log_entry = "[{$timestamp}] AAT ERROR: {$sanitized_message}"; if ( ! empty( $context ) ) { $sanitized_context = wp_json_encode( accessibility_audio_tts_sanitize_log_data( $context ) ); $log_entry .= " | Context: {$sanitized_context}"; } $log_entry .= PHP_EOL; // Use plugin-specific log file instead of WordPress debug.log. $upload_dir = wp_upload_dir(); $plugin_log_file = $upload_dir['basedir'] . '/accessibility-audio-tts/debug.log'; accessibility_audio_tts_write_to_plugin_log( $log_entry, $plugin_log_file ); }