Skip to content

Code Map

Richard Kent Gates edited this page Jun 9, 2026 · 3 revisions

Code Map

A full map of every source file in the Rich Statistics repository — what each file does, what it exports, and how files depend on one another. Use this as a reference when navigating the codebase.

Deliverables

The repository produces three independent deliverables from the same source:

Deliverable Source Distribution
WordPress plugin ZIP All PHP + JS in repo root WordPress.org (free) / Freemius (premium)
PWA / web app docs/app/ Served from app.richstatistics.com
Linux desktop app (.deb) docs/app/ via src-tauri/ APT repo at app.richstatistics.com/apt

The PWA and desktop app share the same JS/CSS source (docs/app/). Tauri's frontendDist: "../docs/app" bundles those files directly into the .deb. Runtime feature detection via window.__TAURI__ splits desktop-only behaviour (e.g. update banners) from the browser PWA.

Plugin Bootstrap

File What it does
rich-statistics.php Plugin entry point. Defines constants (RSA_VERSION, RSA_DIR, RSA_URL, RSA_ASSETS_URL, RSA_APP_URL, RSA_APP_ENV), initialises the Freemius SDK via rs_fs(), autoloads all classes on plugins_loaded. RSA_APP_URL is dynamically determined via rsa_detect_app_url() which reads the site hostname and maps it to the correct PWA subdomain. Premium classes are only loaded when can_use_premium_code__premium_only() returns true.
vendor/freemius/ Committed Freemius SDK — handles licensing, payments, and in-plugin auto-updates. Never downloaded at build time.

Database Layer

File What it does
includes/class-db.php Schema definition and all database lifecycle logic. install() creates tables via dbDelta(). prune_old_data() deletes rows beyond the retention window (default 90 days). aggregate_heatmap() runs nightly and buckets yesterday's clicks into a 2 % grid. seed_defaults() writes first-run option values.

Five tables (all prefixed {wpdb->prefix}rsa_):

Table Contents
rsa_events One row per pageview — session_id, page, referrer_domain, OS, browser, browser_version, language, timezone, viewport, time_on_page, bot_score, UTM fields, created_at
rsa_sessions One row per browser session — session_id (UNIQUE), pages_viewed, total_time, entry_page, exit_page, OS, browser, language, timezone, created_at, updated_at
rsa_clicks (premium) One row per tracked click — element tag/id/class/text, href protocol/value, matched rule, x_pct, y_pct
rsa_heatmap (premium) Nightly-aggregated click buckets — page, x_pct, y_pct, weight, date_bucket
rsa_wc_events (WooCommerce) WooCommerce events — event_type, product_id, product_name, product_sku, quantity, order_total, order_currency

Tracking — Browser to Database

File What it does
includes/class-tracker.php Enqueues tracker.js on the frontend. Handles the rsa_track AJAX action: verifies nonce, rate-limits per session, sanitises all fields, calls RSA_Bot_Detection::score(), then upserts rsa_sessions and inserts into rsa_events.
assets/js/tracker.js Frontend tracker (ES5). Respects Do Not Track and Global Privacy Control. Gathers OS, browser, UTM, viewport, and time-on-page. Builds a client-side bot signal bitmask from 10 checks. Sends the payload via the Beacon API (or fetch fallback) to admin-ajax.php?action=rsa_track. In premium mode also sends click events.
includes/class-bot-detection.php Two-layer scoring. score(int $bitmask, ?string $ua) combines client-side signal weights (1–4 pts each) with server-side User-Agent pattern matching. Returns a total score; events at or above the configured threshold are discarded.
includes/class-click-tracking.php (premium) AJAX ingest handler for click events sent by tracker.js. Validates session UUID format, sanitises all element fields, and inserts into rsa_clicks.
includes/class-woocommerce.php (premium) Hooks into WooCommerce actions to record product views, add-to-cart, and order completions as rows in rsa_wc_events. Gated by rsa_woocommerce_enabled option.

Analytics Queries

File What it does
includes/class-analytics.php All read-only SQL aggregation. Key methods: get_overview(), get_top_pages(), get_audience(), get_referrers(), get_campaigns(), get_woocommerce(), get_user_flow(). Every query uses $wpdb->prepare() and applies bot filtering. Called by the admin UI, REST API, email digest, and WP-CLI.

WordPress Admin UI

File What it does
includes/class-admin.php Registers admin menus and sub-pages. Enqueues admin assets. Handles the rsa_save_settings form post. Serves the PWA at the /rs-app/ rewrite rule. Renders the profile-page OTP section (premium). Exposes user_can_access_app() static helper used by the REST API, OTP handler, and profile display.
assets/js/admin-charts.js Chart.js wrappers for the admin dashboard. Reads the RSA_DATA global injected by PHP and renders charts appropriate to the current view.
assets/css/admin.css Admin styles.
templates/admin/*.php One partial per admin sub-page: overview, pages, audience, referrers, campaigns, behavior, user-flow, click-map, heatmap, preferences, export, network-dashboard, network-settings, woocommerce, install, maintenance.

Premium Features

File What it does
includes/class-rest-api.php REST namespace rsa/v1. Endpoints: /info, /track, /verify-otp (public); /overview, /pages, /audience, /referrers, /behavior, /campaigns, /filter-options, /user-settings (free, requires rsa_manage_statistics); /clicks, /heatmap, /export, /woocommerce, /wc-event, /user-flow, /user-flow/journey, /user-flow/sources, /purge-page, /ai/tool (premium). Auth via WordPress Application Passwords. CORS headers allow cross-origin requests including Tauri's tauri:// scheme.
includes/class-heatmap.php Enqueues heatmap assets on the admin heatmap page. The actual nightly aggregation runs via RSA_DB::aggregate_heatmap() on the rsa_daily_maintenance cron.
assets/js/heatmap-overlay.js Canvas-based heatmap renderer. Reads aggregated bucket data from the REST API and draws a weighted heat grid over the page.
assets/css/heatmap.css Heatmap overlay styles.
includes/class-pwa-download.php OTP generation for PWA site pairing and PWA ZIP download. Generates a 6-digit code (SHA-256 hashed transient, 15-minute TTL, single-use). Per-IP rate-limiting (5 wrong attempts per 5 minutes) on the verification endpoint.

Email Digest

File What it does
includes/class-email.php Scheduled HTML digest. Resolves recipients either from a manual list or from all WordPress users with the allowed roles (rsa_allowed_roles). Composes overview + top pages + referrers sections, plus a WooCommerce section when WC tracking is active and premium is enabled. Sends via wp_mail().
templates/email/digest.php HTML email template. Token placeholders: {{OVERVIEW_*}}, {{TOP_PAGES}}, {{REFERRERS}}, {{WC_SECTION}}, {{DASH_URL}}.

WP-CLI

File What it does
cli/class-cli.php Registers the wp rich-stats command group. Subcommands: overview, top-pages, audience, export, purge, email-test, status, clicks (premium), woocommerce (premium).

PWA & Desktop App (docs/app/)

These files are served as the live PWA and are also bundled directly into the Tauri .deb desktop app via frontendDist: "../docs/app".

File What it does
docs/app/index.html PWA shell. When loaded through the WordPress plugin rewrite rule, the admin handler injects the RSA_CONFIG global with the site URL, nonce, and app URL.
docs/app/config.js Auto-detects the WordPress site URL from the script's own src path. Sets window.RSA_CONFIG for use by app.js.
docs/app/app.js All PWA and desktop app logic. Multi-site management via localStorage. OTP two-step pairing flow. REST API calls with Basic auth. View rendering for overview, pages, audience, referrers, behavior, and clicks. Offline cache. Desktop-only features (e.g. showDesktopUpdateBanner()) are gated behind window.__TAURI__ or window.__TAURI_INTERNALS__.
docs/app/sw.js Service Worker. Caches static assets (JS, CSS, chart library). Uses network-first strategy for API calls with cache fallback for offline use.
docs/app/app.css PWA and desktop app UI styles.
docs/app/manifest.json PWA manifest — name, icons, theme colour, display mode.
docs/app/versions.json JSON array of versioned snapshot directory names. Updated automatically by CI on each release tag. Used by the desktop app's version-check logic to detect when a newer app bundle is available.
docs/app/v/{version}/{stable,beta}/ Immutable snapshots of each released app (committed by CI) with channel subdirectories. Allows the desktop app to match its bundled version against the plugin version.

Tauri Desktop App (src-tauri/)

File What it does
src-tauri/tauri.conf.json Tauri configuration. frontendDist: "../docs/app" bundles the shared PWA source. Build target: deb. Window dimensions 1200×800 (min 360×560). CSP allows connect-src * for cross-origin calls to any WordPress install.
src-tauri/src/main.rs Minimal Rust shim. Opens a WebKitGTK window and loads the docs/app/ frontend.

CI / CD (.github/workflows/)

File Trigger What it does
tests.yml Push / PR to main or develop Unit tests (PHP 8.1–8.3, Brain Monkey) and integration tests (PHP 8.1–8.2, WordPress + MySQL 8.0).
build-release.yml v*.*.* tag on main build job — validates PHP syntax, creates plugin ZIP, publishes GitHub Release, commits versioned docs/app/{version}/ snapshot and updates versions.json. build-desktop job (amd64 + arm64) — Tauri builds .deb, SCPs to app server, runs rsa-apt-repo-update. ping-deploy — POSTs to /_deploy/ webhook; server pulls docs/app/ and goes live.

Server Scripts (bin/)

File Status What it does
bin/server-webhook.php Committed — source for _deploy/index.php on the app server Receives POST from CI, verifies DEPLOY_WEBHOOK_TOKEN, runs rsa-app-update.
bin/server-update-webapp.sh Committed — source for /usr/local/bin/rsa-app-update Pulls latest docs/app/ from GitHub and copies to web root.
bin/server-apt-repo-update.sh Committed — source for /usr/local/bin/rsa-apt-repo-update Adds a new .deb to the APT repo, re-signs Release files.
bin/install-wp-tests.sh Committed — used by CI integration tests Downloads and configures a WordPress test suite against a local MySQL instance.
bin/setup-app-server.sh Local only (gitignored) Provisions a new Debian 12 VPS from scratch: Apache, PHP, certbot, ufw, fail2ban, APT repo, CI SSH keypair, webhook token.
bin/setup-apt-repo.sh Local only (gitignored) Initialises the APT repo GPG key and directory structure on the server.

Data Flow

The path a pageview takes from the browser all the way to the analytics dashboard:

  1. Browsertracker.js collects signals, builds a bot bitmask, and sends a POST to admin-ajax.php?action=rsa_track via the Beacon API.
  2. IngestRSA_Tracker::handle_ingest() verifies the nonce, rate-limits, sanitises fields, calls RSA_Bot_Detection::score(), then upserts rsa_sessions and inserts into rsa_events.
  3. Storage — rows live in MySQL until the nightly cron prunes anything beyond the retention window (default 90 days).
  4. Read — Admin UIRSA_Analytics queries aggregate the data; results are injected via wp_localize_script() and rendered by admin-charts.js / Chart.js.
  5. Read — PWA / Desktop — the app authenticates with Application Passwords and calls /wp-json/rsa/v1/*; RSA_Rest_API delegates to RSA_Analytics and returns JSON.
  6. Read — Email — the rsa_send_digest cron calls RSA_Email::send_digest(), which queries RSA_Analytics and sends HTML via wp_mail().
  7. Nightly maintenance — the rsa_daily_maintenance cron runs RSA_DB::prune_old_data() and RSA_DB::aggregate_heatmap().

Option Reference

Default values set by RSA_DB::seed_defaults():

Option key Default Description
rsa_retention_days 90 Days of event data to keep before pruning
rsa_bot_score_threshold 5 Minimum combined bot score to discard a request
rsa_remove_data_on_uninstall 0 Drop tables on plugin deletion
rsa_track_protocol_tel 1 Track tel: link clicks
rsa_track_protocol_mailto 1 Track mailto: link clicks
rsa_track_protocol_geo 1 Track geo: link clicks
rsa_track_protocol_sms 1 Track sms: link clicks
rsa_track_protocol_download 1 Track file download clicks
rsa_click_track_ids "" Comma-separated element IDs to track (premium)
rsa_click_track_classes "" Comma-separated CSS classes to track (premium)
rsa_email_digest_enabled 0 Enable scheduled email digest
rsa_email_digest_frequency weekly Digest frequency: daily / weekly / monthly
rsa_email_digest_recipients admin email Comma-separated recipient addresses
rsa_email_digest_use_roles 0 Send to all users with allowed roles instead of manual list
rsa_allowed_roles ["administrator"] Roles that can access the app, REST API, and OTP generation
rsa_beta_channel 0 Enable beta channel updates for this site
rsa_consent_banner 0 Enable visitor-facing consent banner
rsa_consent_auto 1 Auto-consent all categories on first visit
rsa_network_disable_tracker 0 Network-wide tracker disable (multisite)
rsa_default_retention_days 90 Default retention for new sites (multisite)
rsa_woocommerce_enabled 1 Enable WooCommerce event tracking (premium)

Documentation

Features

User Guide

Compliance


External Links

Clone this wiki locally