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.
Download keyagency/kai-personalize
More information about keyagency/kai-personalize
Files in keyagency/kai-personalize
Package kai-personalize
Short Description Adaptive content delivery based on visitor attributes and behavior
License proprietary
Informations about the package kai-personalize
Kai Personalize - Statamic Add-on
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:
- Visitor tracking & sessions
- Basic rules (max 5 active)
- Geolocation (MaxMind)
- API connections (max 2)
- Behavioral tracking (page views, scroll, clicks)
Pro Edition
Advanced features for growing businesses:
- Everything in Lite
- Unlimited rules & API connections
- Analytics dashboard & engagement scoring
- Dynamic segments
- ActiveCampaign integration
- Data export functionality
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
Version: v1.2.1 - Production Ready Status: All core features complete and functional. Now compatible with Statamic 6!
✅ What's Working Now:
- ✅ Visitor tracking (server-side)
- ✅ Session management
- ✅ Database structure (12 tables)
- ✅ All Antlers tags
- ✅ API services (Weather, Geolocation, Custom)
- ✅ Artisan commands
- ✅ Complete Control Panel Interface:
- ✅ Dashboard with real-time statistics
- ✅ Analytics & Engagement Scoring (NEW)
- ✅ Rules management (CRUD, condition builder, statistics)
- ✅ Visitors management (browse, search, profiles, sessions, page history, behavioral summary)
- ✅ Segments (CRUD, visitor assignment, criteria builder)
- ✅ API Connections (CRUD, testing, cache management)
- ✅ Settings page (configuration overview)
- ✅ Privacy features (IP encryption, DNT, GDPR compliance)
🔨 Next Up:
- Enhanced dashboard with charts
- Export/Import functionality
- Segment-based condition support in Rules
Features
- Browser Detection: Comprehensive browser, device, and bot detection via jenssegers/agent
- Local Geolocation: Fast IP-to-location lookups using MaxMind GeoIP2 local databases (no API calls)
- Browser Fingerprinting: Advanced visitor identification using canvas, WebGL, audio, and more
- Session Management: Leverages Statamic's built-in session system with visitor tracking
- Behavioral Tracking: Monitor page views, time on site, referrers, and UTM parameters
- External API Integration: Connect to weather, news, exchange rates, and custom APIs
- ActiveCampaign Integration: Automatic email campaign visitor tracking and CRM data sync
- Bot Blacklist: Block unwanted bots and monitoring tools from polluting your analytics
- Minified JavaScript: Optimized tracker.js for faster page loads (62% smaller)
- Rule-Based Personalization: Create complex conditions to show different content
- Privacy Compliant: GDPR support, IP encryption, DNT respect, and data anonymization
- Multilingual: Full English and Dutch support
- Control Panel Interface: Comprehensive dashboard for managing all aspects
- Performance Optimized: Caching, queueing, and batch operations
Dependencies
- PHP: ^8.2
- Statamic: ^6.0
- jenssegers/agent: ^2.6 - Browser/device detection
- geoip2/geoip2: ^3.0 - MaxMind GeoIP2 local database reader
Quick Start
Once installed, you can immediately:
- View visitor data: Go to
/cp/kai-personalizein your Control Panel - Use Antlers tags: Add personalization to your templates (see examples below)
- Check settings: Configure features at
/cp/kai-personalize/settings
The addon automatically tracks visitors as they browse your site!
Installation
-
Add the addon to your project:
-
Publish configuration and translations:
-
Run migrations:
-
Configure your API keys in
.env: -
(Optional) Set up MaxMind GeoIP2 for local geolocation:
- (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
- Create a free MaxMind account at https://www.maxmind.com/en/geolite2/signup
- Generate a license key in your MaxMind account
- Download the databases using the Artisan command:
Available databases:
- GeoLite2-City.mmdb - Full location data (country, region, city, postal, timezone, coordinates)
- GeoLite2-Country.mmdb - Country only (smaller, faster)
- GeoLite2-ASN.mmdb - ISP/organization info (optional)
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_modeis 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
- User clicks link in ActiveCampaign email → lands on site with tracking cookie (
vgo_ee,__actc, etc.) - TrackVisitor middleware detects the AC cookie
- Server-side API call fetches contact data (tags, lists, custom fields)
- Data stored as visitor attributes (type:
crm) - 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:
- Base64 encoded email
- URL-encoded + Base64
- Plain text email
- URL-encoded email
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
- Cookie consent - Only reads AC cookie if consent given (when
cookie_consent_requiredis enabled) - Data retention - Cache TTL respects AC rate limits (default 24 hours)
- Right to be forgotten - AC attributes are cleared when visitor data is deleted
- 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.
How It Works
- Blacklist entries are stored in the database and managed via the Control Panel
- When a request arrives, the blacklist service checks:
- Bot names (e.g., "semrush", "ahrefsbot")
- User agent patterns (e.g., "scrapy", "curl")
- Essential SEO bots are always whitelisted (Googlebot, Bingbot, etc.)
- Blocked requests skip tracking but still access the site normally
- All blocked requests are logged with hit counts for analysis
Configuration
Add these settings to your .env file:
Default Blacklist
The addon comes pre-seeded with common bots and tools:
SEO/Marketing Bots:
- Semrush, AhrefsBot, MJ12bot, DotBot
Monitoring/Uptime Services:
- UptimeRobot, Pingdom, StatusCake, Uptrends, Site24x7
AI Scrapers:
- ChatGPT, GPTBot, CCBot, Anthropic, Claude
User Agent Patterns:
- Scrapy, cURL, Wget, Python-requests, Go-http-client
Note: All pre-seeded entries are inactive by default. Enable them individually via the Control Panel.
Whitelist (Always Allowed)
These bots are never blocked, regardless of blacklist settings:
| Bot | Purpose |
|---|---|
| Googlebot | Google Search |
| Bingbot | Bing Search |
| Slurp | Yahoo Search |
| DuckDuckBot | DuckDuckGo Search |
| BaiduSpider | Baidu Search |
| YandexBot | Yandex Search |
| FacebookExternalHit | Facebook link previews |
| TwitterBot | Twitter link previews |
| LinkedInBot | LinkedIn link previews |
Management via Control Panel
Navigate to Kai Personalize > Blacklist in your Control Panel to:
- View all entries - Type, pattern, description, status, hit count
- Add new entries - Bot name or user agent pattern
- Toggle active status - Click the badge to enable/disable
- View logs - See blocked requests with details
- 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:
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:
- DNT header - Stops tracking if
navigator.doNotTrack === '1' - Cookie consent - Checks for common consent cookie implementations
- Custom consent callback - Use
window.KaiConsentCallbackfunction for custom logic
JavaScript API
The tracker exposes a global API for manual control:
How It Works
- The tag outputs a config script with visitor/session IDs
- Loads
tracker.jsfrom/kai-personalize/tracker.js - Events are queued and batched (configurable threshold and interval)
- Queue is persisted to localStorage (survives page refreshes)
- Uses
sendBeaconfor reliable delivery on page unload - 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:
- Events are saved to localStorage as they're queued
- Survives page refreshes and navigation
- Automatically restored on page load
- Stale events (older than
maxEventAge) are discarded - Gracefully handles quota exceeded errors
kai:behavior
Get behavioral statistics for the current visitor:
kai:tracking
Generates cryptographic signatures for secure tracking endpoint validation. Only required when KAI_TRACKING_SECRET is configured.
Usage
When HMAC signature validation is enabled, use this tag to generate a signature for the tracking endpoint:
JavaScript Integration
The signature must be included with tracking requests:
When to Use
- Required when
KAI_TRACKING_SECRETis set in.env - Not needed for basic tracking without signature validation
- The
{{ kai:track }}tag automatically handles this internally
Installation - CSRF Exceptions
When using the tracking endpoint, you must add CSRF token exceptions to bootstrap/app.php:
This allows the tracking JavaScript to POST events without CSRF tokens.
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
Add the following to your .env file:
Alternatively, you can specify Cloudflare's IP ranges explicitly:
Why This Is Needed
Without trusting proxies, Laravel/Statamic will see Cloudflare's IP addresses instead of your visitors' real IP addresses, causing:
- Incorrect geolocation data
- All visitors appearing from the same location
- Rate limiting to affect all users collectively
- Visitor tracking to be less accurate
Verifying IP Detection
After setting 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:
- OpenWeatherMap
- WeatherAPI
- AccuWeather
Geolocation APIs:
- IPapi
- MaxMind GeoIP2
- IP2Location
- ipstack
Custom API Connections
Manage your external API connections via the Control Panel:
- Navigate to Kai Personalize > API Connections
- Click Create Connection
- 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)
- Test the connection to ensure it works
- View statistics: Total requests, success rate, cache usage
- Manage cache: Clear cached responses when needed
Testing Connections
Test API connections from the command line:
Artisan Commands
Database Structure
The addon uses the following tables (all prefixed with kai_personalize_):
- visitors - Unique visitors identified by fingerprint
- visitor_sessions - Individual browsing sessions
- visitor_attributes - Custom visitor attributes
- page_views - Page view tracking with entry metadata
- events - Behavioral events (scroll depth, clicks, reading time, etc.)
- rules - Personalization rules and conditions
- segments - Visitor segments with criteria
- segment_visitor - Pivot table for visitor-segment relationships
- logs - Personalization event logs
- api_connections - External API configurations
- api_cache - Cached API responses
- api_logs - API request logs
Privacy & GDPR
The addon includes several privacy features:
- IP Encryption: Automatically encrypt stored IP addresses
- Do Not Track: Respect DNT browser headers
- Data Anonymization: Automatically anonymize data after specified period
- GDPR Mode: Additional privacy controls for EU compliance
- Cookie Consent: Optional cookie consent requirement
- Data Retention: Configurable retention periods for all data types
- Right to be Forgotten: Delete visitor data via CP or API
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 |
| HMAC Signatures | Cryptographic validation of tracking requests | ⚠️ Optional |
| Timestamp Validation | Rejects expired signatures (5 min) | ⚠️ Optional |
| Replay Protection | Nonce caching prevents duplicate requests | ⚠️ Optional |
| Origin Validation | Whitelist allowed domains | ⚠️ Optional |
Enabling HMAC Signature Validation (Recommended for Production)
To enable cryptographic signature validation, configure a secret key:
How Signature Validation Works
-
Server generates signature using the
{{ kai:tracking }}tag: -
Client includes signature with tracking requests:
- Server verifies before processing:
- Signature matches (HMAC SHA-256)
- Timestamp is recent (within 5 minutes)
- Nonce hasn't been used before
Security Best Practices
- Always use HTTPS - Signatures can be intercepted over HTTP
- Generate a strong secret - Use
php artisan key:generate --show - Set allowed origins - Restricts cross-origin requests
- Monitor logs - Failed signature attempts are logged
- Use a WAF - CloudFlare or similar for DDoS protection
Performance
The addon is optimized for performance:
- Caching: Redis/file-based caching for API responses and visitor data
- Queueing: Optional queue support for heavy operations
- Batch Operations: Efficient bulk inserts and updates
- CDN-Friendly: Static asset delivery
- Rate Limiting: Prevent API overuse
- Circuit Breaker: Graceful degradation when APIs fail
Multilingual Support
The addon is fully translated in:
- English (en)
- Dutch (nl)
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:
✅ Fully Implemented:
- Dashboard: Overview of visitors, sessions, top pages, and top engaged visitors
- Analytics: Page-level analytics with views, unique visitors, scroll depth, and reading time
- Rules: Create and manage personalization rules with condition builder
- Visitors: Browse visitor profiles with engagement scores, page history, behavioral summary, sessions, and attributes
- Segments: Create dynamic visitor segments with criteria-based assignment
- API Connections: Manage external API integrations with testing and cache management
- Settings: Configure features, privacy, and performance
Analytics & Engagement Scoring
The addon now includes comprehensive analytics and engagement tracking:
Engagement Score (0-100)
Each visitor receives an engagement score based on:
- Visit Frequency (0-30 points):
visit_count × 3, max 30 - Page Views (0-25 points):
page_views × 2, max 25 - Reading Time (0-25 points): For every 10 seconds of reading time, 1 point, max 25
- Scroll Depth (0-20 points): Max scroll depth / 5, max 20
Color-coded badges:
- 🟢 Green (70-100): Highly engaged
- 🟡 Yellow (40-69): Moderately engaged
- ⚪ Gray (0-39): Low engagement
Behavioral Summary
For each visitor, track:
- Max Scroll Depth: Deepest scroll percentage recorded
- Reading Time: Total time spent reading (in minutes)
- Total Clicks: Number of click events tracked
- Total Events: All behavioral events combined
Page Analytics
Navigate to Analytics > Pages to see:
- Total views per page
- Unique visitors per page
- First and last view timestamps
- Average scroll depth
- Average reading time
- Recent views with visitor links
Visitor Page History
Each visitor profile now includes:
- Complete browsing history with pagination
- Entry title and collection
- URL path
- View timestamp
Available Event Types
The addon tracks these behavioral events via the kai:track tag:
scroll_depth- Maximum scroll percentage on a pageclick- Click events on elementsvisibility- Element visibility trackingreading_time- Time spent reading contentcustom- Custom events
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
- 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.
-
Install the addon:
-
Verify the symlink was created:
- 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:
- Email: [email protected]
- Website: https://keyagency.nl
License
Proprietary - Copyright © Key Agency
Credits
Developed by Key Agency with AI agent Kai.
Roadmap
✅ Completed (v1.0)
- [x] Control Panel UI for Rules management
- [x] Control Panel UI for Visitors management
- [x] Control Panel UI for Segments management
- [x] Control Panel UI for API Connections management
- [x] Dashboard with real-time statistics
- [x] Settings management interface
✅ Completed (v1.1)
- [x] Analytics & Engagement Scoring
- [x] Page-level analytics with scroll depth and reading time
- [x] Visitor page history with pagination
- [x] Behavioral summary (max scroll, reading time, clicks, events)
- [x] Top engaged visitors ranking
- [x] Event tracking tags (kai:track, kai:behavior)
Short Term (Next Release)
- [ ] Enhanced Dashboard with charts and graphs
- [ ] Export/Import functionality for rules and settings
- [ ] Segment-based condition support in Rules
Medium Term
- [ ] A/B testing capabilities
- [ ] Rule templates and presets
- [ ] Visitor journey visualization
- [ ] Segment-based condition support in Rules
Long Term
- [ ] Machine learning predictions
- [ ] GraphQL API support
- [ ] WebSocket connections for real-time data
- [ ] Content recommendation engine
- [ ] Multi-variant testing
- [ ] More API provider integrations
All versions of kai-personalize with dependencies
statamic/cms Version ^6.0
jenssegers/agent Version ^2.6
geoip2/geoip2 Version ^3.0