publish ?? 0 ) + intval( $counts->draft ?? 0 ) + intval( $counts->pending ?? 0 ) + intval( $counts->private ?? 0 ); } /** * The counted values, plus `counted_at`: when every query last succeeded, * in UTC ISO 8601, or null before that. Each value was counted then or later. * * @return array */ public static function read(): array { $snapshot = self::stored(); if ( null === $snapshot ) { $snapshot = self::refresh(); } elseif ( self::isStale( $snapshot ) ) { $snapshot = self::countAgainLater( $snapshot ); } $counts = $snapshot['values']; $counts['counted_at'] = null !== $snapshot['counted_at'] ? gmdate( 'Y-m-d\TH:i:s\Z', $snapshot['counted_at'] ) : null; return $counts; } /** * The background event: count again. * * @return void */ public static function cron_callback(): void { try { self::refresh(); } catch ( \Throwable $e ) { Logger::error( 'cron', 'Toolkit statistics refresh failed', array( 'error' => $e->getMessage() ) ); } } /** * Queue one background count for a stale count, and show the stale one; * count now when WP-Cron cannot run that event ({@see BackgroundRefresh}). * * @param array{values:array,complete:bool,at:int,counted_at:int|null} $snapshot Stale count. * @return array{values:array,complete:bool,at:int,counted_at:int|null} The count to show. */ private static function countAgainLater( array $snapshot ): array { if ( BackgroundRefresh::RUN_NOW === BackgroundRefresh::request( self::CRON_HOOK ) ) { return self::refresh(); } return $snapshot; } /** * Count again and store the result. A count whose query failed keeps the * value of the previous count (0 when there is none) and marks the result * incomplete, so it is made again sooner; the catalog size and the missing * description count are kept together. A kept value is as old as the count * it came from, so `counted_at` moves only when every query succeeded. * * @return array{values:array,complete:bool,at:int,counted_at:int|null} */ private static function refresh(): array { $previous = self::stored(); $counted = self::count(); $values = array(); foreach ( self::KEYS as $key ) { $fallback = null !== $previous ? $previous['values'][ $key ] : 0; $values[ $key ] = $counted[ $key ] ?? $fallback; } if ( null === $counted['counted_total'] || null === $counted['missing_description'] ) { foreach ( array( 'counted_total', 'missing_description' ) as $key ) { $values[ $key ] = null !== $previous ? $previous['values'][ $key ] : 0; } } $complete = ! in_array( null, $counted, true ); $snapshot = array( 'values' => $values, 'complete' => $complete, 'at' => time(), 'counted_at' => $complete ? time() : ( null !== $previous ? $previous['counted_at'] : null ), ); if ( ! update_option( self::OPTION, $snapshot, false ) && get_option( self::OPTION ) !== $snapshot ) { Logger::error( 'settings', 'Toolkit statistics could not be stored' ); } return $snapshot; } /** * The stored count, or null when there is none. * * @return array{values:array,complete:bool,at:int,counted_at:int|null}|null */ private static function stored(): ?array { $stored = get_option( self::OPTION ); if ( ! is_array( $stored ) || ! is_array( $stored['values'] ?? null ) || ! is_numeric( $stored['at'] ?? null ) ) { return null; } $values = array(); foreach ( self::KEYS as $key ) { $values[ $key ] = intval( $stored['values'][ $key ] ?? 0 ); } return array( 'values' => $values, 'complete' => ! empty( $stored['complete'] ), 'at' => intval( $stored['at'] ), 'counted_at' => is_numeric( $stored['counted_at'] ?? null ) ? intval( $stored['counted_at'] ) : null, ); } /** * Too old, or a complete count made when the catalog had another number * of products (the coverage would pair a missing count with a total from * another moment). A count with a failed query waits its minute either way. * * @param array{values:array,complete:bool,at:int,counted_at:int|null} $snapshot Stored count. * @return bool */ private static function isStale( array $snapshot ): bool { $age = time() - $snapshot['at']; if ( $age < 0 ) { return true; } if ( ! $snapshot['complete'] ) { return $age > self::RETRY_SECONDS; } return $age > self::FRESH_SECONDS || self::catalogSize( wp_count_posts( 'product' ) ) !== $snapshot['values']['counted_total']; } /** * Run the queries. A failed query answers null. * * @return array */ private static function count(): array { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- COUNT queries over the catalog; their result is stored as the snapshot. $counts = array( 'counted_total' => self::countCatalogSize(), 'missing_description' => self::builderCount( 'missing_description', ( new ProductFilterBuilder() )->contentFilters( array( 'without_full' ) ) ), 'ai_generated' => self::countQuery( 'ai_generated', static function () use ( $wpdb ) { return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT post_id) FROM {$wpdb->postmeta} WHERE meta_key = %s", MetaKeys::ROLLUP ) ); } ), 'recent_products' => self::countQuery( 'recent_products', static function () use ( $wpdb ) { return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status IN ('publish', 'draft') AND post_date >= %s", wp_date( 'Y-m-d H:i:s', time() - 7 * DAY_IN_SECONDS ) ) ); } ), 'out_of_stock' => self::countQuery( 'out_of_stock', static function () use ( $wpdb ) { return $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'product' AND p.post_status = 'publish' AND pm.meta_key = '_stock_status' AND pm.meta_value = 'outofstock'" ); } ), 'no_tags' => self::countQuery( 'no_tags', static function () use ( $wpdb ) { return $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} p WHERE p.post_type = 'product' AND p.post_status IN ('publish', 'draft') AND p.ID NOT IN ( SELECT DISTINCT tr.object_id FROM {$wpdb->term_relationships} tr INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'product_tag' )" ); } ), ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $counts; } /** * The catalog size now, or null when its query failed: wp_count_posts() * answers zeros then, which would read as an empty catalog. * * @return int|null */ private static function countCatalogSize(): ?int { global $wpdb; wp_cache_delete( _count_posts_cache_key( 'product' ), 'counts' ); $wpdb->last_error = ''; $counts = wp_count_posts( 'product' ); if ( '' !== (string) $wpdb->last_error ) { Logger::warn( 'settings', 'Dashboard statistic could not be read', array( 'statistic' => 'counted_total', 'error' => (string) $wpdb->last_error ) ); return null; } return self::catalogSize( $counts ); } /** * Count with the shared product filter. A failed count is logged and answers null. * * @param string $statistic Count name, for the log. * @param ProductFilterBuilder $filter The filter to count. * @return int|null */ private static function builderCount( string $statistic, ProductFilterBuilder $filter ): ?int { $count = $filter->countProducts(); if ( null === $count ) { Logger::warn( 'settings', 'Dashboard statistic could not be read', array( 'statistic' => $statistic ) ); } return $count; } /** * Run one COUNT query. A thrown error or a null answer (wpdb answers null * when the database refused the query) is logged and answers null. * * @param string $statistic Count name, for the log. * @param callable $query Runs the query and answers its value. * @return int|null */ private static function countQuery( string $statistic, callable $query ): ?int { global $wpdb; try { $value = $query(); } catch ( Exception $e ) { Logger::warn( 'settings', 'Dashboard statistic could not be read', array( 'statistic' => $statistic, 'error' => $e->getMessage() ) ); return null; } if ( null === $value ) { Logger::warn( 'settings', 'Dashboard statistic could not be read', array( 'statistic' => $statistic, 'error' => (string) $wpdb->last_error ) ); return null; } return intval( $value ); } }