$value) {
if (!preg_match('/^--[a-z0-9-]+$/', (string)$property)) continue;
$parts[] = (string)$property . ':' . (string)$value;
}
return implode(';', $parts) . ($parts ? ';' : '');
}
function affgsc_public_assets(): void {
wp_register_style('affgsc-public', AFFGSC_URL . 'assets/public.css', [], file_exists(AFFGSC_DIR . 'assets/public.css') ? (string)filemtime(AFFGSC_DIR . 'assets/public.css') : AFFGSC_VERSION);
wp_register_script('affgsc-public', AFFGSC_URL . 'assets/public.js', ['jquery'], file_exists(AFFGSC_DIR . 'assets/public.js') ? (string)filemtime(AFFGSC_DIR . 'assets/public.js') : AFFGSC_VERSION, true);
wp_register_script('affgsc-echarts', AFFGSC_URL . 'assets/vendor/echarts.min.js', [], '6.1.0', true);
wp_register_script('affgsc-interest-chart', AFFGSC_URL . 'assets/interest-chart.js', ['affgsc-echarts'], file_exists(AFFGSC_DIR . 'assets/interest-chart.js') ? (string)filemtime(AFFGSC_DIR . 'assets/interest-chart.js') : AFFGSC_VERSION, true);
wp_localize_script('affgsc-public', 'AFFGSC', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('affgsc_public_action'),
'cacheImageEnabled' => affgsc_should_cache_images_to_media() ? 1 : 0,
'cacheImageDelayMs' => 5000,
/* translators: 1: average rating, 2: vote count. */
'ratingSummary' => __('%1$s/5 from %2$s votes', 'affgate-slot-catalog'),
'reportSent' => __('Report sent. Thank you.', 'affgate-slot-catalog'),
'reportRequired' => __('Please describe the problem before sending the report.', 'affgate-slot-catalog'),
'reportLimit' => __('You have already reported this game today.', 'affgate-slot-catalog'),
]);
}
function affgsc_enqueue_public(): void {
wp_enqueue_style('affgsc-public');
wp_enqueue_script('affgsc-public');
$color = affgsc_sanitize_hex_color((string)affgsc_setting('primary_color', '#166534'));
$free_color = affgsc_sanitize_hex_color((string)affgsc_setting('free_play_color', $color));
$real_color = affgsc_sanitize_hex_color((string)affgsc_setting('real_play_color', $color));
$free_text_color = affgsc_sanitize_hex_color((string)affgsc_setting('free_play_text_color', '#ffffff'));
$real_text_color = affgsc_sanitize_hex_color((string)affgsc_setting('real_play_text_color', '#ffffff'));
$casino_visit_color = affgsc_sanitize_hex_color((string)affgsc_setting('casino_visit_color', $color));
$casino_visit_text_color = affgsc_sanitize_hex_color((string)affgsc_setting('casino_visit_text_color', '#ffffff'), '#ffffff');
$casino_review_color = affgsc_sanitize_hex_color((string)affgsc_setting('casino_review_color', '#4b5563'), '#4b5563');
$casino_review_text_color = affgsc_sanitize_hex_color((string)affgsc_setting('casino_review_text_color', '#ffffff'), '#ffffff');
$index_colors = '';
for ($step = 0; $step <= 53; $step++) {
$index = $step / 2;
$hue = $index <= 10 ? ($index / 10) * 55 : 55 + (($index - 10) / 16.5) * 65;
$index_colors .= '.affgsc-popularity-index--' . $step . '{color:hsl(' . round($hue) . ',78%,42%)!important;}';
}
wp_add_inline_style('affgsc-public', '.affgsc-catalog,.affgsc-single,.affgsc-related,.affgsc-providers,.affgsc-breadcrumbs,.affgsc-interest-chart,.affgsc-casinos{--affgsc-accent:' . esc_html($color) . ';--affgsc-free-play:' . esc_html($free_color) . ';--affgsc-free-play-text:' . esc_html($free_text_color) . ';--affgsc-real-play:' . esc_html($real_color) . ';--affgsc-real-play-text:' . esc_html($real_text_color) . ';--affgsc-casino-visit:' . esc_html($casino_visit_color) . ';--affgsc-casino-visit-text:' . esc_html($casino_visit_text_color) . ';--affgsc-casino-review:' . esc_html($casino_review_color) . ';--affgsc-casino-review-text:' . esc_html($casino_review_text_color) . ';}' . $index_colors);
}
function affgsc_interest_chart_affgate_url(): string {
$locale = function_exists('determine_locale') ? determine_locale() : get_locale();
$language = strtolower(substr((string)$locale, 0, 2));
$paths = [
'ru' => '',
'en' => 'en/',
'pt' => 'pt/',
'es' => 'es/',
'fr' => 'fr/',
'de' => 'de/',
'id' => 'id/',
'tr' => 'tr/',
];
return 'https://affgate.com/' . ($paths[$language] ?? 'en/');
}
function affgsc_interest_chart_month_label(string $month): string {
$date = DateTimeImmutable::createFromFormat('!Y-m', $month, wp_timezone());
return $date instanceof DateTimeImmutable ? wp_date('M', $date->getTimestamp(), wp_timezone()) : $month;
}
/**
* Return a country name in the current WordPress locale when PHP Intl is available.
* The browser repeats this localization with Intl.DisplayNames; the feed name is
* retained only as a compatibility fallback for installations without either API.
*/
function affgsc_interest_chart_country_name(string $code, string $fallback, string $locale): string {
$code = strtoupper(trim($code));
$fallback = sanitize_text_field($fallback);
if (!preg_match('/^[A-Z]{2}$/', $code)) return $fallback;
if (class_exists('Locale') && method_exists('Locale', 'getDisplayRegion')) {
$display_locale = str_replace('_', '-', sanitize_text_field($locale));
$localized = Locale::getDisplayRegion('und-' . $code, $display_locale);
if (is_string($localized)) {
$localized = sanitize_text_field($localized);
if ($localized !== '' && strtoupper($localized) !== $code) return $localized;
}
}
return $fallback !== '' ? $fallback : $code;
}
function affgsc_interest_chart_html(int $post_id, array $options = []): string {
if ($post_id <= 0) return '';
$requested = isset($options['view']) && is_array($options['view']) ? $options['view'] : ['graf1', 'graf2'];
$show_lines = in_array('graf1', $requested, true) && (string)affgsc_setting('show_interest_chart', '0') === '1';
$show_countries = in_array('graf2', $requested, true) && (string)affgsc_setting('show_country_chart', '0') === '1';
if (!$show_lines && !$show_countries) return '';
$source_id = absint(get_post_meta($post_id, 'affgsc_source_id', true));
if ($source_id <= 0) return '';
global $wpdb;
$frequency_table = affgsc_frequency_table();
$frequency_cache_key = 'frequency_' . $source_id;
$stored = wp_cache_get($frequency_cache_key, 'affgsc');
if (false === $stored) {
// The table name is generated by affgsc_frequency_table(); source_id is prepared below.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$stored = $wpdb->get_row($wpdb->prepare(
"SELECT monthly, countries FROM {$frequency_table} WHERE source_id = %d LIMIT 1",
$source_id
), ARRAY_A);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
wp_cache_set($frequency_cache_key, is_array($stored) ? $stored : [], 'affgsc', HOUR_IN_SECONDS);
}
$stored = is_array($stored) ? $stored : [];
$stored_series = affgsc_frequency_series_values(json_decode((string)($stored['monthly'] ?? ''), true));
$country_data = affgsc_frequency_country_values(json_decode((string)($stored['countries'] ?? ''), true));
$game_title = affgsc_game_title_plain($post_id);
$series_config = [
'slot' => [
'enabled' => (string)affgsc_setting('interest_chart_slot', '1') === '1',
'color' => affgsc_sanitize_hex_color((string)affgsc_setting('interest_chart_slot_color', '#dc2626')),
/* translators: %s: game name. */
'label' => sprintf(__('%s + slot', 'affgate-slot-catalog'), $game_title),
],
'demo' => [
'enabled' => (string)affgsc_setting('interest_chart_demo', '1') === '1',
'color' => affgsc_sanitize_hex_color((string)affgsc_setting('interest_chart_demo_color', '#f97316')),
/* translators: %s: game name. */
'label' => sprintf(__('%s + demo', 'affgate-slot-catalog'), $game_title),
],
'freeplay' => [
'enabled' => (string)affgsc_setting('interest_chart_freeplay', '1') === '1',
'color' => affgsc_sanitize_hex_color((string)affgsc_setting('interest_chart_freeplay_color', '#16a34a')),
/* translators: %s: game name. */
'label' => sprintf(__('%s + free play', 'affgate-slot-catalog'), $game_title),
],
];
$months = [];
$chart_series = [];
if ($show_lines) {
foreach ($series_config as $key => $config) {
if (empty($config['enabled']) || empty($stored_series[$key])) continue;
$months = array_merge($months, array_keys($stored_series[$key]));
}
$months = array_values(array_unique($months));
sort($months, SORT_STRING);
if (count($months) > 12) $months = array_slice($months, -12);
foreach ($series_config as $key => $config) {
if (empty($config['enabled']) || empty($stored_series[$key])) continue;
$values = [];
foreach ($months as $month) {
$values[] = array_key_exists($month, $stored_series[$key]) ? (int)$stored_series[$key][$month] : null;
}
$chart_series[] = ['name' => (string)$config['label'], 'color' => (string)$config['color'], 'data' => $values];
}
}
if (!$chart_series) $show_lines = false;
$locale = function_exists('determine_locale') ? determine_locale() : get_locale();
$country_slices = [];
if ($show_countries && $country_data) {
$top_total = 0.0;
foreach ($country_data['top'] as $country) {
$top_total += (float)$country['value'];
$country['name'] = affgsc_interest_chart_country_name(
(string)($country['code'] ?? ''),
(string)($country['name'] ?? ''),
(string)$locale
);
$country_slices[] = $country;
}
$other = max(0.0, (float)$country_data['total'] - $top_total);
if ($other > 0) $country_slices[] = ['code' => '', 'name' => __('Other countries', 'affgate-slot-catalog'), 'value' => round($other, 4), 'other' => true];
}
if (!$country_slices) $show_countries = false;
if (!$show_lines && !$show_countries) return '';
affgsc_enqueue_public();
wp_enqueue_script('affgsc-interest-chart');
$scheme = affgsc_shortcode_color_scheme($options['style_theme'] ?? '');
$labels = array_map('affgsc_interest_chart_month_label', $months);
$chart_title_template = array_key_exists('title', $options)
? (string)$options['title']
: (string)affgsc_setting('interest_chart_title', '');
$chart_title = affgsc_expand_game_placeholders($chart_title_template, $post_id);
$chart_title_size = affgsc_sanitize_title_font_size(affgsc_setting('interest_chart_title_size', 18));
$chart_title_color = affgsc_sanitize_hex_color((string)affgsc_setting('interest_chart_title_color', '#374151'), '#374151');
$interactive_legend = count($chart_series) > 1;
$country_type = in_array((string)($options['type'] ?? ''), ['tn1', 'tn2'], true) ? (string)$options['type'] : (string)affgsc_setting('country_chart_type', 'tn1');
$country_view = in_array((string)($options['country_view'] ?? ''), ['cv1', 'cv2', 'cv3'], true) ? (string)$options['country_view'] : (string)affgsc_setting('country_chart_view', 'cv1');
$affgate_link = 'AffGate';
/* translators: %s: linked AffGate brand name. */
$caption = sprintf(__('Data provided by %s', 'affgate-slot-catalog'), $affgate_link);
ob_start();
?>
style=" (string)$chart_title_size . 'px', '--affgsc-block-title-color' => $chart_title_color])); ?>">
['href' => true, 'target' => true, 'rel' => true]]); ?>
0) return get_post_type($id) === AFFGSC_POST_TYPE ? $id : 0;
if (is_singular(AFFGSC_POST_TYPE)) {
$queried = (int)get_queried_object_id();
if ($queried > 0) return $queried;
}
return 0;
}
function affgsc_shortcode_game_id_warning(): string {
return '
' . esc_html__('Specify the required game ID.', 'affgate-slot-catalog') . '
';
}
function affgsc_shortcode_interest_chart($atts = []): string {
$raw_atts = is_array($atts) ? $atts : [];
$has_title = array_key_exists('title', $raw_atts);
$atts = shortcode_atts(['id' => '', 'title' => '', 'view' => 'all', 'type' => '', 'country_view' => '', 'style_theme' => '', 'main_color' => ''], $raw_atts, 'affgsc_interest_chart');
$id = affgsc_shortcode_game_context_id($atts['id']);
if ($id <= 0) return affgsc_shortcode_game_id_warning();
$raw_view = strtolower(trim((string)$atts['view']));
$views = $raw_view === '' || $raw_view === 'all' ? ['graf1', 'graf2'] : array_values(array_intersect(['graf1', 'graf2'], array_map('trim', explode(',', $raw_view))));
if (!$views) $views = ['graf1', 'graf2'];
$options = [
'view' => $views,
'type' => (string)$atts['type'],
'country_view' => (string)$atts['country_view'],
'style_theme' => (string)$atts['style_theme'],
'main_color' => (string)$atts['main_color'],
'shortcode_instance' => true,
];
if ($has_title) $options['title'] = (string)$atts['title'];
return affgsc_interest_chart_html($id, $options);
}
function affgsc_reorder_game_content_for_interest_chart(string $content): string {
if (is_admin() || !is_singular(AFFGSC_POST_TYPE) || !in_the_loop() || !is_main_query()) {
return $content;
}
$post = get_post();
if (!$post instanceof WP_Post || $post->post_type !== AFFGSC_POST_TYPE) {
return $content;
}
if (strpos($content, '[affgsc_game') === false) {
return $content;
}
if (!preg_match('/(?:\s*)?\[affgsc_game\b[^\]]*\](?:\s*\[\/affgsc_game\])?(?:\s*)?/i', $content, $match, PREG_OFFSET_CAPTURE)) {
return $content;
}
$shortcode = (string)$match[0][0];
$offset = (int)$match[0][1];
$before = substr($content, 0, $offset);
$after = substr($content, $offset + strlen($shortcode));
$manual_chart = has_shortcode((string)$post->post_content, 'affgsc_interest_chart');
$chart_enabled = (string)affgsc_setting('show_interest_chart', '0') === '1' || (string)affgsc_setting('show_country_chart', '0') === '1';
$chart = !$manual_chart && $chart_enabled ? affgsc_interest_chart_html((int)$post->ID) : '';
$manual_casino = has_shortcode((string)$post->post_content, 'affgsc_casinos');
$casino_position = (string)affgsc_setting('casino_block_position', 'after_characteristics');
$casino = !$manual_casino && in_array($casino_position, ['before_chart', 'after_chart'], true)
? affgsc_casino_block_html((int)$post->ID)
: '';
$manual_chart_casino_inserted = false;
if ($manual_chart && $casino !== '' && has_shortcode((string)$post->post_content, 'affgsc_related_provider_games')) {
$replacement = $casino . "\n\n" . '$1';
$updated_after = preg_replace('/(\[affgsc_related_provider_games\b)/i', $replacement, $after, 1);
if (is_string($updated_after) && $updated_after !== $after) {
$after = $updated_after;
$casino = '';
$manual_chart_casino_inserted = true;
} else {
$updated_before = preg_replace('/(\[affgsc_related_provider_games\b)/i', $replacement, $before, 1);
if (is_string($updated_before) && $updated_before !== $before) {
$before = $updated_before;
$casino = '';
$manual_chart_casino_inserted = true;
}
}
}
$inserted_before_related = false;
if (!$manual_casino && $casino_position === 'before_related' && has_shortcode((string)$post->post_content, 'affgsc_related_provider_games')) {
$before_related = affgsc_casino_block_html((int)$post->ID);
if ($before_related !== '') {
$replacement = $before_related . "\n\n" . '$1';
$updated_after = preg_replace('/(\[affgsc_related_provider_games\b)/i', $replacement, $after, 1);
if (is_string($updated_after) && $updated_after !== $after) {
$after = $updated_after;
$inserted_before_related = true;
} else {
$updated_before = preg_replace('/(\[affgsc_related_provider_games\b)/i', $replacement, $before, 1);
if (is_string($updated_before) && $updated_before !== $before) {
$before = $updated_before;
$inserted_before_related = true;
}
}
}
}
if ($chart === '' && $casino === '') {
return ($inserted_before_related || $manual_chart_casino_inserted) ? $before . $shortcode . $after : $content;
}
$middle = $before;
if ($chart !== '') {
if ($casino !== '' && $casino_position === 'before_chart') $middle .= "\n\n" . $casino;
$middle .= "\n\n" . $chart;
if ($casino !== '' && $casino_position === 'after_chart') $middle .= "\n\n" . $casino;
return $shortcode . "\n\n" . $middle . "\n\n" . $after;
}
$result = $shortcode . "\n\n" . $before . "\n\n" . $after;
return $casino !== '' ? $result . "\n\n" . $casino : $result;
}
function affgsc_game_image(int $post_id): string {
$img = get_the_post_thumbnail_url($post_id, 'medium_large');
if ($img) return esc_url($img);
if ((string)affgsc_setting('enable_affgate_images', '0') !== '1') {
return '';
}
return esc_url((string)get_post_meta($post_id, 'affgsc_logo_url', true));
}
function affgsc_demo_placeholder_image(int $post_id): array {
$custom_id = absint(affgsc_setting('demo_placeholder_image_id', 0));
if ($custom_id > 0) {
$url = wp_get_attachment_image_url($custom_id, 'full');
if ($url) {
return ['url' => esc_url($url), 'custom' => true];
}
}
return ['url' => affgsc_game_image($post_id), 'custom' => false];
}
function affgsc_button_label(string $key, string $fallback): string {
return affgsc_sanitize_button_label((string)affgsc_setting($key, $fallback), $fallback);
}
function affgsc_tax_terms(int $post_id, string $taxonomy): array {
if (!taxonomy_exists($taxonomy)) return [];
$terms = get_the_terms($post_id, $taxonomy);
return (!is_wp_error($terms) && is_array($terms)) ? array_values($terms) : [];
}
function affgsc_term_names(int $post_id, string $taxonomy, int $limit = 0): array {
$names = array_map(static function ($term): string {
return (string)$term->name;
}, affgsc_tax_terms($post_id, $taxonomy));
return $limit > 0 ? array_slice($names, 0, $limit) : $names;
}
function affgsc_game_title_plain(int $post_id): string {
$post = get_post($post_id);
return $post instanceof WP_Post ? trim(wp_strip_all_tags((string)$post->post_title)) : '';
}
function affgsc_expand_game_placeholders(string $template, int $post_id): string {
$values = [
'name' => affgsc_game_title_plain($post_id),
'provider' => implode(', ', affgsc_term_names($post_id, AFFGSC_TAX_PROVIDER)),
'type' => implode(', ', affgsc_term_names($post_id, AFFGSC_TAX_TYPE)),
'theme' => implode(', ', affgsc_term_names($post_id, AFFGSC_TAX_THEME)),
];
$replacements = [];
foreach ($values as $key => $value) {
$replacements['[' . $key . ']'] = $value;
$replacements['{' . $key . '}'] = $value;
$replacements['%%' . $key . '%%'] = $value;
}
return trim(preg_replace('/\s+/', ' ', strtr($template, $replacements)) ?: '');
}
function affgsc_game_h1(int $post_id): string {
$template = (string)affgsc_setting('h1_template', '[name]');
$title = affgsc_game_title_plain($post_id);
$value = affgsc_expand_game_placeholders($template, $post_id);
return $value !== '' ? $value : $title;
}
function affgsc_filter_game_title(string $title, int $post_id = 0): string {
if (is_admin() || $post_id <= 0 || get_post_type($post_id) !== AFFGSC_POST_TYPE) return $title;
if (!is_singular(AFFGSC_POST_TYPE) || (int)get_queried_object_id() !== $post_id || !in_the_loop()) return $title;
return esc_html(wp_strip_all_tags(affgsc_game_h1($post_id)));
}
function affgsc_term_value_html(int $post_id, string $taxonomy, string $link_setting, string $public_setting): string {
$items = [];
$link_terms = (string)affgsc_setting($link_setting, '0') === '1' && (string)affgsc_setting($public_setting, '0') === '1';
foreach (affgsc_tax_terms($post_id, $taxonomy) as $term) {
if ($link_terms) {
$url = get_term_link($term);
if (!is_wp_error($url)) {
$items[] = '' . esc_html($term->name) . '';
continue;
}
}
$items[] = esc_html($term->name);
}
return implode(', ', $items);
}
function affgsc_game_release_date(int $post_id): string {
$raw = trim((string)get_post_meta($post_id, 'affgsc_release_date', true));
if ($raw === '') return '';
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})/', $raw, $matches)) {
$year = (int)$matches[1];
$month = (int)$matches[2];
$day = (int)$matches[3];
return checkdate($month, $day, $year) ? sprintf('%02d.%02d.%04d', $day, $month, $year) : '';
}
$timestamp = strtotime($raw);
return $timestamp ? wp_date('d.m.Y', $timestamp) : '';
}
function affgsc_game_popularity_index(int $post_id): ?float {
$raw = str_replace(',', '.', trim((string)get_post_meta($post_id, 'affgsc_slot_index', true)));
return $raw !== '' && is_numeric($raw) ? max(0.0, (float)$raw) : null;
}
function affgsc_popularity_index_html(float $index, bool $with_help = true): string {
$bucket = min(26.5, floor(max(0.0, $index) * 2) / 2);
$step = (int)round($bucket * 2);
$tooltip = __('The index shows the game popularity across all countries worldwide', 'affgate-slot-catalog');
return ''
. esc_html(affgsc_format_number_plain($index, 2))
. ' ' . esc_html__('out of 30', 'affgate-slot-catalog') . ''
. ($with_help ? '?' : '') . '';
}
function affgsc_game_attributes_html(int $post_id): string {
$rows = [];
if ((string)affgsc_setting('public_provider_pages', '0') === '1') {
$rows[] = [
'label' => __('Provider', 'affgate-slot-catalog'),
'value' => affgsc_term_value_html($post_id, AFFGSC_TAX_PROVIDER, 'link_provider_terms', 'public_provider_pages'),
];
}
if ((string)affgsc_setting('public_type_pages', '0') === '1') {
$rows[] = [
'label' => __('Type', 'affgate-slot-catalog'),
'value' => affgsc_term_value_html($post_id, AFFGSC_TAX_TYPE, 'link_type_terms', 'public_type_pages'),
];
}
if ((string)affgsc_setting('public_theme_pages', '0') === '1') {
$rows[] = [
'label' => __('Theme', 'affgate-slot-catalog'),
'value' => affgsc_term_value_html($post_id, AFFGSC_TAX_THEME, 'link_theme_terms', 'public_theme_pages'),
];
}
if ((string)affgsc_setting('show_volatility', '0') === '1') {
$rows[] = [
'label' => __('Volatility', 'affgate-slot-catalog'),
'value' => esc_html(implode(', ', affgsc_term_names($post_id, AFFGSC_TAX_VOLATILITY))),
];
}
if ((string)affgsc_setting('show_release_date', '0') === '1') {
$rows[] = [
'label' => __('Release date', 'affgate-slot-catalog'),
'value' => esc_html(affgsc_game_release_date($post_id)),
];
}
if ((string)affgsc_setting('show_popularity_index', '1') === '1') {
$popularity_index = affgsc_game_popularity_index($post_id);
$rows[] = [
'label' => __('Game popularity index', 'affgate-slot-catalog'),
'value' => $popularity_index !== null ? affgsc_popularity_index_html($popularity_index) : '',
];
}
$rows = array_values(array_filter($rows, static function ($row): bool {
return (string)$row['value'] !== '';
}));
if (!$rows) return '';
ob_start();
?>
0 ? wp_get_attachment_image_url($image_id, 'medium') : '';
$bonus = trim((string)($casino['bonus'] ?? ''));
$providers = (int)($casino['providers'] ?? 0);
$games = (int)($casino['games'] ?? 0);
$rating_raw = trim((string)($casino['rating'] ?? ''));
$rating = $rating_raw !== '' && is_numeric($rating_raw) ? min(5, max(0, (float)$rating_raw)) : 0;
$show_rating = $rating > 0;
$show_providers = $providers > 0;
$show_games = $games > 0;
$show_details = $bonus !== '' || $show_providers || $show_games;
$has_url = $casino_id !== '' && affgsc_sanitize_https_url((string)($casino['url'] ?? '')) !== '';
$review_url = affgsc_sanitize_https_url((string)($casino['review_url'] ?? ''));
/* translators: %s: casino score. */
$rating_label = sprintf(__('Score: %s out of 5', 'affgate-slot-catalog'), affgsc_format_number_plain($rating, 1));
/* translators: %s: provider count. */
$providers_label = sprintf(__('Providers: %s', 'affgate-slot-catalog'), affgsc_format_number_plain($providers));
/* translators: %s: game count. */
$games_label = sprintf(__('Games: %s', 'affgate-slot-catalog'), affgsc_format_number_plain($games));
?>
'', 'per_page' => '', 'style_theme' => '', 'main_color' => ''], $raw_atts, 'affgsc_casinos');
$post_id = get_the_ID();
if ($post_id <= 0) $post_id = 0;
$options = [];
if ($has_title) $options['title'] = (string)$atts['title'];
if (trim((string)$atts['per_page']) !== '') $options['per_page'] = min(50, max(1, (int)$atts['per_page']));
$options['style_theme'] = (string)$atts['style_theme'];
$options['main_color'] = (string)$atts['main_color'];
return affgsc_casino_block_html($post_id, $options);
}
function affgsc_should_auto_insert_casinos(int $post_id, string $position): bool {
if ((string)affgsc_setting('casino_block_enabled', '0') !== '1') return false;
if ((string)affgsc_setting('casino_block_position', 'after_characteristics') !== $position) return false;
$post = get_post($post_id);
return $post instanceof WP_Post && !has_shortcode((string)$post->post_content, 'affgsc_casinos');
}
function affgsc_append_casinos_before_related(string $content): string {
if (is_admin() || !is_singular(AFFGSC_POST_TYPE) || !in_the_loop() || !is_main_query()) return $content;
$post_id = get_the_ID();
if ($post_id <= 0 || !affgsc_should_auto_insert_casinos($post_id, 'before_related')) return $content;
$post = get_post($post_id);
if ($post instanceof WP_Post && has_shortcode((string)$post->post_content, 'affgsc_related_provider_games')) return $content;
$casino = affgsc_casino_block_html($post_id);
return $casino !== '' ? $content . $casino : $content;
}
function affgsc_related_provider_games_html(int $post_id, array $options = []): string {
$respect_setting = !array_key_exists('respect_setting', $options) || !empty($options['respect_setting']);
if ($respect_setting && (string)affgsc_setting('show_related_provider_games', '1') !== '1') {
return '';
}
$related_count = min(12, max(1, (int)($options['per_page'] ?? affgsc_setting('related_games_count', 5))));
$sort_by = sanitize_key((string)($options['sort_by'] ?? 'popular'));
if (!isset(affgsc_catalog_sort_choices()[$sort_by])) $sort_by = 'popular';
$query_args = [
'post_type' => AFFGSC_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => $related_count,
// phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- Excludes the single game currently being viewed.
'post__not_in' => [$post_id],
'no_found_rows' => true,
];
$requested_ids_raw = trim((string)($options['ids'] ?? ''));
$requested_ids = affgsc_parse_id_list($requested_ids_raw);
if ($requested_ids_raw !== '') {
if (!$requested_ids) return '';
$post_ids = array_values(array_filter($requested_ids, static function (int $related_id) use ($post_id): bool {
return $related_id !== $post_id && get_post_type($related_id) === AFFGSC_POST_TYPE && get_post_status($related_id) === 'publish';
}));
$post_ids = array_values(array_unique($post_ids));
if (!$post_ids) return '';
$query_args['post__in'] = $post_ids;
$query_args['orderby'] = 'post__in';
} else {
$filter = sanitize_key((string)($options['filter'] ?? 'provider'));
$taxonomies = [
'provider' => AFFGSC_TAX_PROVIDER,
'type' => AFFGSC_TAX_TYPE,
'theme' => AFFGSC_TAX_THEME,
];
if (!isset($taxonomies[$filter])) $filter = 'provider';
$taxonomy = $taxonomies[$filter];
$terms = affgsc_tax_terms($post_id, $taxonomy);
$term_ids = array_values(array_filter(array_map(static function ($term): int {
return $term instanceof WP_Term ? (int)$term->term_id : 0;
}, $terms)));
if (!$term_ids) return '';
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Related games must match the selected taxonomy terms.
$query_args['tax_query'] = [[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_ids,
]];
$query_args = array_merge($query_args, affgsc_catalog_sort_args($sort_by));
}
$q = new WP_Query($query_args);
if (!$q->have_posts()) {
wp_reset_postdata();
return '';
}
affgsc_enqueue_public();
$title_template = array_key_exists('title', $options)
? (string)$options['title']
: (string)affgsc_setting('related_games_title', 'More games from this provider');
if ($title_template === 'More games from this provider') {
$title_template = __('More games from this provider', 'affgate-slot-catalog');
}
$block_title = affgsc_expand_game_placeholders($title_template, $post_id);
$block_title_size = affgsc_sanitize_title_font_size(affgsc_setting('related_games_title_size', 18));
$block_title_color = affgsc_sanitize_hex_color((string)affgsc_setting('related_games_title_color', '#374151'), '#374151');
ob_start();
?>
0, 'count' => 0, 'user_rating' => 0];
$average = (float)($summary['average'] ?? 0);
$count = (int)($summary['count'] ?? 0);
$user_rating = (int)($summary['user_rating'] ?? 0);
$active = $user_rating > 0 ? $user_rating : (int)round($average);
/* translators: 1: average rating, 2: vote count. */
$rating_summary = sprintf(__('%1$s/5 from %2$d votes', 'affgate-slot-catalog'), affgsc_format_number_plain($average, 1), $count);
ob_start();
?>
0 ? esc_html__('You have already rated this game.', 'affgate-slot-catalog') : ''; ?>
[
'viewbox' => true,
'aria-hidden' => true,
],
'path' => [
'd' => true,
'fill' => true,
'stroke' => true,
'stroke-width' => true,
'stroke-linecap' => true,
'stroke-linejoin' => true,
],
];
}
function affgsc_icon(string $name): string {
if ($name === 'chevron-left') {
return '';
}
if ($name === 'chevron-right') {
return '';
}
if ($name === 'filter') {
return '';
}
if ($name === 'report') {
return '';
}
if ($name === 'fullscreen') {
return '';
}
return '';
}
function affgsc_catalog_sort_choices(): array {
return [
'popular' => __('By popularity', 'affgate-slot-catalog'),
'release_date' => __('By release date', 'affgate-slot-catalog'),
'rating' => __('By rating', 'affgate-slot-catalog'),
'title' => __('By title', 'affgate-slot-catalog'),
];
}
function affgsc_catalog_sort_args(string $sort_by): array {
switch ($sort_by) {
case 'release_date':
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- User-selected catalog ordering requires the imported release-date field.
return ['meta_key' => 'affgsc_release_date', 'orderby' => 'meta_value', 'order' => 'DESC'];
case 'rating':
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- User-selected catalog ordering requires the rating field.
return ['meta_key' => 'affgsc_rating_average', 'orderby' => 'meta_value_num', 'order' => 'DESC'];
case 'title':
return ['orderby' => 'title', 'order' => 'ASC'];
case 'popular':
default:
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- User-selected catalog ordering requires the imported popularity field.
return ['meta_key' => 'affgsc_slot_index', 'orderby' => 'meta_value_num', 'order' => 'DESC'];
}
}
function affgsc_catalog_filter_section_enabled(string $section): bool {
$allowed = ['provider', 'type', 'theme', 'volatility', 'sorting'];
return in_array($section, $allowed, true)
&& (string)affgsc_setting('catalog_filter_' . $section, '1') === '1';
}
function affgsc_catalog_has_filter_sections(): bool {
foreach (['provider', 'type', 'theme', 'volatility', 'sorting'] as $section) {
if (affgsc_catalog_filter_section_enabled($section)) return true;
}
return false;
}
function affgsc_render_filters(array $current = []): string {
if (!affgsc_catalog_has_filter_sections()) return '';
$sort_choices = affgsc_catalog_sort_choices();
$current_sort = sanitize_key((string)($current['sort'] ?? affgsc_setting('catalog_default_sort', 'popular')));
if (!isset($sort_choices[$current_sort])) {
$current_sort = 'popular';
}
$position = in_array((string)($current['position'] ?? ''), ['left', 'top', 'bottom'], true) ? (string)$current['position'] : 'top';
$columns = min(6, max(1, (int)affgsc_setting('catalog_filter_columns', 5)));
$labels = [
'provider' => __('Provider', 'affgate-slot-catalog'),
'type' => __('Type', 'affgate-slot-catalog'),
'theme' => __('Theme', 'affgate-slot-catalog'),
'volatility' => __('Volatility', 'affgate-slot-catalog'),
];
ob_start();
?>
'',
'type' => '',
'theme' => '',
'volatility' => '',
'ids' => '',
'per_page' => 0,
'limit' => 0,
'show_filters' => $default_show_filters,
'layout' => '',
'mode' => 'catalog',
'nav' => '',
'order_by' => '',
'order' => '',
'sort_by' => '',
'filter_position' => '',
'style_theme' => '',
'main_color' => '',
], is_array($atts) ? $atts : [], 'affgsc_games');
$layout = in_array((string)$atts['layout'], ['grid', 'list'], true) ? (string)$atts['layout'] : (string)affgsc_setting('catalog_layout', 'grid');
$scheme = affgsc_shortcode_color_scheme($atts['style_theme']);
$mode = in_array((string)$atts['mode'], ['catalog', 'carousel'], true) ? (string)$atts['mode'] : 'catalog';
$nav_mode = in_array((string)$atts['nav'], ['pagination', 'load_more', 'none'], true) ? (string)$atts['nav'] : (string)affgsc_setting('catalog_nav_mode', 'pagination');
$filter_position = in_array((string)$atts['filter_position'], ['off', 'left', 'top', 'bottom'], true) ? (string)$atts['filter_position'] : (string)affgsc_setting('catalog_filter_position', 'top');
$show_filters = affgsc_shortcode_bool($atts['show_filters'], true) && $filter_position !== 'off' && $mode !== 'carousel' && affgsc_catalog_has_filter_sections();
$default_per_page = (int)affgsc_setting('catalog_per_page', 36);
$per_page_attr = max(0, (int)$atts['per_page']);
$limit_attr = max(0, (int)$atts['limit']);
$per_page = min(120, max(1, $per_page_attr > 0 ? $per_page_attr : $default_per_page));
$total_limit = min(500, $limit_attr);
$paged = max(1, absint(affgsc_query_value('affgsc-page', '1')));
$tax_query = [];
foreach ([AFFGSC_TAX_PROVIDER => 'provider', AFFGSC_TAX_TYPE => 'type', AFFGSC_TAX_THEME => 'theme', AFFGSC_TAX_VOLATILITY => 'volatility'] as $tax => $key) {
$filter_value = $show_filters && affgsc_catalog_filter_section_enabled($key) ? affgsc_query_value('affgsc-' . $key) : '';
$value = sanitize_title((string)($filter_value ?: ($atts[$key] ?? '')));
if ($value !== '' && taxonomy_exists($tax)) {
$tax_query[] = ['taxonomy' => $tax, 'field' => 'slug', 'terms' => [$value]];
}
}
$legacy_sort = '';
if ((string)$atts['sort_by'] === '' && (string)$atts['order_by'] !== '') {
$legacy_order_by = sanitize_key((string)$atts['order_by']);
if ($legacy_order_by === 'slot_index') $legacy_sort = 'popular';
if ($legacy_order_by === 'release_date') $legacy_sort = 'release_date';
if ($legacy_order_by === 'rating') $legacy_sort = 'rating';
if ($legacy_order_by === 'title') $legacy_sort = 'title';
}
$filter_sort = $show_filters && affgsc_catalog_filter_section_enabled('sorting') ? affgsc_query_value('affgsc-sort') : '';
$sort_by = sanitize_key((string)($filter_sort ?: $atts['sort_by'] ?: $legacy_sort ?: affgsc_setting('catalog_default_sort', 'popular')));
$sort_choices = affgsc_catalog_sort_choices();
if (!isset($sort_choices[$sort_by])) {
$sort_by = 'popular';
}
$sort_args = affgsc_catalog_sort_args($sort_by);
$query_count = $mode === 'carousel'
? ($total_limit > 0 ? $total_limit : 12)
: $per_page;
$offset = $mode === 'catalog' ? ($paged - 1) * $per_page : 0;
$remaining = $total_limit > 0 ? $total_limit - $offset : $query_count;
$outside_limit = $mode === 'catalog' && $total_limit > 0 && $remaining <= 0;
if ($mode === 'catalog' && $total_limit > 0 && !$outside_limit) {
$query_count = min($per_page, $remaining);
}
$args = [
'post_type' => AFFGSC_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => max(1, $query_count),
];
if ($mode === 'carousel') {
$args['no_found_rows'] = true;
} elseif ($total_limit > 0) {
$args['offset'] = max(0, $offset);
} else {
$args['paged'] = $paged;
}
if ($tax_query) {
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Catalog filters intentionally query selected taxonomies.
$args['tax_query'] = $tax_query;
}
$ids_raw = trim((string)$atts['ids']);
$ids = affgsc_parse_id_list($ids_raw);
if ($ids_raw !== '') {
$args['post__in'] = $ids ?: [0];
}
if ($outside_limit) $args['post__in'] = [0];
$args = array_merge($args, $sort_args);
if ($ids && $filter_sort === '' && (string)$atts['sort_by'] === '' && (string)$atts['order_by'] === '') {
$args['orderby'] = 'post__in';
unset($args['meta_key'], $args['order']);
}
$q = new WP_Query($args);
$max_num_pages = $mode === 'catalog'
? ($total_limit > 0 ? (int)ceil(min((int)$q->found_posts, $total_limit) / $per_page) : (int)$q->max_num_pages)
: 1;
$collapse_classes = [];
if ((string)affgsc_setting('catalog_filter_collapse_desktop', '0') === '1') $collapse_classes[] = 'affgsc-filter-collapse-desktop';
if ((string)affgsc_setting('catalog_filter_collapse_tablet', '1') === '1') $collapse_classes[] = 'affgsc-filter-collapse-tablet';
if ((string)affgsc_setting('catalog_filter_collapse_mobile', '1') === '1') $collapse_classes[] = 'affgsc-filter-collapse-mobile';
ob_start();
?>
sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-provider') : '') ?: ($atts['provider'] ?? ''))),
'type' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-type') : '') ?: ($atts['type'] ?? ''))),
'theme' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-theme') : '') ?: ($atts['theme'] ?? ''))),
'volatility' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-volatility') : '') ?: ($atts['volatility'] ?? ''))),
'sort' => $sort_by,
'position' => 'top',
]); ?>
have_posts()) : ?>
have_posts()) : $q->the_post(); ?>
have_posts()) : while ($q->have_posts()) : $q->the_post(); ?>
1) : ?>
sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-provider') : '') ?: ($atts['provider'] ?? ''))),
'type' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-type') : '') ?: ($atts['type'] ?? ''))),
'theme' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-theme') : '') ?: ($atts['theme'] ?? ''))),
'volatility' => sanitize_title((string)(($show_filters ? affgsc_query_value('affgsc-volatility') : '') ?: ($atts['volatility'] ?? ''))),
'sort' => $sort_by,
'position' => 'bottom',
]); ?>
['class' => true],
'small' => [],
]); ?>
0, 'style_theme' => '', 'main_color' => ''], is_array($atts) ? $atts : [], 'affgsc_game');
$id = affgsc_shortcode_game_context_id($atts['id']);
if ($id <= 0) return affgsc_shortcode_game_id_warning();
affgsc_record_event($id, 'view');
$demo_url = esc_url((string)get_post_meta($id, 'affgsc_demo_url', true));
$status = sanitize_key((string)get_post_meta($id, 'affgsc_demo_status', true));
$placeholder = affgsc_demo_placeholder_image($id);
$img = (string)($placeholder['url'] ?? '');
$placeholder_class = !empty($placeholder['custom']) ? ' affgsc-placeholder--custom' : ' affgsc-placeholder--game';
$scheme = affgsc_shortcode_color_scheme($atts['style_theme']);
$real_play_url = affgsc_real_play_url($id);
$free_label = affgsc_button_label('free_play_label', 'Play for Free');
$real_label = affgsc_button_label('real_play_label', 'Real Play');
ob_start();
?>
0,
'ids' => '',
'title' => '',
'filter' => 'provider',
'per_page' => '',
'sort_by' => 'popular',
'style_theme' => '',
'main_color' => '',
], $raw_atts, 'affgsc_related_provider_games');
$id = affgsc_shortcode_game_context_id($atts['id']);
if ($id <= 0) return affgsc_shortcode_game_id_warning();
$options = [
'respect_setting' => false,
'ids' => (string)$atts['ids'],
'filter' => (string)$atts['filter'],
'sort_by' => (string)$atts['sort_by'],
'style_theme' => (string)$atts['style_theme'],
'main_color' => (string)$atts['main_color'],
];
if ($has_title) $options['title'] = (string)$atts['title'];
if (trim((string)$atts['per_page']) !== '') {
$options['per_page'] = min(12, max(1, (int)$atts['per_page']));
}
return affgsc_related_provider_games_html($id, $options);
}
function affgsc_append_related_games_after_content(string $content): string {
if (is_admin() || !is_singular(AFFGSC_POST_TYPE) || !in_the_loop() || !is_main_query()) {
return $content;
}
if ((string)affgsc_setting('show_related_provider_games', '1') !== '1') {
return $content;
}
$post = get_post();
if (!$post instanceof WP_Post || $post->post_type !== AFFGSC_POST_TYPE) {
return $content;
}
if (has_shortcode((string)$post->post_content, 'affgsc_related_provider_games')) {
return $content;
}
$related = affgsc_related_provider_games_html((int)$post->ID);
if ($related === '') {
return $content;
}
return $content . $related;
}
function affgsc_should_cache_images_to_media(): bool {
return (string)affgsc_setting('enable_affgate_images', '0') === '1'
&& (string)affgsc_setting('cache_images_to_media', '0') === '1';
}
function affgsc_image_cache_queue(): array {
$queue = get_option('affgsc_image_cache_queue', []);
if (!is_array($queue)) return [];
$queue = array_values(array_unique(array_filter(array_map('absint', $queue))));
if (count($queue) > 10000) {
$queue = array_slice($queue, 0, 10000);
}
return $queue;
}
function affgsc_write_image_cache_queue(array $queue): void {
$queue = array_values(array_unique(array_filter(array_map('absint', $queue))));
if (count($queue) > 10000) {
$queue = array_slice($queue, 0, 10000);
}
update_option('affgsc_image_cache_queue', $queue, false);
}
function affgsc_kick_image_cache_worker(int $delay = 15): void {
$delay = max(5, $delay);
if (!wp_next_scheduled('affgsc_image_cache_worker')) {
wp_schedule_single_event(time() + $delay, 'affgsc_image_cache_worker', [], true);
}
if (function_exists('spawn_cron')) {
spawn_cron(time());
}
}
function affgsc_enqueue_image_cache(int $post_id): bool {
$post_id = absint($post_id);
if ($post_id <= 0) return false;
$queue = affgsc_image_cache_queue();
if (count($queue) >= 10000) {
return false;
}
if (in_array($post_id, $queue, true)) {
return false;
}
$queue[] = $post_id;
affgsc_write_image_cache_queue($queue);
update_post_meta($post_id, 'affgsc_image_cache_status', 'pending');
update_post_meta($post_id, 'affgsc_image_cache_last_try', time());
affgsc_kick_image_cache_worker(15);
return true;
}
function affgsc_maybe_schedule_game_image_cache(int $post_id): void {
if ($post_id <= 0 || get_post_type($post_id) !== AFFGSC_POST_TYPE) return;
if (!affgsc_should_cache_images_to_media()) return;
if (has_post_thumbnail($post_id)) return;
$logo_url = affgsc_sanitize_https_url((string)get_post_meta($post_id, 'affgsc_logo_url', true));
if ($logo_url === '') return;
$status = sanitize_key((string)get_post_meta($post_id, 'affgsc_image_cache_status', true));
$last_try = (int)get_post_meta($post_id, 'affgsc_image_cache_last_try', true);
$now = time();
if ($status === 'pending' && $last_try > ($now - HOUR_IN_SECONDS)) return;
if ($status === 'error' && $last_try > ($now - (12 * HOUR_IN_SECONDS))) return;
if ($status === 'ok') return;
affgsc_enqueue_image_cache($post_id);
}
function affgsc_is_probably_bot_ua(): bool {
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower(sanitize_text_field(wp_unslash((string)$_SERVER['HTTP_USER_AGENT']))) : '';
if ($ua === '') return false;
$needles = [
'bot', 'spider', 'crawler', 'slurp', 'headless', 'lighthouse',
'pagespeed', 'wget', 'curl', 'python-requests', 'facebookexternalhit'
];
foreach ($needles as $needle) {
if (strpos($ua, $needle) !== false) {
return true;
}
}
return false;
}
function affgsc_image_cache_rate_limited(int $post_id): bool {
$ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash((string)$_SERVER['REMOTE_ADDR'])) : '';
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash((string)$_SERVER['HTTP_USER_AGENT'])) : '';
$base = md5($ip . '|' . $ua);
$global_key = 'affgsc_imgq_rate_' . $base;
$global_count = (int)get_transient($global_key);
if ($global_count >= 120) {
return true;
}
set_transient($global_key, $global_count + 1, HOUR_IN_SECONDS);
$post_key = 'affgsc_imgq_post_' . md5($base . '|' . $post_id);
if ((int)get_transient($post_key) > 0) {
return true;
}
set_transient($post_key, 1, 10 * MINUTE_IN_SECONDS);
return false;
}
function affgsc_ajax_queue_image_cache(): void {
check_ajax_referer('affgsc_public_action', 'nonce');
$post_id = isset($_POST['post_id']) && is_scalar($_POST['post_id']) ? absint(wp_unslash((string)$_POST['post_id'])) : 0;
if (!affgsc_is_public_game($post_id)) {
wp_send_json_success(['queued' => false, 'reason' => 'invalid_post']);
}
if (!affgsc_should_cache_images_to_media()) {
wp_send_json_success(['queued' => false, 'reason' => 'disabled']);
}
if (affgsc_is_probably_bot_ua()) {
wp_send_json_success(['queued' => false, 'reason' => 'bot']);
}
if (affgsc_image_cache_rate_limited($post_id)) {
wp_send_json_success(['queued' => false, 'reason' => 'rate_limited']);
}
affgsc_maybe_schedule_game_image_cache($post_id);
wp_send_json_success(['queued' => true]);
}
function affgsc_image_cache_worker(): void {
if (get_transient('affgsc_image_cache_worker_lock')) {
return;
}
set_transient('affgsc_image_cache_worker_lock', 1, 55);
try {
$queue = affgsc_image_cache_queue();
if (!$queue) {
return;
}
$per_tick = max(1, (int)apply_filters('affgsc_image_cache_per_tick', 2));
$processed = 0;
while ($queue && $processed < $per_tick) {
$post_id = (int)array_shift($queue);
affgsc_write_image_cache_queue($queue);
if ($post_id > 0) {
affgsc_cache_game_image_job($post_id);
}
$processed++;
}
if ($queue) {
affgsc_kick_image_cache_worker(20);
}
} finally {
delete_transient('affgsc_image_cache_worker_lock');
}
}
function affgsc_cache_game_image_job(int $post_id): void {
$post_id = absint($post_id);
if ($post_id <= 0 || get_post_type($post_id) !== AFFGSC_POST_TYPE) return;
if (!affgsc_should_cache_images_to_media()) return;
if (has_post_thumbnail($post_id)) {
update_post_meta($post_id, 'affgsc_image_cache_status', 'ok');
return;
}
$logo_url = affgsc_sanitize_https_url((string)get_post_meta($post_id, 'affgsc_logo_url', true));
if ($logo_url === '') {
update_post_meta($post_id, 'affgsc_image_cache_status', 'error');
update_post_meta($post_id, 'affgsc_image_cache_error', 'Empty image URL');
return;
}
update_post_meta($post_id, 'affgsc_image_cache_last_try', time());
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$attachment_id = media_sideload_image($logo_url, $post_id, affgsc_game_title_plain($post_id), 'id');
if (is_wp_error($attachment_id)) {
update_post_meta($post_id, 'affgsc_image_cache_status', 'error');
update_post_meta($post_id, 'affgsc_image_cache_error', sanitize_text_field($attachment_id->get_error_message()));
update_post_meta($post_id, 'affgsc_image_cache_attempts', (int)get_post_meta($post_id, 'affgsc_image_cache_attempts', true) + 1);
return;
}
set_post_thumbnail($post_id, (int)$attachment_id);
update_post_meta((int)$attachment_id, '_affgsc_cached_game_image', '1');
update_post_meta($post_id, 'affgsc_image_cache_status', 'ok');
update_post_meta($post_id, 'affgsc_image_cache_cached_at', affgsc_now());
delete_post_meta($post_id, 'affgsc_image_cache_error');
}
function affgsc_real_play_url(int $post_id): string {
if ((string)affgsc_setting('real_play_enabled', '0') !== '1') {
return '';
}
$custom = affgsc_sanitize_https_url((string)get_post_meta($post_id, 'affgsc_real_play_url', true));
if ($custom !== '') {
return $custom;
}
$global = affgsc_sanitize_https_url((string)affgsc_setting('real_play_url', ''));
if ($global !== '') {
return $global;
}
return get_permalink($post_id) ?: '';
}
function affgsc_ajax_real_play_url(): void {
check_ajax_referer('affgsc_public_action', 'nonce');
if (affgsc_public_rate_limited('real_play_url', 120, HOUR_IN_SECONDS)) {
wp_send_json_error(['message' => __('Too many requests. Please try again later.', 'affgate-slot-catalog')], 429);
}
$post_id = isset($_POST['post_id']) && is_scalar($_POST['post_id']) ? absint(wp_unslash((string)$_POST['post_id'])) : 0;
if (!affgsc_is_public_game($post_id)) {
wp_send_json_error(['message' => __('Invalid game.', 'affgate-slot-catalog')], 400);
}
$url = affgsc_real_play_url($post_id);
if ($url === '') {
wp_send_json_error(['message' => __('Real Play URL is not available.', 'affgate-slot-catalog')], 404);
}
wp_send_json_success(['url' => esc_url_raw($url)]);
}
function affgsc_casino_redirect(): void {
check_ajax_referer('affgsc_public_action', 'nonce');
if (affgsc_public_rate_limited('casino_redirect', 120, HOUR_IN_SECONDS)) {
wp_die(esc_html__('Too many requests. Please try again later.', 'affgate-slot-catalog'), '', ['response' => 429]);
}
$casino_id = isset($_POST['casino_id']) && is_scalar($_POST['casino_id']) ? sanitize_key(wp_unslash((string)$_POST['casino_id'])) : '';
$link_type = isset($_POST['link_type']) && is_scalar($_POST['link_type']) ? sanitize_key(wp_unslash((string)$_POST['link_type'])) : 'visit';
if (!in_array($link_type, ['visit', 'review'], true)) $link_type = 'visit';
$redirect_url = '';
$casinos = affgsc_setting('casinos', []);
if ($casino_id !== '' && is_array($casinos)) {
foreach ($casinos as $casino) {
if (!is_array($casino) || !hash_equals((string)($casino['id'] ?? ''), $casino_id)) continue;
$url_key = $link_type === 'review' ? 'review_url' : 'url';
$redirect_url = affgsc_sanitize_https_url((string)($casino[$url_key] ?? ''));
break;
}
}
if ($redirect_url === '') {
wp_die(esc_html__('Casino link is not available.', 'affgate-slot-catalog'), '', ['response' => 404]);
}
nocache_headers();
header('X-Robots-Tag: noindex, nofollow', true);
header('Referrer-Policy: no-referrer', true);
$redirect_host = strtolower((string)wp_parse_url($redirect_url, PHP_URL_HOST));
$allow_redirect_host = static function (array $hosts) use ($redirect_host): array {
if ($redirect_host !== '') $hosts[] = $redirect_host;
return array_values(array_unique($hosts));
};
add_filter('allowed_redirect_hosts', $allow_redirect_host);
wp_safe_redirect($redirect_url, 302, 'AffGate Slot Catalog');
remove_filter('allowed_redirect_hosts', $allow_redirect_host);
exit;
}
function affgsc_taxonomy_directory(string $taxonomy, string $public_setting, string $query_key, array $options = []): string {
affgsc_enqueue_public();
$ids_raw = trim((string)($options['id'] ?? ''));
$ids = affgsc_parse_id_list($ids_raw);
if ($ids_raw !== '' && !$ids) return '';
$limit = min(500, max(0, (int)($options['limit'] ?? 0)));
$term_args = [
'taxonomy' => $taxonomy,
'hide_empty' => true,
'number' => $limit > 0 ? $limit : 500,
];
if ($ids) {
$term_args['include'] = $ids;
$term_args['orderby'] = 'include';
}
$terms = get_terms($term_args);
if (is_wp_error($terms) || !$terms) return '';
$catalog_page_id = affgsc_catalog_page_id('catalog');
$catalog_url = $catalog_page_id > 0 ? get_permalink($catalog_page_id) : home_url('/');
$scheme = affgsc_shortcode_color_scheme($options['style_theme'] ?? '');
ob_start();
?>
term_id, 'affgsc_provider_logo', true));
/* translators: %d: game count. */
$term_game_count = sprintf(__('%d games', 'affgate-slot-catalog'), (int)$term->count);
?>
slug, $catalog_url);
?>
name); ?>
'', 'limit' => '', 'style_theme' => '', 'main_color' => ''], is_array($atts) ? $atts : [], 'affgsc_providers');
return affgsc_taxonomy_directory(AFFGSC_TAX_PROVIDER, 'public_provider_pages', 'provider', $atts);
}
function affgsc_shortcode_types($atts = []): string {
$atts = shortcode_atts(['id' => '', 'limit' => '', 'style_theme' => '', 'main_color' => ''], is_array($atts) ? $atts : [], 'affgsc_types');
return affgsc_taxonomy_directory(AFFGSC_TAX_TYPE, 'public_type_pages', 'type', $atts);
}
function affgsc_shortcode_themes($atts = []): string {
$atts = shortcode_atts(['id' => '', 'limit' => '', 'style_theme' => '', 'main_color' => ''], is_array($atts) ? $atts : [], 'affgsc_themes');
return affgsc_taxonomy_directory(AFFGSC_TAX_THEME, 'public_theme_pages', 'theme', $atts);
}
function affgsc_breadcrumbs_html(string $kind, string $current_label): string {
$page_id = affgsc_catalog_page_id($kind);
if ($page_id <= 0) return '';
$ids = array_reverse(array_map('absint', get_post_ancestors($page_id)));
$ids[] = $page_id;
$items = [];
$items[] = '' . esc_html__('Home', 'affgate-slot-catalog') . '';
foreach ($ids as $id) {
$items[] = '' . esc_html(get_the_title($id)) . '';
}
$items[] = '' . esc_html($current_label) . '';
return '';
}
function affgsc_prepend_game_breadcrumbs(string $content): string {
if (is_admin() || !is_singular(AFFGSC_POST_TYPE) || !in_the_loop() || !is_main_query()) return $content;
$post_id = get_the_ID();
if ($post_id <= 0 || get_post_type($post_id) !== AFFGSC_POST_TYPE) return $content;
return affgsc_breadcrumbs_html('catalog', affgsc_game_h1($post_id)) . $content;
}
function affgsc_taxonomy_setting_key(string $taxonomy): string {
if ($taxonomy === AFFGSC_TAX_PROVIDER) return 'public_provider_pages';
if ($taxonomy === AFFGSC_TAX_TYPE) return 'public_type_pages';
if ($taxonomy === AFFGSC_TAX_THEME) return 'public_theme_pages';
return '';
}
function affgsc_taxonomy_archive_enabled(string $taxonomy): bool {
$key = affgsc_taxonomy_setting_key($taxonomy);
if ($key === '') return false;
return (string)affgsc_setting($key, '0') === '1';
}
function affgsc_taxonomy_template_include(string $template): string {
if (!is_tax([AFFGSC_TAX_PROVIDER, AFFGSC_TAX_TYPE, AFFGSC_TAX_THEME])) {
return $template;
}
$term = get_queried_object();
if (!$term instanceof WP_Term) {
return $template;
}
if (!affgsc_taxonomy_archive_enabled((string)$term->taxonomy)) {
return $template;
}
$custom = AFFGSC_DIR . 'includes/templates/taxonomy-archive.php';
return file_exists($custom) ? $custom : $template;
}