prefix . 'schema_ai_generations' ); $cutoff_logs = gmdate( 'Y-m-d H:i:s', strtotime( '-' . self::LOG_RETENTION_DAYS . ' days' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; write/DDL operation, caching not applicable. $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "DELETE FROM {$generations_table} WHERE created_at < %s", $cutoff_logs ) ); // 2. Delete analytics data older than 90 days. $analytics_table = esc_sql( $wpdb->prefix . 'schema_ai_analytics' ); $cutoff_analytics = gmdate( 'Y-m-d', strtotime( '-' . self::ANALYTICS_RETENTION_DAYS . ' days' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; write/DDL operation, caching not applicable. $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "DELETE FROM {$analytics_table} WHERE date < %s", $cutoff_analytics ) ); // 3. Clear expired transients matching the schema_ai_ prefix. $this->clear_expired_transients(); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'Schema AI: Daily cleanup completed.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Daily usage reset cron callback. * * Runs on the `schema_ai_usage_reset` hook. Usage counters are date-based * so no actual "reset" is needed. This method cleans up old usage rows * beyond the retention period. * * @return void */ public function usage_reset() { global $wpdb; $usage_table = esc_sql( $wpdb->prefix . 'schema_ai_usage' ); $cutoff_usage = gmdate( 'Y-m-d', strtotime( '-' . self::USAGE_RETENTION_DAYS . ' days' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; write/DDL operation, caching not applicable. $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "DELETE FROM {$usage_table} WHERE date < %s", $cutoff_usage ) ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'Schema AI: Usage cleanup completed.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Analytics sync cron callback. * * Runs on the `schema_ai_analytics_sync` hook. If the site is connected * to the Schema AI SaaS via an API key, syncs aggregated stats upstream. * * @return void */ public function analytics_sync() { $settings = get_option( 'schema_ai_settings', array() ); $api_key = ! empty( $settings['saas_api_key'] ) ? $settings['saas_api_key'] : ''; if ( empty( $api_key ) ) { return; } // Gather stats to send. $stats = $this->gather_sync_stats(); if ( empty( $stats ) ) { return; } $api_url = defined( 'SCHEMA_AI_API_BASE' ) ? SCHEMA_AI_API_BASE : 'https://api.aischemagen.com/api/v1'; $response = wp_remote_post( $api_url . '/analytics/sync', array( 'timeout' => 30, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ), 'body' => wp_json_encode( $stats ), ) ); if ( is_wp_error( $response ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'Schema AI: Analytics sync failed: ' . $response->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } return; } $code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $code && 201 !== $code ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'Schema AI: Analytics sync returned HTTP ' . $code ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } return; } // Mark sync time. update_option( 'schema_ai_last_analytics_sync', current_time( 'mysql', true ) ); } /** * Validate a single schema by ID. * * Runs on the `schema_ai_validate` single-event hook. Loads the schema * row from the database, runs it through the validator, and updates * the validation columns. * * @param int $schema_id The schema row ID. * @return void */ public function validate_schema( $schema_id ) { global $wpdb; $table = esc_sql( $wpdb->prefix . 'schema_ai_schemas' ); $schema_id = absint( $schema_id ); if ( ! $schema_id ) { return; } // Load schema row. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $row = $wpdb->get_row( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT * FROM {$table} WHERE id = %d LIMIT 1", $schema_id ) ); if ( ! $row ) { return; } $schema_data = json_decode( $row->schema_data, true ); if ( ! is_array( $schema_data ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; write operation (UPDATE), caching not applicable. $wpdb->update( $table, array( 'validation_status' => 'invalid', 'validation_errors' => wp_json_encode( array( __( 'Schema data is not valid JSON.', 'ai-schema-gen' ) ) ), 'last_validated' => current_time( 'mysql', true ), ), array( 'id' => $schema_id ), array( '%s', '%s', '%s' ), array( '%d' ) ); return; } // Run through the validator. if ( ! class_exists( 'Schema_AI_Schema_Validator' ) ) { $validator_file = dirname( dirname( __FILE__ ) ) . '/schema/class-schema-validator.php'; if ( file_exists( $validator_file ) ) { require_once $validator_file; } else { return; } } $validator = new Schema_AI_Schema_Validator(); $result = $validator->validate( $schema_data ); $status = 'valid'; if ( ! $result['valid'] ) { $status = 'invalid'; } elseif ( ! empty( $result['warnings'] ) ) { $status = 'warnings'; } $errors_json = null; if ( ! empty( $result['errors'] ) || ! empty( $result['warnings'] ) ) { $errors_json = wp_json_encode( array( 'errors' => $result['errors'], 'warnings' => $result['warnings'], 'score' => $result['score'], ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; write operation (UPDATE), caching not applicable. $wpdb->update( $table, array( 'validation_status' => $status, 'validation_errors' => $errors_json, 'last_validated' => current_time( 'mysql', true ), ), array( 'id' => $schema_id ), array( '%s', '%s', '%s' ), array( '%d' ) ); } /** * Bulk validate schemas that need re-validation. * * Runs on the `schema_ai_bulk_validate` hook. Selects schemas with * validation_status = 'pending' or those not validated in the last 7 days. * Processes up to VALIDATE_BATCH_LIMIT per run. * * @return void */ public function bulk_validate() { global $wpdb; $table = esc_sql( $wpdb->prefix . 'schema_ai_schemas' ); $revalidate_date = gmdate( 'Y-m-d H:i:s', strtotime( '-' . self::REVALIDATE_AFTER_DAYS . ' days' ) ); // Get schemas that need validation. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $schemas = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT id FROM {$table} WHERE validation_status = 'pending' OR last_validated IS NULL OR last_validated < %s ORDER BY last_validated ASC, id ASC LIMIT %d", $revalidate_date, self::VALIDATE_BATCH_LIMIT ) ); if ( empty( $schemas ) ) { return; } foreach ( $schemas as $schema ) { $this->validate_schema( $schema->id ); } if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'Schema AI: Bulk validation completed. Processed ' . count( $schemas ) . ' schemas.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Schedule all recurring cron events. * * Called during plugin activation to ensure all cron events are * registered. Safe to call multiple times; checks for existing * scheduled events before adding. * * @return void */ public static function schedule_events() { // Daily cleanup. if ( ! wp_next_scheduled( 'schema_ai_daily_cleanup' ) ) { wp_schedule_event( time(), 'daily', 'schema_ai_daily_cleanup' ); } // Daily usage reset. if ( ! wp_next_scheduled( 'schema_ai_usage_reset' ) ) { wp_schedule_event( strtotime( 'tomorrow midnight' ), 'daily', 'schema_ai_usage_reset' ); } // Twice-daily analytics sync. if ( ! wp_next_scheduled( 'schema_ai_analytics_sync' ) ) { wp_schedule_event( time(), 'twicedaily', 'schema_ai_analytics_sync' ); } // Weekly bulk validation. if ( ! wp_next_scheduled( 'schema_ai_bulk_validate' ) ) { wp_schedule_event( time(), 'weekly', 'schema_ai_bulk_validate' ); } } /** * Unschedule all plugin cron events. * * Called during plugin deactivation. * * @return void */ public static function unschedule_events() { $hooks = array( 'schema_ai_daily_cleanup', 'schema_ai_usage_reset', 'schema_ai_analytics_sync', 'schema_ai_bulk_validate', ); foreach ( $hooks as $hook ) { $timestamp = wp_next_scheduled( $hook ); if ( $timestamp ) { wp_unschedule_event( $timestamp, $hook ); } } } /** * Clear expired transients matching the schema_ai_ prefix. * * @return int Number of transients deleted. */ private function clear_expired_transients() { global $wpdb; $prefix = '_transient_timeout_schema_ai_'; $now = time(); // Find expired transients. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $expired = $wpdb->get_col( $wpdb->prepare( 'SELECT option_name FROM ' . $wpdb->options . ' WHERE option_name LIKE %s AND option_value < %d', $wpdb->esc_like( $prefix ) . '%', $now ) ); $count = 0; foreach ( $expired as $timeout_option ) { // Convert '_transient_timeout_schema_ai_xxx' to 'schema_ai_xxx'. $transient_name = str_replace( '_transient_timeout_', '', $timeout_option ); if ( delete_transient( $transient_name ) ) { $count++; } } return $count; } /** * Gather aggregated stats for the analytics sync. * * @return array Stats payload for the SaaS API. */ private function gather_sync_stats() { global $wpdb; $schemas_table = esc_sql( $wpdb->prefix . 'schema_ai_schemas' ); $usage_table = esc_sql( $wpdb->prefix . 'schema_ai_usage' ); // Total schemas count. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $total_schemas = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT COUNT(*) FROM {$schemas_table}" ); // Schemas by type. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $type_counts = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT schema_type, COUNT(*) as count FROM {$schemas_table} GROUP BY schema_type", ARRAY_A ); $types = array(); if ( is_array( $type_counts ) ) { foreach ( $type_counts as $row ) { $types[ $row['schema_type'] ] = (int) $row['count']; } } // Validation stats. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $valid_count = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT COUNT(*) FROM {$schemas_table} WHERE validation_status = %s", 'valid' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $invalid_count = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT COUNT(*) FROM {$schemas_table} WHERE validation_status = %s", 'invalid' ) ); // Recent usage (last 7 days). $recent_date = gmdate( 'Y-m-d', strtotime( '-7 days' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for custom table; no WP API alternative exists. $recent_usage = $wpdb->get_row( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized via esc_sql() and not user input. "SELECT COALESCE(SUM(ai_generations), 0) as ai_generations, COALESCE(SUM(manual_generations), 0) as manual_generations, COALESCE(SUM(validations), 0) as validations FROM {$usage_table} WHERE date >= %s", $recent_date ), ARRAY_A ); return array( 'site_url' => home_url(), 'wp_version' => get_bloginfo( 'version' ), 'plugin_version' => defined( 'SCHEMA_AI_VERSION' ) ? SCHEMA_AI_VERSION : '1.0.0', 'total_schemas' => $total_schemas, 'schemas_by_type' => $types, 'valid_count' => $valid_count, 'invalid_count' => $invalid_count, 'recent_usage' => $recent_usage ? $recent_usage : array(), 'synced_at' => current_time( 'mysql', true ), ); } }