prefix . 'domo_stats'; } function domo_install_stats(): void { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = domo_stats_table(); $charset = $wpdb->get_charset_collate(); dbDelta("CREATE TABLE $table ( post_id bigint(20) unsigned NOT NULL, day date NOT NULL, country char(2) NOT NULL DEFAULT '', lang varchar(5) NOT NULL DEFAULT '', source varchar(40) NOT NULL DEFAULT '', views int(10) unsigned NOT NULL DEFAULT 0, uniques int(10) unsigned NOT NULL DEFAULT 0, enquiries int(10) unsigned NOT NULL DEFAULT 0, whatsapp int(10) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (post_id,day,country,lang,source), KEY day (day) ) $charset;"); update_option('domo_db_version', DOMO_DB_VERSION, false); } add_action('admin_init', function () { if (get_option('domo_db_version') !== DOMO_DB_VERSION) { domo_install_stats(); } }); /** Add to today's counters for one page/country/language/source row. */ function domo_stats_bump(int $post_id, string $lang, string $source, array $add): void { global $wpdb; $cols = array_intersect_key(array_merge(['views' => 0, 'uniques' => 0, 'enquiries' => 0, 'whatsapp' => 0], $add), array_flip(['views', 'uniques', 'enquiries', 'whatsapp'])); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- write to the plugin's own counter table; nothing to cache. $wpdb->query($wpdb->prepare( 'INSERT INTO %i (post_id, day, country, lang, source, views, uniques, enquiries, whatsapp) VALUES (%d, %s, %s, %s, %s, %d, %d, %d, %d) ON DUPLICATE KEY UPDATE views = views + VALUES(views), uniques = uniques + VALUES(uniques), enquiries = enquiries + VALUES(enquiries), whatsapp = whatsapp + VALUES(whatsapp)', domo_stats_table(), $post_id, current_time('Y-m-d'), domo_visitor_country(), substr(sanitize_key($lang), 0, 5), $source, $cols['views'], $cols['uniques'], $cols['enquiries'], $cols['whatsapp'] )); } /** Country from the CDN or server, never from a third-party lookup. */ function domo_visitor_country(): string { foreach (['HTTP_CF_IPCOUNTRY', 'GEOIP_COUNTRY_CODE', 'HTTP_X_COUNTRY_CODE', 'HTTP_CLOUDFRONT_VIEWER_COUNTRY'] as $h) { $c = strtoupper(sanitize_text_field(wp_unslash($_SERVER[$h] ?? ''))); if (preg_match('/^[A-Z]{2}$/', $c) && $c !== 'XX' && $c !== 'T1') { return $c; } } return ''; } /** Group a referrer or utm_source into a short, readable source label. */ function domo_source(string $utm, string $referrer): string { $utm = sanitize_key($utm); if ($utm !== '') { return substr($utm, 0, 40); } $host = strtolower((string) wp_parse_url($referrer, PHP_URL_HOST)); $host = preg_replace('/^(www|m|l|lm)\./', '', $host); if ($host === '' || $host === strtolower((string) wp_parse_url(home_url(), PHP_URL_HOST))) { return 'direct'; } $groups = ['google' => 'google', 'bing' => 'bing', 'facebook' => 'facebook', 'fb.' => 'facebook', 'instagram' => 'instagram', 'whatsapp' => 'whatsapp', 'linkedin' => 'linkedin', 'idealista' => 'idealista', 'kyero' => 'kyero', 't.co' => 'x', 'twitter' => 'x', 'youtube' => 'youtube', 'tiktok' => 'tiktok', 'mail.' => 'email']; foreach ($groups as $needle => $label) { if (str_contains($host, $needle)) { return $label; } } return substr($host, 0, 40); } /** A visitor is counted once per page per day using a salted hash that is never stored. */ function domo_is_new_visitor(int $post_id): bool { $day = current_time('Ymd'); $salt = get_option('domo_salt'); if (!is_array($salt) || ($salt['day'] ?? '') !== $day) { $salt = ['day' => $day, 'value' => wp_generate_password(32, true, true)]; update_option('domo_salt', $salt, false); } $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'] ?? '')); $ua = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? '')); $key = 'domo_v_' . substr(hash('sha256', $salt['value'] . '|' . $ip . '|' . $ua . '|' . $post_id), 0, 32); if (get_transient($key)) { return false; } set_transient($key, 1, DAY_IN_SECONDS); return true; } function domo_is_bot(): bool { $ua = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? '')); return $ua === '' || (bool) preg_match('/bot|crawl|spider|slurp|preview|facebookexternalhit|whatsapp|headless|lighthouse|pingdom|monitor/i', $ua); } // Beacon endpoint: works with page caching because it runs from JavaScript. add_action('wp_ajax_nopriv_domo_track', 'domo_track'); add_action('wp_ajax_domo_track', 'domo_track'); function domo_track(): void { // Every beacon carries a nonce printed on the page. If a page cache served an expired one, the visit is simply not counted. if (!check_ajax_referer('domo_track', 'n', false)) { wp_die('', '', ['response' => 204]); } $post_id = absint($_POST['p'] ?? 0); $type = sanitize_key($_POST['t'] ?? ''); if (!$post_id || get_post_type($post_id) !== 'domo_property' || get_post_status($post_id) !== 'publish' || domo_is_bot() || is_user_logged_in()) { wp_die('', '', ['response' => 204]); } $lang = sanitize_key($_POST['l'] ?? ''); $source = domo_source(sanitize_text_field(wp_unslash($_POST['u'] ?? '')), esc_url_raw(wp_unslash($_POST['r'] ?? ''))); if ($type === 'view') { domo_stats_bump($post_id, $lang, $source, ['views' => 1, 'uniques' => domo_is_new_visitor($post_id) ? 1 : 0]); } elseif ($type === 'wa') { domo_stats_bump($post_id, $lang, $source, ['whatsapp' => 1]); } wp_die('', '', ['response' => 204]); } /** Totals and breakdowns for one page over the last N days. */ function domo_stats_summary(int $post_id, int $days = 30): array { global $wpdb; $table = domo_stats_table(); $since = gmdate('Y-m-d', strtotime(current_time('Y-m-d') . ' -' . ($days - 1) . ' days')); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aggregate read from the plugin's own table, shown on one admin screen. $totals = $wpdb->get_row($wpdb->prepare('SELECT COALESCE(SUM(views),0) views, COALESCE(SUM(uniques),0) uniques, COALESCE(SUM(enquiries),0) enquiries, COALESCE(SUM(whatsapp),0) whatsapp FROM %i WHERE post_id = %d AND day >= %s', $table, $post_id, $since), ARRAY_A) ?: ['views' => 0, 'uniques' => 0, 'enquiries' => 0, 'whatsapp' => 0]; $by = function (string $col) use ($wpdb, $table, $post_id, $since) { if (!in_array($col, ['country', 'lang', 'source'], true)) { return []; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- aggregate read from the plugin's own table; column is whitelisted above. return $wpdb->get_results($wpdb->prepare('SELECT %i AS label, SUM(uniques) uniques, SUM(enquiries) + SUM(whatsapp) leads FROM %i WHERE post_id = %d AND day >= %s GROUP BY %i ORDER BY uniques DESC LIMIT 6', $col, $table, $post_id, $since, $col), ARRAY_A) ?: []; }; return ['days' => $days, 'totals' => array_map('intval', $totals), 'country' => $by('country'), 'lang' => $by('lang'), 'source' => $by('source')]; } function domo_country_name(string $code): string { if ($code === '') { return __('Unknown', 'domopage'); } if (class_exists('Locale')) { $name = \Locale::getDisplayRegion('-' . $code, get_user_locale()); if ($name && $name !== $code) { return $name; } } return $code; } /** Seller report card on the review screen. Printable to PDF from the browser. */ function domo_render_report(int $post_id, array $d): void { $sum = domo_stats_summary($post_id); $t = $sum['totals']; $leads = $t['enquiries'] + $t['whatsapp']; $rate = $t['uniques'] ? round($leads / $t['uniques'] * 100, 1) : 0; $names = domo_language_names(); $s = domo_settings(); ?>