$e->getMessage(), 'table' => $name )`. * - Pass ids, counts, versions and exception messages only. Never pass prompts, generated * content, customer data, API keys or stack traces. A context key whose name contains key, * token, secret, password, authorization, prompt, content, email, cookie or nonce is stored as * `[REDACTED]`, but the key list is a safety net, not a licence. * * Storage: `error` and `warn` entries live in the option `aipt_diagnostic_log` (autoload off, one * row per site on multisite), a ring of at most 30 entries ordered by when each event last * happened. A full ring evicts the oldest warn entry first and never evicts the newest error of * a channel. The same event with the same context inside 300 seconds is dropped without any * write, and one event is written at most three times in 300 seconds however its context * varies, so a failure that repeats on every request costs one read of the option. Both counts * are taken from the ring: an entry that other events pushed out of it no longer counts, so * more than 30 writes of other events inside the window let an event through again. Two requests * that append at the same moment can lose one entry, and a read that fails is taken for an * empty ring, so the next write replaces the history: this is diagnostics, so there is no lock * and no retry. * * The class stands alone on purpose. It is called from Migration, cron callbacks, the Activator * and the Uninstaller, so it depends on no other plugin class, and every public method catches * Throwable and never throws. * * @since 2.8.4 */ final class Logger { /** Option that holds the ring. */ public const OPTION = 'aipt_diagnostic_log'; /** Maximum number of stored entries. */ public const MAX_ENTRIES = 30; /** Seconds during which an identical event is not written again. */ public const THROTTLE_SECONDS = 300; /** * Times one event is written inside the throttle window, however its context varies. * Counted over the entries that are still in the ring. */ public const MAX_WRITES_PER_EVENT = 3; /** Maximum length of any stored text. */ public const MAX_TEXT_LENGTH = 300; /** Maximum number of context keys per entry. */ public const MAX_CONTEXT_KEYS = 12; /** Stored level for failures. */ private const LEVEL_ERROR = 'error'; /** Stored level for recoverable problems. */ private const LEVEL_WARN = 'warn'; /** Maximum length of an event phrase. */ private const MAX_EVENT_LENGTH = 120; /** Characters of a raw text the redaction rules look at. */ private const MAX_SCAN_LENGTH = 4000; /** Context key fragments whose values are never stored. */ private const SENSITIVE_KEY_PARTS = array( 'key', 'token', 'secret', 'password', 'authorization', 'prompt', 'content', 'email', 'cookie', 'nonce', ); /** * Record a failure. Also writes one line to the PHP error log when the entry was recorded. * * @param string $channel Short slug. * @param string $event Short fixed English phrase. * @param array $context Variable details. * @return void */ public static function error( string $channel, string $event, array $context = array() ): void { try { $entry = self::record( self::LEVEL_ERROR, $channel, $event, $context ); if ( null !== $entry ) { self::writePhpLog( self::LEVEL_ERROR, $entry['channel'], $entry['event'], $entry['context'] ); } } catch ( \Throwable $e ) { return; } } /** * Record a recoverable problem. Stored only, never written to the PHP error log. * * @param string $channel Short slug. * @param string $event Short fixed English phrase. * @param array $context Variable details. * @return void */ public static function warn( string $channel, string $event, array $context = array() ): void { try { self::record( self::LEVEL_WARN, $channel, $event, $context ); } catch ( \Throwable $e ) { return; } } /** * Write a development line to the PHP error log. Never stored. * * Active only when WP_DEBUG and WP_DEBUG_LOG are both true. * * @param string $channel Short slug. * @param string $event Short fixed English phrase. * @param array $context Variable details. * @return void */ public static function debug( string $channel, string $event, array $context = array() ): void { try { if ( ! self::constantIsTrue( 'WP_DEBUG' ) || ! self::constantIsTrue( 'WP_DEBUG_LOG' ) ) { return; } self::writePhpLog( 'debug', self::cleanChannel( $channel ), self::cleanEvent( $event ), self::cleanContext( $context ) ); } catch ( \Throwable $e ) { return; } } /** * Stored entries, oldest first. * * @return array> */ public static function recent(): array { try { return self::readRing(); } catch ( \Throwable $e ) { return array(); } } /** * Newest stored error, optionally limited to one channel. * * @param string|null $channel Channel slug, or null for any channel. * @return array|null */ public static function lastError( ?string $channel = null ): ?array { try { $wanted = null === $channel ? null : self::cleanChannel( $channel ); $ring = self::readRing(); for ( $i = count( $ring ) - 1; $i >= 0; $i-- ) { if ( self::LEVEL_ERROR !== $ring[ $i ]['level'] ) { continue; } if ( null === $wanted || $wanted === $ring[ $i ]['channel'] ) { return $ring[ $i ]; } } return null; } catch ( \Throwable $e ) { return null; } } /** * Strip secrets, personal data and server paths from a text and cut it to a safe length. * * A safety net, not a guarantee. It masks SQL statements and the values MySQL quotes in its * errors, a credential by its name or its shape, email and IPv4 addresses and absolute * paths. A path outside the WordPress directory is masked only up to its first space. When a * rule cannot run, the whole text is replaced. * * @param string $text Raw text, for example an exception message. * @return string */ public static function redact( string $text ): string { try { $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $text = self::replace( '~<(?!!--|[/!?]?[A-Za-z][A-Za-z0-9-]*(?:[\s/][^<>]*)?>)~', '< ', $text ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Plain PHP keeps the logger free of load-order assumptions. $text = strip_tags( $text ); $text = self::cut( $text, self::MAX_SCAN_LENGTH ); if ( 1 !== preg_match( '//u', $text ) ) { $text = self::replace( '~[^\x00-\x7F]~', '?', $text ); } $text = self::replace( '~\s+~u', ' ', $text ); $text = self::maskServerValues( trim( $text ) ); $patterns = array( '~\b(?:SELECT\s.+?\sFROM|(?:INSERT(?:\s+IGNORE)?|REPLACE)\s+INTO|UPDATE\s+\S+\s+SET|DELETE\s+(?:\S+\s+)?FROM)\s.*~' => '[SQL]', '~(\bnear \').*?(\' at line \d+)~' => '$1[SQL]$2', '~(\bDuplicate entry \').*?(\' for key\b)~' => '$1[VALUE]$2', '~(\bincorrect [\w(), ]+ value: \').*?(\' for column\b)~i' => '$1[VALUE]$2', '~(\bincorrect [\w(), ]+ value: \')(?!\[VALUE\]).*(\')~i' => '$1[VALUE]$2', '~(\bcharacter string: \').*(\')~i' => '$1[VALUE]$2', '~((?:(?:api|secret|private|access)[_-]?key|token|secret|password|passwd|authorization)["\']?\s*[=:]\s*)((?:Bearer|Basic)\s+)?(?!(?:YES|NO)\))(?:"[^"]*"|\'[^\']*\'|[^\s"\'&,;}]+)~i' => '$1$2[REDACTED]', '~\bBearer\s+\S+~i' => 'Bearer [REDACTED]', '~\bBasic\s+(?![A-Z]?[a-z]+(?![A-Za-z0-9+/=]))[A-Za-z0-9+/]{8,}={0,2}~' => 'Basic [REDACTED]', '~\beyJ[A-Za-z0-9_\-]{5,}\.[A-Za-z0-9_\-]{5,}\.[A-Za-z0-9_\-]*~' => '[REDACTED]', '~\bsk-(?:ant-)?[A-Za-z0-9_\-]{8,}~' => '[REDACTED]', '~\bAIza[0-9A-Za-z_\-]{20,}~' => '[REDACTED]', '~\b(?:gh[pousr]_|xox[a-z]-)[A-Za-z0-9_\-]{10,}~' => '[REDACTED]', '~\b(?:AKIA|ASIA)[0-9A-Z]{16,}~' => '[REDACTED]', '~(\b[a-z][a-z0-9+.\-]*://)[^\s/@]+@~i' => '$1[REDACTED]@', '~[\p{L}\p{N}._%+\-]+@[\p{L}\p{N}.\-]+\.\p{L}{2,}~u' => '[EMAIL]', '~\b\d{1,3}(?:\.\d{1,3}){3}\b~' => '[IP]', '~\bfile://[^\s\'"<>]+~i' => '[PATH]', '~(?|*?:]*~' => '[PATH]', '~(?|*?]+~' => '[PATH]', '~(? '[PATH]', '~(? '[REDACTED]', ); foreach ( $patterns as $pattern => $replacement ) { $text = self::replace( $pattern, $replacement, $text ); } return self::cut( $text, self::MAX_TEXT_LENGTH ); } catch ( \Throwable $e ) { return '[REDACTION FAILED]'; } } /** * Remove every stored entry. * * @return void */ public static function clear(): void { try { delete_option( self::OPTION ); } catch ( \Throwable $e ) { return; } } /** * Store one entry unless an identical one was stored recently. * * @param string $level Stored level. * @param string $channel Raw channel. * @param string $event Raw event. * @param array $context Raw context. * @return array|null The sanitized entry, or null when it was throttled. */ private static function record( string $level, string $channel, string $event, array $context ): ?array { $channel = self::cleanChannel( $channel ); $event = self::cleanEvent( $event ); $context = self::cleanContext( $context ); $now = time(); $ring = self::readRing(); $sig = self::signature( $level, $channel, $event, $context ); $match = null; $written = 0; foreach ( $ring as $index => $stored ) { if ( $level !== $stored['level'] || $channel !== $stored['channel'] || $event !== $stored['event'] ) { continue; } $recent = $stored['last'] <= $now && $now - $stored['last'] < self::THROTTLE_SECONDS; if ( $recent ) { ++$written; } if ( $sig === self::signature( $stored['level'], $stored['channel'], $stored['event'], $stored['context'] ) ) { if ( $recent ) { return null; } $match = $index; } } if ( $written >= self::MAX_WRITES_PER_EVENT ) { return null; } if ( null !== $match ) { $entry = $ring[ $match ]; $entry['count'] = $entry['count'] + 1; $entry['last'] = $now; unset( $ring[ $match ] ); $ring[] = $entry; self::save( $ring ); return $entry; } while ( count( $ring ) >= self::MAX_ENTRIES ) { array_splice( $ring, self::pickVictim( $ring ), 1 ); } $entry = array( 't' => $now, 'level' => $level, 'channel' => $channel, 'event' => $event, 'count' => 1, 'last' => $now, 'context' => $context, ); $ring[] = $entry; self::save( $ring ); return $entry; } /** * Write the ring. A failing write is dropped: the logger has nowhere else to report it. * * @param array> $ring Entries. * @return void */ private static function save( array $ring ): void { try { update_option( self::OPTION, array_values( $ring ), false ); } catch ( \Throwable $e ) { return; } } /** * Read and validate the stored ring. * * @return array> */ private static function readRing(): array { try { $raw = get_option( self::OPTION, array() ); } catch ( \Throwable $e ) { return array(); } if ( ! is_array( $raw ) ) { return array(); } $ring = array(); foreach ( $raw as $entry ) { if ( ! is_array( $entry ) || ! isset( $entry['level'], $entry['channel'], $entry['event'] ) ) { continue; } $t = isset( $entry['t'] ) ? (int) $entry['t'] : 0; $ring[] = array( 't' => $t, 'level' => (string) $entry['level'], 'channel' => (string) $entry['channel'], 'event' => (string) $entry['event'], 'count' => isset( $entry['count'] ) ? max( 1, (int) $entry['count'] ) : 1, 'last' => isset( $entry['last'] ) ? (int) $entry['last'] : $t, 'context' => isset( $entry['context'] ) && is_array( $entry['context'] ) ? $entry['context'] : array(), ); } return $ring; } /** * Index of the entry to drop from a full ring: the oldest warn, then the oldest error that * is not the newest of its channel, then the oldest entry. * * @param array> $ring Entries, oldest first. * @return int */ private static function pickVictim( array $ring ): int { $protected = array(); $seen = array(); for ( $i = count( $ring ) - 1; $i >= 0; $i-- ) { if ( self::LEVEL_ERROR === $ring[ $i ]['level'] && ! isset( $seen[ $ring[ $i ]['channel'] ] ) ) { $seen[ $ring[ $i ]['channel'] ] = true; $protected[ $i ] = true; } } foreach ( $ring as $index => $entry ) { if ( self::LEVEL_ERROR !== $entry['level'] ) { return (int) $index; } } foreach ( $ring as $index => $entry ) { if ( ! isset( $protected[ $index ] ) ) { return (int) $index; } } return 0; } /** * Identity of an event for throttling. * * @param string $level Level. * @param string $channel Channel. * @param string $event Event. * @param array $context Sanitized context. * @return string */ private static function signature( string $level, string $channel, string $event, array $context ): string { return md5( $level . '|' . $channel . '|' . $event . '|' . serialize( $context ) ); } /** * Reduce a channel to a short slug. * * @param string $channel Raw channel. * @return string */ private static function cleanChannel( string $channel ): string { $slug = substr( (string) preg_replace( '~[^a-z0-9_\-]~', '', strtolower( $channel ) ), 0, 32 ); return '' === $slug ? 'general' : $slug; } /** * Redact and shorten an event phrase. * * @param string $event Raw event. * @return string */ private static function cleanEvent( string $event ): string { $clean = self::cut( self::redact( $event ), self::MAX_EVENT_LENGTH ); return '' === $clean ? 'unspecified' : $clean; } /** * Bound a context array: few keys, scalar values, redacted strings, no secrets, no traces. * * @param array $context Raw context. * @return array */ private static function cleanContext( array $context ): array { $clean = array(); $count = 0; foreach ( $context as $key => $value ) { if ( $count >= self::MAX_CONTEXT_KEYS ) { break; } ++$count; $name = substr( (string) preg_replace( '~[^A-Za-z0-9_\-]~', '', (string) $key ), 0, 40 ); if ( '' === $name ) { $name = 'key' . $count; } if ( self::isSensitiveKey( $name ) ) { $clean[ $name ] = '[REDACTED]'; } elseif ( is_string( $value ) ) { $clean[ $name ] = false !== strpos( $value, '#0 ' ) ? '[TRACE REMOVED]' : self::redact( $value ); } elseif ( null === $value || is_bool( $value ) || is_int( $value ) || is_float( $value ) ) { $clean[ $name ] = $value; } else { $clean[ $name ] = gettype( $value ); } } return $clean; } /** * Whether a context key name marks a value that must not be stored. * * @param string $name Context key. * @return bool */ private static function isSensitiveKey( string $name ): bool { foreach ( self::SENSITIVE_KEY_PARTS as $part ) { if ( false !== stripos( $name, $part ) ) { return true; } } return false; } /** * Replace the install paths and the database identity with tokens. * * DB_PASSWORD is never read. * * @param string $text Text to mask. * @return string */ private static function maskServerValues( string $text ): string { $map = array( 'WP_CONTENT_DIR' => '[WP_CONTENT]', 'ABSPATH' => '[ABSPATH]/', ); foreach ( $map as $name => $token ) { $value = self::stringConstant( $name ); if ( strlen( $value ) < 4 ) { continue; } $value = rtrim( $value, '/\\' ); $token = rtrim( $token, '/' ); $text = str_replace( array( $value, str_replace( '/', '\\', $value ) ), $token, $text ); } foreach ( array( 'DB_NAME', 'DB_USER', 'DB_HOST' ) as $name ) { $value = self::stringConstant( $name ); if ( '' === $value ) { continue; } $text = self::replace( '~(? $context Sanitized context. * @return void */ private static function writePhpLog( string $level, string $channel, string $event, array $context ): void { $json = array() === $context ? '' : (string) wp_json_encode( $context ); $line = '[AIPT][' . $channel . '][' . $level . '] ' . $event . ( '' === $json ? '' : ' ' . $json ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- The plugin's one sink for the PHP error log. error_log( $line ); } }