Site Health > Info, so a merchant can paste one block into a support ticket. * * Registered from the plugin bootstrap, not from Init: Init never runs without WooCommerce, and * this section is needed exactly when the plugin is half-working. Nothing is read until Site * Health asks for the debug information. No field is marked private because every value is * already redacted by the Logger or is a version, a table name or a time. * * @since 2.8.4 */ final class DiagnosticsDebugInfo { /** Site Health section key. */ public const SECTION = 'aipt_diagnostics'; /** * Seconds a cron event may be late before it is reported as overdue. Until then it is only * due: WP-Cron runs on page loads, so a quiet site is always a little late. */ public const OVERDUE_AFTER_SECONDS = 3600; /** Number of logged events listed. */ public const MAX_EVENTS = 10; /** Prefix of the cron hooks that belong to the plugin. */ private const CRON_HOOK_PREFIX = 'aipt_'; /** * Hook the section into Site Health. Safe to call more than once. * * @return void */ public static function register(): void { if ( false === has_filter( 'debug_information', array( self::class, 'addSection' ) ) ) { add_filter( 'debug_information', array( self::class, 'addSection' ) ); } } /** * Add the section to the Site Health debug data. * * @param mixed $info Debug information sections. * @return mixed */ public static function addSection( $info ) { if ( ! is_array( $info ) ) { return $info; } $fields = array_merge( self::versionFields(), self::tableFields(), self::cronFields(), self::eventFields() ); $info[ self::SECTION ] = array( 'label' => __( 'AI Product Tools: diagnostics', 'ai-product-tools' ), 'description' => __( 'Versions, database tables, scheduled tasks and the latest logged problems. Values are redacted and safe to paste into a support ticket.', 'ai-product-tools' ), 'fields' => $fields, ); return $info; } /** * Plugin and schema versions, stored and expected. * * @return array> */ private static function versionFields(): array { $not_stored = __( 'Not stored', 'ai-product-tools' ); $running = defined( 'AIPT_VERSION' ) ? (string) AIPT_VERSION : __( 'Unknown', 'ai-product-tools' ); return array( 'plugin_version_stored' => self::field( __( 'Plugin version (stored)', 'ai-product-tools' ), self::storedVersion( 'aipt_version', $not_stored ) ), 'plugin_version_running' => self::field( __( 'Plugin version (running)', 'ai-product-tools' ), $running ), 'schema_version_stored' => self::field( __( 'Database schema version (stored)', 'ai-product-tools' ), self::storedVersion( 'aipt_schema_version', $not_stored ) ), 'schema_version_wanted' => self::field( __( 'Database schema version (expected)', 'ai-product-tools' ), self::expectedSchemaVersion() ), ); } /** * Missing tables and the last schema error. * * @return array> */ private static function tableFields(): array { $none = __( 'None', 'ai-product-tools' ); $missing = self::missingTables(); if ( null === $missing ) { $missing_value = __( 'Could not be checked', 'ai-product-tools' ); } else { $missing_value = array() === $missing ? $none : implode( ', ', $missing ); } $error = Logger::lastError( 'schema' ); $error_value = $none; if ( null !== $error ) { $error_value = self::formatTime( (int) $error['last'] ) . ' - ' . Logger::redact( (string) $error['event'] ); if ( isset( $error['context']['error'] ) && is_string( $error['context']['error'] ) ) { $error_value .= ': ' . Logger::redact( $error['context']['error'] ); } } return array( 'database_upgrade' => self::field( __( 'Database upgrade', 'ai-product-tools' ), self::upgradeStateText() ), 'missing_tables' => self::field( __( 'Missing database tables', 'ai-product-tools' ), $missing_value ), 'last_schema_error' => self::field( __( 'Last schema error', 'ai-product-tools' ), $error_value ), ); } /** * The schema upgrade state in words. * * @return string */ private static function upgradeStateText(): string { self::loadMigration(); $state = Migration::schema_status()['state']; if ( 'failed' === $state ) { return __( 'Failed', 'ai-product-tools' ); } return 'pending' === $state ? __( 'Pending', 'ai-product-tools' ) : __( 'Up to date', 'ai-product-tools' ); } /** * WP-Cron state and one row per scheduled plugin hook. * * @return array> */ private static function cronFields(): array { $disabled = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON; $fields = array( 'wp_cron' => self::field( __( 'WP-Cron', 'ai-product-tools' ), $disabled ? __( 'Not started by page loads (DISABLE_WP_CRON). Tasks run only when a server cron calls wp-cron.php.', 'ai-product-tools' ) : __( 'Started by page loads', 'ai-product-tools' ) ), ); $now = time(); foreach ( self::nextRunByHook() as $hook => $timestamp ) { if ( $timestamp > $now ) { /* translators: %s: length of time, for example "5 minutes" */ $value = sprintf( __( 'Next run in %s', 'ai-product-tools' ), human_time_diff( $now, $timestamp ) ); } elseif ( $now - $timestamp > self::OVERDUE_AFTER_SECONDS ) { /* translators: %s: length of time, for example "3 hours" */ $value = sprintf( __( 'Overdue by %s', 'ai-product-tools' ), human_time_diff( $timestamp, $now ) ); } else { /* translators: %s: length of time, for example "5 minutes" */ $value = sprintf( __( 'Due %s ago', 'ai-product-tools' ), human_time_diff( $timestamp, $now ) ); } $fields[ 'cron_' . $hook ] = self::field( $hook, $value ); } return $fields; } /** * The latest logged events, newest first, one row each. * * @return array> */ private static function eventFields(): array { $entries = array_slice( array_reverse( Logger::recent() ), 0, self::MAX_EVENTS ); if ( array() === $entries ) { return array( 'events' => self::field( __( 'Logged events', 'ai-product-tools' ), __( 'None', 'ai-product-tools' ) ), ); } $fields = array(); foreach ( $entries as $index => $entry ) { $position = $index + 1; /* translators: %d: position of the event in the list, newest first */ $label = sprintf( __( 'Logged event %d', 'ai-product-tools' ), $position ); $detail = self::contextText( $entry['context'] ); $value = sprintf( '%s | %s | %s%s | x%d | %s', Logger::redact( (string) $entry['level'] ), Logger::redact( (string) $entry['channel'] ), Logger::redact( (string) $entry['event'] ), '' === $detail ? '' : ' (' . $detail . ')', (int) $entry['count'], self::formatTime( (int) $entry['last'] ) ); $fields[ 'event_' . $position ] = self::field( $label, $value ); } return $fields; } /** * The stored context of an event as one line, for example `error: Table missing, hook: aipt_x`. * The Logger redacted every value when it stored it; this redacts the joined line once more * and so also cuts it to the Logger's text length. * * @param mixed $context Stored context. * @return string */ private static function contextText( $context ): string { if ( ! is_array( $context ) ) { return ''; } $parts = array(); foreach ( $context as $key => $value ) { if ( is_bool( $value ) ) { $value = $value ? 'true' : 'false'; } if ( is_scalar( $value ) && '' !== (string) $value ) { $parts[] = $key . ': ' . $value; } } return array() === $parts ? '' : Logger::redact( implode( ', ', $parts ) ); } /** * Required plugin tables that the database does not have. * * @return string[]|null Missing names, or null when the check could not run. */ public static function missingTables(): ?array { global $wpdb; if ( ! is_object( $wpdb ) ) { return null; } self::loadMigration(); $like = $wpdb->esc_like( $wpdb->prefix . 'aipt_' ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Schema diagnostics; SHOW TABLES has no WP API equivalent $existing = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $like ) ); if ( ! is_array( $existing ) || ! empty( $wpdb->last_error ) ) { return null; } return Migration::missing_table_names( $existing ); } /** * Schema version the running code expects. * * @return string */ private static function expectedSchemaVersion(): string { self::loadMigration(); return Migration::DB_SCHEMA_VERSION; } /** * Load the Migration class, which is deliberately not autoloaded and has no WooCommerce dependency. * * @return void */ private static function loadMigration(): void { if ( ! class_exists( Migration::class, false ) ) { require_once AIPT_PLUGIN_DIR . 'src/Core/Database/Migration.php'; } } /** * Earliest scheduled run of every plugin cron hook. * * @return array Hook name to timestamp. */ private static function nextRunByHook(): array { $cron = _get_cron_array(); if ( ! is_array( $cron ) ) { return array(); } $runs = array(); foreach ( $cron as $timestamp => $hooks ) { if ( ! is_array( $hooks ) ) { continue; } foreach ( array_keys( $hooks ) as $hook ) { $hook = (string) $hook; if ( 0 !== strpos( $hook, self::CRON_HOOK_PREFIX ) ) { continue; } if ( ! isset( $runs[ $hook ] ) || (int) $timestamp < $runs[ $hook ] ) { $runs[ $hook ] = (int) $timestamp; } } } ksort( $runs ); return $runs; } /** * A stored version option as text. * * @param string $option Option name. * @param string $fallback Text for a missing or non-text value. * @return string */ private static function storedVersion( string $option, string $fallback ): string { $value = get_option( $option, '' ); return is_string( $value ) && '' !== $value ? Logger::redact( $value ) : $fallback; } /** * Format a Unix time as UTC text. * * @param int $timestamp Unix time. * @return string */ private static function formatTime( int $timestamp ): string { return gmdate( 'Y-m-d H:i:s', $timestamp ) . ' UTC'; } /** * One Site Health field. * * @param string $label Field label. * @param string $value Field value. * @return array */ private static function field( string $label, string $value ): array { return array( 'label' => $label, 'value' => $value, ); } }