Skip to content

Latest commit

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Analytics Manager Package

A comprehensive Laravel package providing privacy-compliant web analytics functionality for content management systems.

Description

This package provides a complete analytics solution for Laravel applications, with a strong focus on privacy compliance and GDPR adherence. It offers detailed visitor tracking, real-time statistics, and an intuitive admin dashboard widget without relying on external services. The package is designed to be lightweight, extensible, and fully integrated with the Core CMS ecosystem.

Features

  • ✅ Privacy-compliant visitor tracking with IP anonymization
  • ✅ Real-time analytics dashboard with interactive charts
  • ✅ Bot detection and filtering capabilities
  • ✅ GDPR-compliant data collection with consent management
  • ✅ Custom event tracking system
  • ✅ Page visit time tracking with session management
  • ✅ Browser, platform, and device analytics
  • ✅ Referrer analysis with data sanitization
  • ✅ Automatic cache management for performance
  • ✅ Multi-language support (EN/FR included)
  • ✅ RESTful API endpoints with rate limiting
  • ✅ Single Page Application (SPA) tracking support

Requirements

  • PHP ^8.1
  • Laravel ^12.0
  • netauratech/core-cms ^1.0

Installation

Via Composer (recommended)

composer require netauratech/analytics-manager

Manual Installation

  1. Clone the repository into your Laravel project
  2. Add the dependency to your composer.json
  3. Run composer install

Configuration

1. Service Provider

The service provider is automatically registered thanks to Laravel's automatic discovery. If you want to register it manually, add it to config/app.php:

'providers' => [
// ...Netauratech\AnalyticsManager\AnalyticsManagerServiceProvider::class,
],

2. Database Setup

Run the migrations to create the analytics database tables:

php artisan migrate

This will create the visits table with the following structure:

  • Visit tracking data (URL, referrer, timestamps)
  • Privacy-compliant user identification (hashed IP addresses)
  • Browser and device information
  • Custom data storage (JSON format)
  • Comprehensive indexing for performance

3. Frontend Integration

The package automatically registers a tracking script that integrates with your frontend. The script includes:

  • GDPR consent management integration
  • Single Page Application (SPA) support
  • Automatic event tracking capabilities
  • Time-on-page measurement

Basic Implementation

The tracking script is automatically included via the Core CMS asset manager. Make sure to initialize tracking in your frontend:

// The script automatically initializes when CSRF token is available// and GDPR consent is givenwindow.addEventListener("csrf-ready",function(event){// Tracking automatically starts if consent is available});// For GDPR compliancewindow.addEventListener('gdpr:consent-given',function(){// Tracking starts automatically after consent});

Custom Event Tracking

Track custom events programmatically:

// Track custom eventswindow.trackEvent('button_click',{button_id: 'signup-btn',location: 'header'});// Track external link clicks (automatic)// Track scroll depth (automatic: 25%, 50%, 75%, 90%)// Track element clicks with data-track attribute (automatic)

Usage

Admin Dashboard

The package automatically adds an analytics widget to your Core CMS admin dashboard. The widget provides:

Real-time Statistics

  • Total visits and unique visitors
  • Page views and bounce rate
  • Time-based filtering (7 days, 30 days, all time)
  • URL-specific analytics

Interactive Charts

  • Daily visits line chart
  • Daily unique visitors chart
  • Browser distribution pie chart
  • Platform distribution pie chart
  • Device type distribution pie chart

Top Pages Analysis

  • Most visited pages ranking
  • Visit counts per page
  • Direct navigation to page analytics

API Endpoints

The package provides RESTful API endpoints for analytics tracking:

Visit Tracking

POST /api/track-visitContent-Type: application/json
{
"url": "/current-page",
"referer": "https://example.com/previous-page",
"screen_width": 1920,
"screen_height": 1080,
"utm_source": "google",
"utm_medium": "cpc",
"utm_campaign": "summer2024"
}

Time Tracking

POST /api/track-timeContent-Type: application/json
{
"visit_id": 123,
"time_spent": 45,
"url": "/current-page"
}

Event Tracking

POST /api/track-eventContent-Type: application/json
{
"visit_id": 123,
"event": "video_play",
"url": "/current-page",
"data": {
"video_title": "Product Demo",
"duration": "2:30"
}
}

Privacy Features

IP Address Anonymization

// IP addresses are automatically hashed with daily saltprivatefunctionhashIP(string$ipAddress): string
{
$salt = config('app.key') . date('Y-m-d');
// IPv4 anonymization: 192.168.1.1 → 192.xxx.xxx.xxx// IPv6 anonymization: full address → ipv6.xxxreturnhash('sha256', $ipAddress . $salt);
}

Data Sanitization

// Referrer URLs are automatically sanitizedprivatefunctionsanitizeReferer(?string$referer): ?string
{
// Only scheme, domain, and path are retained// Query parameters and fragments are removed// Length is limited to 500 characters
}

Bot Detection

// Comprehensive bot detectionprivatefunctionisBot(?string$userAgent): bool
{
// Detects: googlebot, bingbot, crawlers, spiders// Identifies: curl, wget, automated tools// Filters: empty or suspicious user agents
}

Analytics Data Retrieval

Quick Statistics

useNetauratech\AnalyticsManager\Models\Visit;
// Get overall statistics$stats = Visit::getQuickStats('7_days');
// Returns: total_visits, unique_visitors, pages_visited, bounce_rate// Get statistics for specific URL$stats = Visit::getQuickStats('30_days', '/specific-page');

Custom Queries

// Get visits for specific period$visits = Visit::period('7_days')
->excludeBots()
->with('custom_data')
->get();
// Get unique visitors$uniqueVisitors = Visit::period('30_days')
->excludeBots()
->distinct('ip_hash')
->count('ip_hash');
// Browser statistics$browsers = Visit::selectRaw('browser, COUNT(*) as count')
->period('7_days')
->excludeBots()
->groupBy('browser')
->orderByDesc('count')
->get();

Available Scopes

// Period filtering
Visit::period('7_days'); // Last 7 days
Visit::period('30_days'); // Last 30 days
Visit::period('today'); // Today only
Visit::period('this_week'); // Current week
Visit::period('this_month'); // Current month// URL filtering
Visit::forUrl('/specific-page');
// Bot filtering
Visit::excludeBots();
// Unique visitors only
Visit::uniqueOnly();

Model Relationships and Attributes

Visit Model Methods

$visit = Visit::find(1);
// Device type checks$visit->isMobile(); // boolean$visit->isTablet(); // boolean $visit->isDesktop(); // boolean// Display names$visit->getBrowserDisplayName(); // "Google Chrome"$visit->getPlatformDisplayName(); // "Windows"// Referrer analysis$visit->getRefererDomain(); // "google.com"$visit->isDirectVisit(); // boolean// Date formatting$visit->getFormattedVisitDate(); // "19 Sep 2025 14:30"

Caching System

The package includes intelligent caching to ensure optimal performance:

Automatic Cache Management

// Cache keys are automatically generated and managed$cacheKey = md5(json_encode(['period' => $period, 'url' => $url]));
// Cache is automatically invalidated when new visits are recordedprivatefunctioninvalidateAnalyticsCache(): void
{
// Clears relevant cache entries for all periods and categories
}

Cache Configuration

// Uses Laravel's default cache store$cache = Cache::store(config('cache.default'));
// 15-minute TTL for dashboard data$ttl = now()->addMinutes(15);

Customization

Extending the Visit Model

useNetauratech\AnalyticsManager\Models\Visit;
class CustomVisit extends Visit
{
// Add custom methods or override existing onespublicfunctiongetCustomMetric(): float
{
// Your custom logic here
}
}

Custom Analytics Widget

useNetauratech\AnalyticsManager\Widgets\AnalyticsWidget;
class CustomAnalyticsWidget extends AnalyticsWidget
{
publicfunctionrender(): View
{
// Get base data$data = parent::render()->getData();
// Add your custom data$data['customMetric'] = $this->getCustomMetric();
returnview('your-package::custom-analytics', $data);
}
privatefunctiongetCustomMetric()
{
// Your custom analytics logic
}
}

Custom Event Tracking

// In your service provideruseNetauratech\CoreCms\Services\AssetManager;
publicfunctionboot(AssetManager$assetManager)
{
$assetManager->registerView('your-package::custom-tracking');
}

Create custom-tracking.blade.php:

<script>document.addEventListener('DOMContentLoaded',function(){// Custom tracking logicdocument.querySelectorAll('.track-download').forEach(element=>{element.addEventListener('click',function(){window.trackEvent('file_download',{file_name: this.getAttribute('data-file'),file_type: this.getAttribute('data-type')});});});});</script>

File Structure

src/
├── Http/
│ └── Controllers/
│ └── Api/
│ └── AnalyticsController.php # Main API controller
├── Models/
│ └── Visit.php # Visit model with scopes
├── Widgets/
│ └── AnalyticsWidget.php # Dashboard widget
├── database/
│ └── migrations/
│ └── 2025_09_13_000000_create_visits_table.php
├── lang/ # Multi-language support
│ ├── en/
│ │ └── admin.php
│ └── fr/
│ └── admin.php
├── resources/
│ └── views/
│ ├── script.blade.php # Frontend tracking script
│ └── widgets/
│ └── analytics.blade.php # Dashboard widget view
├── routes/
│ └── api.php # API routes definition
└── AnalyticsManagerServiceProvider.php # Main service provider

API Reference

AnalyticsController Methods

trackVisit(Request $request): JsonResponse

Tracks a website visit with comprehensive data collection:

  • Browser and device detection
  • IP anonymization and hashing
  • Bot detection and filtering
  • Unique visitor identification
  • UTM parameter extraction
  • Screen dimension recording

trackTime(Request $request): JsonResponse

Records time spent on a page:

  • Validates reasonable time ranges (0-7200 seconds)
  • Links to existing visit records
  • Updates custom data with time metrics
  • Prevents data manipulation

trackEvent(Request $request): JsonResponse

Tracks custom events:

  • Event name sanitization
  • Visit association validation
  • Custom data storage
  • Event spam prevention (max 50 events per visit)

Rate Limiting

All API endpoints include rate limiting:

Route::post('/track-visit', [AnalyticsController::class, 'trackVisit'])
->middleware(['throttle:100,1']); // 100 requests per minute
Route::post('/track-time', [AnalyticsController::class, 'trackTime'])
->middleware(['throttle:50,1']); // 50 requests per minute
Route::post('/track-event', [AnalyticsController::class, 'trackEvent'])
->middleware(['throttle:200,1']); // 200 requests per minute

Translations

Available Languages

The package includes translations for:

  • English (en/admin.php)
  • French (fr/admin.php)

Adding Custom Languages

  1. Create a new language directory: src/lang/{locale}/
  2. Copy admin.php from an existing language
  3. Translate all string values
  4. The package will automatically load the translations

Translation Keys

// Dashboard labels'analytics.period' => 'Period'
'analytics.total_visits' => 'Total visits'
'analytics.unique_visitors' => 'Unique visitors'
'analytics.bounce_rate' => 'Bounce rate'// Time periods
'analytics.7_days' => '7 days'
'analytics.30_days' => '30 days' 'analytics.all_time' => 'All time'// Chart labels
'analytics.visits_per_day' => 'Visits per day'
'analytics.browsers' => 'Browsers'
'analytics.platforms' => 'Platforms'
'analytics.devices' => 'Devices'

Performance Considerations

Database Indexing

The migration includes comprehensive indexing:

$table->index(['visited_at', 'url']);
$table->index(['visited_at', 'ip_hash']);
$table->index(['visited_at', 'is_bot']);
$table->index(['session_id', 'visited_at']);

Caching Strategy

  • Dashboard data cached for 15 minutes
  • Automatic cache invalidation on new visits
  • Separate cache keys for different periods/URLs
  • Uses Laravel's configured cache driver

Data Retention

Consider implementing data retention policies:

// Example: Delete visits older than 2 years
Visit::where('visited_at', '<', now()->subYears(2))->delete();

Security Features

GDPR Compliance

  • IP address anonymization with daily salt rotation
  • Referrer URL sanitization (removes query parameters)
  • Custom data filtering and validation
  • Consent-based tracking activation
  • Right to be forgotten support (via IP hash deletion)

Data Protection

  • CSRF protection on all endpoints
  • Rate limiting to prevent abuse
  • Input sanitization and validation
  • SQL injection prevention via Eloquent ORM
  • XSS protection in dashboard views

Privacy by Design

  • No personally identifiable information stored
  • Minimal data collection (only necessary analytics data)
  • Automatic bot exclusion from statistics
  • Session-based unique visitor detection

Development

Contributing

Contributions are welcome! Please:

  1. Fork the project
  2. Create a feature branch (git checkout -b feature/analytics-feature)
  3. Commit your changes (git commit -m 'Add analytics feature')
  4. Push to the branch (git push origin feature/analytics-feature)
  5. Open a Pull Request

Development Setup

# Clone the repository
git clone https://github.com/NetAuraTech/analytics-manager.git
# Install dependencies
composer install

Troubleshooting

Common Issues

Analytics not tracking

  1. Verify GDPR consent is properly implemented
  2. Check CSRF token availability
  3. Ensure API routes are accessible
  4. Verify JavaScript console for errors

Dashboard not showing data

  1. Check database migrations have run
  2. Verify visits table has data
  3. Clear application cache: php artisan cache:clear
  4. Check browser console for JavaScript errors

Performance issues

  1. Verify database indexes exist
  2. Check cache configuration
  3. Consider data retention policies
  4. Monitor database query performance

License

This package is open-source software licensed under the MIT license.

Support

For support or questions:

Changelog

v1.0.0

  • Initial release
  • Privacy-compliant visitor tracking
  • Real-time analytics dashboard
  • Bot detection and filtering
  • GDPR compliance features
  • Multi-language support
  • Comprehensive API endpoints
  • SPA tracking support
  • Custom event tracking

Authors


© 2025 NetAuraTech. All rights reserved.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages