Download the PHP package keyagency/kai-personalize without Composer

On this page you can find all versions of the php package keyagency/kai-personalize. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package kai-personalize

Kai Personalize - Statamic Add-on

Statamic Marketplace Latest Version

Adaptive content delivery based on visitor attributes and behavior

Overview

Kai Personalize is a professional Statamic add-on that enables you to deliver personalized content based on visitor attributes (browser, IP, location, device fingerprint) and external data sources (weather, news, etc.). Built by Key Agency with AI agent Kai.

Editions

Kai Personalize is available in two editions:

Lite Edition

Perfect for getting started with personalization:

Pro Edition

Advanced features for growing businesses:

Upgrade to Pro at statamic.com/marketplace/addons/kai-personalize

Feature Comparison

Feature Lite Pro
Visitor Tracking ✅ ✅
Session Management ✅ ✅
Browser Detection ✅ ✅
Geolocation (MaxMind) ✅ ✅
API Connections 2 max Unlimited
Personalization Rules 5 max Unlimited
Behavioral Tracking ✅ ✅
Analytics Dashboard ❌ ✅
Engagement Scoring ❌ ✅
Dynamic Segments ❌ ✅
ActiveCampaign Integration ❌ ✅
Bot Blacklist ✅ ✅
Data Export ❌ ✅

Current Status

Status: All core features complete and functional. Now compatible with Statamic 6! See the version badge above for the current release, and CHANGELOG.md for what changed.

✅ What's Working Now:

🔨 Next Up:

Features

Dependencies

Quick Start

Once installed, you can immediately:

  1. View visitor data: Go to /cp/kai-personalize in your Control Panel
  2. Use Antlers tags: Add personalization to your templates (see examples below)
  3. Check settings: Configure features at /cp/kai-personalize/settings

The addon automatically tracks visitors as they browse your site!

Installation

  1. Add the addon to your project:

  2. Publish configuration, translations and assets:

The assets tag holds the Control Panel stylesheet and the tracker script. Publishing lets your webserver hand the tracker out directly; skip it and the addon falls back to serving the file through PHP, which still works but costs a full framework boot per visitor. Republish with --force after every upgrade, and add it to your deploy script — public/vendor is usually gitignored, so a fresh release starts without it.

  1. Run migrations:

  2. Configure your API keys in .env:

  3. (Optional) Set up MaxMind GeoIP2 for local geolocation:

  4. (Optional) Build minified JavaScript:

The minified tracker.min.js (~62% smaller) is served automatically when available. Rebuild after modifying tracker.js.

Configuration

The configuration file is located at config/kai-personalize.php. Key settings include:

MaxMind GeoIP2 (Local Geolocation)

The addon uses MaxMind GeoIP2 for fast, local geolocation lookups without API calls.

Setup

  1. Create a free MaxMind account at https://www.maxmind.com/en/geolite2/signup
  2. Generate a license key in your MaxMind account
  3. Download the databases using the Artisan command:

Available databases:

The command downloads and extracts the .mmdb files to storage/app/geoip/

Configuration

Stored Attributes

When enabled, MaxMind stores these visitor attributes (type: external):

Attribute Example Database
country Netherlands City/Country
country_code NL City/Country
region North Holland City
region_code NH City
city Amsterdam City
postal_code 1012 City
continent Europe City/Country
continent_code EU City/Country
timezone Europe/Amsterdam City
is_eu 1 City/Country
latitude 52.3676 City
longitude 4.9041 City
isp KPN B.V. ASN

Note: Coordinates are not stored when gdpr_mode is enabled.

ActiveCampaign Integration

The addon integrates with ActiveCampaign to automatically identify visitors from email campaigns and personalize content based on their CRM data.

How It Works

  1. User clicks link in ActiveCampaign email → lands on site with tracking cookie (vgo_ee, __actc, etc.)
  2. TrackVisitor middleware detects the AC cookie
  3. Server-side API call fetches contact data (tags, lists, custom fields)
  4. Data stored as visitor attributes (type: crm)
  5. Available via {{ kai:visitor }} tag for personalization

Configuration

Add these settings to your .env file:

Stored Attributes

When a visitor arrives from an ActiveCampaign email, these attributes are stored (type: crm):

Attribute Type Description
ac_contact_id string ActiveCampaign contact ID
ac_email string Contact email address
ac_first_name string First name
ac_last_name string Last name
ac_phone string Phone number
ac_tags json Array of tag names
ac_lists json Object with list membership status
ac_custom_fields json Custom field values
ac_created_at timestamp Account created date
ac_updated_at timestamp Last updated in AC

Usage Examples

Personalize by Tag

Personalize by List Membership

Personalize by Custom Field

Condition Tag with AC Data

Testing

Test the ActiveCampaign integration via command line:

Cookie Decoding

The service automatically handles multiple ActiveCampaign cookie encoding formats:

The default cookie name is vgo_ee but can be configured via KAI_ACTIVECAMPAIGN_COOKIE. Alternative cookies (__actc, contact_email) are checked as fallbacks.

Privacy & GDPR

  1. Cookie consent - Only reads AC cookie if consent given (when cookie_consent_required is enabled)
  2. Data retention - Cache TTL respects AC rate limits (default 24 hours)
  3. Right to be forgotten - AC attributes are cleared when visitor data is deleted
  4. Logging - API calls are logged but sensitive data is masked

Bot Blacklist

The blacklist feature allows you to block specific bots and monitoring tools from being tracked, keeping your analytics clean and focused on real visitors.

Upgrading to 1.2.8? Two things changed here:

  1. The blacklist is now on by default. Prior to 1.2.8 a duplicate blacklist key in the config silently forced it off, so it was inactive even if you thought otherwise. Set KAI_BLACKLIST_ENABLED=false if you want the old behaviour.
  2. If you published the config before 1.2.4, your config/kai-personalize.php has no blacklist key at all. Republish it with php artisan vendor:publish --tag=kai-personalize-config --force so the new options are present.

How It Works

  1. Blacklist entries are stored in the database and managed via the Control Panel
  2. When a request arrives, the blacklist service checks:
    • Bot names (e.g., "semrush", "ahrefsbot")
    • User agent patterns (e.g., "scrapy", "curl")
  3. If KAI_SKIP_KNOWN_BOTS is on, any user agent the parser recognises as a bot is skipped too, so you do not have to maintain a pattern for every crawler — including the search and social crawlers
  4. Blocked requests skip tracking but still access the site normally
  5. Requests matching a blacklist entry are logged with hit counts for analysis

The blacklist check runs before the entry lookup, so bot traffic never pays for resolving a Statamic entry. Patterns are cached (10 minutes by default) and the cache is invalidated automatically when you add, edit or delete an entry.

Why this matters: on a production site we measured 18% of all tracked visitors as recognised bots, each generating a visitor row plus ~29 attribute rows. Leaving the blacklist off is the single largest source of database growth.

Configuration

Add these settings to your .env file:

Default Blacklist

The addon comes pre-seeded with common bots and tools:

SEO/Marketing Bots:

Monitoring/Uptime Services:

AI Scrapers:

User Agent Patterns:

Note: All pre-seeded entries are inactive by default. Enable them individually via the Control Panel.

Search and social crawlers

Googlebot, Bingbot, Slurp, DuckDuckBot, BaiduSpider, YandexBot, FacebookExternalHit, TwitterBot and LinkedInBot get the page exactly like any other visitor, and do not get a visitor row.

Changed in 1.3.0. These nine used to sit on a whitelist that returned early from the blacklist check, which skipped both the patterns and KAI_SKIP_KNOWN_BOTS — so they were the only bots that were tracked. The whitelist was meant to prevent cloaking, but this addon never blocks a request: the check only decides whether to record a visitor. Since a crawler runs no JavaScript it never gets past the temp_ placeholder, so every request left a dead row behind. On one production install 2.921 of 3.538 visitors (83%) were Facebook's link-preview crawler.

Set KAI_SKIP_KNOWN_BOTS=false if you want recognised bots in your statistics.

Management via Control Panel

Navigate to Kai Personalize > Blacklist in your Control Panel to:

  1. View all entries - Type, pattern, description, status, hit count
  2. Add new entries - Bot name or user agent pattern
  3. Toggle active status - Click the badge to enable/disable
  4. View logs - See blocked requests with details
  5. Edit/Delete entries - Full CRUD operations

Seeding the Database

To populate the default blacklist entries, run the seeder:

Or add it to your main DatabaseSeeder:

Browser Detection

The addon uses jenssegers/agent for comprehensive browser and device detection.

Stored Attributes

These attributes are automatically stored for each visitor (type: technical):

Attribute Example Description
browser Chrome Browser name
browser_version 120.0.0.0 Full version string
browser_version_major 120 Major version number
platform OS X Operating system
platform_version 10_15_7 OS version
device Macintosh Device name
device_type desktop mobile, tablet, or desktop
is_mobile 0 Is mobile device (includes tablets)
is_tablet 0 Is tablet
is_desktop 1 Is desktop
is_phone 0 Is phone (mobile but not tablet)
is_bot 0 Is bot/crawler
bot_name Googlebot Bot name (if detected)
accepted_languages en,nl From Accept-Language header

Conditional Content by Browser/Device

Antlers Tags

kai:visitor

Get information about the current visitor:

Derived values (since 1.2.8): google_maps_link, time_of_day and day_of_week are computed when you read them instead of being written to the database. They behave exactly as before in your templates, but no longer cost a row per visitor. time_of_day and day_of_week were already computed live by kai:condition and kai:content, so storing them was pure overhead — they were rewritten on every single page view.

kai:condition

Show content based on conditions:

kai:external

Fetch data from external APIs:

kai:content

Display content based on rules:

kai:session

Manage session data:

kai:api

Make direct API calls with caching:

kai:track

Outputs the client-side tracking script for behavioral analytics. This enables automatic tracking of user interactions without requiring manual event tagging.

Usage

Add to your main layout file (typically in <head> or before closing </body>):

What It Tracks

When enabled, the tracker automatically captures:

Feature Description
Page Views URL, title, referrer, screen dimensions
Scroll Depth Thresholds: 25%, 50%, 75%, 90%, 100%
Reading Time Active reading time per page
Clicks All clicks with element, position, and hesitation time
Rage Clicks 3+ clicks on same element within 2 seconds
Dead Clicks Clicks on non-interactive elements
Visibility Page visibility changes (hidden/visible/pagehide)
Exit Intent Mouse leaving viewport (potential exit)
Idle Detection No activity for 60+ seconds
Device Viewport, screen, touch, connection info
Preferences Dark mode, reduced motion, language, timezone
Fingerprint Browser fingerprint (canvas, WebGL, audio)

Configuration

Features are controlled via config/kai-personalize.php:

Master Switch

To completely disable tracking:

Or in config:

When disabled, the tag outputs nothing.

Privacy

The tracker respects:

JavaScript API

The tracker exposes a global API for manual control:

How It Works

  1. The tag outputs a config script with visitor/session IDs
  2. Loads tracker.js from /kai-personalize/tracker.js
  3. Events are queued and batched (configurable threshold and interval)
  4. Queue is persisted to localStorage (survives page refreshes)
  5. Uses sendBeacon for reliable delivery on page unload
  6. Cached for 1 day on the client

Queue Configuration

The tracker uses intelligent queue management to ensure reliable event delivery:

Setting Default Description
threshold 5 events Auto-send when queue reaches this size
sendInterval 20000 ms (20s) Periodic send interval
persistQueue true Enable localStorage persistence
storageKey kai_tracker_queue localStorage key name
maxEventAge 3600000 ms (1h) Maximum event age before discarding

Configure via .env:

localStorage Persistence:

kai:behavior

Get behavioral statistics for the current visitor:

kai:tracking

Returns the tracking endpoint and whether behavioural tracking is on.

You rarely need this — {{ kai:track }} renders the tracker and wires up the endpoint itself.

Tracking endpoint security

The tracking endpoint needs no setup in the host application. It is exempt from CSRF verification by the addon itself (routes/actions.php), because the tracker sends its final batch with navigator.sendBeacon() on page unload — which cannot set headers — and events must keep arriving after a visitor's session has expired.

Requests are guarded two ways instead:

Upgrading from < 1.2.12? The rate limit counters of earlier versions never expired on a file cache store, which left an IP on 429 for good once it had passed the limit. Run php artisan cache:clear after upgrading to drop those entries; the new counters use different cache keys and expire on their own.

Upgrading from < 1.2.9? Earlier versions asked you to add a validateCsrfTokens(except: …) rule to bootstrap/app.php. That is no longer needed and the rule can be removed. The HMAC signature layer and KAI_TRACKING_SECRET were dropped in the same release.

Cloudflare Configuration

When using Cloudflare (or any reverse proxy/load balancer), you must configure trusted proxies to ensure correct IP address detection for visitor tracking.

Trusting Cloudflare Proxies

Earlier versions of this README told you to set TRUSTED_PROXIES in .env. That does nothing on Laravel 11 and 12 — no middleware reads that variable any more. Trusted proxies are configured in bootstrap/app.php.

Add this to bootstrap/app.php, with Cloudflare's ranges in config/trusted-proxies.php:

*Use an explicit list, not `''.** Symfony honours theX-Forwarded-headers only whenREMOTE_ADDRis in the list, which is what keeps this safe on an installation where some hosts sit behind Cloudflare and others are served directly. With''any visitor on a directly served host can send an X-Forwarded-For` of their choosing and get fabricated geolocation plus a fresh rate-limit bucket per request.

The current ranges are published at https://www.cloudflare.com/ips-v4 and /ips-v6. They change rarely; re-check them when geolocation starts looking wrong.

Why This Is Needed

Without trusting proxies, Laravel/Statamic will see Cloudflare's IP addresses instead of your visitors' real IP addresses, causing:

Verifying IP Detection

After configuring trusted proxies, verify that visitor IPs are correctly detected:

The IP displayed by the addon should match your actual IP address, not Cloudflare's.

API Connections

Built-in Providers

The addon supports these built-in API providers:

Weather APIs:

Geolocation APIs:

Custom API Connections

Manage your external API connections via the Control Panel:

  1. Navigate to Kai Personalize > API Connections
  2. Click Create Connection
  3. Fill in the details:
    • Name
    • Provider type (Weather, Geolocation, News, Exchange, Custom)
    • API URL
    • Authentication (None, API key, Bearer, Basic, OAuth2, Custom)
    • Rate limits
    • Cache duration
    • Custom headers (optional)
  4. Test the connection to ensure it works
  5. View statistics: Total requests, success rate, cache usage
  6. Manage cache: Clear cached responses when needed

Testing Connections

Test API connections from the command line:

Artisan Commands

Visitor Identity

A visitor row is keyed on fingerprint_hash, and that column holds one of three forms. Which one you see tells you how much the identity is worth:

Form Example Meaning
v2_ + 32 hex v2_e8eaefd6… A random identifier the browser stores. Stable and collision-free.
fp2_ + 8 hex fp2_cf4fe6e0 A fingerprint computed from device properties. Fallback only.
temp_ + session id temp_4h3Dwg… A server-side placeholder; no client has reported in yet.

The stored identifier is the primary key of a visitor's identity. The tracker generates it once, keeps it in localStorage under kai_visitor, and sends it as visitor_key with every batch. The server prefers it over the fingerprint.

The computed fingerprint is a fallback, not an identity. It is derived from canvas, WebGL, screen size, colour depth, timezone, language and platform — and those collide. Safari on iOS withholds canvas and the WebGL debug extension, so every visitor on that platform with the same screen and locale lands on one value. On a production install 50 fingerprints covered 55% of all sessions, one of them spanning 58 different user agents. Treat a fp2_ visitor as "probably several people" and a v2_ visitor as one.

A visitor falls back to fp2_ when storage is unavailable — a private window, blocked storage, or consent that was refused (the identifier is only stored with consent; see Privacy & GDPR).

temp_ rows are not visitors. They are placeholders waiting for the tracker to report in, and a client that never runs JavaScript — a crawler, a browser with scripting off — leaves one behind per request. kai:cleanup-fingerprints removes the ones that never became anything.

Database Structure

The addon uses the following tables (all prefixed with kai_personalize_):

Privacy & GDPR

The addon includes several privacy features:

Cookie consent

The tracker asks, in this order:

  1. window.KaiConsentCallback — define this and it decides, full stop. Use it for a consent tool the addon does not know.
  2. Cookiebot, through Cookiebot.consent.statistics. It also listens for CookiebotOnAccept and CookiebotOnDecline, so consent given after page load starts tracking without a reload, and withdrawing it clears the queue and the stored identifier.
  3. The consent cookies of a few other tools (cookie_consent, cookieconsent_status, cc_cookie, catConsent), where an explicit false/deny counts as a refusal.
  4. Nothing found: tracking continues, unless KAI_COOKIE_CONSENT_REQUIRED=true.

A site without a consent tool is unaffected — step 2 only runs when Cookiebot is actually present. A tool that is present and says no is always honoured, whatever KAI_COOKIE_CONSENT_REQUIRED is set to; that setting only decides what happens when nobody answers.

The setting drives both sides: the tracker in the browser and TrackVisitor on the server, which otherwise creates a visitor row before the banner is answered.

The v2_ identifier is only written to localStorage once consent is given. Without it a visitor falls back to the computed fingerprint, which is weaker — see Visitor Identity.

Tracking Security

The addon includes multiple layers of protection to prevent data pollution and abuse:

Built-in Protections

Protection Description Default
Rate Limiting Max 60 requests/minute, 500/hour per IP ✅ Enabled
Input Sanitization Event types validated, HTML stripped, whitelist keys ✅ Enabled
Max Events Maximum 50 events per request ✅ Enabled
Event Type Regex Only alphanumeric + underscore allowed ✅ Enabled
Origin Validation Whitelist allowed domains ⚠️ Optional

Restricting Origins (Recommended for Production)

The tracking endpoint accepts requests from any origin until you list the ones you trust:

Every host that serves pages carrying the tracker has to be in this list — including each subdomain and any additional domain. A host that is missing gets its requests rejected with 403 Invalid origin, logged as Kai tracking: Invalid referer.

Security Best Practices

  1. Always use HTTPS - Tracking payloads can be read over HTTP
  2. Set allowed origins - Restricts cross-origin requests
  3. Monitor logs - Rejected origins and rate-limit hits are logged
  4. Use a WAF - CloudFlare or similar for DDoS protection

Performance

The addon is optimized for performance:

Multilingual Support

The addon is fully translated in:

All Control Panel text, error messages, and documentation are available in both languages. The addon automatically detects the current site locale.

Control Panel

Access the Control Panel interface at /cp/kai-personalize:

Tools tab

Settings → Tools runs three maintenance commands from the browser, for environments without shell access:

Tool Runs
Remove provisional visitors kai:cleanup-fingerprints --apply
Clear API cache kai:refresh-cache --all
Delete visitor data older than 30 days kai:cleanup --days=30 --force

Requires the Manage Settings permission. The two destructive tools ask for confirmation first, and the command output is shown as-is.

The browser sends a short slug, never a command string, and the arguments are part of the server-side definition. There is no way to reach a command that is not one of these three, or to hand one an argument it was not given here — --all on the cleanup would wipe everything rather than 30 days.

✅ Fully Implemented:

Analytics & Engagement Scoring

The addon now includes comprehensive analytics and engagement tracking:

Engagement Score (0-100)

Each visitor receives an engagement score based on:

All four components are measured within the selected period, so the score answers "how engaged is this visitor right now", not "how engaged have they ever been".

Visit frequency counts session rows rather than the visit_count column. That column is an all-time total and cannot be scoped to a window, so mixing the two would make the same data score differently depending on the period selected — "all time" could even rank lower than "last 30 days".

visit_count itself counts visits, not page views: it is incremented once per session. Before 1.3.0 it was raised inside the per-page-view path, which only looked right because a stale session key made every page view a new visitor row. Values recorded before 1.3.0 are not comparable with newer ones.

Color-coded badges:

Behavioral Summary

For each visitor, track:

Page Analytics

Navigate to Analytics > Pages to see:

Visitor Page History

Each visitor profile now includes:

Available Event Types

The addon tracks these behavioral events via the kai:track tag:

Example Use Cases

Weather-Based Content

Returning Visitor Welcome

Location-Based Content

Device-Specific CTAs

Development

Local Development Setup

When developing the addon locally, use Composer's path repository to symlink the addon directory. Changes reflect instantly, and you commit in the addon repo separately.

Complete Setup

  1. Add path repository to your project's composer.json:

Note: The path repository tells Composer "this package is right here on my disk." Using just "dev-main" without the path repository makes Composer look for the package on Packagist.

  1. Install the addon:

  2. Verify the symlink was created:

  3. Develop normally - Changes in the addon directory reflect instantly in your project. Commit in the addon repo separately.

This is the standard Statamic addon development workflow recommended by the Statamic team.

Running Tests

Code Style

Support

For support, please contact:

License

Proprietary - Copyright © Key Agency

Credits

Developed by Key Agency with AI agent Kai.

Roadmap

✅ Completed (v1.0)

✅ Completed (v1.1)

Short Term (Next Release)

Medium Term

Long Term


All versions of kai-personalize with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1
statamic/cms Version ^6.0
jenssegers/agent Version ^2.6
geoip2/geoip2 Version ^3.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package keyagency/kai-personalize contains the following files

Loading the files please wait ...