'idle', 'mode' => '', 'apply_demand_filter' => '0', 'queue' => [], 'current_games' => [], 'current_provider' => '', 'current_index' => 0, 'current_provider_total' => 0, 'current_provider_done' => 0, 'total_expected' => 0, 'total_providers' => 0, 'total_imported' => 0, 'total_updated' => 0, 'total_skipped' => 0, 'last_error' => '', 'started_at' => '', 'updated_at' => '', 'finished_at' => '', ]; } function affgsc_state(): array { $state = get_option(AFFGSC_STATE_OPT, []); return array_replace(affgsc_default_state(), is_array($state) ? $state : []); } function affgsc_write_state(array $state): void { $state['updated_at'] = affgsc_now(); update_option(AFFGSC_STATE_OPT, array_replace(affgsc_default_state(), $state), false); } function affgsc_start_import(string $mode = 'manual', bool $refresh_manifest = false, array $runtime = []): array { $connection = affgsc_ensure_installation_secret(); if (empty($connection['ok'])) { $state = affgsc_state(); $state['status'] = 'error'; $state['last_error'] = (string)($connection['message'] ?? 'Could not connect securely to AffGate'); affgsc_write_state($state); return $state; } $manifest = affgsc_fetch_manifest($refresh_manifest); if (!empty($manifest['error'])) { $state = affgsc_state(); $state['status'] = 'error'; $state['last_error'] = (string)$manifest['error']; affgsc_write_state($state); return $state; } $settings = affgsc_settings(); $providers = affgsc_manifest_provider_files($manifest); $selected = array_values(array_filter(array_map('sanitize_title', (array)($settings['selected_providers'] ?? [])))); $game_ids = affgsc_parse_id_list((string)($settings['selected_game_ids'] ?? '')); $force_existing_only = !empty($runtime['force_existing_only']); $disable_demand_filter = !empty($runtime['disable_demand_filter']); $update_existing_only = $force_existing_only || (string)($settings['update_existing_only'] ?? '0') === '1'; $apply_demand_filter = $disable_demand_filter ? false : ((string)($settings['import_demand_only'] ?? '0') === '1'); $queue = []; $total_expected = 0; if ($update_existing_only) { $existing_count = count(affgsc_existing_source_ids_map()); if ($existing_count <= 0) { $state = affgsc_state(); $state['status'] = 'error'; $state['last_error'] = 'No existing games found to update'; affgsc_write_state($state); return $state; } foreach ($providers as $slug => $file) { $queue[] = ['type' => 'provider_existing_only', 'provider_slug' => $slug, 'file' => $file]; } $total_expected = $existing_count; } elseif ($game_ids) { foreach ($providers as $slug => $file) { $queue[] = ['type' => 'provider_scan_ids', 'provider_slug' => $slug, 'file' => $file, 'game_ids' => $game_ids]; } $total_expected = count($game_ids); } else { if (!$selected) { $state = affgsc_state(); $state['status'] = 'error'; $state['last_error'] = 'No providers selected for import'; affgsc_write_state($state); return $state; } foreach ($providers as $slug => $file) { if (!in_array($slug, $selected, true)) continue; $queue[] = ['type' => 'provider', 'provider_slug' => $slug, 'file' => $file]; $total_expected += max(0, (int)($file['count'] ?? 0)); } } if (!$queue) { $state = affgsc_state(); $state['status'] = 'error'; $state['last_error'] = 'No providers or game IDs selected for import'; affgsc_write_state($state); return $state; } $state = affgsc_default_state(); $state['status'] = 'running'; $state['mode'] = $mode; $state['apply_demand_filter'] = $apply_demand_filter ? '1' : '0'; $state['queue'] = $queue; $state['total_expected'] = $total_expected; $state['total_providers'] = count($queue); $state['started_at'] = affgsc_now(); affgsc_write_state($state); affgsc_kick_import(); return affgsc_state(); } function affgsc_weekly_sync(): void { if ((string)affgsc_setting('weekly_sync', '0') !== '1') return; $state = affgsc_state(); if ((string)$state['status'] === 'running') return; $connection = affgsc_ensure_installation_secret(); if (empty($connection['ok'])) return; affgsc_send_stats(); affgsc_start_import('weekly', true, [ 'force_existing_only' => true, 'disable_demand_filter' => true, ]); } function affgsc_import_tick(): void { if (get_transient('affgsc_import_tick_lock')) { return; } set_transient('affgsc_import_tick_lock', 1, 60); try { affgsc_import_tick_worker(); } finally { delete_transient('affgsc_import_tick_lock'); } } function affgsc_import_tick_worker(): void { $state = affgsc_state(); if ((string)($state['status'] ?? '') !== 'running') return; $apply_demand_filter = (string)($state['apply_demand_filter'] ?? '0') === '1'; $batch_size = (int)affgsc_setting('import_batch_size', 20); $processed = 0; while ($processed < $batch_size) { if (empty($state['current_games'])) { $next = array_shift($state['queue']); if (!$next) { $state['status'] = 'done'; $state['finished_at'] = affgsc_now(); affgsc_write_state($state); affgsc_send_stats(); affgsc_schedule_frequency_refresh(5); return; } $payload = affgsc_fetch_provider_payload((array)($next['file'] ?? [])); if (!empty($payload['error'])) { $state['total_skipped']++; $state['last_error'] = (string)$payload['error']; continue; } $games = isset($payload['games']) && is_array($payload['games']) ? $payload['games'] : []; if (($next['type'] ?? '') === 'provider_scan_ids') { $wanted = array_flip(array_map('intval', (array)($next['game_ids'] ?? []))); $games = array_values(array_filter($games, static function ($game) use ($wanted): bool { return is_array($game) && isset($wanted[(int)($game['source_id'] ?? 0)]); })); } elseif (($next['type'] ?? '') === 'provider_existing_only') { $existing = affgsc_existing_source_ids_map(); $games = array_values(array_filter($games, static function ($game) use ($existing): bool { return is_array($game) && isset($existing[(int)($game['source_id'] ?? 0)]); })); } $games = array_values(array_filter($games, static function ($game) use ($apply_demand_filter): bool { return is_array($game) && affgsc_should_import_game_by_demand($game, $apply_demand_filter); })); $state['current_games'] = $games; $state['current_provider'] = (string)($next['provider_slug'] ?? ''); $state['current_index'] = 0; $state['current_provider_total'] = count($games); $state['current_provider_done'] = 0; if (!$state['current_games']) { continue; } } $game = array_shift($state['current_games']); $result = is_array($game) ? affgsc_import_game($game, $apply_demand_filter) : ['status' => 'skipped']; if (($result['status'] ?? '') === 'inserted') $state['total_imported']++; elseif (($result['status'] ?? '') === 'updated') $state['total_updated']++; else $state['total_skipped']++; $state['current_index']++; $state['current_provider_done']++; $processed++; } affgsc_write_state($state); affgsc_kick_import(); } function affgsc_import_loopback(): void { // This loopback request is authenticated with a site-specific HMAC token, not a user nonce. // phpcs:disable WordPress.Security.NonceVerification.Missing $token = isset($_POST['token']) && is_scalar($_POST['token']) ? sanitize_text_field(wp_unslash((string)$_POST['token'])) : ''; // phpcs:enable WordPress.Security.NonceVerification.Missing if (!hash_equals(affgsc_import_loopback_token(), $token)) { wp_send_json_error(['message' => 'Invalid token'], 403); } delete_transient('affgsc_import_loopback_pending'); affgsc_import_tick(); wp_send_json_success(['status' => (string)(affgsc_state()['status'] ?? 'idle')]); } function affgsc_find_post_by_source(int $source_id): int { if ($source_id <= 0) return 0; $posts = get_posts([ 'post_type' => AFFGSC_POST_TYPE, 'post_status' => 'any', 'posts_per_page' => 1, 'fields' => 'ids', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Source IDs are the canonical imported-game lookup key. 'meta_key' => 'affgsc_source_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Source IDs are the canonical imported-game lookup value. 'meta_value' => $source_id, 'no_found_rows' => true, ]); return !empty($posts[0]) ? (int)$posts[0] : 0; } function affgsc_existing_source_ids_map(): array { static $map = null; if (is_array($map)) { return $map; } global $wpdb; // The result is held in a request-local static cache; all values are prepared against core table names. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_col($wpdb->prepare( "SELECT DISTINCT CAST(pm.meta_value AS UNSIGNED) AS source_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND p.post_type = %s AND p.post_status != %s", 'affgsc_source_id', AFFGSC_POST_TYPE, 'trash' )); $map = []; if (is_array($rows)) { foreach ($rows as $source_id) { $id = (int)$source_id; if ($id > 0) { $map[$id] = true; } } } return $map; } function affgsc_game_slot_index(array $game): float { $raw = $game['slot_index'] ?? ($game['features']['slot_index'] ?? 0); if (is_string($raw)) { $raw = str_replace(',', '.', trim($raw)); } return is_numeric($raw) ? (float)$raw : 0.0; } function affgsc_should_import_game_by_demand(array $game, ?bool $enabled = null): bool { if ($enabled === null) { $enabled = (string)affgsc_setting('import_demand_only', '0') === '1'; } if (!$enabled) { return true; } return affgsc_game_slot_index($game) > 0.5; } function affgsc_import_game(array $game, ?bool $apply_demand_filter = null): array { if (!affgsc_should_import_game_by_demand($game, $apply_demand_filter)) { return ['status' => 'skipped']; } $source_id = (int)($game['source_id'] ?? 0); $title = wp_strip_all_tags((string)($game['title'] ?? '')); if ($source_id <= 0 || $title === '') return ['status' => 'skipped']; $post_id = affgsc_find_post_by_source($source_id); $post_data = [ 'post_type' => AFFGSC_POST_TYPE, 'post_title' => $title, 'post_name' => sanitize_title((string)($game['slug'] ?? $title)), 'post_status' => (string)affgsc_setting('post_status', 'publish'), ]; if ($post_id > 0) { $post_data['ID'] = $post_id; $saved = wp_update_post($post_data, true); $status = 'updated'; } else { $post_data['post_content'] = '[affgsc_game id="' . $source_id . '"]'; $saved = wp_insert_post($post_data, true); $status = 'inserted'; } if (is_wp_error($saved)) return ['status' => 'skipped', 'error' => $saved->get_error_message()]; $post_id = (int)$saved; if ($status === 'inserted') { wp_update_post([ 'ID' => $post_id, 'post_content' => '[affgsc_game id="' . $post_id . '"]', ]); } update_post_meta($post_id, 'affgsc_source_id', $source_id); update_post_meta($post_id, 'affgsc_demo_url', affgsc_sanitize_https_url((string)($game['demo_url'] ?? ''))); update_post_meta($post_id, 'affgsc_demo_status', sanitize_key((string)($game['demo_status'] ?? 'unknown'))); update_post_meta($post_id, 'affgsc_demo_error_reason', sanitize_text_field((string)($game['demo_error_reason'] ?? ''))); update_post_meta($post_id, 'affgsc_demo_checked_at', sanitize_text_field((string)($game['demo_checked_at'] ?? ''))); update_post_meta($post_id, 'affgsc_release_date', sanitize_text_field((string)($game['release_date'] ?? ''))); update_post_meta($post_id, 'affgsc_slot_index', sanitize_text_field((string)($game['slot_index'] ?? ($game['features']['slot_index'] ?? '')))); update_post_meta($post_id, 'affgsc_rtp', sanitize_text_field((string)($game['rtp'] ?? ($game['features']['rtp'] ?? '')))); update_post_meta($post_id, 'affgsc_source_permalink', affgsc_sanitize_https_url((string)($game['permalink'] ?? ''))); update_post_meta($post_id, 'affgsc_logo_url', affgsc_sanitize_https_url((string)($game['logo'] ?? ''))); update_post_meta($post_id, 'affgsc_imported_at', affgsc_now()); affgsc_assign_terms($post_id, $game); return ['status' => $status, 'post_id' => $post_id]; } function affgsc_assign_terms(int $post_id, array $game): void { $provider = is_array($game['provider'] ?? null) ? $game['provider'] : null; if ($provider) { $term_id = affgsc_upsert_term($provider, AFFGSC_TAX_PROVIDER); if ($term_id > 0) { wp_set_object_terms($post_id, [$term_id], AFFGSC_TAX_PROVIDER); if (!empty($provider['logo'])) { update_term_meta($term_id, 'affgsc_provider_logo', affgsc_sanitize_https_url((string)$provider['logo'])); } } } if (taxonomy_exists(AFFGSC_TAX_TYPE) && is_array($game['type'] ?? null)) { $term_id = affgsc_upsert_term($game['type'], AFFGSC_TAX_TYPE); if ($term_id > 0) wp_set_object_terms($post_id, [$term_id], AFFGSC_TAX_TYPE); } if (taxonomy_exists(AFFGSC_TAX_THEME) && !empty($game['themes']) && is_array($game['themes'])) { $ids = []; foreach ($game['themes'] as $theme) { if (!is_array($theme)) continue; $term_id = affgsc_upsert_term($theme, AFFGSC_TAX_THEME); if ($term_id > 0) $ids[] = $term_id; } if ($ids) wp_set_object_terms($post_id, $ids, AFFGSC_TAX_THEME); } $volatility_payload = affgsc_term_payload_normalize($game['volatility'] ?? ($game['features']['volatility'] ?? null)); if (taxonomy_exists(AFFGSC_TAX_VOLATILITY) && is_array($volatility_payload)) { $term_id = affgsc_upsert_term($volatility_payload, AFFGSC_TAX_VOLATILITY); if ($term_id > 0) { wp_set_object_terms($post_id, [$term_id], AFFGSC_TAX_VOLATILITY); } } } function affgsc_term_payload_normalize($value): ?array { if (is_array($value)) { $name = sanitize_text_field((string)($value['name'] ?? '')); $slug = sanitize_title((string)($value['slug'] ?? $name)); if ($name === '' || $slug === '') { return null; } return [ 'source_id' => (int)($value['source_id'] ?? 0), 'name' => $name, 'slug' => $slug, ]; } if (is_string($value)) { $name = sanitize_text_field($value); $slug = sanitize_title($name); if ($name === '' || $slug === '') { return null; } return [ 'source_id' => 0, 'name' => $name, 'slug' => $slug, ]; } return null; } function affgsc_upsert_term(array $payload, string $taxonomy): int { $name = sanitize_text_field((string)($payload['name'] ?? '')); $slug = sanitize_title((string)($payload['slug'] ?? $name)); if ($name === '' || $slug === '' || !taxonomy_exists($taxonomy)) return 0; $term = get_term_by('slug', $slug, $taxonomy); if ($term instanceof WP_Term) { if ($term->name !== $name) { wp_update_term($term->term_id, $taxonomy, ['name' => $name]); } $term_id = (int)$term->term_id; } else { $created = wp_insert_term($name, $taxonomy, ['slug' => $slug]); if (is_wp_error($created)) return 0; $term_id = (int)$created['term_id']; } update_term_meta($term_id, 'affgsc_source_id', (int)($payload['source_id'] ?? 0)); update_term_meta($term_id, 'affgsc_source_slug', $slug); return $term_id; }